Information wants to be free...

Kermit in x86 Assembly

This is kind of a follow up to my other project on file transfers in DOS. I have made a huge improvement by implementing the Kermit Protocol in 16-bit x86 assembly language. Instead of relying on the horrible BIOS service routines, this program interfaces directly to the 8250/16550 UART chip on the PC.

The purpose of this program is bootstrapping, so it has several limitations. It is based loosely on the "Baby Kermit" BASIC program that can be found in the official Kermit manuals. It's hard coded to run at 9600 baud with 8-N-1 parameters on the COM1 port. Both sending and receiving is performed by hogging the CPU and busy-waiting. I recommend to use this program as a means to transfer the real full-feature MS-DOS Kermit.

Apart from testing the program in both the DOSBox and Bochs emulators, I have also tried it on two real machines. On a 8MHz 8088 XT-class machine, it gets some transmission errors, but those are corrected. On a 25MHz 80486SX it runs fine without any errors.

I have uploaded the code to GitHub in case of further improvements, by me or anyone else. But here is the first version, assembled with NASM as follows: nasm kermit.asm -fbin -o kermit.com

org 0x100
bits 16
cpu 8086

COM1_BASE equ 0x3f8
COM1_THR  equ COM1_BASE + 0 ; Transmitter Holding Buffer
COM1_RBR  equ COM1_BASE + 0 ; Receiver Buffer
COM1_IER  equ COM1_BASE + 1 ; Interrupt Enable Register
COM1_FCR  equ COM1_BASE + 2 ; FIFO Control Register
COM1_IIR  equ COM1_BASE + 2 ; Interrupt Identification Register
COM1_LCR  equ COM1_BASE + 3 ; Line Control Register
COM1_LSR  equ COM1_BASE + 5 ; Line Status Register
COM1_DLL  equ COM1_BASE + 0 ; Divisor Latch Low Byte
COM1_DLH  equ COM1_BASE + 1 ; Divisor Latch High Byte

RECV_BUFFER_SIZE equ 100 ; As per Kermit documentation.
SEND_BUFFER_SIZE equ 16 ; No packets sent from this program exceed this.
PACKET_DATA_SIZE equ 94 ; Receive buffer size - 6 fields/terminator.

section .text
start:
  ; Set Baudrate on COM1 to 9600, divisor = 12:
  mov dx, COM1_LCR
  in al, dx
  or al, 0b10000000 ; Set Divisor Latch Access Bit (DLAB)
  out dx, al

  mov dx, COM1_DLL
  mov al, 0xc
  out dx, al
  
  mov dx, COM1_DLH
  mov al, 0
  out dx, al

  mov dx, COM1_LCR
  in al, dx
  and al, 0b01111111 ; Reset Divisor Latch Access Bit (DLAB)
  out dx, al

  ; Disable and clear FIFO on COM1, to put it in 8250 compatibility mode:
  mov dx, COM1_FCR
  mov al, 0b00000110 ; Clear both FIFOs.
  out dx, al

  ; Set mode on COM1 to 8 data bits, no parity and 1 stop bit:
  mov dx, COM1_LCR
  mov al, 0b00000011 ; 8-N-1
  out dx, al

  ; Enable interrupt bit on COM1:
  mov dx, COM1_IER
  in al, dx
  or al, 0b00000001 ; Enable Received Data Available Interrupt
  out dx, al

  ; Initialize sequence number:
  mov byte [send_seq_no], 0

  ; Initialize retransmit message in send buffer:
  mov byte [send_buffer],     0x01 ; 'MARK' Start marker (Ctrl-A)
  mov byte [send_buffer + 1], 35   ; 'LEN' Packet length of 3 (+ 32)
  mov byte [send_buffer + 2], 32   ; 'SEQ' Sequence number 0 (+ 32)
  mov byte [send_buffer + 3], 'N'  ; 'TYPE' Packet type 'N' meaning NAK
  mov byte [send_buffer + 4], 0x33 ; 'CHECK' Checksum 0x13 (+ 32)
  mov byte [send_buffer + 5], 0x13 ; Terminator (Carriage Return)
  mov word [send_buffer_index], 6

  ; Get Send Initialization packet, exchange parameters...

  mov dx, message_waiting
  call print_string
  call get_valid_packet

  mov byte al, [packet_type]
  cmp al, 'S' ; 'S' = Send Initiation
  je _handle_s_packet

  ; Simplified version of error message: "<?> Packet in S State"
  mov byte [packet_data], al
  mov byte [packet_data + 1], 'S'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 2
  call send_packet
  jmp _main_end

_handle_s_packet:
  ; Override local EOL marker from sender if available:
  mov byte al, [packet_data_len]
  cmp al, 4
  jb _acknowledge_s_packet
  mov byte bl, [packet_data + 4] ; 'EOL'
  sub bl, 32
  mov [eol_marker], bl

  ; Override local CTL marker from sender if available:
  cmp al, 5
  jb _acknowledge_s_packet
  mov byte bl, [packet_data + 5] ; 'QCTL'
  mov [ctl_marker], bl

_acknowledge_s_packet:
  mov byte [packet_type], 'Y' ; 'Y' = Acknowledgement (ACK)
  mov byte [packet_data],     72  ; 'MAXL'
  mov byte [packet_data + 1], 42  ; 'TIME'
  mov byte [packet_data + 2], 32  ; 'NPAD'
  mov byte [packet_data + 3], 64  ; 'PADC'
  mov byte [packet_data + 4], 45  ; 'EOL' = 0x0d (+ 32)
  mov byte [packet_data + 5], 35  ; 'QCTL' = '#'
  mov byte [packet_data + 6], 'N' ; 'QBIN' = 'N' = Will not do 8-bit quoting.
  mov byte [packet_data + 7], '1' ; 'CHKT' = '1' = Single character checksum.
  mov word [packet_data_len], 8
  call send_packet

_wait_for_file_header_packet:
  ; Get a File Header packet. If a B packet comes, we're all done:
  call get_valid_packet

  mov byte al, [packet_type]
  cmp al, 'B' ; 'B' = Break transmission
  je _handle_b_packet
  cmp al, 'F' ; 'F' = File Header
  je _handle_f_packet

  ; Simplified version of error message: "<?> Packet in F State"
  mov byte [packet_data], al
  mov byte [packet_data + 1], 'F'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 2
  call send_packet
  jmp _main_end

_handle_b_packet:
  call send_acknowledgement_packet
  jmp _main_end

_handle_f_packet:
  mov dx, message_receiving
  call print_string

  ; Dollar terminate the received filename:
  mov word di, [packet_data_len]
  mov byte [packet_data + di], '$'
  mov dx, packet_data
  call print_string

  ; Zero terminate the received filename:
  mov byte [packet_data + di], 0

  ; Call DOS to create new file and handle.
  mov ah, 0x3c
  mov cx, 0 ; Standard attributes.
  ; DX already containing pointer to packet data.
  int 0x21
  jc _handle_f_packet_error
  mov [file_handle], ax

  call send_acknowledgement_packet

_wait_for_data_packet:
  ; Get Data packets. If a Z packet comes, the file is complete:
  call get_valid_packet

  mov byte al, [packet_type]
  cmp al, 'Z' ; 'Z' = End of file
  je _handle_z_packet
  cmp al, 'D' ; 'D' = Data Packet
  je _handle_d_packet

  ; Simplified version of error message: "<?> Packet in D State"
  mov byte [packet_data], al
  mov byte [packet_data + 1], 'D'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 2
  call send_packet
  jmp _main_end

_handle_z_packet:
  ; Call DOS to close file handle.
  mov ah, 0x3e
  mov bx, [file_handle]
  int 0x21

  call send_acknowledgement_packet

  mov dx, message_ok
  call print_string

  jmp _wait_for_file_header_packet

_handle_d_packet:
  ; Call DOS to write to file.
  mov ah, 0x40
  mov word bx, [file_handle]
  mov word cx, [packet_data_len]
  mov dx, packet_data
  int 0x21
  jc _handle_d_packet_error

  call send_acknowledgement_packet

  jmp _wait_for_data_packet

_handle_f_packet_error:
  ; Send error code 'C', since new file could not be created.
  mov byte [packet_data], 'C'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 1
  call send_packet
  jmp _main_end

_handle_d_packet_error:
  ; Send error code 'W', since new file could not be written to.
  mov byte [packet_data], 'W'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 1
  call send_packet
  jmp _main_end

_main_end:
  mov dx, message_done
  call print_string

  ; Disable interrupt bit on COM1:
  mov dx, COM1_IER
  in al, dx
  and al, 0b11111110 ; Disable Received Data Available Interrupt
  out dx, al

  ; Exit to DOS.
  mov ah, 0x4c
  int 0x21

; PROCEDURE: get_valid_packet
;
; INPUT:
;   N/A
;
; OUTPUT:
;   ds:[packet_type]
;   ds:[packet_data]
;   ds:[packet_data_len]
;
get_valid_packet:
  push ax
  push bx
  push cx

  ; Try to get a valid packet with the desired sequence number.

  mov cx, 5 ; Retry maximum 5 times.
_get_valid_packet_loop:
  call recv_packet

  mov byte al, [recv_seq_no]
  mov byte bl, [send_seq_no]
  cmp al, bl
  jne _get_valid_packet_resend
  mov byte al, [packet_type]
  cmp al, 'Q' ; 'Q' = Block check error
  je _get_valid_packet_resend
  jmp _get_valid_packet_return ; Got a valid packet.

_get_valid_packet_resend:
  call com_port_send ; Contains a retransmit message in send buffer already.

  push dx
  mov dl, '%' ; Indicate retry.
  call print_character
  pop dx

  loop _get_valid_packet_loop ; Until CX = 0

  mov byte [packet_type], 'T' ; 'T' = Timeout

_get_valid_packet_return:
  pop cx
  pop bx
  pop ax
  ret

; PROCEDURE: send_acknowledgement_packet
;
; INPUT:
;   N/A
;
; OUTPUT:
;   N/A
;
send_acknowledgement_packet:
  mov byte [packet_type], 'Y' ; 'Y' = Acknowledgement (ACK)
  mov word [packet_data_len], 0
  call send_packet
  ret

; PROCEDURE: send_packet
;
; INPUT:
;   ds:[packet_type]
;   ds:[packet_data]
;   ds:[packet_data_len]
;   
; OUTPUT:
;   N/A
;
send_packet:
  push ax
  push bx
  push cx
  push di
  push si

  mov di, send_buffer
  mov byte [di], 0x01
  inc di

  mov word ax, [packet_data_len]
  add al, 35 ; 32 + 3 bytes for 'SEQ', 'TYPE' & 'CHECK'
  mov bl, al ; Checksum = LEN
  mov byte [di], al
  inc di

  mov byte al, [send_seq_no]
  add al, 32
  add bl, al ; Checksum += SEQ
  mov byte [di], al
  inc di

  mov byte al, [packet_type]
  add bl, al ; Checksum += TYPE
  mov byte [di], al
  inc di

  mov si, packet_data
  mov word cx, [packet_data_len]
  test cx, cx
  jz _send_packet_empty
_send_packet_loop:
  mov al, [si]
  mov [di], al
  add bl, al ; Checksum += DATA
  inc di
  inc si

  loop _send_packet_loop ; Until CX = 0
_send_packet_empty:

  ; Calculate checksum:
  mov cl, bl
  and cl, 192
  shr cl, 1 ; 8086 is limited to one shift at a time.
  shr cl, 1
  shr cl, 1
  shr cl, 1
  shr cl, 1
  shr cl, 1
  add cl, bl
  and cl, 63
  add cl, 32
  mov byte [di], cl
  inc di

  mov byte al, [eol_marker]
  mov byte [di], al

  mov word ax, [packet_data_len]
  add ax, 6 ; Add 'MARK', 'LEN', 'SEQ', 'TYPE' 'CHECK' and terminator.
  mov word [send_buffer_index], ax

  call com_port_send

  ; Increment packet sequence number:
  inc byte [send_seq_no]
  and byte [send_seq_no], 63 ; Always reduce to 6 bits.

  push dx
  mov dl, '.'; Indicate ACK sent.
  call print_character
  pop dx

  pop si
  pop di
  pop cx
  pop bx
  pop ax
  ret

; PROCEDURE: com_port_send
;
; INPUT:
;   ds:[send_buffer]
;   ds:[send_buffer_index]
;   
; OUTPUT:
;   N/A
;
com_port_send:
  push ax
  push cx
  push dx
  push si

  mov si, 0
  mov word cx, [send_buffer_index]
_com_port_send_byte:

  mov dx, COM1_THR
  mov byte al, [send_buffer + si]
  out dx, al

  mov dx, COM1_LSR
_com_port_send_wait:
  in al, dx
  and al, 0b00100000 ; Empty Transmit Holding Register
  test al, al
  jz _com_port_send_wait ; Busy wait...

  inc si
  loop _com_port_send_byte ; Until CX = 0

  pop si
  pop dx
  pop cx
  pop ax
  ret

; PROCEDURE: recv_packet
;
; INPUT:
;   N/A
;   
; OUTPUT:
;   ds:[packet_type]
;   ds:[packet_data]
;   ds:[packet_data_len]
;   ds:[recv_seq_no]
;
recv_packet:
  push ax
  push bx
  push cx
  push dx
  push di
  push si

  call com_port_recv

  ; Look for 'MARK' start marker 0x01 (Ctrl-A) in buffer:
  mov si, -1
_recv_packet_look_for_marker:
  inc si
  mov ax, [recv_buffer_index]
  cmp si, ax
  jge _recv_packet_fail ; Reached end of buffer.
  mov byte al, [recv_buffer + si]
  cmp al, 0x01 ; (Ctrl-A)
  jne _recv_packet_look_for_marker
  ; Start position now in SI register.

  ; Copy initial packet fields:
  ; * Using AL for data.
  ; * Using BL for checksum.
  ; * Using CX for packet length.
  inc si
  xor cx, cx
  mov byte cl, [recv_buffer + si] ; Packet 'LEN' field.
  mov bl, cl ; Checksum = LEN
  sub cx, 35 ; 32 + 3 bytes for 'SEQ', 'TYPE' & 'CHECK'
  inc si
  mov byte al, [recv_buffer + si] ; Packet 'SEQ' field.
  add bl, al ; Checksum += SEQ
  sub al, 32
  mov byte [recv_seq_no], al
  inc si
  mov byte al, [recv_buffer + si] ; Packet 'TYPE' field.
  add bl, al ; Checksum += TYPE
  mov byte [packet_type], al
  inc si
  ; Packet length now in CX register.
  ; Checksum now in BL register.
  ; Start of data position now in SI register.

  mov word [packet_data_len], cx
  test cx, cx
  jz _recv_packet_checksum ; Zero size packet, skip decoding/copying.

  ; Copy packet data:
  ; * Using AL for data.
  ; * Using BL for checksum.
  ; * Using CX for packet length.
  ; * Using DL for comparisons and temporary storage.
  ; * Using DH for decode flag.
  xor dh, dh
  mov di, packet_data
_recv_packet_copy:
  mov byte al, [recv_buffer + si] ; Packet 'DATA' field.
  add bl, al ; Checksum += DATA
  mov byte dl, [packet_type]
  cmp dl, 'S' ; 'S' = Send Initiation
  jne _recv_packet_decode ; Type 'S' packets shall not be decoded!
  mov [di], al ; Copy un-decoded.
  jmp _recv_packet_increment

_recv_packet_decode:
  cmp dh, 0
  jne _recv_packet_decode_flag_not_set_1
  mov byte dl, [ctl_marker]
  cmp dl, al
  jne _recv_packet_decode_flag_not_set_1
  mov dh, 1
  dec byte [packet_data_len] ; Decoding reduces resulting packet size.
  jmp _recv_packet_increment_source_only

_recv_packet_decode_flag_not_set_1:
  cmp dh, 1
  jne _recv_packet_decode_flag_not_set_2
  xor dh, dh

  mov dl, al
  and dl, 127
  cmp dl, 62
  jng _recv_packet_decode_flag_not_set_2
  cmp dl, 96
  jg _recv_packet_decode_flag_not_set_2
  xor al, 64

_recv_packet_decode_flag_not_set_2:
  mov [di], al
_recv_packet_increment:
  inc di
_recv_packet_increment_source_only:
  inc si
  loop _recv_packet_copy ; Until CX = 0

_recv_packet_checksum:
  ; Calculate and check checksum:
  mov dl, bl
  and dl, 192
  shr dl, 1 ; 8086 is limited to one shift at a time.
  shr dl, 1
  shr dl, 1
  shr dl, 1
  shr dl, 1
  shr dl, 1
  add dl, bl
  and dl, 63
  mov byte al, [recv_buffer + si] ; Packet 'CHECK' field.
  sub al, 32
  cmp al, dl
  jne _recv_packet_fail

  ; All OK!
  jmp _recv_packet_ok

_recv_packet_fail:
  mov byte [packet_type], 'Q' ; 'Q' = Block check error
_recv_packet_ok:
  pop si
  pop di
  pop dx
  pop cx
  pop bx
  pop ax
  ret

; PROCEDURE: com_port_recv
;
; INPUT:
;   N/A
;   
; OUTPUT:
;   ds:[recv_buffer]
;   ds:[recv_buffer_index]
;
com_port_recv:
  push ax
  push dx
  push di

  mov di, 0
_com_port_recv_byte:

  mov dx, COM1_IIR
_com_port_recv_wait:
  in al, dx
  and al, 0b00001110 ; Identification
  cmp al, 0b00000100 ; Enable Received Data Available Interrupt
  jne _com_port_recv_wait ; Busy wait...

  mov dx, COM1_RBR
  in al, dx

  cmp di, RECV_BUFFER_SIZE
  jb _com_port_recv_copy
  mov di, 0 ; Reset and wrap to prevent overflow.
_com_port_recv_copy:
  mov byte [recv_buffer + di], al
  inc di

  ; Keep reading until a terminator 0x0d (Carriage Return) arrives:
  cmp al, 0x0d
  jne _com_port_recv_byte

  mov word [recv_buffer_index], di

  pop di
  pop dx
  pop ax
  ret

; PROCEDURE: print_character
;
; INPUT:
;   dl
;   
; OUTPUT:
;   N/A
;
print_character:
  push ax
  push dx
  ; Call DOS to display character:
  mov ah, 0x2
  ; DL set by caller...
  int 0x21
  pop dx
  pop ax
  ret

; PROCEDURE: print_string
;
; INPUT:
;   dx
;   
; OUTPUT:
;   N/A
;
print_string:
  push ax
  ; Call DOS to display string:
  mov ah, 0x9
  ; DS is already same as CS, no need to change.
  ; DX set by caller...
  int 0x21
  pop ax
  ret

section .data:
recv_buffer_index:
  dw 0 ; 16-bit word due to SI/DI registers.
recv_buffer:
  times RECV_BUFFER_SIZE db 0

send_buffer_index:
  dw 0 ; 16-bit word due to SI/DI registers.
send_buffer:
  times SEND_BUFFER_SIZE db 0

send_seq_no:
  db 0
recv_seq_no:
  db 0

packet_type:
  db 0
packet_data_len:
  dw 0 ; 16-bit word due to SI/DI registers.
packet_data:
  times PACKET_DATA_SIZE db 0

ctl_marker:
  db '#'  ; Default
eol_marker:
  db 0x0d ; Default

file_handle:
  dw 0

message_waiting:
  db "Waiting...", 0x0d, 0x0a, "$"
message_receiving:
  db "Receiving: $"
message_ok:
  db "(OK)", 0x0d, 0x0a, "$"
message_done:
  db "(DONE)", 0x0d, 0x0a, "$"
          


For convenience, here is an example of commands to send a file with C-Kermit on Linux:

set modem type none
set line /dev/ttyUSB0
set carrier-watch off
set speed 9600
set flow none
set parity none
set stop-bits 1
send <filename>
          


Topic: Scripts and Code, by Kjetil @ 06/06-2020, Article Link

M.I.A. in Wine

M.I.A.: Missing In Action is a relatively unknown game that came out for Windows back in 1998. I got the game back then in my childhood as part of some bundle with a new computer. I do remember the game being fun, but I had issues getting it to run later on because it will only install on Windows 98. Fast forward some 20 years, Wine has now become a better Windows than Windows on Linux in many aspects, especially running older games.
I have been using Wine version 4.0.2 for these experiments.

Using some tricks I finally got to run and play this on Linux! In order to get there I had do spend some time with both Winedbg and OllyDbg debuggers to figure out what the game tried to do and failed on.

The first problem was the detection of the CDs, which I figured out it does by calling GetVolumeInformationA() and looking at the volume label. This is fixed by creating a ".windows-label" file in the emulated CD drive with the correct label.

The second problem was getting the CD audio to work correctly. Apart from having to fake this somehow, the game uses the ancient Media Control Interface which still have some missing features (bugs?) in Wine at the time of writing. Maybe this will be fixed in an upcoming version, but I had no time to wait for that. The root of the problem is that Wine returns the code (as string) "1088" instead of the string "audio" when the game asks what type of track is on the CD. The quickest way to fix this is to simply patch the game binary to look for that other string.

To actually play the CD audio without the CDs I figured out it was easiest to hack the Wine "mcicda.dll" library and make it call MPlayer to play the tracks as .FLAC files. This is done in MPlayer's FIFO mode to avoid blocking anything.

A third problem is that the in-game video cutscenes, using Smacker Video Technology still does not play correctly in Wine. The symptom is that the video may play for some seconds, but then just hangs. Since it's possible to bypass this by hitting Escape, I have simply ignored this for now.

Anyway, the common steps to install and run are as follows:
1) Create a new directory to store a Wine prefix for M.I.A.:
mkdir -p ~/opt/mia
2) Run winecfg on the prefix, in 32-bit mode, and set it has "Windows 98":
WINEARCH=win32 WINEPREFIX=~/opt/mia winecfg
3) Create two directories for each M.I.A. CD in the prefix:
mkdir ~/opt/mia/cd1
mkdir ~/opt/mia/cd2
4) Copy the CD contents into the respective directories.
Either directly from the CDs or ISO images mounted as loopback devices.
5) Create fake volume labels for each CD, as needed by the game:
echo "MIA_VOL1" > ~/opt/mia/cd1/.windows-label
echo "MIA_VOL2" > ~/opt/mia/cd2/.windows-label
6) Create a symbolic link kalled "drive_d" pointing to "cd1"
ln -s "cd1" ~/opt/mia/drive_d
7) Run winecfg again to map D: to the newly created "drive_d" directory.
Also set the type as "CD-ROM".
WINEARCH=win32 WINEPREFIX=~/opt/mia winecfg
8) Allow low memory to be mapped, since it is needed by M.I.A. installer.
sudo sysctl vm.mmap_min_addr=0
9) Start the M.I.A. installation through Wine,
WINEARCH=win32 WINEPREFIX=~/opt/mia wine ~/opt/mia/drive_d/mia.exe
10) When prompted for installation of installation type...
Select "Leave ground textures on CD".
This is needed because the installer has issues finding CD #2.
11) Run the following script to easily start the game:

#!/bin/sh
export WINEPREFIX=~/opt/mia

sudo sysctl vm.mmap_min_addr=0 # Wine needs to be allowed to map low memory.

CD_NO=0
while [ "$CD_NO" != "1" ] && [ "$CD_NO" != "2" ]; do
  read -p "CD Number? (1 or 2) " CD_NO
done

rm -f "${WINEPREFIX}/drive_d"
ln -s "cd$CD_NO" "${WINEPREFIX}/drive_d"

(cd "${WINEPREFIX}/drive_c/MIA" && WINEARCH=win32 wine miarel.exe -avhpd)
          


If you also want the in-game music, some additional steps are required:
12) Assuming all tracks are ripped from the CD's in FLAC format.
4 audio tracks from CD #1 named from "track02.flac" to "track05.flac".
5 audio tracks from CD #2 mamed from "track02.flac" to "track06.flac".
Copy .flac files into the root of each respective directory "cd1" and "cd2".
13) Patch the "mcicda.dll" file in ~/opt/mia/drive_c/windows/system32/
14) Patch the "miarel.exe" file in ~/opt/mia/drive_c/MIA/
15) Run the following modified script to start the game:

#!/bin/sh
export WINEPREFIX=~/opt/mia

MPLAYER_FIFO=/tmp/mplayer.fifo # Do not change, hardcoded in patched mcicda.dll

sudo sysctl vm.mmap_min_addr=0 # Wine needs to be allowed to map low memory.

CD_NO=0
while [ "$CD_NO" != "1" ] && [ "$CD_NO" != "2" ]; do
  read -p "CD Number? (1 or 2) " CD_NO
done

rm -f "${WINEPREFIX}/drive_d"
ln -s "cd$CD_NO" "${WINEPREFIX}/drive_d"

if [ ! -p "$MPLAYER_FIFO" ]; then
  mkfifo "$MPLAYER_FIFO"
fi

cd "${WINEPREFIX}/drive_d"
mplayer -idle -slave -input file=$MPLAYER_FIFO 1&>/dev/null &
MPLAYER_PID=$!
cd -

rm -f "${WINEPREFIX}/drive_d"
ln -s "cd$CD_NO" "${WINEPREFIX}/drive_d"

(cd "${WINEPREFIX}/drive_c/MIA" && WINEARCH=win32 wine miarel.exe -avhpd)

kill $MPLAYER_PID
rm -f "$MPLAYER_FIFO"
          


To patch "miarel.exe", open it in a hex-editor and go to offset 0x1427c4. At this location the string "audio" should be present. Replace this with 0x31 0x30 0x38 0x38 0x00 which represents the string "1088" with an additional NULL terminator.

Patching "mcicda.dll" is more complicated as it requires a rebuild of Wine. Get the Wine source code and apply the following source code patch to "./dlls/mcicda/mcicda.c":

--- mcicda.c.orig	2020-05-13 17:55:02.433346437 +0200
+++ mcicda.c	2020-05-13 17:54:53.230346338 +0200
@@ -25,6 +25,12 @@
 #include <stdio.h>
 #include <string.h>
 
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <limits.h>
+
 #define WIN32_NO_STATUS
 #include "windef.h"
 #include "winbase.h"
@@ -79,10 +85,72 @@
 typedef HRESULT(WINAPI*LPDIRECTSOUNDCREATE)(LPCGUID,LPDIRECTSOUND*,LPUNKNOWN);
 static LPDIRECTSOUNDCREATE pDirectSoundCreate;
 
+static void mplayer_command(const char *command)
+{
+    int fd, written;
+
+    fd = open("/tmp/mplayer.fifo", O_NONBLOCK | O_WRONLY);
+    if (fd == -1) {
+        TRACE("No pipe\n");
+        return;
+    }
+
+    written = write(fd, command, strlen(command));
+    if (written <= 0) {
+        TRACE("Write failed\n");
+    }
+
+    close(fd);
+}
+
 static BOOL device_io(HANDLE dev, DWORD code, void *inbuffer, DWORD insize, void *outbuffer, DWORD outsize, DWORD *retsize, OVERLAPPED *overlapped)
 {
     const char *str;
-    BOOL ret = DeviceIoControl(dev, code, inbuffer, insize, outbuffer, outsize, retsize, overlapped);
+//    BOOL ret = DeviceIoControl(dev, code, inbuffer, insize, outbuffer, outsize, retsize, overlapped);
+
+    int i;
+    BOOL ret = TRUE;
+    CDROM_TOC *toc;
+
+    *retsize = 0;
+
+    switch (code) {
+    case IOCTL_CDROM_READ_TOC:
+        toc = (CDROM_TOC *)outbuffer;
+
+        toc->FirstTrack = 1;
+        toc->LastTrack = 6;
+
+        // Set up first track as data track.
+        toc->TrackData[0].TrackNumber = 1;
+        toc->TrackData[0].Control = 0x4;
+        toc->TrackData[0].Address[1] = 0;
+        toc->TrackData[0].Address[2] = 0;
+        toc->TrackData[0].Address[3] = 0;
+
+        // Set up remaining tracks as dummy audio tracks.
+        for (i = 1; i < toc->LastTrack; i++) {
+            toc->TrackData[i].TrackNumber = i + 1;
+            toc->TrackData[i].Control = 0;
+            toc->TrackData[i].Address[1] = i;
+            toc->TrackData[i].Address[2] = 0;
+            toc->TrackData[i].Address[3] = 0;
+        }
+
+        *retsize = CDROM_TOC_SIZE;
+        break;
+
+    case IOCTL_CDROM_STOP_AUDIO:
+        mplayer_command("stop\n");
+        break;
+
+    case IOCTL_CDROM_PAUSE_AUDIO:
+        mplayer_command("stop\n");
+        break;
+
+    default:
+        break;
+    }
 
 #define XX(x) case (x): str = #x; break
     switch (code)
@@ -906,6 +974,9 @@
     SUB_Q_CHANNEL_DATA          data;
     CDROM_TOC			toc;
 
+    int track_no;
+    char command[PATH_MAX];
+
     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
 
     if (lpParms == NULL)
@@ -914,6 +985,20 @@
     if (wmcda == NULL)
 	return MCIERR_INVALID_DEVICE_ID;
 
+    // HIJACK START
+
+    mplayer_command("stop\n");
+
+    track_no = MCI_TMSF_TRACK(lpParms->dwFrom);
+    TRACE("Track no: %d\n", track_no);
+
+    snprintf(command, PATH_MAX, "loadfile track%02d.flac\n", track_no);
+    mplayer_command(command);
+
+    return 0;
+
+    // HIJACK END
+
     if (!MCICDA_ReadTOC(wmcda, &toc, &br))
         return MCICDA_GetError(wmcda);
          

To build the DLL file, it should be enough to run ./configure and make on the Wine source code. The resulting file will be named "mcicda.dll.so" but can be renamed to "mcicda.dll".

Topic: Configuration, by Kjetil @ 24/05-2020, Article Link

Amiga 500 Capacitor Replacement

I recently replaced all the electrolytic capacitors on my Commodore Amiga 500. This was originally for troubleshooting and diagnostics purposes, but sometimes it is a good idea anyway because electrolytic capacitors are prone to drying up and become worse over time. I understand that this varies a lot between manufacturers and production batches, so it's not always the case. As for the Amiga 500, there seems to be some dispute.

Anyway, in this process I had to come up with a easy way to track the work while soldering. So I made this "map" with all the capacitors and their values. It might be helpful to others later:

Amiga 500 Capacitor Locations


Note that this is a Amiga 500 revision 5 board, so others might be different.

Topic: Repair, by Kjetil @ 01/05-2020, Article Link

Dell 2005FPW Display Resolution Fix

I have an old Dell 2005FPW LCD display from around 2005. I had some problems getting this to display the native 1680x1050 resolution in Linux. Instead it would always want to display 1280x1024, and everything would look ugly. The cause of this seems to be bad EDID data being sent by the monitor, because I managed to fix it by manually creating a EDID firmware file with a resolution of 1680x1050 and the refresh rate forced to 59Hz, instead of the more common 60Hz.

There is a nice piece of software here on GitHub to create EDID firmware files from X modeline configuration. I used this together with this handy Online modeline generator.

Here is the modeline generated from the online tool:

# 1680x1050 @ 59.00 Hz (GTF) hsync: 64.07 kHz; pclk: 144.55 MHz
Modeline "1680x1050_59.00" 144.55 1680 1784 1968 2256 1050 1051 1054 1086 -HSync +Vsync
          


I had to trim away the excess ".00" from the string, or else the EDID firwmare file would be too big, 131 bytes instead of 128 bytes, so this should be the actual input to the 'modeline2edid' tool in the EDID generator package:

Modeline "1680x1050_59" 144.55 1680 1784 1968 2256 1050 1051 1054 1086 -HSync +Vsync
          


For reference, here is a hexdump of the newly created EDID firmware:

00000000  00 ff ff ff ff ff ff 00  31 d8 00 00 00 00 00 00  |..1......|
00000010  05 16 01 03 6d 2b 1b 78  ea 5e c0 a4 59 4a 98 25  |....m+.x^YJ.%|
00000020  20 50 54 00 00 00 b3 00  01 01 01 01 01 01 01 01  | PT............|
00000030  01 01 01 01 01 01 77 38  90 40 62 1a 24 40 68 b8  |......w8.@b.$@h|
00000040  13 00 b5 11 11 00 00 1e  00 00 00 ff 00 4c 69 6e  |...........Lin|
00000050  75 78 20 23 30 0a 20 20  20 20 00 00 00 fd 00 3b  |ux #0.    ....;|
00000060  3d 3f 41 0f 00 0a 20 20  20 20 20 20 00 00 00 fc  |=?A...      ...|
00000070  00 31 36 38 30 78 31 30  35 30 5f 35 39 0a 00 e1  |.1680x1050_59..|
          


The file needs to be loaded by putting it in /lib/firmware/edid/ and adding this to the Linux boot kernel parameters:

drm.edid_firmware=edid/1680x1050.bin
          


After this, the resolution became correct in both the framebuffer console and X on the computer where I use this LCD display. The computer has a NVIDIA GeForce FX 5200 graphics gard with the "nouveau" driver in use.

Topic: Configuration, by Kjetil @ 02/04-2020, Article Link

NCR System 3330 Dallas RTC Mod

The Dallas DS12887 RTC inside my NCR System 3330 PC had died a long time ago. Unfortunately, this made the machine unbootable from the hard drive, since it would forget the hard drive settings on each restart. Instead of finding a replacement, like for the Commodore PC 30-III, I opted for the external battery modification instead. I got this working with just two regular AA 1.5V alkaline batteries, a huge success!

The initial error on every startup was as follows:

NCR Battery Power Lost


Fortunately, the Dallas RTC is a in a socket on this machine, easily extracted:

NCR Dallas RTC Extracted


To perform the mod, two sections of the case needs to be opened, which I did with a Dremel tool:

NCR Dallas RTC Dremeled


Afterwards, it's possible to solder on leads for a new battery:

NCR Dallas RTC with new battery leads


I installed a new 2xAA battery holder inside the case, connected to the RTC:

NCR Dallas RTC external battery


The machine is now working again, settings can be saved to CMOS and booting from hard drive is possible:

NCR Powered On


Topic: Repair, by Kjetil @ 14/03-2020, Article Link

Reverse SSH Tunnel Listener

The Reverse SSH Tunnel Launcher script I posted a while ago has some limitations. The worst part is that the tunnel is only open for 5 minutes, leaving too little time to get any work done. This is kind of by design, to prevent having these connections open and "live" when not in use.

The solution to this limitation is another small script, this time just hacked together as a Bourne shell script. Take a look:

#!/bin/sh

while /bin/true; do
  if /bin/netstat -tln | fgrep 127.0.0.1:1337 > /dev/null; then
    ssh localhost -p 1337 screen -d -m ssh -v -R 1338:localhost:22 -N -p 22 192.168.0.1
    echo "New tunnel established!"
    exit
  fi
  sleep 10
done
          


This script will loop forever and wait for a socket to appear on the port (1337) opened by the original launcher. Once this happens, a new tunnel is created (on port 1338) in parallel which will persist forever through a screen session.

Topic: Scripts and Code, by Kjetil @ 02/02-2020, Article Link

Strawman

This is a game project I have had lying around for many years, which I finally made into something usable. The initial idea was to make a side-scroller using the SDL library, and the project codename was "Strawman", so that just became the title as well.

The end result is a highly configurable yet simple game. The map data is stored in a text file and can be easily changed. The "game engine" itself is configured through a bunch of #define macros.

Here's a screenshot:

Strawman screenshot


And the corresponding part of the map data, rotated by 90 degrees on purpose, so adding more lines makes the map longer horizontally:

#
# P
#
###
###  #  CCC
###  #E CCC
###  #  CCC
###
#
#E
#
#
#
##

        # CC
#       # CC
##      # CC
###
####
          


The source code is released under the MIT license and can be downloaded here.

Topic: Open Source, by Kjetil @ 01/01-2020, Article Link