	.macro declare_psect nam
	.psect nam
	.endm
	.macro instruction_mb
	evax_imb
	.endm
evax=0
; This little gem checks to see if xdelta is loaded and if it isn't
; loads the execlet. In either case, a breakpoint will be taken.

	DECLARE_PSECT EXEC$NONPAGED_DATA

ref_inf: .blkl	3

filnam: .ascid /SYSTEM_DEBUG/


	DECLARE_PSECT EXEC$NONPAGED_CODE

start::	.call_entry

	tstl	xdt$gl_scb		; is there an xdelta scb page?
	beql	load_xdelta		; assume if not zero, xdelta is already
					; loaded, so just take the breakpoint
do_bpt:	$cmkrnl_s bpt

exit:   ret

; SYSTEM_DEBUG is not loaded, so load it...

load_xdelta:

	$cmkrnl_s mem			; allocate scb page for xdelta
	blbc r0,exit

	$cmexec_s routin=load		; load SYSTEM_DEBUG 
	blbs	r0,do_bpt		; if ok, take breakpoint

	cmpl	#ss$_duplnam,r0		; is error duplicate name?
	beql	do_bpt			; assume xdelta is loaded and OK
	
; Close it up only if there was an error loading. XDELTA closes up the system
; after a breakpoint, so in the normal case, it will do it for us.

	pushl	r0
	$cmkrnl_s close			; close up system
	popl	r0
	ret				

; Routine to change the NOP at the ini$brk to a BPT and to allocate
; XDELTA's private SCB page.

mem:    .call_entry

	movl	#1,r1                   ; allocate 1 page
	jsb	exe$alophycntg		; do it
	blbc	r0,15$			; ooops
	movl	r2,xdt$gl_scb		; put the address here
	movc5	#0,(r2),#0,#8192,(r2)	; zero fill the scb 

	jsb	ini$writable		; make system writeable, turn
					; off fault-on-read and GH
	moval	ini$brk,r0		; get pd address for ini$brk
	movl	8(r0),r0		; get code address 
	movl	#^x80,(r0)		; set instruction = BPT
	instruction_mb			; and make it stick
	movl	#ss$_normal,r0

15$:	ret

; This routine make the exec code readonly and turns on fault-on-read and
; granularity hints for the code region.  The SCB page is not deallocated
; but the data cell is zeroed so another load attempt may succeed, but the 
; page of memory is lost.

close:	.call_entry
	clrl	xdt$gl_scb		; throw the scb page away
	jsb	ini$rdonly		; lock it up
	movl	#ss$_normal,r0
	ret

; This routine calls the exec loader to load the system_debug image

load:	.call_entry
        pushal  ref_inf
	pushl   #0
	pushal  filnam
        calls   #3,ldr$load_image 
	ret

; This routine will result in a BPT

bpt:	.call_entry
	jsb ini$brk
	movl	#ss$_normal,r0
	ret

        .END	start
