Advertisement
MichaelPetch

DOS Keyboard Interrupt Handler

Dec 3rd, 2024 (edited)
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1. .model small
  2. .stack 100h
  3.  
  4. .data
  5. old9 dd ?
  6. hello_msg db 'hello$'
  7. what_msg db 'what$'
  8.  
  9. .code
  10. start:
  11. mov ax, @data
  12. mov ds, ax
  13. mov es, ax
  14. jmp setup
  15. KeyboardInterruptHandler proc
  16. push ax
  17. push bx
  18. push cx
  19. push dx
  20. push ds
  21. push es
  22.  
  23. mov ax, @data ; DS = @data segment
  24. mov ds, ax
  25.  
  26. mov ax, 40h ; ES = 40h (BIOS Data Areas BDA)
  27. mov es, ax ; See https://stanislavs.org/helppc/bios_data_area.html
  28.  
  29. mov bx, es:[1ch] ; Keyboard buffer tail ptr at 40h:1ch (41ch)
  30.  
  31. pushf ; Push flags on stack because old interrupt will end with IRET
  32. call [old9] ; Call the old keyboard interrupt handler
  33.  
  34. test byte ptr es:[17h], 8h
  35. ; Test Bit 3 of Keyboard flag (byte 1) in DOS BDA at 40h:17h
  36. ; See https://stanislavs.org/helppc/kb_flags.html
  37. jnz print_hello ; If ALT is pressed print hello
  38.  
  39. cmp bx, es:[1ch] ; Did the keyboard tail ptr change? If not no key to process
  40. je end_handler
  41.  
  42. ; Get the Scan code directly from the keyboard buffer
  43. ; ASCII value at [bx] and SCAN code at [bx+1]
  44. mov al, es:[bx+1]
  45.  
  46. cmp al, 39h ; If SPACE is pressed print what
  47. je print_what
  48. jmp end_handler ; Otherwise exit
  49.  
  50. ; Beware!! DOS is not re-entrant so calling int 21h functions from
  51. ; inside an interrupt handler can fail!
  52. print_hello:
  53. mov dx, offset hello_msg
  54. jmp print_message
  55. print_what:
  56. mov dx, offset what_msg
  57. print_message:
  58. mov ah, 9
  59. int 21h
  60. end_handler:
  61. ; The original keyboard handler will have sent EOI to PICs
  62. ; meaning we don't need to send 20h to port 20h
  63. pop es
  64. pop ds
  65. pop dx
  66. pop cx
  67. pop bx
  68. pop ax
  69. iret
  70. KeyboardInterruptHandler endp
  71. setup:
  72. cli
  73. mov ax, 0h
  74. mov es, ax
  75. mov bx, es:[9 * 4]
  76. mov word ptr old9, bx
  77. mov bx, es:[9 * 4 + 2]
  78. mov word ptr old9 + 2, bx
  79. mov word ptr es:[9 * 4], offset KeyboardInterruptHandler
  80. mov es:[9 * 4 + 2], cs
  81. sti
  82. mov ah, 1
  83. int 21h
  84. cli
  85. lds dx, dword ptr old9
  86. mov ax, 2509h
  87. int 21h
  88. sti
  89. mov ax, 4c00h
  90. int 21h
  91. end start
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement