
; Public Domain

; test install command: install; checksum 100 l 8; checksum uninstall
; test run command: 100 l 8; .; .

%include "lmacros3.mac"
%include "eld.mac"
%include "eldcall.mac"
%include "elddata.mac"

%assign _CATCHINT0C 0
%assign _CATCHINT0D 0
%assign _CATCHINTFAULTCOND 0
%assign _DEBUG 0
%assign _DELAY_BEFORE_BP 0
%assign _DHIGHLIGHT 0
%assign _GETLINEHIGHLIGHT 0
%assign _IMMASM 0
%assign _INPUT_FILE_BOOT 0
%assign _INPUT_FILE_HANDLES 0
%assign _MS_0RANGE_COMPAT 0
%assign _PM 0
%assign _RH 0
%assign _SYMBOLIC 0
%assign _VXCHG 0
%include "options.mac"

	cpu 8086

	addsection RELOCATEDDATA, nobits vstart=_ELD_RELOC_VSTART
relocateddata:

	addsection HEADER, start=0

	istruc ELD_HEADERX
at eldhxHeader
		; ELD executable header
	istruc ELD_HEADER
at eldhSignature,	db "ELD1"
			db 0,0,0
			db 26
at eldhCodeOffset,	dd CODEOFFSET
at eldhCodeImageLength,	dw code_size
at eldhCodeAllocLength,	dw 0
at eldhDataOffset,	dd DATAOFFSET
at eldhDataImageLength,	dw data_size
at eldhDataAllocLength,	dw total_data_size - data_size
at eldhCodeEntrypoint,	dw linker - code
at eldhReserved
at eldhExtensionSize,	dw header_extension_end - $$
	iend
at eldhxDescriptionOffset,	dd description
at eldhxHelpOffset,		dd DATAOFFSET + msg.help - datastart
header_extension_end:
	iend

description:		asciz "Provide CHECKSUM command."


	align 16, db 0

CODEOFFSET equ $ - $$
	addsection CODE, follows=HEADER vstart=_ELD_CODE_VSTART
%define CODEFIXUP - code + 0
code:
code_start:
		; ELD instance header
	istruc ELD_INSTANCE
at eldiStartCode
at eldiEndCode
at eldiStartData
at eldiEndData
at eldiIdentifier,	fill 8, 32, db "CHECKSUM"
at eldiListing,		asciz _ELD_LISTING
	iend


DATAOFFSET equ CODEOFFSET + code_size
	addsection DATA, follows=CODE vstart=_ELD_DATA_VSTART
%define DATAFIXUP - datastart + 0
datastart:


	usesection CODE

command:
	jmp strict short .entry
.chain:
	extcall cmd3_not_ext, required	; must NOT be extcallcall
	times 10 - ($ - command) nop
.entry:
	push si
	cmp al, '-'
	jne @F
	extcallcall skipcomma
@@:
	dec si

	mov dx, msg.checksum
internaldatarelocation
	extcallcall isstring?
	je .ours
	pop si
	dec si
	lodsb
	jmp .chain

.ours:
	pop ax
	extcallcall skipcomma
	dec si
reloc2	mov word [relocateddata], relocateddata
linkdatarelocation lastcmd, -4
linkdatarelocation dmycmd
	mov dx, relocateddata
linkdatarelocation msg.uninstall
	extcallcall isstring?
	je uninstall

	call run
	extcallcall cmd3


%assign _PM 1
%assign _ONLY386 0
%assign _ONLYNON386 0
%define lDEBUG_CODE CODE
%define lDEBUG_DATA_ENTRY DATA
%assign _WPT_LABELS 0

%include "386.mac"

		; INP:	ds:(e)si -> string to hash
		;	(e)cx = length of string (may be zero)
		;	(commented) edx = mask
		; OUT:	bx = hash value computed
		;	(e)cx = 0
		; CHG:	ax, (e)si
		; STT:	UP
zz_hash:
	mov bx, 1

		; INP:	ds:(e)si -> string to hash
		;	(e)cx = length of string (may be zero)
		;	bx = initial hash value
		;	(commented) edx = mask
		; OUT:	bx = hash value computed
		;	(e)cx = 0
		; CHG:	ax, (e)si
		; STT:	UP
.bx_init:
	_386_PM_a32
	jcxz .end
.loop:
	xor ax, ax
	_386_PM_a32
	lodsb
%if 0
	_386_PM_o32
	and si, dx
%endif
	sub ax, bx
	push cx
	mov cl, 5
	shl bx, cl
	pop cx
	add bx, ax
	_386_PM_a32
	loop .loop
.end:
	retn


errorj2a:
	jmp error

;	GETSTR - Get string of bytes.  Put the answer in line_out.
;		Entry	AL	first character
;			SI	address of next character
;		Exit	[line_out] first byte of string
;			DI	address of last+1 byte of string
;		Uses	AX, cx, dx,SI
getstr_text:
	extcallcall skipcomm0
	mov di, relocateddata
linkdatarelocation line_out
	extcallcall iseol?
	je short errorj2a	; we don't allow empty byte strings

getstr_loop:
	extcallcall skipcomm0
	cmp al, "'"
	je getstr_start_quote	; if string
	cmp al, '"'
	je getstr_start_quote	; ditto

	cmp di, strict word relocateddata - 1
linkdatarelocation line_out_end
	ja errorj2a

	extcallcall getbyte	; byte in DL
	mov byte [di], dl	; store the byte
	inc di
	jmp short getstr_next

getstr_start_quote:
	mov ah, al		; save quote character
getstr_loop_quoted:
	lodsb
	cmp al, ah
	je getstr_quote_quoted	; if possible end of string
	extcallcall iseol?.notsemicolon
	je short errorj2a	; if end of line
getstr_store_quoted:
	cmp di, strict word relocateddata - 1
linkdatarelocation line_out_end
	ja errorj2a

	stosb			; save character and continue
	jmp short getstr_loop_quoted

getstr_quote_quoted:
	lodsb
	cmp al, ah
	je getstr_store_quoted	; if doubled quote character
getstr_next:
	extcallcall skipcomm0	; go back for more
	extcallcall iseol?
	je .ret
	dec si
	mov dx, msg.end
internaldatarelocation
	extcallcall isstring?
	lodsb
	jne getstr_loop			; if not done yet
.ret:
	retn


uninstall:
	lodsb
	extcallcall chkeol

	mov es, word [relocateddata]
linkdatarelocation extdssel
	extcallcall ispm
	jz @F
	mov es, word [relocateddata]
linkdatarelocation extseg
@@:
	push es
	pop ds
	xor bx, bx		; = 0 (no prior, modify ext_command_handler)
	mov di, command		; di -> us
internalcoderelocation
	mov si, word [ss:relocateddata]
linkdatarelocation ext_command_handler
				; si -> first
	test si, si		; none installed ?
	jz .error		; error -->

.loop:
	cmp di, si		; found ?
	je .bx			; yes, use bx -->
	mov bx, si		; bx -> prior handler
	lodsw			; skip entrypoint jmp strict short
	lodsb			; get first byte of chainer
	cmp al, 0E9h		; expecting jmp near ?
	jne .error		; no, error -->
	lodsw			; get rel16 displacement
	add si, ax		; -> next handler
	jmp .loop

.bx:
	test bx, bx		; any prior ?
	jnz .bxnz		; yes -->
	scasw			; skip entrypoint jmp strict short
	cmp byte [di], 0E8h	; is it a call to cmd3_not_ext ?
	jne @F			; no -->
				; yes, reset ext_command_handler to zero
.setbx:
	mov word [ss:relocateddata], bx
linkdatarelocation ext_command_handler
	jmp .done

@@:
	cmp byte [di], 0E9h	; validate
	jne .error		; failure -->
	inc di			; -> rel16 displacement
	mov bx, word [di]	; get displacement
	scasw			; -> after jmp near
	add bx, di		; -> next handler
	jmp .setbx		; set ext_command_handler to next

.bxnz:
	mov si, bx		; -> prior handler with us as downlink
	xchg di, si		; si -> ours, di -> prior
	cmpsw			; skip entrypoint jmp strict short
	movsb			; copy 0E8h/0E9h
	lodsw			; ax = near rel16 displacement
	add ax, si		; add in our base (= absolute offset)
	sub ax, di
	dec ax
	dec ax			; subtract new base (= relative displacement)
	stosw			; store new rel16 displacement
	movsw			; jmp strict short
	movsw			; linkcall target
	movsb			; trailer
.done:
	clropt [code + eldiFlags], eldifResident
internalcoderelocation -3	; mark block as free
	mov dx, msg.uninstall_done
internaldatarelocation
@@:
	push ss
	pop ds
	extcallcall putsz
	extcallcall cmd3	; return

.error:
	mov ax, 0E01h
	extcallcall setrc
	mov dx, msg.uninstall_error
internaldatarelocation
	jmp @B


run:
	mov dx, msg.list
internaldatarelocation
	extcallcall isstring?
	jne .range

	call getstr_text
	mov bx, ss
	_386_o32
	mov dx, relocateddata
linkdatarelocation line_out
_386	dw 0			; extend mov imm32 immediate to 32 bits
_386	xor ecx, ecx		; ecxh = 0
	mov cx, di
	sub cx, dx
	jnz @F
	jmp error

.range:
	lodsb
	_386_o32		; mov ecx
	mov cx, 512
_386	dw 0			; extend mov imm32 immediate to 32 bits
_386	xor edx, edx		; ecxh = 0 and edxh = 0
	mov bx, word [relocateddata]
linkdatarelocation reg_ds
	extcallcall getrangeX
	_386_o32
	sub cx, dx
	_386_o32
	inc cx
@@:
	mov di, 1		; default initial checksum
	extcallcall iseol?
	je @F
	push dx
	extcallcall getword	; get initial checksum
	mov di, dx
	pop dx

@@:
	extcallcall chkeol

	_386_o32
	mov si, dx

%if 0
	_386_o32
	xor dx, dx		; edx = 0
	extcallcall test_high_limit
_386	jz @F
	_386_o32		; edx = 0FFFF_FFFFh
@@:
	dec dx			; edx = 0FFFFh
%endif

	mov ds, bx
	mov bx, di		; = initial checksum

	_386_o32
	test cx, cx		; (e)cx == 0 ? (means 4 GiB or 64 KiB)
	jnz @F			; no, normal -->
	inc cx			; (e)cx = 1
	call zz_hash.bx_init	; resets (e)cx = 0
	_386_o32
	dec cx			; (e)cx = -1
@@:
	call zz_hash.bx_init	; continue

	push ss
	pop ds
	mov di, relocateddata
linkdatarelocation line_out
	mov ax, bx
	extcallcall hexword

	extcallcall putsline_crlf
	retn


error:
	extcall error

	eldcall_dump_callcall ELDCALL_CALLCALL_LIST

endinstalled equ ($ + CODEFIXUP + 15) & ~15

	align 2, db 0				; align on word boundary
		; Table of patches that are to be set NOP if not running on a 386.
writepatchtable patch_no386_table, PATCH_NO386_TABLE
%undef PATCH_NO386_TABLE

	align 2, db 0
		; Table of patches that are to be set NOP if running on a 386.
writepatchtable patch_386_table, PATCH_386_TABLE
%undef PATCH_386_TABLE


start:
	houdini
	push si
	mov dx, code
internalcoderelocation
	testopt [relocateddata], has386
linkdatarelocation internalflags, -3
	jz @F
	mov si, patch_386_table		; table of patches to set for 386+
internalcoderelocation
%if __patch_386_table_method == 1
	mov cx, patch_386_table_size_w
	call .patch1
%else
	call .patch2
%endif
	jmp .patch_code1_end

@@:
	mov si, patch_no386_table	; table of patches to set for 16-bit CPU
internalcoderelocation
%if __patch_no386_table_method == 1
	mov cx, patch_no386_table_size_w
	call .patch1
%else
	call .patch2
%endif
	jmp .patch_code1_end

		; Complicated table patch code.
%if __patch_no386_table_method == 2 || __patch_386_table_method == 2
.patch2:
	mov di, code_start		; initialise offset
internalcoderelocation
	xor ax, ax			; initialise ah
.looppatch2:
	cs lodsb
	add di, ax			; skip number of bytes to skip
	cmp al, 255			; really repositioning?
	jne .l2patch			; no -->
	xchg ax, di			; (to preserve ah)
	cs lodsw			; ax = new address
	add ax, dx
	xchg ax, di			; di = new address
.l2patch:
	cs lodsb
	mov cx, ax			; cx = number of bytes to patch
	jcxz .patchesdone		; end of table -->
	mov al, 90h			; patch to NOP
	rep stosb			; patch as many bytes as specified
	jmp short .looppatch2
%endif

		; Simple table patch code.
%if __patch_no386_table_method == 1 || __patch_386_table_method == 1
.patch1:
	jcxz .patchesdone
.looppatch1:
	cs lodsw			; load address of patch
	add ax, dx
	xchg bx, ax			; (set bx = ax, CHG ax)
	mov byte [es:bx], 90h		; patch
	loop .looppatch1
%endif
.patchesdone:
	retn

.patch_code1_end:
	pop si

	mov bx, es
	 push ss
	 pop es

	call skipcomma
	dec si
	mov dx, relocateddata
linkdatarelocation msg.install
	call isstring?
	je install

	mov dx, msg.help_noun
internaldatarelocation
	call isstring?
	je help

	call iseol?
	je help

	call run
@@:
	call uninstall_oneshot
	xor ax, ax
	retf

help:
	call chkeol
	mov dx, msg.help
internaldatarelocation
	extcall putsz
	jmp @B


uninstall_oneshot:
	testopt [ss:relocateddata], 1
linkdatarelocation options7, -3
	jnz @F

	mov ax, word [cs:code + eldiEndCode]
internalcoderelocation
	sub ax, word [cs:code + eldiStartCode]
internalcoderelocation
	sub word [relocateddata], ax
linkdatarelocation extseg_used

	mov ax, word [cs:code + eldiEndData]
internalcoderelocation
	sub ax, word [cs:code + eldiStartData]
internalcoderelocation
	sub word [relocateddata], ax
linkdatarelocation extdata_used
@@:
	retn


	usesection DATA

msg:
.checksum:		asciz "CHECKSUM"
.uninstall_done:	db "CHECKSUM command uninstalled."
%if _ELD_RECLAIM_HINT
			db " (Don't forget to use reclaim.eld)"
%endif
			asciz 13,10
.uninstall_error:	asciz "CHECKSUM command unable to uninstall!",13,10
.list:			asciz "LIST"
.end:			asciz "END"

uinit_data: equ $

.installed:	asciz "CHECKSUM command installed.",13,10
.help_noun:	asciz "HELP"
.help:		db "Install this ELD using an INSTALL keyword.",13,10
		db 13,10
		db "Run with CHECKSUM range [initialchecksum] to do checksum on a range.",13,10
		db "Or run with CHECKSUM LIST list [END initialchecksum] to do checksum on a list.",13,10
		db "Run with CHECKSUM UNINSTALL to uninstall resident ELD.",13,10
		asciz

	align 16, db 0
init_data_end:
data_size equ $ - datastart
transient_data_size equ data_size

	absolute uinit_data

	alignb 16
uinit_data_end:
resident_data_end:
resident_data_size equ resident_data_end - datastart

%if uinit_data_end >= init_data_end
 total_data_size equ $ - datastart
%else
 total_data_size equ init_data_end - datastart
%endif
%assign _DATA_SIZE total_data_size


	usesection CODE

install:
	lodsb
	extcall chkeol

	houdini
	mov es, bx		; => ext seg (writable)

	mov ax, endresident - endinstalled
	sub word [es:code + eldiEndCode], ax
internalcoderelocation		; adjust size
	sub word [relocateddata], ax
linkdatarelocation extseg_used	; adjust size

%if (transient_data_size - resident_data_size) > 0
	mov ax, transient_data_size - resident_data_size
	sub word [es:code + eldiEndData], ax
internalcoderelocation		; adjust size
	sub word [relocateddata], ax
linkdatarelocation extdata_used	; adjust size
%endif

	mov bx, word [relocateddata]
linkdatarelocation ext_command_handler
				; -> prior
	mov di, command		; -> our handler
internalcoderelocation
	test bx, bx		; installing as first ?
	jz .only_first		; yes, simple --> (leave as extcall cmd3_not_ext)
	scasw			; skip entrypoint jmp strict short
	mov al, 0E9h		; = jmp near opcode
	stosb			; store
	xchg ax, bx		; ax -> next handler
	sub ax, di
	dec ax
	dec ax			; ax = ax - (di + 2)
	stosw			; store our downlink as rel16 displacement

.only_first:
	setopt [es:code + eldiFlags], eldifResident
internalcoderelocation -3	; mark block as resident
	mov word [relocateddata], command
linkdatarelocation ext_command_handler, -4
internalcoderelocation		; -> our entrypoint

	testopt [relocateddata], 4
linkdatarelocation options7, -3
	jnz @F
	mov dx, msg.installed
internaldatarelocation
	call putsz
@@:
	xor ax, ax
	retf


%include "eldlink.asm"

	align 16
code_size equ $ - code
