comp-arch-exc/2-24.asm
Arija Arčenytė d271fbaf94
Ofast not O3
Signed-off-by: Arija Arčenytė <ari@ari.lt>
2026-10-28 02:35:01 +02:00

1653 lines
42 KiB
NASM

; -----------------------------------------------------------------------------
; Big-integer GCD for 16-bit DOS, assembled with TASM.
;
; Author: Arija A. <ari@ari.lt>
; Licence: WTFPL version 2
; Usage: 2-24.EXE input1.txt input2.txt output.txt (or /? for help)
; Each input file must contain one positive decimal integer.
; Testing: Compile and run the test-2-24.c programme to run tests:
; C:\> tasm 2-24.asm
; C:\> link 2-24.OBJ
; C:\> gcc test-2-24.c -Ofast -s -pedantic -Wall -Wextra
; C:\> .\a.exe
; -----------------------------------------------------------------------------
LOCALS @@
.model small, C
.stack 200h
.data
; Help
help_arg db "/?", 0
help db "Usage: 2-24.EXE <input1.txt> <input2.txt> <output.txt> (or /? for help)", 13, 10
db "Supply two files, each containing a positive decimal integer, and an output file.", 13, 10
db "The greatest common divisor (GCD) is written to the output file.", 13, 10, "$"
; Errors
error_mem_oom db "DOS: Out of memory.", 13, 10, "$"
error_cli_args db "Invalid command-line arguments. Try: 2-24.EXE /?", 13, 10, "$"
error_failed_read_head db "Failed to read from file: $"
error_failed_write_head db "Failed to write to file: $"
error_invalid_number db "Input files must contain positive decimal integers.", 13, 10, "$"
; Output newline
output_newline db 13, 10, '$'
output_newline_bytelen equ 2
; argc counts parsed arguments.
; Each WORD in argv is a DOS allocation segment; each string starts at offset 0.
argc db 0
argv dw 127 dup(0)
.code
; Read an entire file into a DOS-allocated block.
; Arguments:
; - filename segment/offset
; - segment:offset pointers to output WORDs for buffer segment and size
; Output:
; AX=0 on success, AX=1 on I/O/allocation/size failure.
; The caller owns the output slots.
read_file PROC USES bx cx si di ds es, filename_seg:WORD, filename_off:WORD, out_buffer_off:WORD, out_buffer_seg:WORD, out_size_off:WORD, out_size_seg:WORD
LOCAL file_handle:WORD
; AL=0 opens the path read-only (DS:DX); AX is the file handle.
; If opening fails, there is no handle or buffer to close/free.
mov ds, filename_seg
mov dx, filename_off
mov ax, 3D00h ; opens read-only. CF reports an open error.
int 21h
jnc @@opened
; Failed to open file
mov ax, 1
ret
@@opened:
mov file_handle, ax
; AX=4202h seeks zero bytes from EOF.
; DX:AX is the resulting 32-bit position.
; This implementation tracks lengths in one word,
; so files above 65535 bytes are rejected.
mov bx, file_handle
mov ax, 4202h
xor cx, cx
xor dx, dx
int 21h ; DOS returns the absolute file position in DX:AX; CF is status.
jnc @@at_eof
; The seek failed -- close the already-open handle before returning.
mov bx, file_handle
mov ah, 3Eh ; AH=3Eh closes the file handle.
int 21h
mov ax, 1
ret
@@at_eof:
or dx, dx
jz @@size_fits_word
; The high word is non-zero: the file exceeds the supported 65535-byte length.
mov bx, file_handle
mov ah, 3Eh
int 21h
mov ax, 1
ret
@@size_fits_word:
mov si, ax ; Keep the byte count while the file pointer is repositioned.
; AX=4200h seeks to absolute offset zero.
mov bx, file_handle
mov ax, 4200h
xor cx, cx
xor dx, dx
int 21h ; DOS returns the new position in DX:AX; CF is status.
jnc @@at_file_start
; Rewinding failed
mov bx, file_handle
mov ah, 3Eh
int 21h
mov ax, 1
ret
@@at_file_start:
; DOS allocates in 16-byte paragraphs.
; Round the file size up to the required paragraph count.
; Keep one paragraph for an empty file, which input validation rejects.
mov ax, si
mov cl, 4
shr ax, cl
test si, 000Fh
jz @@paragraph_count_ready
inc ax
@@paragraph_count_ready:
or ax, ax
jnz @@paragraph_count_nonzero
inc ax
@@paragraph_count_nonzero:
mov bx, ax
mov ah, 48h ; AH=48h allocates the requested buffer paragraphs.
int 21h ; AX=segment on success; CF set if allocation fails.
jnc @@buffer_allocated
; Allocation failed after the file was opened
mov bx, file_handle
mov ah, 3Eh
int 21h
mov ax, 1
ret
@@buffer_allocated:
mov di, ax
; AH=3Fh reads CX bytes from handle BX into DS:DX.
; AX is the count actually read.
; A CF error or short read fails this read.
mov bx, file_handle
mov cx, si
xor dx, dx
mov ds, di
mov ah, 3Fh
int 21h
jc @@read_failed
cmp ax, si
je @@read_complete
@@read_failed:
mov bx, file_handle
mov ah, 3Eh ; Close the file after a read error or short read.
int 21h
mov ax, di
mov es, ax
mov ah, 49h ; Free the buffer that cannot be returned to the caller.
int 21h
mov ax, 1
ret
@@read_complete:
; Publish segment/size only after close also succeeds,
; keeping the caller's output slots zero on every failed read path.
mov bx, file_handle
mov ah, 3Eh
int 21h
jnc @@file_closed
; Close failed
mov ax, di
mov es, ax
mov ah, 49h
int 21h
mov ax, 1
ret
@@file_closed:
; Publish results through the caller-supplied pointers only after every I/O step succeeded.
mov ax, out_buffer_seg
mov es, ax
mov bx, out_buffer_off
mov word ptr es:[bx], di
mov ax, out_size_seg
mov es, ax
mov bx, out_size_off
mov word ptr es:[bx], si
xor ax, ax
ret
read_file ENDP
; Print a NUL-terminated string followed by CRLF.
; Input:
; string segment/offset on the stack.
; Output:
; none
puts PROC USES ax dx si ds, string_seg:WORD, string_off:WORD
mov ds, string_seg
mov si, string_off
@@print_char:
mov dl, byte ptr ds:[si]
or dl, dl
jz @@print_newline
mov ah, 02h ; AH=02h writes the character held in DL.
int 21h
inc si
jmp @@print_char
@@print_newline:
mov ax, @data
mov ds, ax
mov ah, 09h
mov dx, OFFSET output_newline
int 21h
ret
puts ENDP
; Compare two NUL-terminated strings byte by byte.
; Input:
; The (2x) segment and offset for each string are stack arguments.
; Output:
; AX=0 if equal, AX=1 if different.
strcmp PROC USES si di ds es, first_seg:WORD, first_off:WORD, second_seg:WORD, second_off:WORD
mov ds, first_seg
mov si, first_off
mov es, second_seg
mov di, second_off
@@compare:
mov al, byte ptr ds:[si]
cmp al, byte ptr es:[di]
jne @@different
test al, al
jz @@equal
inc si
inc di
jmp @@compare
@@different:
mov ax, 1
ret
@@equal:
xor ax, ax
ret
strcmp ENDP
; Free every argument string allocated by parse_arguments and clear its argv entries/count.
; Input:
; argc/argv globals.
; Output:
; None. Global argc/argv side-effect.
free_arguments PROC USES ax bx cx
push es
xor cx, cx
mov cl, byte ptr argc
jcxz @@free_done ; no arguments => done
@@free_arg:
mov bx, cx
dec bx
shl bx, 1 ; one index = one word = 2 bytes => idx << 1
; ES = argv[index] (allocation segment)
mov es, word ptr argv[bx]
mov word ptr argv[bx], 0
; Free the allocation.
mov ah, 49h ; AH=49h frees the block identified by ES.
int 21h
loop @@free_arg
@@free_done:
pop es
mov byte ptr argc, 0
ret
free_arguments ENDP
; Classify whitespace
; Input:
; AL = character
; Output:
; CF=1 if whitespace, CF=0 otherwise
; !!! This is DOS convention, not C.
_is_whitespace PROC
cmp al, 32 ; Space
je @@whitespace
cmp al, 9 ; Horizontal tab
je @@whitespace
cmp al, 10 ; Line feed
je @@whitespace
cmp al, 13 ; Carriage return
je @@whitespace
cmp al, 12 ; Form feed
je @@whitespace
cmp al, 11 ; Vertical tab
je @@whitespace
; Not whitespace!
clc
ret
@@whitespace:
stc
ret
_is_whitespace ENDP
; Locate the non-whitespace token without changing the input buffer.
; Input:
; - Buffer segment/offset and byte length
; - Two pointers receive token start and length.
; Output:
; AX=0 on success, AX=1 for empty/whitespace-only input.
trim_whitespace PROC USES bx si di ds es, buffer_seg:WORD, buffer_off:WORD, input_len:WORD, out_start_off:WORD, out_start_seg:WORD, out_len_off:WORD, out_len_seg:WORD
mov ds, buffer_seg
mov bx, buffer_off
mov cx, input_len
xor si, si
@@leading_loop:
cmp si, cx
jae @@empty
mov al, byte ptr ds:[bx+si]
call _is_whitespace
jc @@skip_leading
jmp @@leading_done
@@skip_leading:
inc si
jmp @@leading_loop
@@leading_done:
; Start DI at input_len, an exclusive end.
; Decrement before each read.
; The same exclusive-end convention makes length = end - start straightforward.
mov di, cx
@@trailing_loop:
cmp di, si
jbe @@empty
dec di
mov al, byte ptr ds:[bx+di]
call _is_whitespace
jc @@trailing_loop
; DI currently points at the last non-whitespace byte.
; Increment it to make the end exclusive, then subtract the start:
; token_length = exclusive_end - token_start.
inc di
sub di, si
mov es, out_start_seg
mov bx, out_start_off
mov word ptr es:[bx], si
mov es, out_len_seg
mov bx, out_len_off
mov word ptr es:[bx], di
xor ax, ax
ret
@@empty:
; Reaching the end from either direction means the file contains only whitespace (or nothing).
mov ax, 1
ret
trim_whitespace ENDP
; Validate each token byte and compact the digits at buffer offset zero.
; Input:
; - Buffer segment/offset
; - Token start index and token length.
; Output:
; AX=number of digits on success, AX=0 for empty or invalid input.
compact_decimal PROC USES bx cx dx si di ds, buffer_seg:WORD, buffer_off:WORD, start_idx:WORD, token_len:WORD
; Validate every token byte as ASCII '0'..'9' while copying it to offset 0.
; Since destination index DI never exceeds source index SI, this in-place compaction
; cannot overwrite unread bytes.
; AX is the number of copied digits; zero signals invalid/empty input.
mov ds, buffer_seg
mov bx, buffer_off
mov si, start_idx
mov cx, token_len
or cx, cx
jnz @@copy_next
xor ax, ax
ret
@@copy_next:
xor di, di
@@copy_digit:
; Reject any sign, internal whitespace, decimal point, or other non-digit at the first occurrence.
mov al, byte ptr ds:[bx+si]
cmp al, '0'
jb @@invalid
cmp al, '9'
ja @@invalid
mov byte ptr ds:[bx+di], al
inc si
inc di
loop @@copy_digit
; Return the digit count; the caller tracks the buffer by length.
mov ax, di
ret
@@invalid:
xor ax, ax
ret
compact_decimal ENDP
; Remove redundant leading zeroes while preserving one digit for numeric zero.
; Input:
; - buffer segment/offset
; - digit length
; Output:
; AX=canonical length, or zero for empty input.
decimal_trim PROC USES bx cx dx si di ds, buffer_seg:WORD, buffer_off:WORD, input_len:WORD
mov ds, buffer_seg
mov bx, buffer_off
mov cx, input_len
or cx, cx
jnz @@length_valid
xor ax, ax
ret
@@length_valid:
xor si, si
; Leave the final digit untouched even when it is zero.
mov di, cx
dec di
@@find_leading_zeroes:
cmp si, di
jae @@copy_start
cmp byte ptr ds:[bx+si], '0'
jne @@copy_start
inc si
jmp @@find_leading_zeroes
@@copy_start:
; If SI=0 there were no leading zeroes to remove.
; Otherwise copy the significant suffix left.
or si, si
jz @@return_length
xor di, di
@@copy_significant_digits:
cmp si, cx
jae @@copy_done
mov al, byte ptr ds:[bx+si]
mov byte ptr ds:[bx+di], al
inc si
inc di
jmp @@copy_significant_digits
@@copy_done:
mov cx, di
@@return_length:
mov ax, cx ; Return normalised length, zero only for invalid empty input.
ret
decimal_trim ENDP
; Determine whether the canonical decimal value is positive or zero.
; Input:
; - Buffer segment/offset
; - Input length after digit validation and leading-zero removal.
; Output:
; AX=0 for a positive value, AX=1 for zero or empty input.
decimal_is_positive PROC USES bx ds, buffer_seg:WORD, buffer_off:WORD, input_len:WORD
mov ds, buffer_seg
mov bx, buffer_off
mov ax, input_len
; A zero length is invalid
or ax, ax
jz @@invalid
; A one-digit value is invalid (zero) only when that digit is ASCII "0"
cmp ax, 1
jne @@positive
cmp byte ptr ds:[bx], '0'
je @@invalid
@@positive:
xor ax, ax
ret
@@invalid:
mov ax, 1
ret
decimal_is_positive ENDP
; Normalise a decimal token and reject invalid or zero values.
; Input:
; - Buffer segment/offset
; - Input length.
; Output:
; AX=canonical digit count on success, AX=0 for empty, malformed, or zero input.
clean_number PROC USES bx ds, buffer_seg:WORD, buffer_off:WORD, input_len:WORD
LOCAL token_start:WORD, token_len:WORD, digit_len:WORD
; Normalisation pipeline:
; - trim outer whitespace
; - validate/copy digits
; - remove leading zeroes;
; - reject zero.
push ss ; out_len_seg
lea ax, token_len
push ax ; out_len_off
push ss ; out_start_seg
lea ax, token_start
push ax ; out_start_off
push word ptr input_len
push word ptr buffer_off
push word ptr buffer_seg
call trim_whitespace
add sp, 14 ; Clean up arguments
or ax, ax
jnz @@invalid
; Validate the token and compact its digits at the start of the buffer.
push word ptr token_len
push word ptr token_start
push word ptr buffer_off
push word ptr buffer_seg
call compact_decimal
add sp, 8
mov digit_len, ax
or ax, ax
jz @@invalid
; Remove redundant leading zeroes
push word ptr digit_len
push word ptr buffer_off
push word ptr buffer_seg
call decimal_trim
add sp, 6
mov digit_len, ax
or ax, ax
jz @@invalid
; Reject the numeric value zero.
push word ptr digit_len
push word ptr buffer_off
push word ptr buffer_seg
call decimal_is_positive
add sp, 6
or ax, ax
jnz @@invalid
mov ax, digit_len
ret
@@invalid:
xor ax, ax
ret
clean_number ENDP
; Compare two canonical decimal strings without binary conversion.
; Input:
; - Each buffer segment/offset and digit length.
; Output:
; AX=0 if A<B, AX=1 if A=B, AX=2 if A>B.
decimal_compare PROC USES bx si di ds es, a_seg:WORD, a_off:WORD, a_len:WORD, b_seg:WORD, b_off:WORD, b_len:WORD
LOCAL saved_a_len:WORD
mov ds, a_seg
mov dx, a_off
mov es, b_seg
mov di, b_off
mov ax, a_len
mov word ptr saved_a_len, ax
mov cx, b_len
; Compare lengths
cmp ax, cx
jb @@less
ja @@greater
xor si, si
@@compare_digits:
cmp si, word ptr saved_a_len
jae @@equal
mov bx, dx
mov al, byte ptr ds:[bx+si] ; AL = digit from A
mov bx, di
cmp al, byte ptr es:[bx+si] ; Compare A's digit with B's digit
jb @@less ; A's digit < B's digit
ja @@greater ; A's digit > B's digit
inc si
jmp @@compare_digits
@@less:
xor ax, ax
ret
@@equal:
mov ax, 1
ret
@@greater:
mov ax, 2
ret
decimal_compare ENDP
; Subtract B from A in place, assuming A>=B.
; Input:
; - A and B buffer segment/offset and digit lengths.
; Output:
; AX=normalised result length; A contains the result.
decimal_subtract PROC USES bx cx dx si di ds es, a_seg:WORD, a_off:WORD, a_len:WORD, b_seg:WORD, b_off:WORD, b_len:WORD
LOCAL a_base:WORD, b_base:WORD, original_a_len:WORD, borrow:BYTE
mov ds, a_seg
mov es, b_seg
; Keep the buffer offsets and A's original length. A's length is needed
; later because subtraction overwrites its digits but does not resize the buffer.
mov ax, a_off
mov a_base, ax
mov ax, b_off
mov b_base, ax
mov ax, a_len
mov original_a_len, ax
; Subtraction starts with the rightmost digits because each digit's result
; may affect the digit immediately to its left.
; SI and DI track the current positions in A and B, respectively.
mov si, a_len
mov di, b_len
mov borrow, 0
@@subtract_both:
; Process matching decimal positions while B still has digits.
; A is at least as large as B, so A has enough digits for this loop.
or di, di
jz @@subtract_a_remaining
dec si
dec di
; Convert A's current ASCII digit into its numeric value.
mov bx, a_base
mov al, byte ptr ds:[bx+si]
sub al, '0'
; If the previous position borrowed from this one, reduce A's digit by one.
; Then subtract B's digit at the same decimal position.
sub al, borrow
mov bx, b_base
mov ah, byte ptr es:[bx+di]
sub ah, '0'
sub al, ah
; A digit cannot be negative in the final answer.
; If the subtraction went below zero, borrow ten from the next position:
; adding ten gives this position its correct digit, and borrow=1 records
; that the position to the left must give up one.
cmp al, 0
jge @@store_both
add al, 10
mov borrow, 1
jmp @@write_both
@@store_both:
; This digit did not need to borrow :)
mov borrow, 0
@@write_both:
; Write the calculated digit back into A as an ASCII character.
; B remains unchanged.
add al, '0'
mov bx, a_base
mov byte ptr ds:[bx+si], al
jmp @@subtract_both
@@subtract_a_remaining:
or si, si
jz @@normalise ; no digits => go to normalisation
dec si
; B's digits have all been processed. Continue through A's remaining
; digits only if a borrow from the previous position still needs resolving.
mov bx, a_base
mov al, byte ptr ds:[bx+si]
sub al, '0'
sub al, borrow
; If this digit is too small to cover the borrow, add ten and
; carry the borrow to the next digit to the left.
cmp al, 0
jge @@store_a_remaining
add al, 10
mov borrow, 1
jmp @@write_a_remaining
@@store_a_remaining:
; The incoming borrow has been resolved, so clear it.
mov borrow, 0
@@write_a_remaining:
add al, '0'
mov bx, a_base
mov byte ptr ds:[bx+si], al
jmp @@subtract_a_remaining
@@normalise:
; Remove leading zeroes left by the subtraction so the result has
; a canonical representation. decimal_trim returns its length in AX.
push word ptr original_a_len
push word ptr a_base
push word ptr a_seg
call decimal_trim
add sp, 6
ret
decimal_subtract ENDP
; Process one digit of the dividend using decimal long division.
; Append the digit to the current remainder, then subtract B until the
; remainder is smaller than B.
;
; In essence runs a step of R = 10R + d, then repeatedly (R -= B) until R < B
;
; Input:
; - A segment:offset and next digit index (next_idx).
; A is also used as the remainder workspace, starting at a_off.
; - Address next_idx_out_seg:next_idx_out_off, where the updated index is written.
; - Current remainder length (remainder_len).
; - B segment:offset and digit length (b_len).
; - The current remainder must be smaller than B before this step.
;
; Output:
; AX=remainder length on success, AX=0 if subtraction fails.
; On success, the index of the next unread dividend digit is written
; to next_idx_out_seg:next_idx_out_off.
big_mod_step PROC USES bx cx dx si di ds es, a_seg:WORD, a_off:WORD, next_idx:WORD, next_idx_out_off:WORD, next_idx_out_seg:WORD, remainder_len:WORD, b_seg:WORD, b_off:WORD, b_len:WORD
LOCAL remainder_length_local:WORD, consumed_digit:BYTE
; Set up the buffer segments, digit index, and remainder length.
mov ds, a_seg
mov es, b_seg
mov si, next_idx
mov ax, remainder_len
mov remainder_length_local, ax
; Save the next dividend digit before modifying A's prefix, which stores
; the remainder. Advance SI to the next unread digit.
mov bx, a_off
mov al, byte ptr ds:[bx+si]
mov consumed_digit, al
inc si
; Handle the special cases before appending the digit:
; the remainder may be empty, or it may be exactly "0".
cmp remainder_length_local, 0
je @@first_remainder_digit
; A multi-digit remainder can accept the new digit directly.
; A one-digit remainder needs checking in case it is "0".
cmp remainder_length_local, 1
jne @@append_remainder_digit
; If the remainder is "0", replace that digit instead of appending,
; which would create a leading zero such as "03".
mov bx, a_off
cmp byte ptr ds:[bx], '0'
jne @@append_remainder_digit
mov al, consumed_digit
mov byte ptr ds:[bx], al
jmp @@compare_remainder
@@first_remainder_digit:
; An empty remainder becomes the digit just consumed.
mov bx, a_off
mov al, consumed_digit
mov byte ptr ds:[bx], al
mov remainder_length_local, 1
jmp @@compare_remainder
@@append_remainder_digit:
; Append the digit immediately after the current remainder.
mov bx, remainder_length_local
mov di, a_off
mov al, consumed_digit
mov byte ptr ds:[bx+di], al
inc remainder_length_local
@@compare_remainder:
push word ptr b_len
push word ptr b_off
push word ptr b_seg
push word ptr remainder_length_local
push word ptr a_off
push word ptr a_seg
call decimal_compare
add sp, 12
; If R < B (AX = 0), this step is complete.
or ax, ax
jz @@step_done
; Subtract B from R in place.
; AX returns the new remainder length.
; decimal_subtract does not write a NUL terminator, so unread digits
; elsewhere in A's buffer remain intact.
push word ptr b_len
push word ptr b_off
push word ptr b_seg
push word ptr remainder_length_local
push word ptr a_off
push word ptr a_seg
call decimal_subtract
add sp, 12
; A zero length indicates that subtraction failed.
or ax, ax
jz @@step_error
mov remainder_length_local, ax
jmp @@compare_remainder
@@step_done:
; Return the next unread digit index and the final remainder length.
mov es, next_idx_out_seg
mov bx, next_idx_out_off
mov word ptr es:[bx], si
mov ax, remainder_length_local
ret
@@step_error:
; Report failure to the caller.
xor ax, ax
ret
big_mod_step ENDP
; Compute A mod B using decimal long division.
; For each digit, big_mod_step is ran.
; A's buffer is reused to store the remainder.
;
; Input:
; - A segment:offset and digit length (a_len).
; - B segment:offset and digit length (b_len).
; - Both operands must be canonical decimal strings; B must be positive.
;
; Output:
; AX=canonical remainder length on success; A's buffer contains the remainder.
; AX=0 if an operand is zero or empty, or a long-division step fails.
; B remains unchanged.
big_mod PROC USES bx cx dx si di es ds, a_seg:WORD, a_off:WORD, a_len:WORD, b_seg:WORD, b_off:WORD, b_len:WORD
LOCAL current_index:WORD, current_remainder_len:WORD
; Decimal long division: consume A from left to right, maintaining R < B.
; For each digit d, form R := R*10+d and subtract B until R < B.
; A is reused to store the remainder, overwriting consumed digits.
mov ds, a_seg
mov es, b_seg
mov current_index, 0
mov current_remainder_len, 0
; Validate A before reusing its buffer as workspace.
push word ptr a_len
push word ptr a_off
push word ptr a_seg
call decimal_is_positive
add sp, 6
or ax, ax
jz @@dividend_valid
; A is invalid
xor ax, ax
ret
@@dividend_valid:
; Validate B
push word ptr b_len
push word ptr b_off
push word ptr b_seg
call decimal_is_positive
add sp, 6
or ax, ax
jz @@divisor_valid
; B is invalid
xor ax, ax
ret
@@divisor_valid:
@@next_digit:
; If every digit of A has been consumed, return the final remainder length.
mov bx, current_index
cmp bx, a_len
jb @@consume_digit
mov ax, current_remainder_len
ret
@@consume_digit:
; Process one digit. big_mod_step updates current_index through a pointer
; and returns the new remainder length in AX.
push word ptr b_len
push word ptr b_off
push word ptr b_seg
push word ptr current_remainder_len
push ss
lea ax, current_index
push ax
push word ptr current_index
push word ptr a_off
push word ptr a_seg
call big_mod_step
add sp, 18
; A zero length indicates that the step failed.
or ax, ax
jnz @@step_succeeded
xor ax, ax
ret
@@step_succeeded:
; Carry the updated remainder length into the next step.
mov current_remainder_len, ax
jmp @@next_digit
big_mod ENDP
; Report invalid number error
; Input:
; None.
; Output:
; Prints the invalid-number diagnostic.
report_invalid_number PROC USES ax dx ds
mov ax, @data
mov ds, ax
mov ah, 09h
mov dx, OFFSET error_invalid_number
int 21h
ret
report_invalid_number ENDP
; Report read error
; Input:
; - Filename segment and offset.
; Output:
; Prints the read-error header followed by the filename.
report_read_error PROC USES ax dx ds, filename_seg:WORD, filename_off:WORD
mov ax, @data
mov ds, ax
mov ah, 09h
mov dx, OFFSET error_failed_read_head
int 21h
push word ptr filename_off
push word ptr filename_seg
call puts
add sp, 4
ret
report_read_error ENDP
; Report write error
; Input:
; - Filename segment and offset.
; Output:
; - Prints the write-error header followed by the filename.
report_write_error PROC USES ax dx ds, filename_seg:WORD, filename_off:WORD
mov ax, @data
mov ds, ax
mov ah, 09h
mov dx, OFFSET error_failed_write_head
int 21h
push word ptr filename_off
push word ptr filename_seg
call puts
add sp, 4
ret
report_write_error ENDP
; Create/truncate the output file, write the GCD digits and CRLF, and close the handle.
; Input:
; - output filename segment/offset
; - result buffer segment/offset
; - result length
; Output:
; AX=0 on success, AX=1 after S.E. reporting an output error with the filename.
write_result PROC USES bx cx dx si di ds es, filename_seg:WORD, filename_off:WORD, buffer_seg:WORD, buffer_off:WORD, buffer_len:WORD
LOCAL file_handle:WORD
; AH=3Ch creates the output or truncates an existing file. DS:DX is its path,
; CX=0 requests normal attributes; AX receives the handle and CF indicates failure.
; More: https://stanislavs.org/helppc/file_attributes.html
mov ds, filename_seg
mov dx, filename_off
xor cx, cx
mov ah, 3Ch
int 21h
jnc @@output_opened
; Opening failed
push word ptr filename_off
push word ptr filename_seg
call report_write_error
add sp, 4
mov ax, 1
ret
@@output_opened:
mov file_handle, ax
mov ds, buffer_seg
mov dx, buffer_off
mov cx, buffer_len
mov bx, file_handle
mov ah, 40h ; write(fh=bx, buf=ds:dx, count=cx)
int 21h
jc @@digits_failed
cmp ax, buffer_len
je @@digits_written
@@digits_failed:
mov bx, file_handle
mov ah, 3Eh ; close(bx)
int 21h
; Failed to write (all) digits
push word ptr filename_off
push word ptr filename_seg
call report_write_error
add sp, 4
mov ax, 1
ret
@@digits_written:
; output_newline lives in the EXE's data segment, not the input buffer segment.
; Restore DS before the second AH=40h call.
mov ax, @data
mov ds, ax
mov bx, file_handle
mov cx, output_newline_bytelen
mov dx, OFFSET output_newline
mov ah, 40h
int 21h
jc @@newline_failed
cmp ax, 2
je @@newline_written
@@newline_failed:
; Close after a failed/short newline write.
mov bx, file_handle
mov ah, 3Eh
int 21h
push word ptr filename_off
push word ptr filename_seg
call report_write_error
add sp, 4
mov ax, 1
ret
@@newline_written:
mov bx, file_handle
mov ah, 3Eh
int 21h
jnc @@output_closed
push word ptr filename_off
push word ptr filename_seg
call report_write_error
add sp, 4
mov ax, 1
ret
@@output_closed:
xor ax, ax
ret
write_result ENDP
; Read and normalise one input file.
; Input:
; - filename segment/offset
; - caller's buffer-segment and length words.
; Output:
; AX=0 on success; AX=1 after reporting a read or invalid-number error.
load_input PROC USES bx dx es, filename_seg:WORD, filename_off:WORD, out_buffer_off:WORD, out_buffer_seg:WORD, out_length_off:WORD, out_length_seg:WORD
; Zero the output slots so cleanup can safely handle a failed read.
mov es, out_buffer_seg
mov bx, out_buffer_off
mov word ptr es:[bx], 0
mov es, out_length_seg
mov bx, out_length_off
mov word ptr es:[bx], 0
; Read whole file
push word ptr out_length_seg
push word ptr out_length_off
push word ptr out_buffer_seg
push word ptr out_buffer_off
push word ptr filename_off
push word ptr filename_seg
call read_file
add sp, 12
or ax, ax
jz @@file_read
; read_file failed
push word ptr filename_off
push word ptr filename_seg
call report_read_error
add sp, 4
mov ax, 1
ret
@@file_read:
; Read the file length from the caller's output variable.
mov es, out_length_seg
mov bx, out_length_off
mov cx, word ptr es:[bx]
; Read the buffer segment from the caller's output variable.
mov es, out_buffer_seg
mov bx, out_buffer_off
mov dx, word ptr es:[bx]
; Clean the number
push cx
push 0
push dx
call clean_number
add sp, 6
or ax, ax
jnz @@number_valid
; Invalid number -- couldn't clean the number.
call report_invalid_number
mov ax, 1
ret
@@number_valid:
; Publish the canonical digit count in the same output word that held the file byte count.
mov es, out_length_seg
mov bx, out_length_off
mov word ptr es:[bx], ax
xor ax, ax
ret
load_input ENDP
; Compute the GCD using Euclid's algorithm.
; Input:
; - a_seg and a_len: Segment and digit length of A.
; - b_seg and b_len: Segment and digit length of B.
; Both decimal strings start at offset 0 in their respective segments.
; - out_result_seg_seg and out_result_seg_off: Segment and offset of the WORD
; where the result buffer's segment will be written.
; - out_result_len_seg and out_result_len_off: Segment and offset of the WORD
; where the result's digit length will be written.
; Output:
; - AX=0 on success; AX=1 if calculating the remainder fails.
; - On success, writes the GCD buffer's segment and digit length to the output WORDs.
; - The input buffers may be modified; the result points to one of these buffers.
compute_gcd PROC USES bx cx dx si di ds es, a_seg:WORD, a_len:WORD, b_seg:WORD, b_len:WORD, out_result_seg_off:WORD, out_result_seg_seg:WORD, out_result_len_off:WORD, out_result_len_seg:WORD
@@euclid:
; If B is "0", A is the GCD and the algorithm is finished.
cmp word ptr b_len, 1
jne @@calculate_remainder
mov ax, b_seg
mov es, ax
cmp byte ptr es:[0], '0'
je @@gcd_done
@@calculate_remainder:
; Calculate A mod B, storing the remainder in A's buffer.
push word ptr b_len
push 0
push word ptr b_seg
push word ptr a_len
push 0
push word ptr a_seg
call big_mod
add sp, 12
or ax, ax
jnz @@remainder_ready
; big_mod failed :(
mov ax, 1
ret
@@remainder_ready:
; Save the remainder length while updating the working descriptors.
mov si, ax
; Update the pair from (A, B) to (B, A mod B).
; Swap the segments and lengths so each buffer keeps its matching length.
mov ax, a_seg
xchg ax, b_seg
mov a_seg, ax
mov ax, a_len
xchg ax, b_len
mov a_len, ax
; The remainder is stored in A's old buffer.
mov b_len, si
jmp @@euclid
@@gcd_done:
; Store the GCD buffer's segment in the caller's output WORD.
mov es, out_result_seg_seg
mov bx, out_result_seg_off
mov dx, a_seg
mov word ptr es:[bx], dx
; Store the GCD's digit length in the caller's output WORD.
mov es, out_result_len_seg
mov bx, out_result_len_off
mov dx, a_len
mov word ptr es:[bx], dx
xor ax, ax
ret
compute_gcd ENDP
; Parse the command tail in the PSP and store each argument in a separate allocation.
; Input:
; - Segment of the PSP containing the command tail.
; Output:
; - AX=0 on success; AX=1 if argument allocation fails.
; - argc = number of parsed arguments.
; - argv[0..argc-1] = segments containing the NUL-terminated argument strings.
parse_arguments PROC USES bx cx dx si di es, psp_seg:WORD
LOCAL tail_len:BYTE, arg_start:BYTE, arg_end:BYTE, arg_len:BYTE
; Read the command-tail length from PSP:80h.
mov es, psp_seg
mov al, es:[80h]
mov tail_len, al
mov arg_start, 0
mov arg_end, 0
mov arg_len, 0
mov argc, 0
@@fill_argv:
; Restore ES to the PSP before reading the next argument.
; (ES will point to the allocated argument buffer during copying)
mov es, psp_seg
; Skip whitespace before the next argument.
@@skip_whitespace:
xor bx, bx
; If arg_start reaches tail_len, there are no characters left to parse.
mov bl, arg_start
cmp bl, tail_len
jb @@fill_argv_continue
jmp @@fill_argv_done
@@fill_argv_continue:
; Read the current character from the PSP command tail.
; Add 81h because the first character is at PSP:81h, not PSP:0.
add bx, 81h
mov al, byte ptr es:[bx]
call _is_whitespace
; _is_whitespace sets CF if the character is whitespace.
jc @@skip_whitespace_inc
jmp @@find_argument
@@skip_whitespace_inc:
; Advance past this whitespace character and check the next one.
inc arg_start
jmp @@skip_whitespace
@@find_argument:
; Start searching at the first non-whitespace character.
mov al, arg_start
mov arg_end, al
; Find the exclusive end of the argument.
@@find_end:
xor bx, bx
; Stop when arg_end reaches the end of the command tail.
mov bl, arg_end
cmp bl, tail_len
jae @@argument_end
; Read the current character and check whether it is whitespace.
add bx, 81h
mov al, byte ptr es:[bx]
call _is_whitespace
jc @@argument_end
; This character belongs to the argument.
; Advance to the next character.
inc arg_end
jmp @@find_end
@@argument_end:
; arg_end points just past the last argument character.
; Calculate the argument length: end - start.
xor ax, ax
mov al, arg_end
xor bx, bx
mov bl, arg_start
sub ax, bx
mov arg_len, al
; Add one byte for the NUL terminator.
; paragraphs = ceil((argument length + 1) / 16).
inc ax
mov bx, ax ; Preserve the byte count so TEST can check its remainder
mov cl, 4
shr ax, cl
test bx, 000Fh ; remainder => +1 paragraph
jz @@paragraph_count_ready
inc ax
@@paragraph_count_ready:
; Allocate the required number of paragraphs.
; On success, AX contains the segment of the allocated block.
mov bx, ax
mov ah, 48h
int 21h
jnc @@argument_allocated
; Allocation failed.
mov dx, OFFSET error_mem_oom
mov ah, 09h
int 21h
call free_arguments
mov ax, 1
ret
@@argument_allocated:
; Store the allocated buffer's segment in argv[argc].
; Each argv entry is a WORD, so multiply argc by two for its offset.
xor bx, bx
mov bl, argc
shl bx, 1
mov word ptr argv[bx], ax
; ES now points to the allocated argument buffer.
mov es, ax
; Count this argument now that its buffer has been allocated.
inc argc
; Set CX to the number of characters to copy.
xor cx, cx
mov cl, arg_len
; Temporarily set DS to the PSP so DS:SI reads the command tail.
push ds
mov ax, psp_seg
mov ds, ax
; Set SI to the first character of this argument in the PSP.
mov si, 81h
xor ax, ax
mov al, arg_start
add si, ax
; Set DI to offset zero in the allocated destination buffer.
xor di, di
; CLD clears the direction flag so string instructions advance
; SI and DI after each byte instead of moving backwards.
cld
; REP MOVSB copies CX bytes from DS:SI to ES:DI.
; Each MOVSB copies one byte and advances SI and DI.
; REP repeats MOVSB until CX reaches zero.
rep movsb
; DI now points immediately after the copied characters.
; Append a NUL byte to make it ASCIIZ.
mov byte ptr es:[di], 0
; Restore DS to the program's data segment.
pop ds
; Continue at the end of this argument.
mov al, arg_end
mov arg_start, al
jmp @@fill_argv
@@fill_argv_done:
; All command-tail characters have been processed.
xor ax, ax
ret
parse_arguments ENDP
; Print the built-in usage.
; Input:
; None.
; Output:
; AX=0, with output S.E.
print_help PROC USES ax dx
mov ah, 09h
mov dx, OFFSET help
int 21h
xor ax, ax
ret
print_help ENDP
; Coordinate input loading, GCD calculation, output, and cleanup.
; Input:
; argv+0=input 1, argv+2=input 2, argv+4=output.
; Output:
; AX=0 on success, AX=1 on failure.
find_gcd PROC USES bx cx dx si di es
LOCAL a_segment:WORD, a_length:WORD, b_segment:WORD, b_length:WORD
LOCAL result_segment:WORD, result_length:WORD
mov a_segment, 0
mov a_length, 0
mov b_segment, 0
mov b_length, 0
mov result_segment, 0
mov result_length, 0
; Load the first input into its own DOS block.
push ss
lea ax, a_length
push ax
push ss
lea ax, a_segment
push ax
push 0
push word ptr argv[0]
call load_input
add sp, 12
or ax, ax
jz @@first_input_loaded
mov ax, 1
jmp @@cleanup
@@first_input_loaded:
; Load the second input into a separate DOS block.
push ss
lea ax, b_length
push ax
push ss
lea ax, b_segment
push ax
push 0
push word ptr argv[2]
call load_input
add sp, 12
or ax, ax
jz @@second_input_loaded
mov ax, 1
jmp @@cleanup
@@second_input_loaded:
; Compute the GCD.
push ss
lea ax, result_length
push ax
push ss
lea ax, result_segment
push ax
push word ptr b_length
push word ptr b_segment
push word ptr a_length
push word ptr a_segment
call compute_gcd
add sp, 16
or ax, ax
jz @@gcd_computed
mov ax, 1
jmp @@cleanup
@@gcd_computed:
; Write the GCD to the requested output file.
push word ptr result_length
push 0
push word ptr result_segment
push 0
push word ptr argv[4]
call write_result
add sp, 10
@@cleanup:
; Preserve the return status.
push ax
; Free the first input block if it was allocated.
mov ax, a_segment
or ax, ax
jz @@free_second_input
mov es, ax
mov ah, 49h
int 21h
@@free_second_input:
; Free the second input block if it was allocated.
mov ax, b_segment
or ax, ax
jz @@return_status
mov es, ax
mov ah, 49h
int 21h
@@return_status:
pop ax
ret
find_gcd ENDP
; Dispatch the command line using stack-based C calls.
; Input:
; - argc/argv populated by parse_arguments.
; Output:
; AX=0 on success, AX=1 on invalid arguments or computation failure.
execute_args PROC USES dx si di es
; Accept exactly one special argument (/?) or three paths (two inputs and one output)
cmp byte ptr argc, 1
jne @@check_gcd
; strcmp(argv[0], help_arg)
push OFFSET help_arg
mov ax, @data
push ax
push 0
push word ptr argv[0]
call strcmp
add sp, 8
or ax, ax
jz @@show_help
@@check_gcd:
cmp byte ptr argc, 3
je @@find_gcd
jmp @@error
@@show_help:
call print_help
ret
@@find_gcd:
call find_gcd
ret
@@error:
mov ah, 09h
mov dx, OFFSET error_cli_args
int 21h
mov ax, 1
ret
execute_args ENDP
; ---- entry point ----
main PROC
; At EXE entry DS identifies the PSP (Program Segment Prefix)
; which is the base segment of this process's DOS-owned block.
; DOS measures memory in 16-byte paragraphs. SS-PSP gives the paragraphs before
; the stack segment:
mov ax, ss
mov dx, ds
sub ax, dx
; Then ceil(SP/16) covers the stack up to its current top:
mov bx, sp
add bx, 15
mov cl, 4
shr bx, cl
; Their sum is the smallest block that still contains the PSP, loaded program, and stack.
add bx, ax
; BX is the sum now.
; Resize the minimum memory block (this is because the EXE may own almost all of the
; memory so it's better to resize than face weird issues later)
push ds
pop es ; Indirectly copy DS to ES without overwritting any registers
mov ah, 4Ah ; AH=4Ah: resize ES block to BX paragraphs.
int 21h ; CF reports failure; BX is the requested new size.
jnc @@memory_resized
; Failed to resize DOS-owned segment.
mov ax, 4C01h ; exit(1)
int 21h
; --- process terminated ---
@@memory_resized:
; The resize call is finished, so DS can now point at this EXE's data segment.
mov ax, @data
mov ds, ax
; parse_arguments(psp_seg)
push es
call parse_arguments
add sp, 2 ; remove ES from the stack
or ax, ax
jnz @@exit_error
call execute_args
or ax, ax
jnz @@exit_error
call free_arguments
mov ax, 4C00h ; exit(0)
int 21h
; --- process terminated ---
@@exit_error:
call free_arguments
mov ax, 4C01h ; exit(1)
int 21h
; --- process terminated ---
main ENDP
END main