home *** CD-ROM | disk | FTP | other *** search
/ Hackers Toolkit v2.0 / Hackers_Toolkit_v2.0.iso / HTML / archive / Unix / HOWTOs / ASSEMBLY < prev    next >
Text File  |  1999-11-04  |  55KB  |  1,585 lines

  1.   Assembly HOWTO
  2.   Franois-Ren Rideau rideau@ens.fr
  3.   v0.4l, 16 November 1997
  4.  
  5.   This is the Linux Assembly HOWTO.  This document describes how to pro-
  6.   gram in assembly using FREE programming tools, focusing on development
  7.   for or from the Linux Operating System on i386 platforms.  Included
  8.   material may or may not be applicable to other hardware and/or soft-
  9.   ware platforms.  Contributions about these would be gladly accepted.
  10.   keywords: assembly, assembler, free, macroprocessor, preprocessor,
  11.   asm, inline asm, 32-bit, x86, i386, gas, as86, nasm
  12.   ______________________________________________________________________
  13.  
  14.   Table of Contents
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.   1. INTRODUCTION
  68.  
  69.      1.1 Legal Blurp
  70.      1.2 IMPORTANT NOTE
  71.      1.3 Foreword
  72.         1.3.1 How to use this document
  73.         1.3.2 Other related documents
  74.      1.4 History
  75.      1.5 Credits
  76.  
  77.   2. DO YOU NEED ASSEMBLY?
  78.  
  79.      2.1 Pros and Cons
  80.         2.1.1 The advantages of Assembly
  81.         2.1.2 The disadvantages of Assembly
  82.         2.1.3 Assessment
  83.      2.2 How to NOT use Assembly
  84.         2.2.1 General procedure to achieve efficient code
  85.         2.2.2 Languages with optimizing compilers
  86.         2.2.3 General procedure to speed your code up
  87.         2.2.4 Inspecting compiler-generated code
  88.  
  89.   3. ASSEMBLERS
  90.  
  91.      3.1 GCC Inline Assembly
  92.         3.1.1 Where to find GCC
  93.         3.1.2 Where to find docs for GCC Inline Asm
  94.         3.1.3 Invoking GCC to have it properly inline assembly code ?
  95.      3.2 GAS
  96.         3.2.1 Where to find it
  97.         3.2.2 What is this AT&T syntax
  98.         3.2.3 Limited 16-bit mode
  99.      3.3 GASP
  100.         3.3.1 Where to find GASP
  101.         3.3.2 How it works
  102.      3.4 NASM
  103.         3.4.1 Where to find NASM
  104.         3.4.2 What it does
  105.      3.5 AS86
  106.         3.5.1 Where to get AS86
  107.         3.5.2 How to invoke the assembler?
  108.         3.5.3 Where to find docs
  109.         3.5.4 What if I can't compile Linux anymore with this new version ?
  110.      3.6 OTHER ASSEMBLERS
  111.         3.6.1 Win32Forth assembler
  112.         3.6.2 Terse
  113.         3.6.3 Non-free and/or Non-32bit x86 assemblers.
  114.  
  115.   4. METAPROGRAMMING/MACROPROCESSING
  116.  
  117.      4.1 What's integrated into the above
  118.         4.1.1 GCC
  119.         4.1.2 GAS
  120.         4.1.3 GASP
  121.         4.1.4 NASM
  122.         4.1.5 AS86
  123.         4.1.6 OTHER ASSEMBLERS
  124.      4.2 External Filters
  125.         4.2.1 CPP
  126.         4.2.2 M4
  127.         4.2.3 Macroprocessing with yer own filter
  128.         4.2.4 Metaprogramming
  129.            4.2.4.1 Backends from existing compilers
  130.            4.2.4.2 The New-Jersey Machine-Code Toolkit
  131.            4.2.4.3 Tunes
  132.  
  133.   5. CALLING CONVENTIONS
  134.  
  135.      5.1 Linux
  136.         5.1.1 Linking to GCC
  137.         5.1.2 ELF vs a.out problems
  138.         5.1.3 Direct Linux syscalls
  139.         5.1.4 I/O under Linux
  140.         5.1.5 Accessing 16-bit drivers from Linux/i386
  141.      5.2 DOS
  142.      5.3 Winblows and suches
  143.      5.4 Yer very own OS
  144.  
  145.   6. TODO & POINTERS
  146.  
  147.  
  148.  
  149.   ______________________________________________________________________
  150.  
  151.   1.  INTRODUCTION
  152.  
  153.   1.1.  Legal Blurp
  154.  
  155.   Copyright (C) 1996,1997 by Franois-Ren Rideau.  This document may be
  156.   distributed under the terms set forth in the LDP license at
  157.   <http://sunsite.unc.edu/LDP/COPYRIGHT.html>.
  158.  
  159.  
  160.  
  161.   1.2.  IMPORTANT NOTE
  162.  
  163.   This is expectedly the last release I'll make of this document.
  164.   There's one candidate new maintainer, but until he really takes the
  165.   HOWTO over, I'll accept feedback.
  166.  
  167.   You are especially invited to ask questions, to answer to questions,
  168.   to correct given answers, to add new FAQ answers, to give pointers to
  169.   other software, to point the current maintainer to bugs or
  170.   deficiencies in the pages.  If you're motivated, you could even TAKE
  171.   OVER THE MAINTENANCE OF THE FAQ.  In one word, contribute!
  172.  
  173.   To contribute, please contact whoever appears to maintain the
  174.   Assembly-HOWTO.  Current maintainers are Franois-Ren Rideau
  175.   <mailto:rideau@clipper.ens.fr> and now Paul Anderson
  176.   <mailto:paul@geeky1.ebtech.net>.
  177.  
  178.  
  179.  
  180.   1.3.  Foreword
  181.  
  182.   This document aims at answering frequently asked questions of people
  183.   who program or want to program 32-bit x86 assembly using free
  184.   assemblers, particularly under the Linux operating system.  It may
  185.   also point to other documents about non-free, non-x86, or non-32-bit
  186.   assemblers, though such is not its primary goal.
  187.  
  188.   Because the main interest of assembly programming is to build to write
  189.   the guts of operating systems, interpreters, compilers, and games,
  190.   where a C compiler fails to provide the needed expressivity
  191.   (performance is more and more seldom an issue), we stress on
  192.   development of such software.
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.   1.3.1.  How to use this document
  200.  
  201.   This document contains answers to some frequently asked questions.  At
  202.   many places, Universal Resource Locators (URL) are given for some
  203.   software or documentation repository.  Please see that the most useful
  204.   repositories are mirrored, and that by accessing a nearer mirror site,
  205.   you relieve the whole Internet from unneeded network traffic, while
  206.   saving your own precious time.  Particularly, there are large
  207.   repositories all over the world, that mirror other popular
  208.   repositories.  You should learn and note what are those places near
  209.   you (networkwise).  Sometimes, the list of mirrors is listed in a
  210.   file, or in a login message. Please heed the advice.  Else, you should
  211.   ask archie about the software you're looking for...
  212.  
  213.   The most recent version for this documents sits in
  214.  
  215.   <http://www.eleves.ens.fr:8080/home/rideau/Assembly-HOWTO> or
  216.   <http://www.eleves.ens.fr:8080/home/rideau/Assembly-HOWTO.sgml>
  217.  
  218.   but what's in Linux HOWTO repositories should be fairly up to date,
  219.   too (I can't know):
  220.  
  221.   <ftp://sunsite.unc.edu/pub/Linux/docs/HOWTO/> (?)
  222.  
  223.   A french translation of this HOWTO can be found around
  224.  
  225.   <ftp://ftp.ibp.fr/pub/linux/french/HOWTO/>
  226.  
  227.  
  228.  
  229.   1.3.2.  Other related documents
  230.  
  231.  
  232.   o  If you don't know what free software is, please do read carefully
  233.      the GNU General Public License, which is used in a lot of free
  234.      software, and is a model for most of their licenses.  It generally
  235.      comes in a file named COPYING, with a library version in a file
  236.      named COPYING.LIB.  Litterature from the FSF (free software
  237.      foundation) might help you, too.
  238.  
  239.   o  Particularly, the interesting kind of free software comes with
  240.      sources that you can consult and correct, or sometimes even borrow
  241.      from.  Read your particular license carefully, and do comply to it.
  242.  
  243.   o  There is a FAQ for comp.lang.asm.x86 that answers generic questions
  244.      about x86 assembly programming, and questions about some commercial
  245.      assemblers in a 16-bit DOS environment.  Some of it apply to free
  246.      32-bit asm programming, so you may want to read this FAQ...
  247.  
  248.      <http://www2.dgsys.com/~raymoon/faq/asmfaq.zip>
  249.  
  250.   o  FAQs and docs exist about programming on your favorite platform,
  251.      whichever it is, that you should consult for platform-specific
  252.      issues not directly related to programming in assembler.
  253.  
  254.  
  255.  
  256.   1.4.  History
  257.  
  258.   Each version includes a few fixes and minor corrections, which needs
  259.   not be repeatedly mentionned every time.
  260.  
  261.      Version 0.1     23 Apr 1996
  262.         Francois-Rene "Far" Rideau <rideau@ens.fr> creates and publishes
  263.         the first mini-HOWTO, because ``I'm sick of answering ever the
  264.         same questions on comp.lang.asm.x86''
  265.      Version 0.2     4 May 1996
  266.         *
  267.  
  268.      Version 0.3c    15 Jun 1996
  269.         *
  270.  
  271.      Version 0.3f    17 Oct 1996
  272.         found -fasm option to enable GCC inline assembler w/o -O
  273.         optimizations
  274.  
  275.      Version 0.3g    2 Nov 1996
  276.         Created the History. Added pointers in cross-compiling section.
  277.         Added section about I/O programming under Linux (particularly
  278.         video).
  279.  
  280.      Version 0.3h    6 Nov 1996
  281.         more about cross-compiling -- See on sunsite: devel/msdos/
  282.  
  283.      Version 0.3i    16 Nov 1996
  284.         NASM is getting pretty slick
  285.  
  286.      Version 0.3j    24 Nov 1996
  287.         point to french translated version
  288.  
  289.      Version 0.3k    19 Dec 1996
  290.         What? I had forgotten to point to terse???
  291.  
  292.      Version 0.3l    11 Jan 1997
  293.         *
  294.  
  295.      Version 0.4pre1 13 Jan 1997
  296.         text mini-HOWTO transformed into a full linuxdoc-sgml HOWTO, to
  297.         see what the SGML tools are like.
  298.  
  299.      Version 0.4     20 Jan 1997
  300.         first release of the HOWTO as such.
  301.  
  302.      Version 0.4a    20 Jan 1997
  303.         CREDITS section added
  304.  
  305.      Version 0.4b    3 Feb 1997
  306.         NASM moved: now is before AS86
  307.  
  308.      Version 0.4c    9 Feb 1997
  309.         Added section "DO YOU NEED ASSEMBLY?"
  310.  
  311.      Version 0.4d    28 Feb 1997
  312.         Vapor announce of a new Assembly-HOWTO maintainer.
  313.  
  314.      Version 0.4e    13 Mar 1997
  315.         Release for DrLinux
  316.  
  317.      Version 0.4f    20 Mar 1997
  318.         *
  319.  
  320.      Version 0.4g    30 Mar 1997
  321.         *
  322.  
  323.      Version 0.4h    19 Jun 1997
  324.         still more on "how not to use assembly"; updates on NASM, GAS.
  325.  
  326.      Version 0.4i    17 July 1997
  327.         info on 16-bit mode access from Linux.
  328.  
  329.      Version 0.4j    7 September 1997
  330.         *
  331.      Version 0.4k    19 October 1997
  332.         *
  333.  
  334.      Version 0.4l    16 November 1997
  335.         release for LSL 6th edition.
  336.  
  337.         This is yet another last-release-by-Far-before-new-maintainer-
  338.         takes-over (?)
  339.  
  340.  
  341.  
  342.  
  343.   1.5.  Credits
  344.  
  345.   I would like to thanks the following persons, by order of appearance:
  346.  
  347.   o  Linus Torvalds <mailto:buried.alive@in.mail> for Linux
  348.  
  349.   o  Bruce Evans <mailto:bde@zeta.org.au> for bcc from which as86 is
  350.      extracted
  351.  
  352.   o  Simon Tatham <mailto:anakin@poboxes.com> and Julian Hall
  353.      <mailto:jules@earthcorp.com> for NASM
  354.  
  355.   o  Jim Neil <mailto:jim-neil@digital.net> for Terse
  356.  
  357.   o  Tim Bynum <mailto:linux-howto@sunsite.unc.edu> for maintaining
  358.      HOWTOs
  359.  
  360.   o  Raymond Moon <mailto:raymoon@moonware.dgsys.com> for his FAQ
  361.  
  362.   o  Eric Dumas <mailto:dumas@excalibur.ibp.fr> for his translation of
  363.      the mini-HOWTO into french (sad thing for the original author to be
  364.      french and write in english)
  365.  
  366.   o  Paul Anderson <mailto:paul@geeky1.ebtech.net> and Rahim Azizarab
  367.      <mailto:rahim@megsinet.net> for helping me, if not for taking over
  368.      the HOWTO.
  369.  
  370.   o  All the people who have contributed ideas, remarks, and moral
  371.      support.
  372.  
  373.  
  374.  
  375.  
  376.   2.  DO YOU NEED ASSEMBLY?
  377.  
  378.   Well, I wouldn't want to interfere with what you're doing, but here
  379.   are a few advice from hard-earned experience.
  380.  
  381.  
  382.  
  383.   2.1.  Pros and Cons
  384.  
  385.  
  386.  
  387.   2.1.1.  The advantages of Assembly
  388.  
  389.   Assembly can express very low-level things:
  390.  
  391.   o  you can access machine-dependent registers and I/O.
  392.  
  393.   o  you can control the exact behavior of code in critical sections
  394.      that might involve hardware or I/O lock-ups
  395.  
  396.  
  397.   o  you can break the conventions of your usual compiler, which might
  398.      allow some optimizations (like temporarily breaking rules about GC,
  399.      threading, etc).
  400.  
  401.   o  get access to unusual programming modes of your processor (e.g. 16
  402.      bit code for startup or BIOS interface on Intel PCs)
  403.  
  404.   o  you can build interfaces between code fragments using incompatible
  405.      conventions (e.g. produced by different compilers, or separated by
  406.      a low-level interface).
  407.  
  408.   o  you can produce reasonably fast code for tight loops to cope with a
  409.      bad non-optimizing compiler (but then, there are free optimizing
  410.      compilers available!)
  411.  
  412.   o  you can produce hand-optimized code that's perfectly tuned for your
  413.      particular hardware setup, though not to anyone else's.
  414.  
  415.   o  you can write some code for your new language's optimizing compiler
  416.      (that's something few will ever do, and even they, not often).
  417.  
  418.  
  419.  
  420.  
  421.   2.1.2.  The disadvantages of Assembly
  422.  
  423.   Assembly is a very low-level language (the lowest above hand-coding
  424.   the binary instruction patterns).  This means
  425.  
  426.   o  it's long and tedious to write initially,
  427.  
  428.   o  it's very bug-prone,
  429.  
  430.   o  your bugs will be very difficult to chase,
  431.  
  432.   o  it's very difficult to understand and modify, i.e. to maintain.
  433.  
  434.   o  the result is very non-portable to other architectures, existing or
  435.      future,
  436.  
  437.   o  your code will be optimized only for a certain implementation of a
  438.      same architecture: for instance, among Intel-compatible platforms,
  439.      each CPU design and variation (bus width, relative speed and size
  440.      of CPU/caches/RAM/Bus/disks presence of FPU, MMX extensions, etc)
  441.      implies potentially completely different optimization techniques.
  442.      CPU designs already include Intel 386, 486, Pentium, PPro, Pentium
  443.      II; Cyrix 5x86, 6x86; AMD K5, K6.  New designs keep appearing, so
  444.      don't expect either this listing or your code to be up-to-date.
  445.  
  446.   o  your code might also be unportable accross different OS platforms
  447.      on the same architecture, by lack of proper tools.  (well, GAS
  448.      seems to work on all platforms; NASM seems to work or be workable
  449.      on all intel platforms).
  450.  
  451.   o  you spend more time on a few details, and can't focus on small and
  452.      large algorithmic design, that are known to bring the largest part
  453.      of the speed up.  [e.g. you might spend some time building very
  454.      fast list/array manipulation primitives in assembly; only a hash
  455.      table would have sped up your program much more; or, in another
  456.      context, a binary tree; or some high-level structure distributed
  457.      over a cluster of CPUs]
  458.  
  459.   o  a small change in algorithmic design might completely invalidate
  460.      all your existing assembly code.  So that either you're ready (and
  461.      able) to rewrite it all, or you're tied to a particular algorithmic
  462.      design;
  463.   o  On code that ain't too far from what's in standard benchmarks,
  464.      commercial optimizing compilers outperform hand-coded assembly
  465.      (well, that's less true on the x86 architecture than on RISC
  466.      architectures, and perhaps less true for widely available/free
  467.      compilers; anyway, for typical C code, GCC is fairly good);
  468.  
  469.   o  And in any case, as says moderator John Levine on comp.compilers,
  470.      ``compilers make it a lot easier to use complex data structures,
  471.      and compilers don't get bored halfway through and generate reliably
  472.      pretty good code.''  They will also correctly propagate code
  473.      transformations throughout the whole (huge) program when optimizing
  474.      code between procedures and module boundaries.
  475.  
  476.  
  477.  
  478.   2.1.3.  Assessment
  479.  
  480.   All in all, you might find that though using assembly is sometimes
  481.   needed, and might even be useful in a few cases where it is not,
  482.   you'll want to:
  483.  
  484.   o  minimize the use of assembly code,
  485.  
  486.   o  encapsulate this code in well-defined interfaces
  487.  
  488.   o  have your assembly code automatically generated from patterns
  489.      expressed in a higher-level language than assembly (e.g. GCC
  490.      inline-assembly macros).
  491.  
  492.   o  have automatic tools translate these programs into assembly code
  493.  
  494.   o  have this code be optimized if possible
  495.  
  496.   o  All of the above, i.e. write (an extension to) an optimizing
  497.      compiler back-end.
  498.  
  499.   Even in cases when Assembly is needed (e.g. OS development), you'll
  500.   find that not so much of it is, and that the above principles hold.
  501.  
  502.   See the sources for the Linux kernel about it: as little assembly as
  503.   needed, resulting in a fast, reliable, portable, maintainable OS.
  504.   Even a successful game like DOOM was almost massively written in C,
  505.   with a tiny part only being written in assembly for speed up.
  506.  
  507.  
  508.  
  509.   2.2.  How to NOT use Assembly
  510.  
  511.  
  512.  
  513.   2.2.1.  General procedure to achieve efficient code
  514.  
  515.   As says Charles Fiterman on comp.compilers about human vs computer-
  516.   generated assembly code,
  517.  
  518.   ``The human should always win and here is why.
  519.  
  520.   o  First the human writes the whole thing in a high level language.
  521.  
  522.   o  Second he profiles it to find the hot spots where it spends its
  523.      time.
  524.  
  525.   o  Third he has the compiler produce assembly for those small sections
  526.      of code.
  527.  
  528.  
  529.   o  Fourth he hand tunes them looking for tiny improvements over the
  530.      machine generated code.
  531.  
  532.      The human wins because he can use the machine.''
  533.  
  534.  
  535.  
  536.   2.2.2.  Languages with optimizing compilers
  537.  
  538.   Languages like ObjectiveCAML, SML, CommonLISP, Scheme, ADA, Pascal, C,
  539.   C++, among others, all have free optimizing compilers that'll optimize
  540.   the bulk of your programs, and often do better than hand-coded
  541.   assembly even for tight loops, while allowing you to focus on higher-
  542.   level details, and without forbidding you to grab a few percent of
  543.   extra performance in the above-mentionned way, once you've reached a
  544.   stable design.  Of course, there are also commercial optimizing
  545.   compilers for most of these languages, too!
  546.  
  547.   Some languages have compilers that produce C code, which can be
  548.   further optimized by a C compiler.  LISP, Scheme, Perl, and many other
  549.   are suches.  Speed is fairly good.
  550.  
  551.  
  552.  
  553.  
  554.   2.2.3.  General procedure to speed your code up
  555.  
  556.   As for speeding code up, you should do it only for parts of a program
  557.   that a profiling tool has consistently identified as being a
  558.   performance bottleneck.
  559.  
  560.   Hence, if you identify some code portion as being too slow, you should
  561.  
  562.   o  first try to use a better algorithm;
  563.  
  564.   o  then try to compile it rather than interpret it;
  565.  
  566.   o  then try to enable and tweak optimization from your compiler;
  567.  
  568.   o  then give the compiler hints about how to optimize (typing
  569.      information in LISP; register usage with GCC; lots of options in
  570.      most compilers, etc).
  571.  
  572.   o  then possibly fallback to assembly programming
  573.  
  574.   Finally, before you end up writing assembly, you should inspect
  575.   generated code, to check that the problem really is with bad code
  576.   generation, as this might really not be the case: compiler-generated
  577.   code might be better than what you'd have written, particularly on
  578.   modern multi-pipelined architectures!  Slow parts of a program might
  579.   be intrinsically so.  Biggest problems on modern architectures with
  580.   fast processors are due to delays from memory access, cache-misses,
  581.   TLB-misses, and page-faults; register optimization becomes useless,
  582.   and you'll more profitably re-think data structures and threading to
  583.   achieve better locality in memory access.  Perhaps a completely
  584.   different approach to the problem might help, then.
  585.  
  586.  
  587.  
  588.   2.2.4.  Inspecting compiler-generated code
  589.  
  590.   There are many reasons to inspect compiler-generated assembly code.
  591.   Here are what you'll do with such code:
  592.  
  593.   o  check whether generated code can be obviously enhanced with hand-
  594.      coded assembly (or by tweaking compiler switches)
  595.   o  when that's the case, start from generated code and modify it
  596.      instead of starting from scratch
  597.  
  598.   o  more generally, use generated code as stubs to modify, which at
  599.      least gets right the way your assembly routines interface to the
  600.      external world
  601.  
  602.   o  track down bugs in your compiler (hopefully rarer)
  603.  
  604.   The standard way to have assembly code be generated is to invoke your
  605.   compiler with the -S flag.  This works with most Unix compilers,
  606.   including the GNU C Compiler (GCC), but YMMV.  As for GCC, it will
  607.   produce more understandable assembly code with the -fverbose-asm
  608.   command-line option.  Of course, if you want to get good assembly
  609.   code, don't forget your usual optimization options and hints!
  610.  
  611.  
  612.  
  613.  
  614.   3.  ASSEMBLERS
  615.  
  616.  
  617.  
  618.   3.1.  GCC Inline Assembly
  619.  
  620.   The well-known GNU C/C++ Compiler (GCC), an optimizing 32-bit compiler
  621.   at the heart of the GNU project, supports the x86 architecture quite
  622.   well, and includes the ability to insert assembly code in C programs,
  623.   in such a way that register allocation can be either specified or left
  624.   to GCC.  GCC works on most available platforms, notably Linux, *BSD,
  625.   VSTa, OS/2, *DOS, Win*, etc.
  626.  
  627.  
  628.   3.1.1.  Where to find GCC
  629.  
  630.   The original GCC site is the GNU FTP site
  631.   <ftp://prep.ai.mit.edu/pub/gnu/> together with all the released
  632.   application software from the GNU project.  Linux-configured and
  633.   precompiled versions can be found in
  634.   <ftp://sunsite.unc.edu/pub/Linux/GCC/> There exists a lot of FTP
  635.   mirrors of both sites.  everywhere around the world, as well as CD-ROM
  636.   copies.
  637.  
  638.   GCC development has split in two branches recently.  See more about
  639.   the experimental version, egcs, at <http://www.cygnus.com/egcs/>
  640.  
  641.   Sources adapted to your favorite OS, and binaries precompiled for it,
  642.   should be found at your usual FTP sites.
  643.  
  644.   For most popular DOS port of GCC is named DJGPP, and can be found in
  645.   directories of such name in FTP sites. See:
  646.  
  647.   <http://www.delorie.com/djgpp/>
  648.  
  649.  
  650.   There is also a port of GCC to OS/2 named EMX, that also works under
  651.   DOS, and includes lots of unix-emulation library routines.  See
  652.   around:
  653.  
  654.   <http://www.leo.org/pub/comp/os/os2/gnu/emx+gcc/>
  655.  
  656.   <http://warp.eecs.berkeley.edu/os2/software/shareware/emx.html>
  657.  
  658.   <ftp://ftp-os2.cdrom.com/pub/os2/emx09c/>
  659.  
  660.  
  661.   3.1.2.  Where to find docs for GCC Inline Asm
  662.  
  663.   The documentation of GCC includes documentation files in texinfo
  664.   format.  You can compile them with tex and print then result, or
  665.   convert them to .info, and browse them with emacs, or convert them to
  666.   .html, or nearly whatever you like.  convert (with the right tools) to
  667.   whatever you like, or just read as is.  The .info files are generally
  668.   found on any good installation for GCC.
  669.  
  670.   The right section to look for is: C Extensions::Extended Asm::
  671.  
  672.   Section Invoking GCC::Submodel Options::i386 Options:: might help too.
  673.   Particularly, it gives the i386 specific constraint names for
  674.   registers: abcdSDB correspond to %eax, %ebx, %ecx, %edx, %esi, %edi,
  675.   %ebp respectively (no letter for %esp).
  676.  
  677.   The DJGPP Games resource (not only for game hackers) has this page
  678.   specifically about assembly:
  679.  
  680.   <http://www.rt66.com/~brennan/djgpp/djgpp_asm.html>
  681.  
  682.   Finally, there is a web page called, ``DJGPP Quick ASM Programming
  683.   Guide'', that covers URLs to FAQs, AT&T x86 ASM Syntax, Some inline
  684.   ASM information, and converting .obj/.lib files:
  685.  
  686.   <http://remus.rutgers.edu/~avly/djasm.html>
  687.  
  688.   GCC depends on GAS for assembling, and follow its syntax (see below);
  689.   do mind that inline asm needs percent characters to be quoted so they
  690.   be passed to GAS.  See the section about GAS below.
  691.  
  692.   Find lots of useful examples in the linux/include/asm-i386/
  693.   subdirectory of the sources for the Linux kernel.
  694.  
  695.  
  696.  
  697.  
  698.   3.1.3.  Invoking GCC to have it properly inline assembly code ?
  699.  
  700.   Be sure to invoke GCC with the -O flag (or -O2, -O3, etc), to enable
  701.   optimizations and inline assembly.  If you don't, your code may
  702.   compile, but not run properly!!!  Actually (kudos to Tim Potter,
  703.   timbo@moshpit.air.net.au), it is enough to use the -fasm flag (and
  704.   perhaps -finline-functions) which is part of all the features enabled
  705.   by -O.  So if you have problems with buggy optimizations in your
  706.   particular implementation/version of GCC, you can still use inline
  707.   asm.  Similarly, use -fno-asm to disable inline assembly (why would
  708.   you?).
  709.  
  710.   More generally, good compile flags for GCC on the x86 platform are
  711.  
  712.   ______________________________________________________________________
  713.           gcc -O2 -fomit-frame-pointer -m386 -Wall
  714.   ______________________________________________________________________
  715.  
  716.  
  717.  
  718.   -O2 is the good optimization level. Optimizing besides it yields code
  719.   that is a lot larger, but only a bit faster; such overoptimizationn
  720.   might be useful for tight loops only (if any), which you may be doing
  721.   in assembly anyway; if you need that, do it just for the few routines
  722.   that need it.
  723.  
  724.   -fomit-frame-pointer allows generated code to skip the stupid frame
  725.   pointer maintenance, which makes code smaller and faster, and frees a
  726.   register for further optimizations.  It precludes the easy use of
  727.   debugging tools (gdb), but when you use these, you just don't care
  728.   about size and speed anymore anyway.
  729.  
  730.   -m386 yields more compact code, without any measurable slowdown, (note
  731.   that small code also means less disk I/O and faster execution) but
  732.   perhaps on the above-mentioned tight loops; you might appreciate
  733.   -mpentium for special pentium-optimizing GCC targetting a specifically
  734.   pentium platform.
  735.  
  736.   -Wall enables all warnings and helps you catch obvious stupid errors.
  737.  
  738.   To optimize even more, option -mregparm=2 and/or corresponding
  739.   function attribute might help, but might pose lots of problems when
  740.   linking to foreign code...
  741.  
  742.   Note that you can add make these flags the default by editing file
  743.   /usr/lib/gcc-lib/i486-linux/2.7.2.2/specs or wherever that is on your
  744.   system (better not add -Wall there, though).
  745.  
  746.  
  747.  
  748.   3.2.  GAS
  749.  
  750.   GAS is the GNU Assembler, that GCC relies upon.
  751.  
  752.  
  753.  
  754.   3.2.1.  Where to find it
  755.  
  756.   Find it at the same place where you found GCC, in a package named
  757.   binutils.
  758.  
  759.  
  760.  
  761.   3.2.2.  What is this AT&T syntax
  762.  
  763.   Because GAS was invented to support a 32-bit unix compiler, it uses
  764.   standard ``AT&T'' syntax, which resembles a lot the syntax for
  765.   standard m68k assemblers, and is standard in the UNIX world.  This
  766.   syntax is no worse, no better than the ``Intel'' syntax.  It's just
  767.   different.  When you get used to it, you find it much more regular
  768.   than the Intel syntax, though a bit boring.
  769.  
  770.   Here are the major caveats about GAS syntax:
  771.  
  772.   o  Register names are prefixed with %, so that registers are %eax, %dl
  773.      and suches instead of just eax, dl, etc.  This makes it possible to
  774.      include external C symbols directly in assembly source, without any
  775.      risk of confusion, or any need for ugly underscore prefixes.
  776.  
  777.   o  The order of operands is source(s) first, and destination last, as
  778.      opposed to the intel convention of destination first and sources
  779.      last.  Hence, what in intel syntax is mov ax,dx (move contents of
  780.      register dx into register ax) will be in att syntax mov %dx, %ax.
  781.  
  782.   o  The operand length is specified as a suffix to the instruction
  783.      name.  The suffix is b for (8-bit) byte, w for (16-bit) word, and l
  784.      for (32-bit) long. For instance, the correct syntax for the above
  785.      instruction would have been movw %dx,%ax.  However, gas does not
  786.      require strict att syntax was, so the suffix is optional when
  787.      length can be guessed from register operands, and else defaults to
  788.      32-bit (with a warning).
  789.  
  790.   o  Immediate operands are marked with a $ prefix, as in addl $5,%eax
  791.      (add immediate long value 5 to register %eax).
  792.  
  793.   o  No prefix to an operand indicates it is a memory-address; hence
  794.      movl $foo,%eax puts the address of variable foo in register %eax,
  795.      but movl foo,%eax puts the contents of variable foo in register
  796.      %eax.
  797.  
  798.   o  Indexing or indirection is done by enclosing the index register or
  799.      indirection memory cell address in parentheses, as in testb
  800.      $0x80,17(%ebp) (test the high bit of the byte value at offset 17
  801.      from the cell pointed to by %ebp).
  802.  
  803.  
  804.   A program exists to help you convert programs from TASM syntax to AT&T
  805.   syntax. See
  806.  
  807.   <ftp://x2ftp.oulu.fi/pub/msdos/programming/convert/ta2asv08.zip>
  808.  
  809.   GAS has comprehensive documentation in TeXinfo format, which comes at
  810.   least with the source distribution.  Browse extracted .info pages with
  811.   Emacs or whatever.  There used to be a file named gas.doc or as.doc
  812.   around the GAS source package, but it was merged into the TeXinfo
  813.   docs.  Of course, in case of doubt, the ultimate documentation is the
  814.   sources themselves!  A section that will particularly interest you is
  815.   Machine Dependencies::i386-Dependent::
  816.  
  817.  
  818.   Again, the sources for Linux (the OS kernel), come in as good
  819.   examples; see under linux/arch/i386, the following files: kernel/*.S,
  820.   boot/compressed/*.S, mathemu/*.S
  821.  
  822.   If you are writing kind of a language, a thread package, etc you might
  823.   as well see how other languages (OCaml, gforth, etc), or thread
  824.   packages (QuickThreads, MIT pthreads, LinuxThreads, etc), or whatever,
  825.   do it.
  826.  
  827.   Finally, just compiling a C program to assembly might show you the
  828.   syntax for the kind of instructions you want.  See section ``Do you
  829.   need Assembly?'' above.
  830.  
  831.  
  832.  
  833.  
  834.   3.2.3.  Limited 16-bit mode
  835.  
  836.   GAS is a 32-bit assembler, meant to support a 32-bit compiler.  It
  837.   currently has only limited support for 16-bit mode, which consists in
  838.   prepending the 32-bit prefixes to instructions, so you write 32-bit
  839.   code that runs in 16-bit mode on a 32 bit CPU.  In both modes, it
  840.   supports 16-bit register usage, but what is unsupported is 16-bit
  841.   addressing.  Use the directive .code16 and .code32 to switch between
  842.   modes.  Note that an inline assembly statement asm(".code16\n") will
  843.   allow GCC to produce 32-bit code that'll run in real mode!
  844.  
  845.   I've been told that most code needed to fully support 16-bit mode
  846.   programming was added to GAS by Bryan Ford (please confirm?), but at
  847.   least, it doesn't show up in any of the distribution I tried, up to
  848.   binutils-2.8.1.x ... more info on this subject would be welcome.
  849.  
  850.   A cheap solution is to define macros (see below) that somehow produce
  851.   the binary encoding (with .byte) for just the 16-bit mode instructions
  852.   you need (almost nothing if you use code16 as above, and can safely
  853.   assume the code will run on a 32-bit capable x86 CPU).  To find the
  854.   proper encoding, you can get inspiration from the sources of 16-bit
  855.   capable assemblers for the encoding.
  856.  
  857.  
  858.  
  859.   3.3.  GASP
  860.  
  861.   GASP is the GAS Preprocessor.  It adds macros and some nice syntax to
  862.   GAS.
  863.  
  864.  
  865.  
  866.   3.3.1.  Where to find GASP
  867.  
  868.   GASP comes together with GAS in the GNU binutils archive.
  869.  
  870.  
  871.  
  872.   3.3.2.  How it works
  873.  
  874.   It works as a filter, much like cpp and the like.  I have no idea on
  875.   details, but it comes with its own texinfo documentation, so just
  876.   browse them (in .info), print them, grok them.  GAS with GASP looks
  877.   like a regular macro-assembler to me.
  878.  
  879.  
  880.  
  881.   3.4.  NASM
  882.  
  883.   The Netwide Assembler project is producing yet another assembler,
  884.   written in C, that should be modular enough to eventually support all
  885.   known syntaxes and object formats.
  886.  
  887.  
  888.   3.4.1.  Where to find NASM
  889.  
  890.   <http://www.cryogen.com/Nasm>
  891.  
  892.   Binary release on your usual sunsite mirror in devel/lang/asm/ Should
  893.   also be available as .rpm or .deb in your usual RedHat/Debian
  894.   distributions' contrib.
  895.  
  896.  
  897.   3.4.2.  What it does
  898.  
  899.   At the time this HOWTO is written, the current NASM version is 0.96.
  900.  
  901.   The syntax is Intel-style.  Some macroprocessing support is
  902.   integrated.
  903.  
  904.   Supported object file formats are bin, aout, coff, elf, as86, (DOS)
  905.   obj, win32, (their own format) rdf.
  906.  
  907.   NASM can be used as a backend for the free LCC compiler (support files
  908.   included).
  909.  
  910.  
  911.   Surely NASM evolves too fast for this HOWTO to be kept up to date.
  912.   Unless you're using BCC as a 16-bit compiler (which is out of scope of
  913.   this 32-bit HOWTO), you should use NASM instead of say AS86 or MASM,
  914.   because it is actively supported online, and runs on all platforms.
  915.  
  916.   Note: NASM also comes with a disassembler, NDISASM.
  917.  
  918.   Its hand-written parser makes it much faster than GAS, though of
  919.   course, it doesn't support three bazillion different architectures.
  920.   For the x86 target, it should be the assembler of choice...
  921.  
  922.  
  923.  
  924.  
  925.   3.5.  AS86
  926.  
  927.   AS86 is a 80x86 assembler, both 16-bit and 32-bit, part of Bruce
  928.   Evans' C Compiler (BCC).  It has mostly Intel-syntax, though it
  929.   differs slightly as for addressing modes.
  930.  
  931.  
  932.  
  933.   3.5.1.  Where to get AS86
  934.  
  935.   A completely outdated version of AS86 is distributed by HJLu just to
  936.   compile the Linux kernel, in a package named bin86 (current version
  937.   0.4), available in any Linux GCC repository.  But I advise no one to
  938.   use it for anything else but compiling Linux.  This version supports
  939.   only a hacked minix object file format, which is not supported by the
  940.   GNU binutils or anything, and it has a few bugs in 32-bit mode, so you
  941.   really should better keep it only for compiling Linux.
  942.  
  943.   The most recent versions by Bruce Evans (bde@zeta.org.au) are
  944.   published together with the FreeBSD distribution.  Well, they were: I
  945.   could not find the sources from distribution 2.1 on :( Hence, I put
  946.   the sources at my place:
  947.  
  948.   <http:///www.eleves.ens.fr:8080/home/rideau/files/bcc-95.3.12.src.tgz>
  949.  
  950.   The Linux/8086 (aka ELKS) project is somehow maintaining bcc (though I
  951.   don't think they included the 32-bit patches).  See around
  952.   <http://www.linux.org.uk/Linux8086.html> <ftp://linux.mit.edu/>.
  953.  
  954.   Among other things, these more recent versions, unlike HJLu's,
  955.   supports Linux GNU a.out format, so you can link you code to Linux
  956.   programs, and/or use the usual tools from the GNU binutil package to
  957.   manipulate your data.  This version can co-exist without any harm with
  958.   the previous one (see according question below).
  959.  
  960.   BCC from 12 march 1995 and earlier version has a misfeature that makes
  961.   all segment pushing/popping 16-bit, which is quite annoying when
  962.   programming in 32-bit mode.  A patch is published in the Tunes project
  963.   <http://www.eleves.ens.fr:8080/home/rideau/Tunes/> subpage
  964.   files/tgz/tunes.0.0.0.25.src.tgz in unpacked subdirectory LLL/i386/
  965.   The patch should also be in available directly from
  966.   <http://www.eleves.ens.fr:8080/home/rideau/files/as86.bcc.patch.gz>
  967.   Bruce Evans accepted this patch, so if there is a more recent version
  968.   of bcc somewhere someday, the patch should have been included...
  969.  
  970.  
  971.  
  972.   3.5.2.  How to invoke the assembler?
  973.  
  974.   Here's the GNU Makefile entry for using bcc to transform .s asm into
  975.   both GNU a.out .o object and .l listing:
  976.  
  977.  
  978.   ______________________________________________________________________
  979.   %.o %.l:        %.s
  980.           bcc -3 -G -c -A-d -A-l -A$*.l -o $*.o $<
  981.   ______________________________________________________________________
  982.  
  983.  
  984.  
  985.   Remove the %.l, -A-l, and -A$*.l, if you don't want any listing.  If
  986.   you want something else than GNU a.out, you can see the docs of bcc
  987.   about the other supported formats, and/or use the objcopy utility from
  988.   the GNU binutils package.
  989.  
  990.  
  991.   3.5.3.  Where to find docs
  992.  
  993.   The docs are what is included in the bcc package.  Man pages are also
  994.   available somewhere on the FreeBSD site.  When in doubt, the sources
  995.   themselves are often a good docs: it's not very well commented, but
  996.   the programming style is straightforward.  You might try to see how
  997.   as86 is used in Tunes 0.0.0.25...
  998.  
  999.  
  1000.  
  1001.   3.5.4.  What if I can't compile Linux anymore with this new version ?
  1002.  
  1003.   Linus is buried alive in mail, and my patch for compiling Linux with a
  1004.   Linux a.out as86 didn't make it to him (!).  Now, this shouldn't
  1005.   matter: just keep your as86 from the bin86 package in /usr/bin, and
  1006.   let bcc install the good as86 as /usr/local/libexec/i386/bcc/as where
  1007.   it should be. You never need explicitly call this ``good'' as86,
  1008.   because bcc does everything right, including conversion to Linux
  1009.   a.out, when invoked with the right options; so assemble files
  1010.   exclusively with bcc as a frontend, not directly with as86.
  1011.  
  1012.  
  1013.  
  1014.  
  1015.   3.6.  OTHER ASSEMBLERS
  1016.  
  1017.   These are other, non-regular, options, in case the previous didn't
  1018.   satisfy you (why?), that I don't recommend in the usual (?) case, but
  1019.   that could prove quite useful if the assembler must be integrated in
  1020.   the software you're designing (i.e. an OS or development environment).
  1021.  
  1022.  
  1023.  
  1024.   3.6.1.  Win32Forth assembler
  1025.  
  1026.   Win32Forth is a free 32-bit ANS FORTH system that successfully runs
  1027.   under Win32s, Win95, Win/NT.  It includes a free 32-bit assembler
  1028.   (either prefix or postfix syntax) integrated into the FORTH language.
  1029.   Macro processing is done with the full power of the reflective
  1030.   language FORTH; however, the only supported input and output contexts
  1031.   is Win32For itself (no dumping of .obj file -- you could add that
  1032.   yourself, of course).  Find it at
  1033.   <ftp://ftp.forth.org/pub/Forth/win32for/>
  1034.  
  1035.  
  1036.  
  1037.   3.6.2.  Terse
  1038.  
  1039.   Terse is a programming tool that provides THE most compact assembler
  1040.   syntax for the x86 family!  See  <http://www.terse.com>.  It is said
  1041.   that there was a free clone somewhere, that was abandonned after
  1042.   worthless pretenses that the syntax would be owned by the original
  1043.   author, and that I invite you to take over, in case the syntax
  1044.   interests you.
  1045.  
  1046.  
  1047.  
  1048.   3.6.3.  Non-free and/or Non-32bit x86 assemblers.
  1049.  
  1050.   You may find more about them, together with the basics of x86 assembly
  1051.   programming, in Raymond Moon's FAQ for comp.lang.asm.x86
  1052.   <http://www2.dgsys.com/~raymoon/faq/asmfaq.zip>
  1053.  
  1054.   Note that all DOS-based assemblers should work inside the Linux DOS
  1055.   Emulator, as well as other similar emulators, so that if you already
  1056.   own one, you can still use it inside a real OS.  Recent DOS-based
  1057.   assemblers also support COFF and/or other object file formats that are
  1058.   supported by the GNU BFD library, so that you can use them together
  1059.   with your free 32-bit tools, perhaps using GNU objcopy (part of the
  1060.   binutils) as a conversion filter.
  1061.  
  1062.  
  1063.  
  1064.  
  1065.   4.  METAPROGRAMMING/MACROPROCESSING
  1066.  
  1067.   Assembly programming is a bore, but for critical parts of programs.
  1068.  
  1069.   You should use the appropriate tool for the right task, so don't
  1070.   choose assembly when it's not fit; C, OCAML, perl, Scheme, might be a
  1071.   better choice for most of your programming.
  1072.  
  1073.   However, there are cases when these tools do not give a fine enough
  1074.   control on the machine, and assembly is useful or needed.  In those
  1075.   case, you'll appreciate a system of macroprocessing and
  1076.   metaprogramming that'll allow recurring patterns to be factored each
  1077.   into a one indefinitely reusable definition, which allows safer
  1078.   programming, automatic propagation of pattern modification, etc.  A
  1079.   ``plain'' assembler is often not enough, even when one is doing only
  1080.   small routines to link with C.
  1081.  
  1082.  
  1083.  
  1084.   4.1.  What's integrated into the above
  1085.  
  1086.  
  1087.   Yes I know this section does not contain much useful up-to-date
  1088.   information.  Feel free to contribute what you discover the hard
  1089.   way...
  1090.  
  1091.  
  1092.  
  1093.   4.1.1.  GCC
  1094.  
  1095.   GCC allows (and requires) you to specify register constraints in your
  1096.   ``inline assembly'' code, so the optimizer always know about it; thus,
  1097.   inline assembly code is really made of patterns, not forcibly exact
  1098.   code.
  1099.  
  1100.   Then, you can make put your assembly into CPP macros, and inline C
  1101.   functions, so anyone can use it in as any C function/macro.  Inline
  1102.   functions resemble macros very much, but are sometimes cleaner to use.
  1103.   Beware that in all those cases, code will be duplicated, so only local
  1104.   labels (of 1: style) should be defined in that asm code.  However, a
  1105.   macro would allow the name for a non local defined label to be passed
  1106.   as a parameter (or else, you should use additional meta-programming
  1107.   methods).  Also, note that propagating inline asm code will spread
  1108.   potential bugs in them, so watch out doubly for register constraints
  1109.   in such inline asm code.
  1110.  
  1111.   Lastly, the C language itself may be considered as a good abstraction
  1112.   to assembly programming, which relieves you from most of the trouble
  1113.   of assembling.
  1114.  
  1115.   Beware that some optimizations that involve passing arguments to
  1116.   functions through registers may make those functions unsuitable to be
  1117.   called from external (and particularly hand-written assembly) routines
  1118.   in the standard way; the "asmlinkage" attribute may prevent a routine
  1119.   to be concerned by such optimization flag; see the linux kernel
  1120.   sources for examples.
  1121.  
  1122.  
  1123.   4.1.2.  GAS
  1124.  
  1125.   GAS has some macro capability included, as detailed in the texinfo
  1126.   docs.  Moreover, while GCC recognizes .s files as raw assembly to send
  1127.   to GAS, it also recognizes .S files as files to pipe through CPP
  1128.   before to feed them to GAS.  Again and again, see Linux sources for
  1129.   examples.
  1130.  
  1131.  
  1132.  
  1133.   4.1.3.  GASP
  1134.  
  1135.   It adds all the usual macroassembly tricks to GAS.  See its texinfo
  1136.   docs.
  1137.  
  1138.  
  1139.  
  1140.   4.1.4.  NASM
  1141.  
  1142.   NASM has some macro support, too.  See according docs.  If you have
  1143.   some bright idea, you might wanna contact the authors, as they are
  1144.   actively developing it.  Meanwhile, see about external filters below.
  1145.  
  1146.  
  1147.  
  1148.   4.1.5.  AS86
  1149.  
  1150.   It has some simple macro support, but I couldn't find docs.  Now the
  1151.   sources are very straightforward, so if you're interested, you should
  1152.   understand them easily.  If you need more than the basics, you should
  1153.   use an external filter (see below).
  1154.  
  1155.  
  1156.  
  1157.   4.1.6.  OTHER ASSEMBLERS
  1158.  
  1159.  
  1160.   o  Win32FORTH: CODE and END-CODE are normal that do not switch from
  1161.      interpretation mode to compilation mode, so you have access to the
  1162.      full power of FORTH while assembling.
  1163.  
  1164.   o  TUNES: it doesn't work yet, but the Scheme language is a real high-
  1165.      level language that allows arbitrary meta-programming.
  1166.  
  1167.  
  1168.  
  1169.   4.2.  External Filters
  1170.  
  1171.   Whatever is the macro support from your assembler, or whatever
  1172.   language you use (even C !), if the language is not expressive enough
  1173.   to you, you can have files passed through an external filter with a
  1174.   Makefile rule like that:
  1175.  
  1176.  
  1177.   ______________________________________________________________________
  1178.   %.s:    %.S other_dependencies
  1179.           $(FILTER) $(FILTER_OPTIONS) < $< > $@
  1180.   ______________________________________________________________________
  1181.  
  1182.  
  1183.  
  1184.  
  1185.  
  1186.  
  1187.  
  1188.  
  1189.   4.2.1.  CPP
  1190.  
  1191.   CPP is truely not very expressive, but it's enough for easy things,
  1192.   it's standard, and called transparently by GCC.
  1193.  
  1194.   As an example of its limitations, you can't declare objects so that
  1195.   destructors are automatically called at the end of the declaring
  1196.   block; you don't have diversions or scoping, etc.
  1197.  
  1198.   CPP comes with any C compiler. If you could make it without one, don't
  1199.   bother fetching CPP (though I wonder how you could).
  1200.  
  1201.  
  1202.  
  1203.   4.2.2.  M4
  1204.  
  1205.   M4 gives you the full power of macroprocessing, with a Turing
  1206.   equivalent language, recursion, regular expressions, etc.  You can do
  1207.   with it everything that CPP cannot.
  1208.  
  1209.   See macro4th/This4th from <ftp://ftp.forth.org/pub/Forth/> in
  1210.   Reviewed/ ANS/ (?), or the Tunes 0.0.0.25 sources as examples of
  1211.   advanced macroprogramming using m4.
  1212.  
  1213.   However, its disfunctional quoting and unquoting semantics force you
  1214.   to use explicit continuation-passing tail-recursive macro style if you
  1215.   want to do advanced macro programming (which is remindful of TeX --
  1216.   BTW, has anyone tried to use TeX as a macroprocessor for anything else
  1217.   than typesetting ?).  This is NOT worse than CPP that does not allow
  1218.   quoting and recursion anyway.
  1219.  
  1220.   The right version of m4 to get is GNU m4 1.4 (or later if exists),
  1221.   which has the most features and the least bugs or limitations of all.
  1222.   m4 is designed to be slow for anything but the simplest uses, which
  1223.   might still be ok for most assembly programming (you're not writing
  1224.   million-lines assembly programs, are you?).
  1225.  
  1226.  
  1227.  
  1228.   4.2.3.  Macroprocessing with yer own filter
  1229.  
  1230.   You can write your own simple macro-expansion filter with the usual
  1231.   tools: perl, awk, sed, etc.  That's quick to do, and you control
  1232.   everything.  But of course, any power in macroprocessing must be
  1233.   earned the hard way.
  1234.  
  1235.  
  1236.  
  1237.   4.2.4.  Metaprogramming
  1238.  
  1239.   Instead of using an external filter that expands macros, one way to do
  1240.   things is to write programs that write part or all of other programs.
  1241.  
  1242.   For instance, you could use a program outputing source code
  1243.  
  1244.   o  to generate sine/cosine/whatever lookup tables,
  1245.  
  1246.   o  to extract a source-form representation of a binary file,
  1247.  
  1248.   o  to compile your bitmaps into fast display routines,
  1249.  
  1250.   o  to extract documentation, initialization/finalization code,
  1251.      description tables, as well as normal code from the same source
  1252.      files,
  1253.  
  1254.  
  1255.   o  to have customized assembly code, generated from a
  1256.      perl/shell/scheme script that does arbitrary processing,
  1257.  
  1258.   o  to propagate data defined at one point only into several cross-
  1259.      referencing tables and code chunks.
  1260.  
  1261.   o  etc.
  1262.  
  1263.   Think about it!
  1264.  
  1265.  
  1266.  
  1267.   4.2.4.1.  Backends from existing compilers
  1268.  
  1269.   Compilers like SML/NJ, Objective CAML, MIT-Scheme, etc, do have their
  1270.   own generic assembler backend, which you might or not want to use, if
  1271.   you intend to generate code semi-automatically from the according
  1272.   languages.
  1273.  
  1274.  
  1275.  
  1276.   4.2.4.2.  The New-Jersey Machine-Code Toolkit
  1277.  
  1278.   There is a project, using the programming language Icon, to build a
  1279.   basis for producing assembly-manipulating code.  See around
  1280.   <http://www.cs.virginia.edu/~nr/toolkit/>
  1281.  
  1282.  
  1283.  
  1284.   4.2.4.3.  Tunes
  1285.  
  1286.   The Tunes OS project is developping its own assembler as an extension
  1287.   to the Scheme language, as part of its development process.  It
  1288.   doesn't run at all yet, though help is welcome.
  1289.  
  1290.   The assembler manipulates symbolic syntax trees, so it could equally
  1291.   serve as the basis for a assembly syntax translator, a disassembler, a
  1292.   common assembler/compiler back-end, etc.  Also, the full power of a
  1293.   real language, Scheme, make it unchallenged as for
  1294.   macroprocessing/metaprograming.
  1295.  
  1296.   <http://www.eleves.ens.fr:8080/home/rideau/Tunes/>
  1297.  
  1298.  
  1299.  
  1300.  
  1301.  
  1302.   5.  CALLING CONVENTIONS
  1303.  
  1304.  
  1305.  
  1306.  
  1307.   5.1.  Linux
  1308.  
  1309.  
  1310.  
  1311.   5.1.1.  Linking to GCC
  1312.  
  1313.   That's the preferred way.  Check GCC docs and examples from Linux
  1314.   kernel .S files that go through gas (not those that go through as86).
  1315.  
  1316.   32-bit arguments are pushed down stack in reverse syntactic order
  1317.   (hence accessed/popped in the right order), above the 32-bit near
  1318.   return address.  %ebp, %esi, %edi, %ebx are callee-saved, other
  1319.   registers are caller-saved; %eax is to hold the result, or %edx:%eax
  1320.   for 64-bit results.
  1321.   FP stack: I'm not sure, but I think it's result in st(0), whole stack
  1322.   caller-saved.
  1323.  
  1324.   Note that GCC has options to modify the calling conventions by
  1325.   reserving registers, having arguments in registers, not assuming the
  1326.   FPU, etc. Check the i386 .info pages.
  1327.  
  1328.   Beware that you must then declare the cdecl attribute for a function
  1329.   that will follow standard GCC calling conventions (I don't know what
  1330.   it does with modified calling conventions).  See in the GCC info pages
  1331.   the section: C Extensions::Extended Asm::
  1332.  
  1333.  
  1334.  
  1335.  
  1336.   5.1.2.  ELF vs a.out problems
  1337.  
  1338.   Some C compilers prepend an underscore before every symbol, while
  1339.   others do not.
  1340.  
  1341.   Particularly, Linux a.out GCC does such prepending, while Linux ELF
  1342.   GCC does not.
  1343.  
  1344.   If you need cope with both behaviors at once, see how existing
  1345.   packages do.  For instance, get an old Linux source tree, the Elk,
  1346.   qthreads, or OCAML...
  1347.  
  1348.   You can also override the implicit C->asm renaming by inserting
  1349.   statements like
  1350.  
  1351.   ______________________________________________________________________
  1352.           void foo asm("bar") (void);
  1353.   ______________________________________________________________________
  1354.  
  1355.  
  1356.   to be sure that the C function foo will be called really bar in assem-
  1357.   bly.
  1358.  
  1359.   Note that the utility objcopy, from the binutils package, should allow
  1360.   you to transform your a.out objects into ELF objects, and perhaps the
  1361.   contrary too, in some cases.  More generally, it will do lots of file
  1362.   format conversions.
  1363.  
  1364.  
  1365.  
  1366.  
  1367.   5.1.3.  Direct Linux syscalls
  1368.  
  1369.   This is specifically NOT recommended, because the conventions change
  1370.   from time to time or from kernel flavor to kernel flavor (cf L4Linux),
  1371.   plus it's not portable, it's a burden to write, it's redundant with
  1372.   the libc effort, AND it precludes fixes and extensions that are made
  1373.   to the libc, like, for instance the zlibc package, that does on-the-
  1374.   fly transparent decompression of gzip-compressed files.  The standard,
  1375.   recommended way to call Linux system services is, and will stay, to go
  1376.   through the libc.
  1377.  
  1378.   Shared objects should keep your stuff small.  And if you really want
  1379.   smaller binaries, do use #! stuff, with the interpreter having all the
  1380.   overhead you want to keep out of your binaries.
  1381.  
  1382.   Now, if for some reason, you don't want to link to the libc, go get
  1383.   the libc and understand how it works!  After all, you're pretending to
  1384.   replace it, ain't you?
  1385.  
  1386.  
  1387.   You might also take a look at how my eforth 1.0c
  1388.   <ftp://ftp.forth.org/pub/Forth/Linux/linux-eforth-1.0c.tgz> does it.
  1389.  
  1390.   The sources for Linux come in handy, too, particularly the
  1391.   asm/unistd.h header file, that describes how to do system calls...
  1392.  
  1393.   Basically, you issue an int $0x80, with the __NR_syscallname number
  1394.   (from asm/unistd.h) in %eax, and parameters (up to five) in %ebx,
  1395.   %ecx, %edx, %esi, %edi respectively.  Result is returned in %eax, with
  1396.   a negative result being an error whose opposite is what libc would put
  1397.   in errno.  The user-stack is not touched, so you needn't have a valid
  1398.   one when doing a syscall.
  1399.  
  1400.  
  1401.  
  1402.   5.1.4.  I/O under Linux
  1403.  
  1404.   If you want to do direct I/O under Linux, either it's something very
  1405.   simple that needn't OS arbitration, and you should see the IO-Port-
  1406.   Programming mini-HOWTO; or it needs a kernel device driver, and you
  1407.   should try to learn more about kernel hacking, device driver
  1408.   development, kernel modules, etc, for which there are other excellent
  1409.   HOWTOs and documents from the LDP.
  1410.  
  1411.   Particularly, if what you want is Graphics programming, then do join
  1412.   the GGI project: <http://synergy.caltech.edu/~ggi/>
  1413.   <http://sunserver1.rz.uni-duesseldorf.de/~becka/doc/scrdrv.html>
  1414.  
  1415.   Anyway, in all these cases, you'll be better off using GCC inline
  1416.   assembly with the macros from linux/asm/*.h than writing full assembly
  1417.   source files.
  1418.  
  1419.  
  1420.  
  1421.   5.1.5.  Accessing 16-bit drivers from Linux/i386
  1422.  
  1423.   Such thing is theoretically possible (proof: see how DOSEMU can
  1424.   selectively grant hardware port access to programs),and I've heard
  1425.   rumors that someone somewhere did actually do it (in the PCI driver?
  1426.   Some VESA access stuff? ISA PnP? dunno).  If you have some more
  1427.   precise information on that, you'll be most welcome.  Anyway, good
  1428.   places to look for more information are the Linux kernel sources,
  1429.   DOSEMU sources (and other programs in the DOSEMU repository
  1430.   <ftp://tsx-11.mit.edu/pub/linux/ALPHA/dosemu/>), and sources for
  1431.   various low-level programs under Linux...  (perhaps GGI if it supports
  1432.   VESA).
  1433.  
  1434.   Basically, you must either use 16-bit protected mode or vm86 mode.
  1435.  
  1436.   The first is simpler to setup, but only works with well-behaved code
  1437.   that won't do any kind of segment arithmetics or absolute segment
  1438.   addressing (particularly addressing segment 0), unless by chance it
  1439.   happens that all segments used can be setup in advance in the LDT.
  1440.  
  1441.   The later allows for more "compatibility" with vanilla 16-bit
  1442.   environments, but requires more complicated handling.
  1443.  
  1444.   In both cases, before you can jump to 16-bit code, you must
  1445.  
  1446.   o  mmap any absolute address used in the 16-bit code (such as ROM,
  1447.      video buffers, DMA targets, and memory-mapped I/O) from /dev/mem to
  1448.      your process' address space,
  1449.  
  1450.   o  setup the LDT and/or vm86 mode monitor.
  1451.  
  1452.  
  1453.   o  grab proper I/O permissions from the kernel (see the above section)
  1454.  
  1455.   Again, carefully read the source for the stuff contributed to the
  1456.   DOSEMU repository above, particularly these mini-emulators for running
  1457.   ELKS and/or simple .COM programs under Linux/i386.
  1458.  
  1459.  
  1460.  
  1461.   5.2.  DOS
  1462.  
  1463.   Most DOS extenders come with some interface to DOS services.  Read
  1464.   their docs about that, but often, they just simulate int $0x21 and
  1465.   such, so you do ``as if'' you were in real mode (I doubt they have
  1466.   more than stubs and extend things to work with 32-bit operands; they
  1467.   most likely will just reflect the interrupt into the real-mode or vm86
  1468.   handler).
  1469.  
  1470.   Docs about DPMI and such (and much more) can be found on
  1471.   <ftp://x2ftp.oulu.fi/pub/msdos/programming/>
  1472.  
  1473.   DJGPP comes with its own (limited) glibc
  1474.   derivative/subset/replacement, too.
  1475.  
  1476.   It is possible to cross-compile from Linux to DOS, see the
  1477.   devel/msdos/ directory of your local FTP mirror for sunsite.unc.edu
  1478.   Also see the MOSS dos-extender from the Flux project in utah.
  1479.  
  1480.   Other documents and FAQs are more DOS-centered.  We do not recommend
  1481.   DOS development.
  1482.  
  1483.  
  1484.  
  1485.   5.3.  Winblows and suches
  1486.  
  1487.   Hey, this document covers only free software.  Ring me when Winblows
  1488.   becomes free, or when there are free dev tools for it!
  1489.  
  1490.   Well, after all there is: Cygnus Solutions <http://www.cygnus.com> has
  1491.   developped the cygwin32.dll library, for GNU programs to run on
  1492.   MacroShit platforms.  Thus, you can use GCC, GAS, all the GNU tools,
  1493.   and many other Unix applications.  Have a look around their homepage.
  1494.   I (Far) don't intend to expand on Losedoze programming, but I'm sure
  1495.   you can find lots of documents about it everywhere...
  1496.  
  1497.  
  1498.  
  1499.   5.4.  Yer very own OS
  1500.  
  1501.   Control being what attract many programmers to assembly, want of OS
  1502.   development is often what leads to or stems from assembly hacking.
  1503.   Note that any system that allows self-development could be qualified
  1504.   an "OS" even though it might run "on top" of an underlying system that
  1505.   multitasking or I/O (much like Linux over Mach or OpenGenera over
  1506.   Unix), etc.  Hence, for easier debugging purpose, you might like to
  1507.   develop your ``OS'' first as a process running on top of Linux
  1508.   (despite the slowness), then use the Flux OS kit
  1509.   <http://ww.cs.utah.edu/projects/flux/> (which grants use of Linux and
  1510.   BSD drivers in yer own OS) to make it standalone.  When your OS is
  1511.   stable, it's still time to write your own hardware drivers if you
  1512.   really love that.
  1513.  
  1514.   This HOWTO will not itself cover topics such as Boot loader code &
  1515.   getting into 32-bit mode, Handling Interrupts, The basics about intel
  1516.   ``protected mode'' or ``V86/R86'' braindeadness, defining your object
  1517.   format and calling conventions.  The main place where to find reliable
  1518.   information about that all is source code of existing OSes and
  1519.   bootloaders.  Lots of pointers lie in the following WWW page:
  1520.   <http://www.eleves.ens.fr:8080/home/rideau/Tunes/Review/OSes.html>
  1521.  
  1522.  
  1523.  
  1524.   6.  TODO & POINTERS
  1525.  
  1526.  
  1527.  
  1528.   o  fill incomplete sections
  1529.  
  1530.   o  add more pointers to software and docs
  1531.  
  1532.   o  add simple examples from real life to illustrate the syntax, power,
  1533.      and limitations of each proposed solution.
  1534.  
  1535.   o  ask people to help with this HOWTO
  1536.  
  1537.   o  find someone who has got some time to takeover the maintenance
  1538.  
  1539.   o  perhaps give a few words for assembly on other platforms?
  1540.  
  1541.   o  A few pointers (in addition to those already in the rest of the
  1542.      HOWTO)
  1543.  
  1544.   o  pentium manuals <http://www.intel.com/design/pentium/manuals/>
  1545.  
  1546.   o  cpu bugs in the x86 family <http://www.xs4all.nl/~feldmann>
  1547.  
  1548.   o  hornet.eng.ufl.edu for assembly coders <http://www.eng.ufl.edu/ftp>
  1549.  
  1550.   o  ftp.luth.se <ftp://ftp.luth.se/pub/msdos/demos/code/>
  1551.  
  1552.   o  PM FAQ <ftp://zfja-gate.fuw.edu.pl/cpu/protect.mod>
  1553.  
  1554.   o  80x86 Assembly Page <http://www.fys.ruu.nl/~faber/Amain.html>
  1555.  
  1556.   o  Courseware <http://www.cit.ac.nz/smac/csware.htm>
  1557.  
  1558.   o  game programming <http://www.ee.ucl.ac.uk/~phart/gameprog.html>
  1559.  
  1560.   o  experiments with asm-only linux programming
  1561.      <http://bewoner.dma.be/JanW>
  1562.  
  1563.   o  And of course, do use your usual Internet Search Tools to look for
  1564.      more information, and tell me anything interesting you find!
  1565.  
  1566.  
  1567.   Authors' .sig:
  1568.  
  1569.   --    ,                                         ,           _ v    ~  ^  --
  1570.   -- Fare -- rideau@clipper.ens.fr -- Francois-Rene Rideau -- +)ang-Vu Ban --
  1571.   --                                      '                   / .          --
  1572.   Join the TUNES project for a computing system based on computing freedom !
  1573.                    TUNES is a Useful, Not Expedient System
  1574.   WWW page at URL: http://www.eleves.ens.fr:8080/home/rideau/Tunes/
  1575.  
  1576.  
  1577.  
  1578.  
  1579.  
  1580.  
  1581.  
  1582.  
  1583.  
  1584.  
  1585.