home *** CD-ROM | disk | FTP | other *** search
/ Piper's Pit BBS/FTP: ibm 0010 - 0019 / ibm0010-0019 / ibm0010.tar / ibm0010 / MKEY30.ZIP / ASMTUTOR next >
Encoding:
Text File  |  1987-02-26  |  65.6 KB  |  1,342 lines

  1.            This uncopyrighted revised IBM Personal Computer Assembly 
  2.       Language Tutorial by Joshua Auerbach of Yale University 
  3.       is included for your familiarization with the 8086 architecture
  4.       if needed.
  5.  
  6. Why Learn Assembler?
  7.  
  8.    Don't use it just because you think it is going to execute faster.
  9. PASCAL, C, FORTRAN, or BASIC can do the job just about as fast as the
  10. same algorithm in assembler. On the other hand, high level languages do tend
  11. to isolate you from the That is both their strength and their weakness.
  12. Usually, when on a micro, a high level language provides an escape mechanism
  13. to the underlying operating system or to the bare machine. So, for
  14. example, BASIC has its PEEK and POKE. But, the route to the bare machine
  15. is often a circuitous one, leading to tricky programming which is hard to
  16. follow.
  17.  
  18.    For those of us working on PC's connected to SHARE-class mainframes, we
  19. are generally concerned with three interfaces:  the keyboard, the screen,
  20. and the communication line or lines. All three of these entities raise machine
  21. dependent issues which are imperfectly addressed by the underlying operat-
  22. ing system or by high level languages.
  23.  
  24.    Sometimes, the system or the language does too little for you. For
  25. example, with the asynch adapter, the system provides no interrupt handler,
  26. no buffer, and no flow control. The application is stuck with the respon-
  27. sibility for monitoring that port and not missing any characters, then
  28. deciding what to do with all errors. BASIC does a reasonable job on some
  29. of this, but that is only BASIC. Most other languages do less.
  30.  
  31. Sometimes, the system may do too much for you. System support for the key-
  32. board is an example. At the hardware level, all 83 keys on the keyboard
  33. send unique codes when they are pressed, held down, and released. But,
  34. someone has decided that certain keys, like Num Lock and Scroll Lock are
  35. going to do certain things before the application even sees them and can't
  36. therefore be used as ordinary keys.
  37. Sometimes, the system does about the right amount of stuff but does it less
  38. efficiently then it should. System support for the screen is in this
  39. class. If you use only the official interface to the screen you sometimes
  40. slow your application down unacceptably. I said before, don't use assem-
  41. bler just to speed things up, but there I was talking about mainline code,
  42. which generally can't be speeded up much by assembler coding. A critical
  43. system interface is a different matter:  sometimes we may have to use
  44. assembler to bypass a hopelessly inefficient implementation. We don't want
  45. to do this if we can avoid it, but sometimes we can't.
  46.  
  47. Assembly language code can overcome these deficiencies. In some cases, you
  48. can also overcome these deficiencies by judicious use of the escape valves
  49. which your high level language provides. In BASIC, you can PEEK and POKE
  50. and INP and OUT your way around a great many issues. In many other lan-
  51. guages you can issue system calls and interrupts and usually manage, one
  52. way or other, to modify system memory. Writing handlers to take real-time
  53. hardware interrupts from the keyboard or asynch port, though, is still
  54. going to be a problem in most languages. Some languages claim to let you
  55. do it but I have yet to see an acceptably clean implementation done that
  56. way.
  57.  
  58. The real reason while assembler is better than "tricky POKEs" for writing
  59. machine-dependent code, though, is the same reason why PASCAL is better
  60. than assembler for writing a payroll package:  it is easier to maintain.
  61. Let the high level language do what it does best, but recognize that there
  62. are some things which are best done in assembler code. The assembler,
  63. unlike the tricky POKE, can make judicious use of equates, macros, labels,
  64. and appropriately placed comments to show what is really going on in this
  65. machine-dependent realm where it thrives.
  66.  
  67. So, there are times when it becomes appropriate to write in assembler; giv-
  68. en that, if you are a responsible programmer or manager, you will want to
  69. be "assembler-literate" so you can decide when assembler code should be
  70. written.
  71.  
  72. What do I mean by "assembler-literate?"  I don't just mean understanding
  73. the 8086 architecture; I think, even if you don't write much assembler code
  74. yourself, you ought to understand the actual process of turning out assem-
  75. bler code and the various ways to incorporate it into an application. You
  76. ought to be able to tell good assembler code from bad, and appropriate
  77. assembler code from inappropriate.
  78.  
  79. Steps to becoming ASSEMBLER-LITERATE
  80.  
  81. 1. Learn the 8086 architecture and most of the instruction set. Learn
  82.    what you need to know and ignore what you don't. Reading:  The 8086
  83.    Primer by Stephen Morse, published by Hayden. You need to read only
  84.    two chapters, the one on machine organization and the one on the
  85.    instruction set.
  86.  
  87. 2. Learn about a few simple DOS function calls. Know what services the
  88.    operating system provides. If appropriate, learn a little about other
  89.    systems too. It will aid portability later on. Reading:  appendices D
  90.    and E of the PC DOS manual.
  91.  
  92. 3. Learn enough about the MACRO assembler and the LINKer to write some
  93.    simple things that really work. Here, too, the main thing is figuring
  94.    out what you don't need to know. Whatever you do, don't study the sam-
  95.    ple programs distributed with the assembler unless you have nothing
  96.    better!
  97.  
  98. 4. At the same time as you are learning the assembler itself, you will
  99.    need to learn a few tools and concepts to properly combine your assem-
  100.    bler code with the other things you do. If you plan to call assembler
  101.    subroutines from a high level language, you will need to study the
  102.    interface notes provided in your language manual. Usually, this forms
  103.    an appendix of some sort. If you plan to package your assembler rou-
  104.    tines as .COM programs you will need to learn to do this. You should
  105.    also learn to use DEBUG.
  106.  
  107. 5. Read the Technical Reference, but very selectively. The most important
  108.    things to know are the header comments in the BIOS listing. Next, you
  109.    will want to learn about the RS 232 port and maybe about the video
  110.    adapters.
  111.  
  112. Notice that the key thing in all five phases is being selective. It is
  113. easy to conclude that there is too much to learn unless you can throw away
  114. what you don't need. Most of the rest of this talk is going to deal with
  115. this very important question of what you need and don't need to learn in
  116. each phase. In some cases, I will have to leave you to do almost all of
  117. the learning, in others, I will teach a few salient points, enough, I hope,
  118. to get you started. I hope you understand that all I can do in an hour is
  119. get you started on the way.
  120.  
  121. Phase 1:  Learn the architecture and instruction set
  122.  
  123. The Morse book might seem like a lot of book to buy for just two really
  124. important chapters; other books devote a lot more space to the instruction
  125. set and give you a big beautiful reference page on each instruction. And,
  126. some of the other things in the Morse book, although interesting, really
  127. aren't very vital and are covered too sketchily to be of any real help.
  128. The reason I like the Morse book is that you can just read it; it has a
  129. very conversational style, it is very lucid, it tells you what you really
  130. need to know, and a little bit more which is by way of background; because
  131. nothing really gets belabored to much, you can gracefully forget the things
  132. you don't use. And, I very much recommend READING Morse rather than study-
  133. ing it. Get the big picture at this point.
  134.  
  135. Now, you want to concentrate on those things which are worth fixing in mem-
  136. ory. After you read Morse, you should relate what you have learned to this
  137. outline.
  138.  
  139. 1. You want to fix in your mind the idea of the four segment registers
  140.    CODE, DATA, STACK, and EXTRA. This part is pretty easy to grasp. The
  141.    8086 and the 8088 use 20 bit addresses for memory, meaning that they
  142.    can address up to 1 megabyte of memory. But, the registers and the
  143.    address fields in all the instructions are no more that 16 bits long.
  144.    So, how to address all of that memory?  Their solution is to put
  145.    together two 16 bit quantities like this:
  146.  
  147.      calculation  SSSS0   ---- value in the relevant segment register SHL 4
  148.      depicted in   AAAA   ---- apparent address from register or instruction
  149.      hexadecimal --------
  150.                RRRRR   ---- real address placed on address bus
  151.  
  152.    In other words, any time memory is accessed, your program will supply a
  153.    sixteen bit address. Another sixteen bit address is acquired from a
  154.    segment register, left shifted four bits (one nibble) and added to it
  155.    to form the real address. You can control the values in the segment
  156.    registers and thus access any part of memory you want. But the segment
  157.    registers are specialized:  one for code, one for most data accesses,
  158.    one for the stack (which we'll mention again) and one "extra" one for
  159.    additional data accesses.
  160.  
  161.    Most people, when they first learn about this addressing scheme become
  162.    obsessed with converting everything to real 20 bit addresses. After a
  163.    while, though, you get use to thinking in segment/offset form. You
  164.    tend to get your segment registers set up at the beginning of the pro-
  165.    gram, change them as little as possible, and think just in terms of
  166.    symbolic locations in your program, as with any assembly language.
  167.  
  168.      EXAMPLE:
  169.          MOV  AX,DATASEG
  170.          MOV  DS,AX       ;Set value of Data segment
  171.          ASSUME DS:DATASEG   ;Tell assembler DS is usable
  172.          .......
  173.          MOV  AX,PLACE     ;Access storage symbolically by 16 bit address
  174.  
  175.    In the above example, the assembler knows that no special issues are
  176.    involved because the machine generally uses the DS register to complete
  177.    a normal data reference.
  178.  
  179.    If you had used ES instead of DS in the above example, the assembler
  180.    would have known what to do, also. In front of the MOV instruction
  181.    which accessed the location PLACE, it would have placed the ES segment
  182.    prefix. This would tell the machine that ES should be used, instead of
  183.    DS, to complete the address.
  184.  
  185.    Some conventions make it especially easy to forget about segment regis-
  186.    ters. For example, any program of the COM type gets control with all
  187.    four segment registers containing the same value. This program exe-
  188.    cutes in a simplified 64K address space. You can go outside this
  189.    address space if you want but you don't have to.
  190.  
  191. 2. You will want to learn what other registers are available and learn
  192.    their personalities:
  193.  
  194.       AX and DX are general purpose registers. They become special only
  195.       when accessing machine and system interfaces.
  196.  
  197.       CX is a general purpose register which is slightly specialized for
  198.       counting.
  199.  
  200.       BX is a general purpose register which is slightly specialized for
  201.       forming base-displacement addresses.
  202.  
  203.       AX-DX can be divided in half, forming AH, AL, BH, BL, CH, CL, DH,
  204.       DL.
  205.  
  206.       SI and DI are strictly 16 bit. They can be used to form indexed
  207.       addresses (like BX) and they are also used to point to strings.
  208.  
  209.       SP is hardly ever manipulated. It is there to provide a stack.
  210.  
  211.       BP is a manipulable cousin to SP. Use it to access data which has
  212.       been pushed onto the stack.
  213.  
  214.       Most sixteen bit operations are legal (even if unusual) when per-
  215.       formed in SI, DI, SP, or BP.
  216.  
  217. 3. You will want to learn the classifications of operations available
  218.    WITHOUT getting hung up in the details of how 8086 opcodes are con-
  219.    structed.
  220.  
  221.    8086 opcodes are complex. Fortunately, the assembler opcodes used to
  222.    assemble them are simple. When you read a book like Morse, you will
  223.    learn some things which are worth knowing but NOT worth dwelling on.
  224.  
  225.    a. 8086 and 8088 instructions can be broken up into subfields and bits
  226.       with names like R/M, MOD, S and W. These parts of the instruction
  227.       modify the basic operation in such ways as whether it is 8 bit or
  228.       16 bit, if 16 bit, whether all 16 bits of the data are given,
  229.       whether the instruction is register to register, register to
  230.       memory, or memory to register, for operands which are registers,
  231.       which register, for operands which are memory, what base and index
  232.       registers should be used in finding the data.
  233.  
  234.    b. Also, some instructions are actually represented by several differ-
  235.       ent machine opcodes depending on whether they deal with immediate
  236.       data or not, or on other issues, and there are some expedited forms
  237.       which assume that one of the arguments is the most commonly used
  238.       operand, like AX in the case of arithmetic.
  239.  
  240.    There is no point in memorizing any of this detail; just distill the
  241.    bottom line, which is, what kinds of operand combinations EXIST in the
  242.    instruction set and what kinds don't. If you ask the assembler to ADD
  243.    two things and the two things are things for which there is a legal ADD
  244.    instruction somewhere in the instruction set, the assembler will find
  245.    the right instruction and fill in all the modifier fields for you.
  246.    I guess if you memorized all the opcode construction rules you might
  247.    have a crack at being able to disassemble hex dumps by eye, like you
  248.    may have learned to do somewhat with 370 assembler. I submit to you
  249.    that this feat, if ever mastered by anyone, would be in the same class
  250.    as playing the "Minute Waltz" in a minute; a curiosity only.
  251.    Here is the basic matrix you should remember:
  252.  
  253.        Two operands:      One operand:
  254.         R <-- M            R
  255.         M <-- R            M
  256.         R <-- R            S *
  257.         R|M <-- I
  258.         R|M <-- S  *
  259.         S <-- R|M  *
  260.  
  261.      * -- data moving instructions (MOV, PUSH, POP) only
  262.      S -- segment register (CS, DS, ES, SS)
  263.      R -- ordinary register (AX, BX, CX, DX, SI, DI, BP, SP,
  264.                        AH, AL, BH, BL, CH, CL, DH, DL)
  265.      M -- one of the following
  266.             pure address
  267.             [BX]+offset
  268.             [BP]+offset
  269.             any of the above indexed by SI
  270.             any of the first three indexed by DI
  271.  
  272. 4. Of course, you want to learn the operations themselves. As I've sug-
  273.    gested, you want to learn the op codes as the assembler presents them,
  274.    not as the CPU machine language presents them. So, even though there
  275.    are many MOV op codes you don't need to learn them. Basically, here is
  276.    the instruction set:
  277.  
  278.    a. Ordinary two operand instructions. These instructions perform an
  279.       operation and leave the result in place of one of the operands.
  280.       They are
  281.  
  282.       1) ADD and ADC -- addition, with or without including a carry from
  283.          a previous addition
  284.  
  285.       2) SUB and SBB -- subtraction, with or without including a borrow
  286.          from a previous subtraction
  287.  
  288.       3) CMP -- compare. It is useful to think of this as a subtraction
  289.          with the answer being thrown away and neither operand actually
  290.          changed
  291.  
  292.       4) AND, OR, XOR -- typical boolean operations
  293.  
  294.       5) TEST -- like an AND, except the answer is thrown away and nei-
  295.          ther operand is changed.
  296.  
  297.       6) MOV -- move data from source to target
  298.  
  299.       7) LDS, LES, LEA -- some specialized forms of MOV with side
  300.          effects
  301.  
  302.    b. Ordinary one operand instructions. These can take any of the oper-
  303.       and forms described above. Usually, the perform the operation and
  304.       leave the result in the stated place:
  305.  
  306.       1)  INC -- increment contents
  307.       2)  DEC -- decrement contents
  308.       3)  NEG -- twos complement
  309.       4)  NOT -- ones complement
  310.       5)  PUSH -- value goes on stack (operand location itself unchanged)
  311.       6)  POP -- value taken from stack, replaces current value
  312.  
  313.    c. Now you touch on some instructions which do not follow the general
  314.       operand rules but which require the use of certain registers. The
  315.       important ones are
  316.  
  317.       1) The multiply and divide instructions
  318.  
  319.       2) The "adjust" instructions which help in performing arithmetic
  320.          on ASCII or packed decimal data
  321.  
  322.       3) The shift and rotate instructions. These have a restriction on
  323.          the second operand:  it must either be the immediate value 1 or
  324.          the contents of the CL register.
  325.  
  326.       4) IN and OUT which send or receive data from one of the 1024
  327.          hardware ports.
  328.  
  329.       5) CBW and CWD -- convert byte to word or word to doubleword by
  330.          sign extension
  331.  
  332.    d. Flow of control instructions. These deserve study in themselves
  333.       and we will discuss them a little more. They include
  334.  
  335.       1) CALL, RET -- call and return
  336.  
  337.       2) INT, IRET -- interrupt and return-from-interrupt
  338.  
  339.       3) JMP -- jump or "branch"
  340.  
  341.       4) LOOP, LOOPNZ, LOOPZ -- special (and useful) instructions which
  342.          implement a counted loop similar to the 370 BCT instruction
  343.  
  344.       5) various conditional jump instructions
  345.  
  346.    e. String instructions. These implement a limited storage-to-storage
  347.       instruction subset and are quite powerful. All of them have the
  348.       property that
  349.  
  350.       1) The source of data is described by the combination DS and SI.
  351.  
  352.       2) The destination of data is described by the combination ES and
  353.          DI.
  354.  
  355.       3) As part of the operation, the SI and/or DI register(s) is(are)
  356.          incremented or decremented so the operation can be repeated.
  357.  
  358.       They include
  359.  
  360.       1) CMPSB/CMPSW -- compare byte or word
  361.       2) LODSB/LODSW -- load byte or word into AL or AX
  362.       3) STOSB/STOSW -- store byte or word from AL or AX
  363.       4) MOVSB/MOVSW -- move byte or word
  364.       5) SCASB/SCASW -- compare byte or word with contents of AL or AX
  365.       6) REP/REPE/REPNE -- a prefix which can be combined with any of
  366.          the above instructions to make them execute repeatedly across a
  367.          string of data whose length is held in CX.
  368.  
  369.    f. Flag instructions: CLI, STI, CLD, STD, CLC, STC. These can set or
  370.       clear the interrupt (enabled) direction (for string operations) or
  371.       carry flags.
  372.  
  373.    The addressing summary and the instruction summary given above masks a
  374.    lot of annoying little exceptions. For example, you can't POP CS, and
  375.    although the R <-- M form of LES is legal, the M <-- R form isn't etc.
  376.    etc. My advice is
  377.  
  378.    a. Go for the general rules
  379.    b. Don't try to memorize the exceptions
  380.    c. Rely on common sense and the assembler to teach you about
  381.       exceptions over time. A lot of the exceptions cover things you
  382.       wouldn't want to do anyway.
  383.  
  384. 5. A few instructions are rich enough and useful enough to warrent careful
  385.    study. Here are a few final study guidelines:
  386.  
  387.    a. It is well worth the time learning to use the string instruction
  388.       set effectively. Among the most useful are
  389.  
  390.             REP MOVSB         ;moves a string
  391.             REP STOSB         ;initializes memory
  392.             REPNE SCASB       ;look up occurance of character in string
  393.             REPE CMPSB        ;compare two strings
  394.  
  395.    b. Similarly, if you have never written for a stack machine before,
  396.       you will need to exercise PUSH and POP and get very comfortable
  397.       with them because they are going to be good friends. If you are
  398.       used to the 370, with lots of general purpose registers, you may
  399.       find yourself feeling cramped at first, with many fewer registers
  400.       and many instructions having register restrictions. But, you have
  401.       a hidden ally:  you need a register and you don't want to throw
  402.       away what's in it?  Just PUSH it, and when you are done, POP it
  403.       back. This can lead to abuse. Never have more than two
  404.       "expedient" PUSHes in effect and never leave something PUSHed
  405.       across a major header comment or for more than 15 instructions or
  406.       so. An exception is the saving and restoring of registers at
  407.       entrance to and exit from a subroutine; here, if the subroutine is
  408.       long, you should probably PUSH everything which the caller may need
  409.       saved, whether you will use the register or not, and POP it in
  410.       reverse order at the end.
  411.       Be aware that CALL and INT push return address information on the
  412.       stack and RET and IRET pop it off. It is a good idea to become
  413.       familiar with the structure of the stack.
  414.  
  415.    c. In practice, to invoke system services you will use the INT
  416.       instruction. It is quite possible to use this instruction effec-
  417.       tively in a cookbook fashion without knowing precisely how it
  418.       works.
  419.  
  420.    d. The transfer of control instructions (CALL, RET, JMP) deserve care-
  421.       ful study to avoid confusion. You will learn that these can be
  422.       classified as follows:
  423.  
  424.       1)  all three have the capability of being either NEAR (CS register
  425.           unchanged) or FAR (CS register changed)
  426.       2)  JMPs and CALLs can be DIRECT (target is assembled into instruc-
  427.           tion) or INDIRECT (target fetched from memory or register)
  428.       3)  if NEAR and DIRECT, a JMP can be SHORT (less than 128 bytes
  429.           away) or LONG
  430.  
  431.       In general, the third issue is not worth worrying about. On a for-
  432.       ward jump which is clearly VERY short, you can tell the assembler
  433.       it is short and save one byte of code:
  434.  
  435.                  JMP SHORT  CLOSEBY
  436.  
  437.       On a backward jump, the assembler can figure it out for you. On a
  438.       forward jump of dubious length, let the assembler default to a LONG
  439.       form; at worst you waste one byte.
  440.       Also leave the assembler to worry about how the target address is
  441.       to be represented, in absolute form or relative form.
  442.  
  443.    e. The conditional jump set is rather confusing when studied apart
  444.       from the assembler, but you do need to get a feeling for it. The
  445.       interactions of the sign, carry, and overflow flags can get your
  446.       mind stuttering pretty fast if you worry about it too much. What
  447.       is boils down to, though, is
  448.  
  449.               JZ        means what it says
  450.               JNZ       means what it says
  451.               JG reater this means "if the SIGNED difference is positive"
  452.               JA bove   this means "if the UNSIGNED difference is positive"
  453.               JL ess    this means "if the SIGNED difference is negative"
  454.               JB elow   this means "if the UNSIGNED difference is negative"
  455.               JC arry   assembles the same as JB; it's an aesthetic choice
  456.  
  457.       You should understand that all conditional jumps are inherently
  458.       DIRECT, NEAR, and "short"; the "short" part means that they can't
  459.       go more than 128 bytes in either direction. Again, this is some-
  460.       thing you could easily imagine to be more of a problem than it is.
  461.       I follow this simple approach:
  462.  
  463.       1)  When taking an abnormal exit from a block of code, I always use
  464.           an unconditional jump. Who knows how far you are going to end
  465.           up jumping by the time the program is finished. For example, I
  466.           wouldn't code this:
  467.  
  468.                  TEST     AL,IDIBIT       ;Is the idiot bit on?
  469.                  JNZ      OYVEY           ;Yes. Go to general cleanup
  470.  
  471.           Rather, I would probably code this:
  472.  
  473.                  TEST     AL,IDIBIT       ;Is the idiot bit on?
  474.                  JZ       NOIDIOCY        ;No. I am saved.
  475.                  JMP      OYVEY           ;Yes. What can we say...
  476.             NOIDIOCY:
  477.  
  478.           The latter, of course, is a jump around a jump. Some would say
  479.           it is evil, but I submit it is hard to avoid in this language.
  480.  
  481.       2)  Otherwise, within a block of code, I use conditional jumps
  482.           freely. If the block eventually grows so long that the assem-
  483.           bler starts complaining that my conditional jumps are too long
  484.           I,
  485.  
  486.           a)  consider reorganizing the block but
  487.           b)  also consider changing some conditional jumps to their
  488.               opposite and use the "jump around a jump" approach as shown
  489.               above.
  490.  
  491.   Enough about specific instructions!
  492.  
  493. 6. Finally, in order to use the assembler effectively, you need to know
  494.    the default rules for which segment registers are used to complete
  495.    addresses in which situations.
  496.  
  497.    a. CS is used to complete an address which is the target of a NEAR
  498.       DIRECT jump. On an NEAR INDIRECT jump, DS is used to fetch the
  499.       address from memory but then CS is used to complete the address
  500.       thus fetched. On FAR jumps, of course, CS is itself altered. The
  501.       instruction counter is always implicitly pointing in the code seg-
  502.       ment.
  503.  
  504.    b. SS is used to complete an address if BP is used in its formation.
  505.       Otherwise, DS is always used to complete a data address.
  506.  
  507.    c. On the string instructions, the target is always formed from ES and
  508.       DI. The source is normally formed from DS and SI. If there is a
  509.       segment prefix, it overrides the source not the target.
  510.  
  511. Learning about DOS
  512.  
  513. I think the best way to learn about DOS internals is to read the technical
  514. appendices in the manual. These are not as complete as we might wish, but
  515. they really aren't bad; I certainly have learned a lot from them. What you
  516. don't learn from them you might eventually learn via judicious disassembly
  517. of parts of DOS, but that shouldn't really be necessary.
  518.  
  519. From reading the technical appendices, you learn that interrupts 20H
  520. through 27H are used to communicate with DOS. Mostly, you will use inter-
  521. rupt 21H, the DOS function manager.
  522.  
  523. The function manager implements a great many services. You request the
  524. individual services by means of a function code in the AH register. For
  525. example, by putting a nine in the AH register and issuing interrupt 21H you
  526. tell DOS to print a message on the console screen.
  527.  
  528. Usually, but by no means always, the DX register is used to pass data for
  529. the service being requested. For example, on the print message service
  530. just mentioned, you would put the 16 bit address of the message in the DX
  531. register. The DS register is also implicitly part of this argument, in
  532. keeping with the universal segmentation rules.
  533.  
  534. In understanding DOS functions, it is useful to understand some history and
  535. also some of the philosophy of MS-DOS with regard to portability. General-
  536. ly, you will find, once you read the technical information on DOS and also
  537. the IBM technical reference, you will know more than one way to do almost
  538. anything. Which is best?  For example, to do asynch adapter I/O, you can
  539. use the DOS calls (pretty incomplete), you can use BIOS, or you can go
  540. directly to the hardware. The same thing is true for most of the other
  541. primitive I/O (keyboard or screen) although DOS is more likely to give you
  542. added value in these areas. When it comes to file I/O, DOS itself offers
  543. more than one interface. For example, there are four calls which read data
  544. from a file.
  545.  
  546. The way to decide rationally among these alternatives is by understanding
  547. the tradeoffs of functionality versus portability. Three kinds of porta-
  548. bility need to be considered:  machine portability, operating system porta-
  549. bility (for example, the ability to assemble and run code under CP/M 86)
  550. and DOS version portability (the ability for a program to run under older
  551. versions of DOS>.
  552.  
  553. Most of the functions originally offered in DOS 1.0 were direct descendents
  554. of CP/M functions; there is even a compatibility interface so that programs
  555. which have been translated instruction for instruction from 8080 assembler
  556. to 8086 assembler might have a reasonable chance of running if they use
  557. only the core CP/M function set. Among the most generally useful in this
  558. original compatibility set are
  559.  
  560.   09   --  print a full message on the screen
  561.   0A   --  get a console input line with full DOS editing
  562.   0F   --  open a file
  563.   10   --  close a file (really needed only when writing)
  564.   11   --  find first file matching a pattern
  565.   12   --  find next file matching a pattern
  566.   13   --  erase a file
  567.   16   --  create a file
  568.   17   --  rename a file
  569.   1A   --  set disk transfer address
  570.  
  571. The next set provide no function above what you can get with BIOS calls or
  572. more specialized DOS calls. However, they are preferable to BIOS calls
  573. when portability is an issue.
  574.  
  575.   00   --  terminate execution
  576.   01   --  read keyboard character
  577.   02   --  write screen character
  578.   03   --  read COM port character
  579.   04   --  write COM port character
  580.   05   --  print a character
  581.   06   --  read keyboard or write screen with no editing
  582.  
  583. The standard file I/O calls are inferior to the specialized DOS calls but
  584. have the advantage of making the program easier to port to CP/M style sys-
  585. tems. Thus they are worth mentioning:
  586.  
  587.   14   --  sequential read from file
  588.   15   --  sequential write to file
  589.   21   --  random read from file
  590.   22   --  random write to file
  591.   23   --  determine file size
  592.   24   --  set random record
  593.  
  594. In addition to the CP/M compatible services, DOS also offers some special-
  595. ized services which have been available in all releases of DOS. These
  596. include
  597.  
  598.   27   --  multi-record random read.
  599.   28   --  multi-record random write.
  600.   29   --  parse filename
  601.   2A-2D -- get and set date and time
  602.  
  603. All of the calls mentioned above which have anything to do with files make
  604. use of a data area called the "FILE CONTROL BLOCK" (FCB). The FCB is any-
  605. where from 33 to 37 bytes long depending on how it is used. You are
  606. responsible for creating an FCB and filling in the first 12 bytes, which
  607. contain a drive code, a file name, and an extension.
  608.  
  609. When you open the FCB, the system fills in the next 20 bytes, which
  610. includes a logical record length. The initial lrecl is always 128 bytes,
  611. to achieve CP/M compatibility. The system also provides other useful
  612. information such as the file size.
  613.  
  614. After you have opened the FCB, you can change the logical record length.
  615. If you do this, your program is no longer CP/M compatible, but that doesn't
  616. make it a bad thing to do. DOS documentation suggests you use a logical
  617. record length of one for maximum flexibility. This is usually a good
  618. recommendation.
  619.  
  620. To perform actual I/O to a file, you eventually need to fill in byte 33 or
  621. possibly bytes 34-37 of the FCB. Here you supply information about the
  622. record you are interested in reading or writing. For the most part, this
  623. part of the interface is compatible with CP/M.
  624.  
  625. In general, you do not need to (and should not) modify other parts of the
  626. FCB.
  627.  
  628. The FCB is pretty well described in appendix E of the DOS manual.
  629. Beginning with DOS 2.0, there is a whole new system of calls for managing
  630. files which don't require that you build an FCB at all. These calls are
  631. quite incompatible with CP/M and also mean that your program cannot run
  632. under older releases of DOS. However, these calls are very nice and easy
  633. to use. They have these characteristics
  634.  
  635. 1. To open, create, delete, or rename a file, you need only a character
  636.    string representing its name.
  637.  
  638. 2. The open and create calls return a 16 bit value which is simply placed
  639.    in the BX register on subsequent calls to refer to the file.
  640.  
  641. 3. There is not a separate call required to specify the data buffer.
  642.  
  643. 4. Any number of bytes can be transfered on a single call; no data area
  644.    must be manipulated to do this.
  645.  
  646. The "new" DOS calls also include comprehensive functions to manipulate the
  647. new chained directory structure and to allocate and free memory.
  648.  
  649. Learning the assembler
  650. ______________________
  651.  
  652. It is my feeling that many people can teach themselves to use the assembler
  653. by reading the MACRO Assembler manual if
  654.  
  655. 1. You have read and understood a book like Morse and thus have a feeling
  656.    for the instruction set
  657.  
  658. 2. You know something about DOS services and so can communicate with the
  659.    keyboard and screen and do something marginally useful with files. In
  660.    the absence of this kind of knowledge, you can't write meaningful prac-
  661.    tice programs and so will not progress.
  662.  
  663. 3. You have access to some good examples (the ones supplied with the
  664.    assembler are not good, in my opinion. I will try to supply you with
  665.    some more relevant ones.
  666.  
  667. 4. You ignore the things which are most confusing and least useful. Some
  668.    of the most confusing aspects of the assembler include the facilities
  669.    combining segments. But, you can avoid using all but the simplest of
  670.    these facilities in many cases, even while writing quite substantial
  671.    applications.
  672.  
  673. 5. The easiest kind of assembler program to write is a COM program. They
  674.    might seem harder, at first, then EXE programs because there is an
  675.    extra step involved in creating the executable file, but COM programs
  676.    are structurally very much simpler.
  677.  
  678. At this point, it is necessary to talk about COM programs and EXE programs.
  679. As you probably know, DOS supports two kinds of executable files. EXE pro-
  680. grams are much more general, can contain many segments, and are generally
  681. built by compilers and sometimes by the assembler. If you follow the lead
  682. given by the samples distributed with the assembler, you will end up with
  683. EXE programs. A COM program, in contrast, always contains just one
  684. segment, and receives control with all four segment registers containing
  685. the same value. A COM program, thus, executes in a simplified environment,
  686. a 64K address space. You can go outside this address space simply by tem-
  687. porarily changing one segment register, but you don't have to, and that is
  688. the thing which makes COM programs nice and simple. Let's look at a very
  689. simple one.
  690.  
  691. The classic text on writing programs for the C language says that the first
  692. thing you should write is a program which says
  693.  
  694.     HELLO, WORLD.
  695.  
  696. when invoked. What's sauce for C is sauce for assembler, so let's start
  697. with a HELLO program of our own. My first presentation of this will be
  698. bare bones, not stylistically complete, but just an illustration of what an
  699. assembler program absolutely has to have:
  700.  
  701. HELLO  SEGMENT                  ;Set up HELLO code and data section
  702.        ASSUME CS:HELLO,DS:HELLO ;Tell assembler about conditions at entry
  703.        ORG  100H                ;A .COM program begins with 100H byte prefix
  704. MAIN:  JMP  BEGIN               ;Control must start here
  705. MSG    DB   'Hello, world.$'    ;But it is generally useful to put data first
  706. BEGIN: MOV  DX,OFFSET MSG       ;Let DX --> message.
  707.        MOV  AH,9                ;Set DOS function code for printing a message
  708.        INT  21H                 ;Invoke DOS
  709.        RET                      ;Return to system
  710. HELLO  ENDS                     ;End of code and data section
  711.        END  MAIN                ;Terminate assembler and specify entry point
  712.  
  713. First, let's attend to some obvious points. The macro assembler uses the
  714. general form
  715.  
  716.    name    opcode    operands
  717.  
  718. Unlike the 370 assembler, though, comments are NOT set off from operands by
  719. blanks. The syntax uses blanks as delimiters within the operand field (see
  720. line 6 of the example) and so all comments must be set off by semi-colons.
  721.  
  722. Line comments are frequently set off with a semi-colon in column 1. I use
  723. this approach for block comments too, although there is a COMMENT statement
  724. which can be used to introduce a block comment.
  725.  
  726. Being an old 370 type, I like to see assembler code in upper case, although
  727. my comments are mixed case. Actually, the assembler is quite happy with
  728. mixed case anywhere.
  729.  
  730. As with any assembler, the core of the opcode set consists of opcodes which
  731. generate machine instructions but there are also opcodes which generate
  732. data and ones which function as instructions to the assembler itself, some-
  733. times called pseudo-ops. In the example, there are five lines which gener-
  734. ate machine code (JMP, MOV, MOV, INT, RET), one line which generates data
  735. (DB) and five pseudo-ops (SEGMENT, ASSUME, ORG, ENDS, and END).
  736. We will discuss all of them.
  737.  
  738. Now, about labels. You will see that some labels in the example end in a
  739. colon and some don't. This is just a bit confusing at first, but no real
  740. mystery. If a label is attached to a piece of code (as opposed to data),
  741. then the assembler needs to know what to do when you JMP to or CALL that
  742. label. By convention, if the label ends in a colon, the assembler will use
  743. the NEAR form of JMP or CALL. If the label does not end in a colon, it
  744. will use the FAR form. In practice, you will always use the colon on any
  745. label you are jumping to inside your program because such jumps are always
  746. NEAR; there is no reason to use a FAR jump within a single code section. I
  747. mention this, though, because leaving off the colon isn't usually trapped
  748. as a syntax error, it will generally cause something more abstruse to go
  749. wrong.
  750.  
  751. On the other hand, a label attached to a piece of data or a pseudo-op never
  752. ends in a colon.
  753.  
  754. Machine instructions will generally take zero, one or two operands. Where
  755. there are two operands, the one which receives the result goes on the left
  756. as in 370 assembler.
  757.  
  758. I tried to explain this before, now maybe it will be even clearer:  there
  759. are many more 8086 machine opcodes then there are assembler opcodes to rep-
  760. resent them. For example, there are five kinds of JMP, four kinds of CALL,
  761. two kinds of RET, and at least five kinds of MOV depending on how you count
  762. them. The macro assembler makes a lot of decisions for you based on the
  763. form taken by the operands or on attributes assigned to symbols elsewhere
  764. in your program. In the example above, the assembler will generate the
  765. NEAR DIRECT form of JMP because the target label BEGIN labels a piece of
  766. code instead of a piece of data (this makes the JMP DIRECT) and ends in a
  767. colon (this makes the JMP NEAR). The assembler will generate the immediate
  768. forms of MOV because the form OFFSET MSG refers to immediate data and
  769. because 9 is a constant. The assembler will generate the NEAR form of RET
  770. because that is the default and you have not told it otherwise.
  771. The DB (define byte) pseudo-op is an easy one:  it is used to put one or
  772. more bytes of data into storage. There is also a DW (define word)
  773. pseudo-op and a  DD (define doubleword) pseudo-op;  in the PC MACRO assem-
  774. bler, the fact that a label refers to a byte of storage, a word of storage,
  775. or a doubleword of storage can be very significant in ways which we will
  776. see presently.
  777.  
  778. About that OFFSET operator, I guess this is the best way to make the point
  779. about how the assembler decides what instruction to assemble:  an analogy
  780. with 370 assembler:
  781.  
  782.   PLACE    DC   ......
  783.          ...
  784.          LA   R1,PLACE
  785.          L    R1,PLACE
  786.  
  787. In 370 assembler, the first instruction puts the address of label PLACE in
  788. register 1, the second instruction puts the contents of storage at label
  789. PLACE in register 1. Notice that two different opcodes are used. In the
  790. PC assembler, the analogous instructions would be
  791.  
  792.   PLACE    DW   ......
  793.          ...
  794.          MOV  DX,OFFSET PLACE
  795.          MOV  DX,PLACE
  796.  
  797. If PLACE is the label of a word of storage, then the second instruction
  798. will be understood as a desire to fetch that data into DX. If X is a
  799. label, then "OFFSET X" means "the ordinary number which represents X's off-
  800. set from the start of the segment."  And, if the assembler sees an ordinary
  801. number, as opposed to a label, it uses the instruction which is equivalent
  802. to LA.
  803.  
  804. If PLACE were the label of a DB pseudo-op, instead of a DW, then
  805.          MOV  DX,PLACE
  806.  
  807. would be illegal. The assembler worries about length attributes of its
  808. operands.
  809.  
  810. Next, numbers and constants in general. The assembler's default radix is
  811. decimal. You can change this, but I don't recommend it. If you want to
  812. represent numbers in other forms of notation such as hex or bit, you gener-
  813. ally use a trailing letter. For example,
  814.  
  815.          21H
  816.   is hexidecimal 21,
  817.  
  818.          00010000B
  819.   is the eight bit binary number pictured.
  820.  
  821. The next elements we should point to are the SEGMENT...ENDS pair and the
  822. END instruction. Every assembler program has to have these elements.
  823. SEGMENT tells the assembler you are starting a section of contiguous mate-
  824. rial (code and/or data). The symmetrically named ENDS statement tells the
  825. assembler you are finished with a section of contiguous material. I wish
  826. they didn't use the word SEGMENT in this context. To me, a "segment" is a
  827. hardware construct:  it is the 64K of real storage which becomes address-
  828. able by virtue of having a particular value in a segment register. Now, it
  829. is true that the "segments" you make with the assembler often correspond to
  830. real hardware "segments" at execution time. But, if you look at things
  831. like the GROUP and CLASS options supported by the linker, you will discover
  832. that this correspondence is by no means exact. So, at risk of maybe con-
  833. fusing you even more, I am going to use the more informal term "section" to
  834. refer to the area set off by means of the SEGMENT and ENDS instructions.
  835. The sections delimited by SEGMENT...ENDS pairs are really a lot like CSECTs
  836. and DSECTs in the 370 world.
  837.  
  838. I strongly recommend that you be selective in your study of the SEGMENT
  839. pseudo-op as described in the manual. Let me just touch on it here.
  840.  
  841.   name     SEGMENT
  842.   name     SEGMENT  PUBLIC
  843.   name     SEGMENT  AT  nnn
  844.  
  845. Basically, you can get away with just the three forms given above. The
  846. first form is what you use when you are writing a single section of assem-
  847. bler code which will not be combined with other pieces of code at link
  848. time.  The second form says that this assembly only contains part of the
  849. section;  other parts might be assembled separately and combined later by
  850. the linker.
  851.  
  852. I have found that one can construct reasonably large modular applications
  853. in assembler by simply making every assembly use the same segment name and
  854. declaring the name to be PUBLIC each time. If you read the assembler and
  855. linker documentation, you will also be bombarded by information about more
  856. complex options such as the GROUP statement and the use of other "combine
  857. types" and "classes."  I don't recommend getting into any of that. I will
  858. talk more about the linker and modular construction of programs a little
  859. later. The assembler manual also implies that a STACK segment is required.
  860. This is not really true. There are numerous ways to assure that you have a
  861. valid stack at execution time.
  862.  
  863. Of course, if you plan to write applications in assembler which are more
  864. than 64K in size, you will need more than what I have told you; but who is
  865. really going to do that?  Any application that large is likely to be coded
  866. in a higher level language.
  867.  
  868. The third form of the SEGMENT statement makes the delineated section into
  869. something like a "DSECT;" that is, it doesn't generate any code, it just
  870. describes what is present somewhere already in the computer's memory.
  871. Sometimes the AT value you give is meaningful. For example, the BIOS work
  872. area is located at location 40 hex. So, you might see
  873.  
  874.   BIOSAREA  SEGMENT AT 40H      ;Map BIOS work area
  875.             ORG  BIOSAREA+10H
  876.   EQUIP     DB   ?              ;Location of equipment flags, first byte
  877.   BIOSAREA  ENDS
  878.  
  879. in a program which was interested in mucking around in the BIOS work area.
  880. At other times, the AT value you give may be arbitrary, as when you are
  881. mapping a repeated control block:
  882.  
  883.   PROGPREF SEGMENT   AT 0      ;Really a DSECT mapping the program prefix
  884.            ORG   PROGPREF+6
  885.   MEMSIZE  DW   ?              ;Size of available memory
  886.   PROGPREF ENDS
  887.  
  888. Really, no matter whether the AT value represents truth or fiction, it is
  889. your responsibility, not the assembler's, to get set up a segment register
  890. so that you can really reach the storage in question.   So, you can't say
  891.  
  892.          MOV  AL,EQUIP
  893.  
  894. unless you first say something like
  895.  
  896.          MOV  AX,BIOSAREA   ;BIOSAREA becomes a symbol with value 40H
  897.          MOV  ES,AX
  898.          ASSUME ES:BIOSAREA
  899.  
  900. Enough about SEGMENT.  The END statement is simple.  It goes at the end of
  901. every assembly.  When you are assembling a subroutine, you just say
  902.  
  903.          END
  904.  
  905. but when you are assembling the main routine of a program you say
  906.  
  907.         END label
  908.  
  909. where 'label' is the place where execution is to begin.
  910.  
  911. Another pseudo-op illustrated in the program is ASSUME.  ASSUME is like the
  912. USING statement in 370 assembler.  However, ASSUME can ONLY refer to seg-
  913. ment registers.  The assembler uses ASSUME information to decide whether to
  914. assemble segment override prefixes and to check that the data you are try-
  915. ing to access is really accessible.  In this case, we can reassure the
  916. assembler that both the CS and DS registers will address the section called
  917. HELLO at execution time.  Actually, the SS and ES registers will too, but
  918. the assembler never needs to make use of this information.
  919.  
  920. I guess I have explained everything in the program except that ORG
  921. pseudo-op.  ORG means the same thing as it does in many assembly languages.
  922. It tells the assembler to move its location counter to some particular
  923. address.  In this case, we have asked the assembler to start assembling
  924. code hex 100 bytes from the start of the section called HELLO instead of at
  925. the very beginning.  This simply reflects the way COM programs are loaded.
  926. When a COM program is loaded by the system, the system sets up all four
  927. segment registers to address the same 64K of storage.  The first 100 hex
  928. bytes of that storage contains what is called the program prefix; this area
  929. is described in appendix E of the DOS manual.  Your COM program physically
  930. begins after this.  Execution begins with the first physical byte of your
  931. program; that is why the JMP instruction is there.
  932.  
  933. Wait a minute, you say, why the JMP instruction at all?  Why not put the
  934. data at the end?  Well, in a simple program like this I probably could have
  935. gotten away with that.  However, I have the habit of putting data first and
  936. would encourage you to do the same because of the way the assembler has of
  937. assembling different instructions depending on the nature of the operand.
  938.  
  939. Unfortunately, sometimes the different choices of instruction which can
  940. assemble from a single opcode have different lengths.  If the assembler has
  941. already seen the data when it gets to the instructions it has a good chance
  942. of reserving the right number of bytes on the first pass.  If the data is
  943. at the end, the assembler may not have enough information on the first pass
  944. to reserve the right number of bytes for the instruction.  Sometimes the
  945. assembler will complain about this, something like "Forward reference is
  946. illegal" but at other times, it will make some default assumption.  On the
  947. second pass, if the assumption turned out to be wrong, it will report what
  948. is called a "Phase error," a very nasty error to track down.  So get in the
  949. habit of putting data and equated symbols ahead of code.
  950.  
  951. OK.  Maybe you understand the program now.  Let's walk through the steps
  952. involved in making it into a real COM file.
  953.  
  954. 1.  The file should be created with the name HELLO.ASM (actually the name
  955.     is arbitrary but the extension .ASM is conventional and useful)
  956.  
  957. 2.  ASM   HELLO,,;
  958.  
  959.     (this is just one example of invoking the assembler; it uses the small
  960.     assembler ASM, it produces an object file and a listing file with the
  961.     same name as the source file.  I am not going exhaustively into how to
  962.     invoke the assembler, which the manual goes into pretty well.  I guess
  963.     this is the first time I mentioned that there are really two
  964.     assemblers; the small assembler ASM will run in a 64K machine and
  965.     doesn't support macros.  I used to use it all the time; now that I have
  966.     a bigger machine and a lot of macro libraries I use the full function
  967.     assembler MASM.  You get both when you buy the package).
  968.  
  969. 3.  If you issue DIR at this point, you will discover that you have
  970.     acquired HELLO.OBJ (the object code resulting from the assembly) and
  971.     HELLO.LST (a listing file).  I guess I can digress for a second here
  972.     concerning the listing file.  It contains TAB characters.  I have found
  973.     there are two good ways to get it printed and one bad way.  The bad way
  974.     is to use LPT1: as the direct target of the listing file or to try
  975.     copying the LST file to LPT1 without first setting the tabs on the
  976.     printer.  The two good ways are to either
  977.  
  978.     a.  direct it to the console and activate the printer with CTRL-PRTSC.
  979.         In this case, DOS will expand the tabs for you.
  980.  
  981.     b.  direct to LPT1: but first send the right escape sequence to LPT1 to
  982.         set the tabs every eight columns.  I have found that on some early
  983.         serial numbers of the IBM PC printer, tabs don't work quite right,
  984.         which forces you to the first option.
  985.  
  986. 4.  LINK  HELLO;
  987.  
  988.     (again, there are lots of linker options but this is the simplest.  It
  989.     takes HELLO.OBJ and makes HELLO.EXE).  HELLO.EXE?  I thought we were
  990.     making a COM program, not an EXE program.  Right.  HELLO.EXE isn't
  991.     really executable; its just that the linker doesn't know about COM pro-
  992.     grams.  That requires another utility.  You don't have this utility if
  993.     you are using DOS 1.0; you have it if you are using DOS 1.1 or DOS 2.0.
  994.     Oh, by the way, the linker will warn you that you have no stack
  995.     segment.  Don't worry about it.
  996.  
  997. 5.  EXE2BIN  HELLO HELLO.COM
  998.  
  999.     This is the final step.  It produces the actual program you will exe-
  1000.     cute.  Note that you have to spell out HELLO.COM; for a nominally
  1001.     rational but actually perverse reason, EXE2BIN uses the default exten-
  1002.     sion BIN instead of COM for its output file.  At this point, you might
  1003.     want to erase HELLO.EXE; it looks a lot more useful than it is.
  1004.     Chances are you won't need to recreate HELLO.COM unless you change the
  1005.     source and then you are going to have to redo the whole thing.
  1006.  
  1007. 6.  HELLO
  1008.  
  1009.     You type hello, that invokes the program, it says
  1010.           HELLO YOURSELF!!!
  1011.     (oops, what did I do wrong....?)
  1012.  
  1013. What about subroutines?
  1014. _______________________
  1015.  
  1016. I started with a simple COM program because I actually think they are easi-
  1017. er to create than subroutines to be called from high level languages, but
  1018. maybe its really the latter you are interested in.  Here, I think you
  1019. should get comfortable with the assembler FIRST with little exercises like
  1020. the one above and also another one which I will finish up with.
  1021.  
  1022. Next you are ready to look at the interface information for your particular
  1023. language.  You usually find this in some sort of an appendix.  For example,
  1024. the BASIC manual has Appendix C on Machine Language Subroutines.  The
  1025. PASCAL manual buries the information a little more deeply:  the interface
  1026. to a separately compiled routine can be found in the Chapter on Procedures
  1027. and Functions, in a subsection called Internal Calling Conventions.
  1028. Each language is slightly different, but here are what I think are some
  1029. common issues in subroutine construction.
  1030.  
  1031. 1.  NEAR versus FAR?  Most of the time, your language will probably call
  1032.     your assembler routine as a FAR routine.  In this case, you need to
  1033.     make sure the assembler will generate the right kind of return.  You do
  1034.     this with a PROC...ENDP statement pair.  The PROC statement is probably
  1035.     a good idea for a NEAR routine too even though it is not strictly
  1036.     required:
  1037.  
  1038.               FAR linkage:        |            NEAR linkage:
  1039.                                   |
  1040.     ARBITRARY SEGMENT             |  SPECIFIC  SEGMENT  PUBLIC
  1041.               PUBLIC THENAME      |            PUBLIC THENAME
  1042.               ASSUME CS:ARBITRARY |            ASSUME CS:SPECIFIC,DS:SPECIFIC
  1043.     THENAME   PROC FAR            |            ASSUME ES:SPECIFIC,SS:SPECIFIC
  1044.               ..... code and data |  THENAME   PROC NEAR
  1045.     THENAME   ENDP                |            ..... code and data ....
  1046.     ARBITRARY ENDS                |  THENAME   ENDP
  1047.               END                 |  SPECIFIC  ENDS
  1048.                                   |            END
  1049.  
  1050.     With FAR linkage, it doesn't really matter what you call the segment.
  1051.     you must declare the name by which you will be called in a PUBLIC pseu-
  1052.     do-op and also show that it is a FAR procedure.  Only CS will be ini-
  1053.     tialized to your segment when you are called.  Generally, the other
  1054.     segment registers will continue to point to the caller's segments.
  1055.     With NEAR linkage, you are executing in the same segment as the caller.
  1056.     Therefore, you must give the segment a specific name as instructed by
  1057.     the language manual.  However, you may be able to count on all segment
  1058.     registers pointing to your own segment (sometimes the situation can be
  1059.     more complicated but I cannot really go into all of the details).  You
  1060.     should be aware that the code you write will not be the only thing in
  1061.     the segment and will be physically relocated within the segment by the
  1062.     linker.  However, all OFFSET references will be relocated and will be
  1063.     correct at execution time.
  1064.  
  1065. 2.  Parameters passed on the stack.  Usually, high level languages pass
  1066.     parameters to subroutines by pushing words onto the stack prior to
  1067.     calling you.  What may differ from language to language is the nature
  1068.     of what is pushed (OFFSET only or OFFSET and SEGMENT) and the order in
  1069.     which it is pushed (left to right, right to left within the CALL state-
  1070.     ment).  However, you will need to study the examples to figure out how
  1071.     to retrieve the parameters from the stack.  A useful fact to exploit is
  1072.     the fact that a reference involving the BP register defaults to a ref-
  1073.     erence to the stack segment.  So, the following strategy can work:
  1074.  
  1075.       ARGS     STRUC
  1076.                DW   3 DUP(?)  ;Saved BP and return address
  1077.       ARG3     DW   ?
  1078.       ARG2     DW   ?
  1079.       ARG1     DW   ?
  1080.       ARGS     ENDS
  1081.            ...........
  1082.                PUSH BP                 ;save BP register
  1083.                MOV  BP,SP              ;Use BP to address stack
  1084.                MOV   ...,[BP].ARG2     ;retrieve second argument
  1085.                (etc.)
  1086.  
  1087.     This example uses something called a structure, which is only available
  1088.     in the large assembler; furthermore, it uses it without allocating it,
  1089.     which is not a well-documented option.  However, I find the above
  1090.     approach generally pleasing.  The STRUC is like a DSECT in that it
  1091.     establishes labels as being offset a certain distance from an arbitrary
  1092.     point; these labels are then used in the body of code by beginning them
  1093.     with a period; the construction ".ARG2" means, basically, " +
  1094.     (ARG2-ARGS)."
  1095.  
  1096.     What you are doing here is using BP to address the stack, accounting
  1097.     for the word where you saved the caller's BP and also for the two words
  1098.     which were pushed by the CALL instruction.
  1099.  
  1100. 3.  How big is the stack?  BASIC only gives you an eight word stack to play
  1101.     with.  On the other hand, it doesn't require you to save any registers
  1102.     except the segment registers.  Other languages give you a liberal
  1103.     stack, which makes things a lot easier.  If you have to create a new
  1104.     stack segment for yourself, the easiest thing is to place the stack at
  1105.     the end of your program and:
  1106.  
  1107.          CLI                      ;suppress interrupts while changing the stack
  1108.          MOV  SSAVE,SS            ;save old SS in local storage (old SP
  1109.                                   ; already saved in BP)
  1110.          MOV  SP,CS               ;switch
  1111.          MOV  SS,SP               ;the
  1112.          MOV  SP,OFFSET STACKTOP  ;stack
  1113.          STI                      ;(maybe)
  1114.  
  1115.     Later, you can reverse these steps before returning to the caller.  At
  1116.     the end of your program, you place the stack itself:
  1117.  
  1118.              DW   128 DUP(?)          ;stack of 128 words (liberal)
  1119.     STACKTOP LABEL WORD
  1120.  
  1121. 4.  Make sure you save and restore those registers required by the caller.
  1122.  
  1123. 5.  Be sure to get the right kind of addressibility.  In the FAR call exam-
  1124.     ple, only CS addresses your segment.  If you are careful with your
  1125.     ASSUME statements the assembler will keep track of this fact and gener-
  1126.     ate CS prefixes when you make data references; however, you might want
  1127.     to do something like
  1128.  
  1129.                     MOV AX,CS      ;get current segment address
  1130.                     MOV DS,AX      ;To DS
  1131.                     ASSUME DS:THISSEG
  1132.  
  1133.     Be sure you keep your ASSUMEs in synch with reality.
  1134.  
  1135. Learning about BIOS and the hardware
  1136. ____________________________________
  1137.  
  1138. You can't do everything with DOS calls.  You may need to learn something
  1139. about the BIOS and about the hardware itself.  In this, the Technical Ref-
  1140. erence is a very good thing to look at.
  1141.  
  1142. The first thing you look at in the Technical Reference, unless you are
  1143. really determined to master the whole ball of wax, is the BIOS listings
  1144. presented in Appendix A. Glory be:  here is the whole 8K of ROM which deals
  1145. with low level hardware support layed out with comments and everything.
  1146. In fact, if you are just interested in learning what BIOS can do for you,
  1147. you just need to read the header comments at the beginning of each section
  1148. of the listing.
  1149.  
  1150. BIOS services are invoked by means of the INT instruction; the BIOS occu-
  1151. pies interrupts 10H through 1FH and also interrupt 5H; actually, of these
  1152. seventeen interrupts, five are used for user exit points or data pointers,
  1153. leaving twelve actual services.
  1154.  
  1155. In most cases, a service deals with a particular hardware interface; for
  1156. example, BIOS interrupt 10H deals with the screen.  As with DOS function
  1157. calls, many BIOS services can be passed a function code in the AH register
  1158. and possible other arguments.
  1159.  
  1160. I am not going to summarize the most useful BIOS features here; you will
  1161. see some examples in the next sample program we will look at.
  1162. The other thing you might want to get into with the Tech reference is the
  1163. description of some hardware options, particularly the asynch adapter,
  1164. which are not well supported in the BIOS.  The writeup on the asynch adapt-
  1165. er is pretty complete.
  1166.  
  1167. Actually, the Tech reference itself is pretty complete and very nice as far
  1168. as it goes.  One thing which is missing from the Tech reference is informa-
  1169. tion on the programmable peripheral chips on the system board.  These
  1170. include
  1171.  
  1172.       the 8259 interrupt controller
  1173.       the 8253 timer
  1174.       the 8237 DMA controller and
  1175.       the 8255 peripheral interface
  1176.  
  1177. To make your library absolutely complete, you should order the INTEL data
  1178. sheets for these beasts.
  1179.  
  1180. I should say, though, that the only I ever found I needed to know about was
  1181. the interrupt controller.  If you happen to have the 8086 Family User's
  1182. Manual, the big book put out by INTEL, which is one of the things people
  1183. sometimes buy to learn about 8086 architecture, there is an appendix there
  1184. which gives an adequate description of the 8259.
  1185.  
  1186. A final example
  1187. _______________
  1188.  
  1189. I leave you with a more substantial example of code which illustrates some
  1190. good elementary techniques; I won't claim its style is perfect, but I think
  1191. it is adequate.  I think this is a much more useful example than what you
  1192. will get with the assembler:
  1193.  
  1194.           PAGE 61,132
  1195.           TITLE SETSCRN -- Establish correct monitor use at boot time
  1196. ;
  1197. ;         This program is a variation on many which toggle the equipment flags
  1198. ;         to support the use of either video option (monochrome or color).
  1199. ;         The thing about this one is it prompts the user in such a way that he
  1200. ;         can select the use of the monitor he is currently looking at (or which
  1201. ;         is currently connected or turned on) without really having to know
  1202. ;         which is which.  SETSCRN is a good program to put first in an
  1203. ;         AUTOEXEC.BAT file.
  1204. ;
  1205. ;         This program is highly dependent on the hardware and BIOS of the IBMPC
  1206. ;         and is hardly portable, except to very exact clones.  For this reason,
  1207. ;         BIOS calls are used in lieu of DOS function calls where both provide
  1208. ;         equal function.
  1209. ;
  1210.  
  1211. OK.  That's the first page of the program.  Notice the PAGE statement,
  1212. which you can use to tell the assembler how to format the listing.  You
  1213. give it lines per page and characters per line.  I have mine setup to print
  1214. on the host lineprinter; I routinely upload my listings at 9600 baud and
  1215. print them on the host; it is faster than using the PC printer.
  1216. There is also a TITLE statement.  This simply provides a nice title for
  1217. each page of your listing.  Now for the second page:
  1218.  
  1219.           SUBTTL -- Provide .COM type environment and Data
  1220.           PAGE
  1221. ;
  1222. ;         First, describe the one BIOS byte we are interested in
  1223. ;
  1224. BIOSDATA  SEGMENT   AT 40H    ;Describe where BIOS keeps his data
  1225.           ORG       10H       ;Skip parts we are not interested in
  1226. EQUIP     DB        ?         ;Equipment flag location
  1227. MONO      EQU       00110000B ;These bits on if monochrome
  1228. COLOR     EQU       11101111B ;Mask to make BIOS think of the color board
  1229. BIOSDATA  ENDS                ;End of interesting part
  1230. ;
  1231. ;         Next, describe some values for interrupts and functions
  1232. ;
  1233. DOS       EQU       21H       ;DOS Function Handler INT code
  1234. PRTMSG    EQU       09H       ;Function code to print a message
  1235. KBD       EQU       16H       ;BIOS keyboard services INT code
  1236. GETKEY    EQU       00H       ;Function code to read a character
  1237. SCREEN    EQU       10H       ;BIOS Screen services INT code
  1238. MONOINIT  EQU       02H       ;Value to initialize monochrome screen
  1239. COLORINIT EQU       03H       ;Value to initialize color screen (80x25)
  1240. ;COLORINIT EQU      01H       ;Value to initialize color screen (40X25)
  1241. ;
  1242. ;         Now, describe our own segment
  1243. ;
  1244. SETSCRN   SEGMENT             ;Set operating segment for CODE and DATA
  1245. ;
  1246.           ASSUME CS:SETSCRN,DS:SETSCRN,ES:SETSCRN,SS:SETSCRN    ;All segments
  1247. ;
  1248.           ORG       100H      ;Begin assembly at standard .COM offset
  1249. ;
  1250. MAIN      PROC      NEAR      ;COM files use NEAR linkage
  1251.           JMP       BEGIN     ;And, it is helpful to put the data first, but
  1252. ;                             ;then you must branch around it.
  1253. ;
  1254. ;         Data used in SETSCRN
  1255. ;
  1256. CHANGELOC   DD      EQUIP     ;Location of the EQUIP, recorded as far pointer
  1257. MONOPROMPT  DB      'Please press the plus ( + ) key.$'    ;User sees on mono
  1258. COLORPROMPT DB      'Please press the minus ( - ) key.$'   ;User sees on color
  1259.  
  1260.  
  1261. Several things are illustrated on this page.  First, in addition to titles,
  1262. the assembler supports subtitles:  hence the SUBTTL pseudo-op.  Second, the
  1263. PAGE pseudo-op can be used to go to a new page in the listing.  You see an
  1264. example here of the DSECT-style segment in the "SEGMENT AT 40H".  Here, our
  1265. our interest is in correctly describing the location of some data in the
  1266. BIOS work area which really is located at segment 40H.
  1267.  
  1268. You will also see illustrated the EQU instruction, which just gives a sym-
  1269. bolic name to a number.  I don't make a fetish of giving a name to every
  1270. single number in a program.  I do feel strongly, though, that interrupts
  1271. and function codes, where the number is arbitrary and the function being
  1272. performed is the thing of interest, should always be given symbolic names.
  1273.  
  1274. One last new element in this section is the define doubleword (DD) instruc-
  1275. tion.  A doubleword constant can refer, as in this case, to a location in
  1276. another segment.  The assembler will be happy to use information at its
  1277. disposal to properly assemble it.  In this case, the assembler knows that
  1278. EQUIP is offset 10 in the segment BIOSDATA which is at 40H.
  1279.  
  1280.           SUBTTL -- Perform function
  1281.           PAGE
  1282. BEGIN:    CALL      MONOON                  ;Turn on mono display
  1283.           MOV       DX,OFFSET MONOPROMPT          ;GET MONO PROMPT
  1284.           MOV       AH,PRTMSG                     ;ISSUE
  1285.           INT       DOS                           ;IT
  1286.           CALL      COLORON                 ;Turn on color display
  1287.           MOV       DX,OFFSET COLORPROMPT         ;GET COLOR PROMPT
  1288.           MOV       AH,PRTMSG                     ;ISSUE
  1289.           INT       DOS                           ;IT
  1290.           MOV       AH,GETKEY               ;Obtain user response
  1291.           INT       KBD
  1292.           CMP       AL,'+'                  ;Does he want MONO?
  1293.           JNZ       NOMONO
  1294.           CALL      MONOON                  ;yes.  give it to him
  1295. NOMONO:   RET
  1296. MAIN      ENDP
  1297.  
  1298. The main code section makes use of subroutines to keep the basic flow sim-
  1299. ple.  About all that's new to you in this section is the use of the BIOS
  1300. interrupt KBD to read a character from the keyboard.
  1301.  
  1302. Now for the subroutines, MONOON and COLORON:
  1303.  
  1304.           SUBTTL -- Routines to turn monitors on
  1305.           PAGE
  1306. MONOON    PROC      NEAR                ;Turn mono on
  1307.           LES       DI,CHANGELOC        ;Get location to change
  1308.           ASSUME    ES:BIOSDATA         ;TELL ASSEMBLER ABOUT CHANGE TO ES
  1309.           OR        EQUIP,MONO
  1310.           MOV       AX,MONOINIT         ;Get screen initialization value
  1311.           INT       SCREEN              ;Initialize screen
  1312.           RET
  1313. MONOON    ENDP
  1314. COLORON   PROC      NEAR                ;Turn color on
  1315.           LES       DI,CHANGELOC        ;Get location to change
  1316.           ASSUME    ES:BIOSDATA         ;TELL ASSEMBLER ABOUT CHANGE TO ES
  1317.           AND       EQUIP,COLOR
  1318.           MOV       AX,COLORINIT        ;Get screen initialization value
  1319.           INT       SCREEN              ;Initialize screen
  1320.           RET
  1321. COLORON   ENDP
  1322. SETSCRN   ENDS                          ;End of segment
  1323.           END       MAIN                ;End of assembly; execution at MAIN
  1324.  
  1325.  
  1326. The instructions LES and LDS are useful ones for dealing with doubleword
  1327. addresses.  The offset is loaded into the operand register and the segment
  1328. into ES (for LES) or DS (for LDS).  By telling the assembler, with an
  1329. ASSUME, that ES now addresses the BIOSDATA segment, it is able to correctly
  1330. assemble the OR and AND instructions which refer to the EQUIP byte.  An ES
  1331. segment prefix is added.
  1332.  
  1333. To understand the action here, you simply need to know that flags in that
  1334. particular byte control how the BIOS screen service initializes the adapt-
  1335. ers.  BIOS will only work with one adapter at a time; by setting the equip-
  1336. ment flags to show one or the other as installed and calling BIOS screen
  1337. initialization, we achieve the desired effect.
  1338.  
  1339. The rest is up to you.
  1340.  
  1341.  
  1342.