<?xml version="1.0"?>
<pkg:package name="t1B" revision="1.0"
xmlns:pkg="http://osoft.com/package"
xmlns:books="http://osoft.com/book">
<pkg:author></pkg:author>
<pkg:publisher></pkg:publisher>
<pkg:content>
<pkg:outlineMarker OutlineName="FreeBSD Developers' Handbook" id="AEN1" visible="true" renderchildren="false">
<div class="sect1">
<h1 class="title">FreeBSD Developers' Handbook</h1><a name="AEN2"></a><center><img src="wee.png" /></center>
<h3 class="corpauthor">The FreeBSD Documentation Project</h3>
<p class="copyright">Copyright © 2000, 2001, 2002, 2003, 2004 The FreeBSD
Documentation Project</p>
<a name="AEN35"></a>
<p>Welcome to the excerpts of this book. This is most definitely not the book you want to read, it is just test data input. 
Most of it makes absolutely no sense because random sections of the original have been deleted.
interested in helping with this project, send email to the <a href="http://lists.freebsd.org/mailman/listinfo/freebsd-doc" target="_top">FreeBSD
documentation project mailing list</a>.</p>
<p>The latest version of the real document is always available from the <a href="http://www.freebsd.org/index.html" target="_top">FreeBSD World Wide Web server</a>. It may
...the <a href="ftp://ftp.freebsd.org/pub/FreeBSD/doc/" target="_top">FreeBSD FTP server</a> or one
of the numerous <a href="pkg://FreeBSD Handbook/MIRRORS-FTP" target="_top">mirror sites</a>.</p>
<a name="LEGALNOTICE"></a>
<p>Redistribution and use in source (SGML DocBook) and 'compiled' forms (SGML, HTML, PDF,
PostScript, RTF and so forth) with or without modification, are permitted provided that
the following conditions are met:</p>
<ol type="1">
<li>
<p>Redistributions of source code (SGML DocBook) must retain the above copyright notice,
this list of conditions and the following disclaimer as the first lines of this file
unmodified.</p>
</li>
<li>
<p>Redistributions in compiled form (transformed to other DTDs, converted to PDF,
PostScript, RTF and other formats) must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.</p>
</li>
</ol>
<blockquote class="important">
<p><b>Important:</b> THIS DOCUMENTATION IS PROVIDED BY THE FREEBSD DOCUMENTATION PROJECT
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE FREEBSD DOCUMENTATION PROJECT BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p>
</blockquote>
<a name="TRADEMARKS"></a>
<p>FreeBSD is a registered trademark of the FreeBSD Foundation.</p>
<p>Apple, FireWire, Mac, Macintosh, Mac OS, Quicktime, and TrueType are trademarks of
Apple Computer, Inc., registered in the United States and other countries.</p>
<p>IBM, AIX, EtherJet, Netfinity, OS/2, PowerPC, PS/2, S/390, and ThinkPad are trademarks
of International Business Machines Corporation in the United States, other countries, or
both.</p>
<p>IEEE, POSIX, and 802 are registered trademarks of Institute of Electrical and
Electronics Engineers, Inc. in the United States.</p>
<p>Intel, Celeron, EtherExpress, i386, i486, Itanium, Pentium, and Xeon are trademarks or
registered trademarks of Intel Corporation or its subsidiaries in the United States and
other countries.</p>
<p>Linux is a registered trademark of Linus Torvalds.</p>
<p>Microsoft, IntelliMouse, MS-DOS, Outlook, Windows, Windows Media and Windows NT are
either registered trademarks or trademarks of Microsoft Corporation in the United States
and/or other countries.</p>
<p>Motif, OSF/1, and UNIX are registered trademarks and IT DialTone and The Open Group
are trademarks of The Open Group in the United States and other countries.</p>
<p>Sun, Sun Microsystems, Java, Java Virtual Machine, JavaServer Pages, JDK, JSP, JVM,
Netra, Solaris, StarOffice, Sun Blade, Sun Enterprise, Sun Fire, SunOS, and Ultra are
trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and
other countries.</p>
<p>Many of the designations used by manufacturers and sellers to distinguish their
products are claimed as trademarks. Where those designations appear in this document, and
the FreeBSD Project was aware of the trademark claim, the designations have been followed
by the ``™'' or the ``®'' symbol.</p>
<hr />
<dl>
<dt><b>Table of Contents</b></dt>
<dt>I. <a href="pkg://t1B/BASICS">Basics</a></dt>
<dd>
<dl>
<dt>1 <a href="pkg://FreeBSD Developers' Handbook/INTRODUCTION">Introduction</a></dt>
<dd>
<dl>
<dt>1.1 <a href="pkg://FreeBSD Developers' Handbook/INTRODUCTION-DEVEL">Developing on FreeBSD</a></dt>
<dt>1.2 <a href="pkg://FreeBSD Developers' Handbook/INTRODUCTION-BSDVISION">The BSD Vision</a></dt>
<dt>1.3 <a href="pkg://FreeBSD Developers' Handbook/INTRODUCTION-ARCHGUIDE">Architectural Guidelines</a></dt>
<dt>1.4 <a href="pkg://FreeBSD Developers' Handbook/INTRODUCTION-LAYOUT">The Layout of <tt class="filename">/usr/src</tt></a></dt>
</dl>
</dd>
<dt>2 <a href="pkg://FreeBSD Developers' Handbook/TOOLS">Programming Tools</a></dt>
<dd>
<dl>
<dt>2.1 <a href="pkg://FreeBSD Developers' Handbook/TOOLS-SYNOPSIS">Synopsis</a></dt>
<dt>2.2 <a href="pkg://FreeBSD Developers' Handbook/TOOLS-INTRO">Introduction</a></dt>
<dt>2.3 <a href="pkg://FreeBSD Developers' Handbook/TOOLS-PROGRAMMING">Introduction to Programming</a></dt>
<dt>2.4 <a href="pkg://FreeBSD Developers' Handbook/TOOLS-COMPILING">Compiling with <tt class="command">cc</tt></a></dt>
<dt>2.5 <a href="pkg://FreeBSD Developers' Handbook/TOOLS-MAKE">Make</a></dt>
<dt>2.6 <a href="pkg://FreeBSD Developers' Handbook/DEBUGGING">Debugging</a></dt>
<dt>2.7 <a href="pkg://FreeBSD Developers' Handbook/EMACS">Using Emacs as a Development Environment</a></dt>
<dt>2.8 <a href="pkg://FreeBSD Developers' Handbook/TOOLS-READING">Further Reading</a></dt>
</dl>
</dd>
<dt>3 <a href="pkg://FreeBSD Developers' Handbook/SECURE">Secure Programming</a></dt>
<dd>
<dl>
<dt>3.1 <a href="pkg://FreeBSD Developers' Handbook/SECURE-SYNOPSIS">Synopsis</a></dt>
<dt>3.2 <a href="pkg://FreeBSD Developers' Handbook/SECURE-PHILOSOPHY">Secure Design Methodology</a></dt>
<dt>3.3 <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
<dt>3.4 <a href="pkg://FreeBSD Developers' Handbook/SECURE-SETUID">SetUID issues</a></dt>
<dt>3.5 <a href="pkg://FreeBSD Developers' Handbook/SECURE-CHROOT">Limiting your program's environment</a></dt>
<dt>3.6 <a href="pkg://FreeBSD Developers' Handbook/SECURE-TRUST">Trust</a></dt>
<dt>3.7 <a href="pkg://FreeBSD Developers' Handbook/SECURE-RACE-CONDITIONS">Race Conditions</a></dt>
</dl>
</dd>
<dt>4 <a href="pkg://FreeBSD Developers' Handbook/L10N">Localization and Internationalization - L10N and I18N</a></dt>
<dd>
<dl>
<dt>4.1 <a href="pkg://FreeBSD Developers' Handbook/L10N-PROGRAMMING">Programming I18N Compliant Applications</a></dt>
</dl>
</dd>
<dt>5 <a href="pkg://FreeBSD Developers' Handbook/POLICIES">Source Tree Guidelines and Policies</a></dt>
<dd>
<dl>
<dt>5.1 <a href="pkg://FreeBSD Developers' Handbook/POLICIES-MAINTAINER"><tt class="makevar">MAINTAINER</tt> on
Makefiles</a></dt>
<dt>5.2 <a href="pkg://FreeBSD Developers' Handbook/POLICIES-CONTRIBUTED">Contributed Software</a></dt>
<dt>5.3 <a href="pkg://FreeBSD Developers' Handbook/POLICIES-ENCUMBERED">Encumbered Files</a></dt>
<dt>5.4 <a href="pkg://FreeBSD Developers' Handbook/POLICIES-SHLIB">Shared Libraries</a></dt>
</dl>
</dd>
<dt>6 <a href="pkg://FreeBSD Developers' Handbook/TESTING">Regression and Performance Testing</a></dt>
<dd>
<dl>
<dt>6.1. <a href="pkg://FreeBSD Developers' Handbook/TESTING/#TESTING-MICRO-BENCHMARK">Micro Benchmark Checklist</a></dt>
</dl>
</dd>
</dl>
</dd>
<dt>II. <a href="pkg://FreeBSD Developers' Handbook/IPC">Interprocess Communication</a></dt>
<dd>
<dl>
<dt>7 <a href="pkg://FreeBSD Developers' Handbook/SIGNALS">* Signals</a></dt>
<dt>8 <a href="pkg://FreeBSD Developers' Handbook/SOCKETS">Sockets</a></dt>
<dd>
<dl>
<dt>8.1 <a href="pkg://FreeBSD Developers' Handbook/SOCKETS-SYNOPSIS">Synopsis</a></dt>
<dt>8.2 <a href="pkg://FreeBSD Developers' Handbook/SOCKETS-DIVERSITY">Networking and Diversity</a></dt>
<dt>8.3 <a href="pkg://FreeBSD Developers' Handbook/SOCKETS-PROTOCOLS">Protocols</a></dt>
<dt>8.4 <a href="pkg://FreeBSD Developers' Handbook/SOCKETS-MODEL">The Sockets Model</a></dt>
<dt>8.5 <a href="pkg://FreeBSD Developers' Handbook/SOCKETS-ESSENTIAL-FUNCTIONS">Essential Socket Functions</a></dt>
<dt>8.6 <a href="pkg://FreeBSD Developers' Handbook/SOCKETS-HELPER-FUNCTIONS">Helper Functions</a></dt>
<dt>8.7 <a href="pkg://FreeBSD Developers' Handbook/SOCKETS-CONCURRENT-SERVERS">Concurrent Servers</a></dt>
</dl>
</dd>
<dt>9 <a href="pkg://FreeBSD Developers' Handbook/IPV6">IPv6 Internals</a></dt>
<dd>
<dl>
<dt>9.1 <a href="pkg://FreeBSD Developers' Handbook/IPV6-IMPLEMENTATION">IPv6/IPsec Implementation</a></dt>
</dl>
</dd>
</dl>
</dd>
<dt>III. <a href="pkg://FreeBSD Developers' Handbook/KERNEL">Kernel</a></dt>
<dd>
<dl>
<dt>10 <a href="pkg://FreeBSD Developers' Handbook/DMA">DMA</a></dt>
<dd>
<dl>
<dt>10.1 <a href="pkg://FreeBSD Developers' Handbook/DMA-BASICS">DMA: What it is and How it Works</a></dt>
</dl>
</dd>
<dt>11 <a href="pkg://FreeBSD Developers' Handbook/KERNELDEBUG">Kernel Debugging</a></dt>
<dd>
<dl>
<dt>11.1 <a href="pkg://FreeBSD Developers' Handbook/KERNELDEBUG-OBTAIN">Obtaining a Kernel Crash Dump</a></dt>
<dt>11.2 <a href="pkg://FreeBSD Developers' Handbook/KERNELDEBUG-GDB">Debugging a Kernel Crash Dump with <tt class="command">kgdb</tt></a></dt>
<dt>11.3 <a href="pkg://FreeBSD Developers' Handbook/KERNELDEBUG-DDD">Debugging a Crash Dump with DDD</a></dt>
<dt>11.4 <a href="pkg://FreeBSD Developers' Handbook/KERNELDEBUG-POST-MORTEM">Post-Mortem Analysis of a Dump</a></dt>
<dt>11.5 <a href="pkg://FreeBSD Developers' Handbook/KERNELDEBUG-ONLINE-DDB">On-Line Kernel Debugging Using DDB</a></dt>
<dt>11.6 <a href="pkg://FreeBSD Developers' Handbook/KERNELDEBUG-ONLINE-GDB">On-Line Kernel Debugging Using Remote
GDB</a></dt>
<dt>11.7 <a href="pkg://FreeBSD Developers' Handbook/KERNELDEBUG-KLD">Debugging Loadable Modules Using GDB</a></dt>
<dt>11.8 <a href="pkg://FreeBSD Developers' Handbook/KERNELDEBUG-CONSOLE">Debugging a Console Driver</a></dt>
</dl>
</dd>
<dt>12 <a href="pkg://FreeBSD Developers' Handbook/UFS">* UFS</a></dt>
<dt>13 <a href="pkg://FreeBSD Developers' Handbook/AFS">* AFS</a></dt>
<dt>14 <a href="pkg://FreeBSD Developers' Handbook/SYSCONS">* Syscons</a></dt>
<dt>15 <a href="pkg://FreeBSD Developers' Handbook/COMPATIBILITY">* Compatibility Layers</a></dt>
<dd>
<dl>
<dt>15.1 <a href="pkg://FreeBSD Developers' Handbook/LINUX">* Linux</a></dt>
</dl>
</dd>
</dl>
</dd>
<dt>IV. <a href="pkg://FreeBSD Developers' Handbook/ARCHITECTURES">Architectures</a></dt>
<dd>
<dl>
<dt>16 <a href="pkg://FreeBSD Developers' Handbook/X86">x86 Assembly Language Programming</a></dt>
<dd>
<dl>
<dt>16.1 <a href="pkg://FreeBSD Developers' Handbook/X86-INTRO">Synopsis</a></dt>
<dt>16.2 <a href="pkg://FreeBSD Developers' Handbook/X86-THE-TOOLS">The Tools</a></dt>
<dt>16.3 <a href="pkg://FreeBSD Developers' Handbook/X86-SYSTEM-CALLS">System Calls</a></dt>
<dt>16.4 <a href="pkg://FreeBSD Developers' Handbook/X86-RETURN-VALUES">Return Values</a></dt>
<dt>16.5 <a href="pkg://FreeBSD Developers' Handbook/X86-PORTABLE-CODE">Creating Portable Code</a></dt>
<dt>16.6 <a href="pkg://FreeBSD Developers' Handbook/X86-FIRST-PROGRAM">Our First Program</a></dt>
<dt>16.7 <a href="pkg://FreeBSD Developers' Handbook/X86-UNIX-FILTERS">Writing <span class="trademark">UNIX</span>®
Filters</a></dt>
<dt>16.8 <a href="pkg://FreeBSD Developers' Handbook/X86-BUFFERED-IO">Buffered Input and Output</a></dt>
<dt>16.9 <a href="pkg://FreeBSD Developers' Handbook/X86-COMMAND-LINE">Command Line Arguments</a></dt>
<dt>16.10 <a href="pkg://FreeBSD Developers' Handbook/X86-ENVIRONMENT"><span class="trademark">UNIX</span>
Environment</a></dt>
<dt>16.11 <a href="pkg://FreeBSD Developers' Handbook/X86-FILES">Working with Files</a></dt>
<dt>16.12 <a href="pkg://FreeBSD Developers' Handbook/X86-ONE-POINTED-MIND">One-Pointed Mind</a></dt>
<dt>16.13 <a href="pkg://FreeBSD Developers' Handbook/X86-FPU">Using the <acronym class="acronym">FPU</acronym></a></dt>
<dt>16.14 <a href="pkg://FreeBSD Developers' Handbook/X86-CAVEATS">Caveats</a></dt>
<dt>16.15 <a href="pkg://FreeBSD Developers' Handbook/X86-ACKNOWLEDGEMENTS">Acknowledgements</a></dt>
</dl>
</dd>
<dt>17 <a href="pkg://FreeBSD Developers' Handbook/ALPHA">* Alpha</a></dt>
</dl>
</dd>
<dt>V. <a href="pkg://FreeBSD Developers' Handbook/APPENDICES">Appendices</a></dt>
<dd>
<dl>
<dt><a href="pkg://FreeBSD Developers' Handbook/APPENDICES/#AEN6428">Bibliography</a></dt>
<dt><a href="pkg://FreeBSD Developers' Handbook/DOC-INDEX">Index</a></dt>
</dl>
</dd>
</dl>
<dl class="lot">
<dt><b>List of Examples</b></dt>
<dt>2-1. <a href="pkg://FreeBSD Developers' Handbook/AEN1140/#AEN1179">A sample <tt class="filename">.emacs</tt> file</a></dt>
</dl>
<div align="right"><img align="right" src="wee.png" /></div>
</div>
<pkg:outlineMarker OutlineName="I. Basics" id="BASICS" visible="true" renderchildren="false">
<div class="sect1">
<h1 class="title">I. Basics</h1>
<dl>
<dt><b>Table of Contents</b></dt>
<dt>1 <a href="pkg://FreeBSD Developers' Handbook/INTRODUCTION">Introduction</a></dt>
<dt>2 <a href="pkg://FreeBSD Developers' Handbook/TOOLS">Programming Tools</a></dt>
<dt>3 <a href="pkg://FreeBSD Developers' Handbook/SECURE">Secure Programming</a></dt>
<dt>4 <a href="pkg://FreeBSD Developers' Handbook/L10N">Localization and Internationalization - L10N and I18N</a></dt>
<dt>5 <a href="pkg://FreeBSD Developers' Handbook/POLICIES">Source Tree Guidelines and Policies</a></dt>
<dt>6 <a href="pkg://FreeBSD Developers' Handbook/TESTING">Regression and Performance Testing</a></dt>
</dl>
<hr />
<pkg:outlineMarker OutlineName="Chapter 1 Introduction" id="INTRODUCTION">
<div class="sect1">
<h1 class="title">Chapter 1 Introduction</h1>
<i class="authorgroup"><span class="contrib">Contributed by</span> Murray Stokely and
Jeroen Ruigrok van der Werven.</i>
<pkg:outlineMarker OutlineName="1.1 Developing on FreeBSD" id="INTRODUCTION-DEVEL">
<div class="sect2">
<h2 class="title">1.1 Developing on
FreeBSD</h2>
<p>So here we are...
</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="1.4 The Layout of /usr/src" id="INTRODUCTION-LAYOUT">
<div class="sect2">
<h2 class="title">1.4 The Layout
of <tt class="filename">/usr/src</tt></h2>
<p>
the following subdirectories:</p>
<p></p>
<a name="AEN89"></a>
<table class="calstable" border="0" frame="void" width="100%">
<col />
<col />
<thead>
<tr>
<th>Directory</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><tt class="filename">bin/</tt></td>
<td>Source for files in <tt class="filename">/bin</tt></td>
</tr>
<tr>
<td><tt class="filename">contrib/</tt></td>
<td>Source for files from contributed software.</td>
</tr>
<tr>
<td><tt class="filename">crypto/</tt></td>
<td>Cryptographical sources</td>
</tr>
<tr>
<td><tt class="filename">etc/</tt></td>
<td>Source for files in <tt class="filename">/etc</tt></td>
</tr>
<tr>
<td><tt class="filename">games/</tt></td>
<td>Source for files in <tt class="filename">/usr/games</tt></td>
</tr>
<tr>
<td><tt class="filename">gnu/</tt></td>
<td>Utilities covered by the GNU Public License</td>
</tr>
<tr>
<td><tt class="filename">include/</tt></td>
<td>Source for files in <tt class="filename">/usr/include</tt></td>
</tr>
<tr>
<td><tt class="filename">kerberosIV/</tt></td>
<td>Source for Kerberos version IV</td>
</tr>
<tr>
<td><tt class="filename">kerberos5/</tt></td>
<td>Source for Kerberos version 5</td>
</tr>
<tr>
<td><tt class="filename">lib/</tt></td>
<td>Source for files in <tt class="filename">/usr/lib</tt></td>
</tr>
<tr>
<td><tt class="filename">libexec/</tt></td>
<td>Source for files in <tt class="filename">/usr/libexec</tt></td>
</tr>
<tr>
<td><tt class="filename">release/</tt></td>
<td>Files required to produce a FreeBSD release</td>
</tr>
<tr>
<td><tt class="filename">sbin/</tt></td>
<td>Source for files in <tt class="filename">/sbin</tt></td>
</tr>
<tr>
<td><tt class="filename">secure/</tt></td>
<td>FreeSec sources</td>
</tr>
<tr>
<td><tt class="filename">share/</tt></td>
<td>Source for files in <tt class="filename">/usr/share</tt></td>
</tr>
<tr>
<td><tt class="filename">sys/</tt></td>
<td>Kernel source files</td>
</tr>
<tr>
<td><tt class="filename">tools/</tt></td>
<td>Tools used for maintenance and testing of FreeBSD</td>
</tr>
<tr>
<td><tt class="filename">usr.bin/</tt></td>
<td>Source for files in <tt class="filename">/usr/bin</tt></td>
</tr>
<tr>
<td><tt class="filename">usr.sbin/</tt></td>
<td>Source for files in <tt class="filename">/usr/sbin</tt></td>
</tr>
</tbody>
</table>
<br />
<br />
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="Chapter 2 Programming Tools" id="TOOLS">
<div class="sect1">
<h1 class="title">Chapter 2 Programming Tools</h1>
<i class="authorgroup"><span class="contrib">Contributed by</span> James Raynard and
Murray Stokely.</i>
<pkg:outlineMarker OutlineName="2.1 Synopsis" id="TOOLS-SYNOPSIS">
<div class="sect2">
<h2 class="title">2.1 Synopsis</h2>
<p>This chapter ...
<span class="trademark">UNIX</span>. It does <span class="emphasis"><i class="emphasis">not</i></span> attempt
...in it.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="2.2 Introduction" id="TOOLS-INTRO">
<div class="sect2">
<h2 class="title">2.2 Introduction</h2>
<p>FreeBSD offers ...
classic <span class="trademark">UNIX</span> tools such as <tt class="command">sed</tt>
and <tt class="command">awk</tt>. there are many more compilers
as <acronym class="acronym"><span class="trademark">POSIX</span>®</acronym> and
<acronym class="acronym">ANSI</acronym> C,
...range of platforms.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="2.3 Introduction to Programming" id="TOOLS-PROGRAMMING">
<div class="sect2">
<h2 class="title">2.3 Introduction to
Programming</h2>
<p>A program is a set of instructions that tell the computer to do various things;
sometimes the instruction it has to perform depends on what happened when it performed a
previous instruction. This section gives an overview of the two main ways in which you
can give these instructions, or ``commands'' as they are usually called. One way uses an
<i class="firstterm">interpreter</i>, the other a <i class="firstterm">compiler</i>. As
human languages are too difficult for a computer to understand in an unambiguous way,
commands are usually written in one or other languages specially designed for the
purpose.</p>
<hr />
<pkg:outlineMarker OutlineName="2.3.1 Interpreters" id="AEN217">
<div class="sect3">
<h3 class="title">2.3.1 Interpreters</h3>
<p>With an interpreter, the language comes as an environment, where you type in commands
at a prompt and the environment executes them for you. For more complicated programs, you
can type the commands into a file and get the interpreter to load the file and execute
the commands in it. If anything goes wrong, many interpreters will drop you into a
debugger to help you track down the problem.</p>
<p>The advantage of this is that you can see the results of your commands immediately,
and mistakes can be corrected readily. The biggest disadvantage comes when you want to
share your programs with someone. They must have the same interpreter, or you must have
some way of giving it to them, and they need to understand how to use it. Also users may
not appreciate being thrown into a debugger if they press the wrong key! From a
performance point of view, interpreters can use up a lot of memory, and generally do not
generate code as efficiently as compilers.</p>
<p>In my opinion, interpreted languages are the best way to start if you have not done
any programming before. This kind of environment is typically found with languages like
Lisp, Smalltalk, Perl and Basic. It could also be argued that the <span class="trademark">UNIX</span> shell (<tt class="command">sh</tt>, <tt class="command">csh</tt>) is itself an interpreter, and many people do in fact write
shell ``scripts'' to help with various ``housekeeping'' tasks on their machine. Indeed,
part of the original <span class="trademark">UNIX</span> philosophy was to provide lots
of small utility programs that could be linked together in shell scripts to perform
useful tasks.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="2.3.2 Interpreters available with FreeBSD" id="AEN228">
<div class="sect3">
<h3 class="title">2.3.2 Interpreters available with
FreeBSD</h3>
<p>Here is a list ... <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/" target="_top">FreeBSD
packages</a>, ...
languages.</p>
<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">pkg_add <var class="replaceable">package name</var></kbd>
</pre>
<dl>
<dt><acronym class="acronym">BASIC</acronym></dt>
<dd>
<p>Short for Beginner's All-purpose Symbolic Instruction Code...
...Basic.</p>
<p>The <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/bwbasic.tgz" target="_top">Bywater Basic Interpreter</a> and the <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/pbasic.tgz" target="_top">Phil Cockroft's Basic Interpreter</a> (formerly Rabbit Basic) are available
as <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/" target="_top">FreeBSD packages</a>.</p>
</dd>
<dt>Lisp</dt>
<dd>
<p>A language ...
``number-crunching''
popular in <acronym class="acronym">AI</acronym> (Artificial Intelligence) circles.</p>
</dd>
<dt>Perl</dt>
<dd>
<p>Very popular ...
.</p>
</dd>
</dl>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="2.3.3 Compilers" id="AEN302">
<div class="sect3">
<h3 class="title">2.3.3 Compilers</h3>
<p>Compilers are rather different.
works properly. <a name="AEN305" href="pkg://FreeBSD Developers' Handbook/FTNAEN305"><span class="footnote">[1]</span></a></p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="2.4 Compiling with cc" id="TOOLS-COMPILING">
<div class="sect2">
<h2 class="title">2.4 Compiling with <tt class="command">cc</tt></h2>
<ol type="1">
<li>
<p>Pre-process your source code to remove comments and do other tricks like expanding
macros in C.</p>
</li>
<li>
<p>Check the syntax of your code to see if you have obeyed the rules of the language. If
you have not, it will complain!</p>
</li>
<li>
<p>Convert the source code into assembly language--this is very close to machine code,
but still understandable by humans. Allegedly. <a name="AEN331" href="pkg://FreeBSD Developers' Handbook/FTNAEN331"><span class="footnote">[2]</span></a></p>
</li>
<li>
<p>Finally, write the executable on the filesystem.</p>
</li>
</ol>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc foobar.c</kbd>
</pre>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc foo.c bar.c</kbd>
</pre>
<p>There are lots and lots of options for <tt class="command">cc</tt>, which are all in
...them.</p>
<dl>
<dt><var class="option">-o <var class="replaceable">filename</var></var></dt>
<dd>
<p>The output name of the file. If you do not use this option, <tt class="command">cc</tt> will produce an executable called <tt class="filename">a.out</tt>. <a name="AEN374" href="pkg://FreeBSD Developers' Handbook/FTNAEN374"><span class="footnote">[4]</span></a></p>
<a name="AEN376"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc foobar.c</kbd> executable is <tt class="filename">a.out</tt>
<samp class="prompt">%</samp> <kbd class="userinput">cc -o foobar foobar.c</kbd> executable is <tt class="filename">foobar</tt>
</pre>
</dd>
</dl>
<hr />
<pkg:outlineMarker OutlineName="2.4.1 Common cc Queries and Problems" id="AEN523">
<div class="sect3">
<h3 class="title">2.4.1 Common <tt class="command">cc</tt>
Queries and Problems</h3>
<dl>
<dt>2.4.1.11. <a href="pkg://FreeBSD Developers' Handbook/Q24111">This dumping core business sounds as though it could
be quite useful, if I can make it happen when I want to. Can I do this, or do I have to
wait until there is an error?</a></dt>
</dl>
<pkg:outlineMarker OutlineName="2.4.1.2. All right, I wrote this simple program to practice using -lm. All it does is raise 2.1 to the power of 6." id="Q2412">
<div class="sect4">
<div class="title"><b>2.4.1.2.</b> All right, I wrote this simple
...power of 6.</div>
<a name="AEN545"></a>
<pkg:outlineMarker OutlineName="code_1" id="code_1" visible="false" copy="true">
<pre class="programlisting">#include <stdio.h>
int main() {
float f;
f = pow(2.1, 6);
printf("2.1 ^ 6 = %f\n", f);
return 0;
}
</pre>
</pkg:outlineMarker>
<p>and I compiled it as:</p>
<a name="AEN548"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc temp.c -lm</kbd>
</pre>
<p>like you said I should, but I get this when I run it:</p>
<a name="AEN553"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">./a.out</kbd>
2.1 ^ 6 = 1023.000000
</pre>
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="IV. Architectures" id="ARCHITECTURES" visible="true" renderchildren="false">
<div class="sect1">
<h1 class="title">IV. Architectures</h1>
<dl>
<dt><b>Table of Contents</b></dt>
<dt>16 <a href="pkg://FreeBSD Developers' Handbook/X86">x86 Assembly Language Programming</a></dt>
<dt>17 <a href="pkg://FreeBSD Developers' Handbook/ALPHA">* Alpha</a></dt>
</dl>
<hr />
<pkg:outlineMarker OutlineName="Chapter 16 x86 Assembly Language Programming" id="X86">
<div class="sect1">
<h1 class="title">Chapter 16 x86 Assembly Language Programming</h1>
<p><span class="emphasis"><i class="emphasis">This chapter was written by G. Adam
Stanislav <code class="email"><<a href="mailto:adam@redprince.net">adam@redprince.net</a>></code>.</i></span></p>
<hr />
<pkg:outlineMarker OutlineName="16.1 Synopsis" id="X86-INTRO">
<div class="sect2">
<h2 class="title">16.1 Synopsis</h2>
<p>Assembly language programming under <span class="trademark">UNIX</span> is highly
undocumented. It is generally assumed that no one would ever want to use it because
various <span class="trademark">UNIX</span> systems run on different microprocessors, so
everything should be written in C for portability.</p>
<p>In reality, C portability is quite a myth. Even C programs need to be modified when
ported from one <span class="trademark">UNIX</span> to another, regardless of what
processor each runs on. Typically, such a program is full of conditional statements
depending on the system it is compiled for.</p>
<p>Even if we believe that all of <span class="trademark">UNIX</span> software should be
written in C, or some other high-level language, we still need assembly language
programmers: Who else would write the section of C library that accesses the kernel?</p>
<p>In this chapter I will attempt to show you how you can use assembly language writing
<span class="trademark">UNIX</span> programs, specifically under FreeBSD.</p>
<p>This chapter does not explain the basics of assembly language. There are enough
resources about that (for a complete online course in assembly language, see Randall
Hyde's <a href="http://webster.cs.ucr.edu/" target="_top">Art of Assembly Language</a>;
or if you prefer a printed book, take a look at Jeff Duntemann's <a href="http://www.int80h.org/cgi-bin/isbn?isbn=0471375233" target="_top">Assembly Language
Step-by-Step</a>). However, once the chapter is finished, any assembly language
programmer will be able to write programs for FreeBSD quickly and efficiently.</p>
<p>Copyright © 2000-2001 G. Adam Stanislav. All rights reserved.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.2 The Tools" id="X86-THE-TOOLS">
<div class="sect2">
<h2 class="title">16.2 The Tools</h2>
<pkg:outlineMarker OutlineName="16.2.1 The Assembler" id="X86-THE-ASSEMBLER">
<div class="sect3">
<h3 class="title">16.2.1 The
Assembler</h3>
<p>The most important tool for assembly language programming is the assembler, the
software that converts assembly language code into machine language.</p>
<p>Two very different assemblers are available for FreeBSD. One is <a href="http://www.freebsd.org/cgi/man.cgi?query=as&sektion=1"><span class="citerefentry"><span class="refentrytitle">as</span>(1)</span></a>, which uses the
traditional <span class="trademark">UNIX</span> assembly language syntax. It comes with
the system.</p>
<p>The other is <b class="application">/usr/ports/devel/nasm</b>. It uses the Intel
syntax. Its main advantage is that it can assemble code for many operating systems. It
needs to be installed separately, but is completely free.</p>
<p>This chapter uses <b class="application">nasm</b> syntax because most assembly
language programmers coming to FreeBSD from other operating systems will find it easier
to understand. And, because, quite frankly, that is what I am used to.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.2.2 The Linker" id="X86-THE-LINKER">
<div class="sect3">
<h3 class="title">16.2.2 The Linker</h3>
<p>The output of the assembler, like that of any compiler, needs to be linked to form an
executable file.</p>
<p>The standard <a href="http://www.freebsd.org/cgi/man.cgi?query=ld&sektion=1"><span class="citerefentry"><span class="refentrytitle">ld</span>(1)</span></a> linker comes
with FreeBSD. It works with the code assembled with either assembler.</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.3 System Calls" id="X86-SYSTEM-CALLS">
<div class="sect2">
<h2 class="title">16.3 System
Calls</h2>
<pkg:outlineMarker OutlineName="16.3.1 Default Calling Convention" id="X86-DEFAULT-CALLING-CONVENTION">
<div class="sect3">
<h3 class="title">16.3.1 Default Calling Convention</h3>
<p>By default, the FreeBSD kernel uses the C calling convention. Further, although the
kernel is accessed using <code class="function">int 80h</code>, it is assumed the program
will call a function that issues <code class="function">int 80h</code>, rather than
issuing <code class="function">int 80h</code> directly.</p>
<p>This convention is very convenient, and quite superior to the <span class="trademark">Microsoft</span> convention used by <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym>. Why? Because the <span class="trademark">UNIX</span> convention allows any program written in any language to
access the kernel.</p>
<p>An assembly language program can do that as well. For example, we could open a
file:</p>
<pkg:outlineMarker OutlineName="code_48" id="code_48" visible="false" copy="true">
<pre class="programlisting">kernel:
int 80h ; Call kernel
ret
open:
push dword mode
push dword flags
push dword path
mov eax, 5
call kernel
add esp, byte 12
ret
</pre>
</pkg:outlineMarker>
<p>This is a very clean and portable way of coding. If you need to port the code to a
<span class="trademark">UNIX</span> system which uses a different interrupt, or a
different way of passing parameters, all you need to change is the kernel procedure.</p>
<p>But assembly language programmers like to shave off cycles. The above example requires
a <code class="function">call/ret</code> combination. We can eliminate it by <code class="function">push</code>ing an extra dword:</p>
<pkg:outlineMarker OutlineName="code_49" id="code_49" visible="false" copy="true">
<pre class="programlisting">open:
push dword mode
push dword flags
push dword path
mov eax, 5
push eax ; Or any other dword
int 80h
add esp, byte 16
</pre>
</pkg:outlineMarker>
<p>The <code class="constant">5</code> that we have placed in <var class="varname">EAX</var> identifies the kernel function, in this case <code class="function">open</code>.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.3.2 Alternate Calling Convention" id="X86-ALTERNATE-CALLING-CONVENTION">
<div class="sect3">
<h3 class="title">16.3.2 Alternate Calling Convention</h3>
<p>FreeBSD is an extremely flexible system. It offers other ways of calling the kernel.
For it to work, however, the system must have Linux emulation installed.</p>
<p>Linux is a <span class="trademark">UNIX</span> like system. However, its kernel uses
the same system-call convention of passing parameters in registers <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym> does. As with the <span class="trademark">UNIX</span> convention, the function number is placed in <var class="varname">EAX</var>. The parameters, however, are not passed on the stack but in
<var class="varname">EBX, ECX, EDX, ESI, EDI, EBP</var>:</p>
<pkg:outlineMarker OutlineName="code_50" id="code_50" visible="false" copy="true">
<pre class="programlisting">open:
mov eax, 5
mov ebx, path
mov ecx, flags
mov edx, mode
int 80h
</pre>
</pkg:outlineMarker>
<p>This convention has a great disadvantage over the <span class="trademark">UNIX</span>
way, at least as far as assembly language programming is concerned: Every time you make a
kernel call you must <code class="function">push</code> the registers, then <code class="function">pop</code> them later. This makes your code bulkier and slower.
Nevertheless, FreeBSD gives you a choice.</p>
<p>If you do choose the Linux convention, you must let the system know about it. After
your program is assembled and linked, you need to brand the executable:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">brandelf -f Linux <var class="replaceable">filename</var></kbd>
</pre>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.3.3 Which Convention Should You Use?" id="X86-USE-GENEVA">
<div class="sect3">
<h3 class="title">16.3.3 Which Convention
Should You Use?</h3>
<p>If you are coding specifically for FreeBSD, you should always use the <span class="trademark">UNIX</span> convention: It is faster, you can store global variables in
registers, you do not have to brand the executable, and you do not impose the
installation of the Linux emulation package on the target system.</p>
<p>If you want to create portable code that can also run on Linux, you will probably
still want to give the FreeBSD users as efficient a code as possible. I will show you how
you can accomplish that after I have explained the basics.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.3.4 Call Numbers" id="X86-CALL-NUMBERS">
<div class="sect3">
<h3 class="title">16.3.4 Call
Numbers</h3>
<p>To tell the kernel which system service you are calling, place its number in <var class="varname">EAX</var>. Of course, you need to know what the number is.</p>
<hr />
<pkg:outlineMarker OutlineName="16.3.4.1 The syscalls File" id="X86-THE-SYSCALLS-FILE">
<div class="sect3">
<h4 class="title">16.3.4.1 The
<tt class="filename">syscalls</tt> File</h4>
<p>The numbers are listed in <tt class="filename">syscalls</tt>. <tt class="command">locate syscalls</tt> finds this file in several different formats, all
produced automatically from <tt class="filename">syscalls.master</tt>.</p>
<p>You can find the master file for the default <span class="trademark">UNIX</span>
calling convention in <tt class="filename">/usr/src/sys/kern/syscalls.master</tt>. If you
need to use the other convention implemented in the Linux emulation mode, read <tt class="filename">/usr/src/sys/i386/linux/syscalls.master</tt>.</p>
<blockquote class="note">
<p><b>Note:</b> Not only do FreeBSD and Linux use different calling conventions, they
sometimes use different numbers for the same functions.</p>
</blockquote>
<p><tt class="filename">syscalls.master</tt> describes how the call is to be made:</p>
<pkg:outlineMarker OutlineName="code_51" id="code_51" visible="false" copy="true">
<pre class="programlisting">0 STD NOHIDE { int nosys(void); } syscall nosys_args int
1 STD NOHIDE { void exit(int rval); } exit rexit_args void
2 STD POSIX { int fork(void); }
3 STD POSIX { ssize_t read(int fd, void *buf, size_t nbyte); }
4 STD POSIX { ssize_t write(int fd, const void *buf, size_t nbyte); }
5 STD POSIX { int open(char *path, int flags, int mode); }
6 STD POSIX { int close(int fd); }
etc...
</pre>
</pkg:outlineMarker>
<p>It is the leftmost column that tells us the number to place in <var class="varname">EAX</var>.</p>
<p>The rightmost column tells us what parameters to <code class="function">push</code>.
They are <code class="function">push</code>ed <span class="emphasis"><i class="emphasis">from right to left</i></span>.</p>
<a name="AEN4689"></a>
<p>For example, to <code class="function">open</code> a file, we need to <code class="function">push</code> the <var class="varname">mode</var> first, then <var class="varname">flags</var>, then the address at which the <var class="varname">path</var> is stored.</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.4 Return Values" id="X86-RETURN-VALUES">
<div class="sect2">
<h2 class="title">16.4 Return
Values</h2>
<p>A system call would not be useful most of the time if it did not return some kind of a
value: The file descriptor of an open file, the number of bytes read to a buffer, the
system time, etc.</p>
<p>Additionally, the system needs to inform us if an error occurs: A file does not exist,
system resources are exhausted, we passed an invalid parameter, etc.</p>
<hr />
<pkg:outlineMarker OutlineName="16.4.1 Man Pages" id="X86-MAN-PAGES">
<div class="sect3">
<h3 class="title">16.4.1 Man Pages</h3>
<p>The traditional place to look for information about various system calls under <span class="trademark">UNIX</span> systems are the manual pages. FreeBSD describes its system
calls in section 2, sometimes in section 3.</p>
<p>For example, <a href="http://www.freebsd.org/cgi/man.cgi?query=open&sektion=2"><span class="citerefentry"><span class="refentrytitle">open</span>(2)</span></a> says:</p>
<a name="AEN4708"></a>
<blockquote class="blockquote">
<p>If successful, <code class="function">open()</code> returns a non-negative integer,
termed a file descriptor. It returns <var class="varname">-1</var> on failure, and sets
<var class="varname">errno</var> to indicate the error.</p>
</blockquote>
<p>The assembly language programmer new to <span class="trademark">UNIX</span> and
FreeBSD will immediately ask the puzzling question: Where is <var class="varname">errno</var> and how do I get to it?</p>
<blockquote class="note">
<p><b>Note:</b> The information presented in the manual pages applies to C programs. The
assembly language programmer needs additional information.</p>
</blockquote>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.4.2 Where Are the Return Values?" id="X86-WHERE-RETURN-VALUES">
<div class="sect3">
<h3 class="title">16.4.2
Where Are the Return Values?</h3>
<p>Unfortunately, it depends... For most system calls it is in <var class="varname">EAX</var>, but not for all. A good rule of thumb, when working with a
system call for the first time, is to look for the return value in <var class="varname">EAX</var>. If it is not there, you need further research.</p>
<blockquote class="note">
<p><b>Note:</b> I am aware of one system call that returns the value in <var class="varname">EDX</var>: <code class="function">SYS_fork</code>. All others I have
worked with use <var class="varname">EAX</var>. But I have not worked with them all
yet.</p>
</blockquote>
<blockquote class="tip">
<p><b>Tip:</b> If you cannot find the answer here or anywhere else, study <b class="application">libc</b> source code and see how it interfaces with the kernel.</p>
</blockquote>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.4.3 Where Is errno?" id="X86-WHERE-ERRNO">
<div class="sect3">
<h3 class="title">16.4.3 Where Is <var class="varname">errno</var>?</h3>
<p>Actually, nowhere...</p>
<p><var class="varname">errno</var> is part of the C language, not the <span class="trademark">UNIX</span> kernel. When accessing kernel services directly, the error
code is returned in <var class="varname">EAX</var>, the same register the proper return
value generally ends up in.</p>
<p>This makes perfect sense. If there is no error, there is no error code. If there is an
error, there is no return value. One register can contain either.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.4.4 Determining an Error Occurred" id="X86-HOW-TO-KNOW-ERROR">
<div class="sect3">
<h3 class="title">16.4.4
Determining an Error Occurred</h3>
<p>When using the standard FreeBSD calling convention, the <var class="varname">carry
flag</var> is cleared upon success, set upon failure.</p>
<p>When using the Linux emulation mode, the signed value in <var class="varname">EAX</var> is non-negative upon success, and contains the return value. In
case of an error, the value is negative, i.e., <var class="varname">-errno</var>.</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.5 Creating Portable Code" id="X86-PORTABLE-CODE">
<div class="sect2">
<h2 class="title">16.5 Creating
Portable Code</h2>
<p>Portability is generally not one of the strengths of assembly language. Yet, writing
assembly language programs for different platforms is possible, especially with <b class="application">nasm</b>. I have written assembly language libraries that can be
assembled for such different operating systems as <span class="trademark">Windows</span>
and FreeBSD.</p>
<p>It is all the more possible when you want your code to run on two platforms which,
while different, are based on similar architectures.</p>
<p>For example, FreeBSD is <span class="trademark">UNIX</span>, Linux is <span class="trademark">UNIX</span> like. I only mentioned three differences between them (from
an assembly language programmer's perspective): The calling convention, the function
numbers, and the way of returning values.</p>
<hr />
<pkg:outlineMarker OutlineName="16.5.1 Dealing with Function Numbers" id="X86-DEAL-WITH-FUNCTION-NUMBERS">
<div class="sect3">
<h3 class="title">16.5.1 Dealing with Function Numbers</h3>
<p>In many cases the function numbers are the same. However, even when they are not, the
problem is easy to deal with: Instead of using numbers in your code, use constants which
you have declared differently depending on the target architecture:</p>
<pkg:outlineMarker OutlineName="code_52" id="code_52" visible="false" copy="true">
<pre class="programlisting">%ifdef LINUX
%define SYS_execve 11
%else
%define SYS_execve 59
%endif
</pre>
</pkg:outlineMarker>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.5.2 Dealing with Conventions" id="X86-DEAL-WITH-GENEVA">
<div class="sect3">
<h3 class="title">16.5.2 Dealing
with Conventions</h3>
<p>Both, the calling convention, and the return value (the <var class="varname">errno</var> problem) can be resolved with macros:</p>
<pkg:outlineMarker OutlineName="code_53" id="code_53" visible="false" copy="true">
<pre class="programlisting">%ifdef LINUX
%macro system 0
call kernel
%endmacro
align 4
kernel:
push ebx
push ecx
push edx
push esi
push edi
push ebp
mov ebx, [esp+32]
mov ecx, [esp+36]
mov edx, [esp+40]
mov esi, [esp+44]
mov ebp, [esp+48]
int 80h
pop ebp
pop edi
pop esi
pop edx
pop ecx
pop ebx
or eax, eax
js .errno
clc
ret
.errno:
neg eax
stc
ret
%else
%macro system 0
int 80h
%endmacro
%endif
</pre>
</pkg:outlineMarker>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.5.3 Dealing with Other Portability Issues" id="X86-DEAL-WITH-OTHER-PORTABILITY">
<div class="sect3">
<h3 class="title">16.5.3 Dealing with Other Portability
Issues</h3>
<p>The above solutions can handle most cases of writing code portable between FreeBSD and
Linux. Nevertheless, with some kernel services the differences are deeper.</p>
<p>In that case, you need to write two different handlers for those particular system
calls, and use conditional assembly. Luckily, most of your code does something other than
calling the kernel, so usually you will only need a few such conditional sections in your
code.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.5.4 Using a Library" id="X86-PORTABLE-LIBRARY">
<div class="sect3">
<h3 class="title">16.5.4 Using a
Library</h3>
<p>You can avoid portability issues in your main code altogether by writing a library of
system calls. Create a separate library for FreeBSD, a different one for Linux, and yet
other libraries for more operating systems.</p>
<p>In your library, write a separate function (or procedure, if you prefer the
traditional assembly language terminology) for each system call. Use the C calling
convention of passing parameters. But still use <var class="varname">EAX</var> to pass
the call number in. In that case, your FreeBSD library can be very simple, as many
seemingly different functions can be just labels to the same code:</p>
<pkg:outlineMarker OutlineName="code_54" id="code_54" visible="false" copy="true">
<pre class="programlisting">sys.open:
sys.close:
[etc...]
int 80h
ret
</pre>
</pkg:outlineMarker>
<p>Your Linux library will require more different functions. But even here you can group
system calls using the same number of parameters:</p>
<pkg:outlineMarker OutlineName="code_55" id="code_55" visible="false" copy="true">
<pre class="programlisting">sys.exit:
sys.close:
[etc... one-parameter functions]
push ebx
mov ebx, [esp+12]
int 80h
pop ebx
jmp sys.return
...
sys.return:
or eax, eax
js sys.err
clc
ret
sys.err:
neg eax
stc
ret
</pre>
</pkg:outlineMarker>
<p>The library approach may seem inconvenient at first because it requires you to produce
a separate file your code depends on. But it has many advantages: For one, you only need
to write it once and can use it for all your programs. You can even let other assembly
language programmers use it, or perhaps use one written by someone else. But perhaps the
greatest advantage of the library is that your code can be ported to other systems, even
by other programmers, by simply writing a new library without any changes to your
code.</p>
<p>If you do not like the idea of having a library, you can at least place all your
system calls in a separate assembly language file and link it with your main program.
Here, again, all porters have to do is create a new object file to link with your main
program.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.5.5 Using an Include File" id="X86-PORTABLE-INCLUDE">
<div class="sect3">
<h3 class="title">16.5.5 Using
an Include File</h3>
<p>If you are releasing your software as (or with) source code, you can use macros and
place them in a separate file, which you include in your code.</p>
<p>Porters of your software will simply write a new include file. No library or external
object file is necessary, yet your code is portable without any need to edit the
code.</p>
<blockquote class="note">
<p><b>Note:</b> This is the approach we will use throughout this chapter. We will name
our include file <tt class="filename">system.inc</tt>, and add to it whenever we deal
with a new system call.</p>
</blockquote>
<p>We can start our <tt class="filename">system.inc</tt> by declaring the standard file
descriptors:</p>
<pkg:outlineMarker OutlineName="code_56" id="code_56" visible="false" copy="true">
<pre class="programlisting">%define stdin 0
%define stdout 1
%define stderr 2
</pre>
</pkg:outlineMarker>
<p>Next, we create a symbolic name for each system call:</p>
<pkg:outlineMarker OutlineName="code_57" id="code_57" visible="false" copy="true">
<pre class="programlisting">%define SYS_nosys 0
%define SYS_exit 1
%define SYS_fork 2
%define SYS_read 3
%define SYS_write 4
; [etc...]
</pre>
</pkg:outlineMarker>
<p>We add a short, non-global procedure with a long name, so we do not accidentally reuse
the name in our code:</p>
<pkg:outlineMarker OutlineName="code_58" id="code_58" visible="false" copy="true">
<pre class="programlisting">section .text
align 4
access.the.bsd.kernel:
int 80h
ret
</pre>
</pkg:outlineMarker>
<p>We create a macro which takes one argument, the syscall number:</p>
<pkg:outlineMarker OutlineName="code_59" id="code_59" visible="false" copy="true">
<pre class="programlisting">%macro system 1
mov eax, %1
call access.the.bsd.kernel
%endmacro
</pre>
</pkg:outlineMarker>
<p>Finally, we create macros for each syscall. These macros take no arguments.</p>
<pkg:outlineMarker OutlineName="code_60" id="code_60" visible="false" copy="true">
<pre class="programlisting">%macro sys.exit 0
system SYS_exit
%endmacro
%macro sys.fork 0
system SYS_fork
%endmacro
%macro sys.read 0
system SYS_read
%endmacro
%macro sys.write 0
system SYS_write
%endmacro
; [etc...]
</pre>
</pkg:outlineMarker>
<p>Go ahead, enter it into your editor and save it as <tt class="filename">system.inc</tt>. We will add more to it as we discuss more syscalls.</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.6 Our First Program" id="X86-FIRST-PROGRAM">
<div class="sect2">
<h2 class="title">16.6 Our First
Program</h2>
<p>We are now ready for our first program, the mandatory <b class="application">Hello,
World!</b></p>
<pkg:outlineMarker OutlineName="code_61" id="code_61" visible="false" copy="true">
<pre class="programlisting"> 1: %include 'system.inc'
2:
3: section .data
4: hello db 'Hello, World!', 0Ah
5: hbytes equ $-hello
6:
7: section .text
8: global _start
9: _start:
10: push dword hbytes
11: push dword hello
12: push dword stdout
13: sys.write
14:
15: push dword 0
16: sys.exit
</pre>
</pkg:outlineMarker>
<p>Here is what it does: Line 1 includes the defines, the macros, and the code from <tt class="filename">system.inc</tt>.</p>
<p>Lines 3-5 are the data: Line 3 starts the data section/segment. Line 4 contains the
string "Hello, World!" followed by a new line (<code class="constant">0Ah</code>). Line 5
creates a constant that contains the length of the string from line 4 in bytes.</p>
<p>Lines 7-16 contain the code. Note that FreeBSD uses the <span class="emphasis"><i class="emphasis">elf</i></span> file format for its executables, which requires every
program to start at the point labeled <var class="varname">_start</var> (or, more
precisely, the linker expects that). This label has to be global.</p>
<p>Lines 10-13 ask the system to write <var class="varname">hbytes</var> bytes of the
<var class="varname">hello</var> string to <var class="varname">stdout</var>.</p>
<p>Lines 15-16 ask the system to end the program with the return value of <code class="constant">0</code>. The <code class="function">SYS_exit</code> syscall never
returns, so the code ends there.</p>
<blockquote class="note">
<p><b>Note:</b> If you have come to <span class="trademark">UNIX</span> from <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym> assembly language
background, you may be used to writing directly to the video hardware. You will never
have to worry about this in FreeBSD, or any other flavor of <span class="trademark">UNIX</span>. As far as you are concerned, you are writing to a file
known as <tt class="filename">stdout</tt>. This can be the video screen, or a <b class="application">telnet</b> terminal, or an actual file, or even the input of another
program. Which one it is, is for the system to figure out.</p>
</blockquote>
<hr />
<pkg:outlineMarker OutlineName="16.6.1 Assembling the Code" id="X86-ASSEMBLE-1">
<div class="sect3">
<h3 class="title">16.6.1 Assembling the
Code</h3>
<p>Type the code (except the line numbers) in an editor, and save it in a file named <tt class="filename">hello.asm</tt>. You need <b class="application">nasm</b> to assemble
it.</p>
<hr />
<pkg:outlineMarker OutlineName="16.6.1.1 Installing nasm" id="X86-GET-NASM">
<div class="sect3">
<h4 class="title">16.6.1.1 Installing <b class="application">nasm</b></h4>
<p>If you do not have <b class="application">nasm</b>, type:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">su</kbd>
Password:<kbd class="userinput"><var class="replaceable">your root password</var></kbd>
<samp class="prompt">#</samp> <kbd class="userinput">cd /usr/ports/devel/nasm</kbd>
<samp class="prompt">#</samp> <kbd class="userinput">make install</kbd>
<samp class="prompt">#</samp> <kbd class="userinput">exit</kbd>
<samp class="prompt">%</samp>
</pre>
<p>You may type <kbd class="userinput">make install clean</kbd> instead of just <kbd class="userinput">make install</kbd> if you do not want to keep <b class="application">nasm</b> source code.</p>
<p>Either way, FreeBSD will automatically download <b class="application">nasm</b> from
the Internet, compile it, and install it on your system.</p>
<blockquote class="note">
<p><b>Note:</b> If your system is not FreeBSD, you need to get <b class="application">nasm</b> from its <a href="http://www.web-sites.co.uk/nasm/" target="_top">home page</a>. You can still use it to assemble FreeBSD code.</p>
</blockquote>
<p>Now you can assemble, link, and run the code:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">nasm -f elf hello.asm</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">ld -s -o hello hello.o</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">./hello</kbd>
Hello, World!
<samp class="prompt">%</samp>
</pre>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.7 Writing UNIX Filters" id="X86-UNIX-FILTERS">
<div class="sect2">
<h2 class="title">16.7 Writing <span class="trademark">UNIX</span>® Filters</h2>
<p>A common type of <span class="trademark">UNIX</span> application is a filter--a
program that reads data from the <tt class="filename">stdin</tt>, processes it somehow,
then writes the result to <tt class="filename">stdout</tt>.</p>
<p>In this chapter, we shall develop a simple filter, and learn how to read from <tt class="filename">stdin</tt> and write to <tt class="filename">stdout</tt>. This filter
will convert each byte of its input into a hexadecimal number followed by a blank
space.</p>
<pkg:outlineMarker OutlineName="code_62" id="code_62" visible="false" copy="true">
<pre class="programlisting">%include 'system.inc'
section .data
hex db '0123456789ABCDEF'
buffer db 0, 0, ' '
section .text
global _start
_start:
; read a byte from stdin
push dword 1
push dword buffer
push dword stdin
sys.read
add esp, byte 12
or eax, eax
je .done
; convert it to hex
movzx eax, byte [buffer]
mov edx, eax
shr dl, 4
mov dl, [hex+edx]
mov [buffer], dl
and al, 0Fh
mov al, [hex+eax]
mov [buffer+1], al
; print it
push dword 3
push dword buffer
push dword stdout
sys.write
add esp, byte 12
jmp short _start
.done:
push dword 0
sys.exit
</pre>
</pkg:outlineMarker>
<p>In the data section we create an array called <var class="varname">hex</var>. It
contains the 16 hexadecimal digits in ascending order. The array is followed by a buffer
which we will use for both input and output. The first two bytes of the buffer are
initially set to <code class="constant">0</code>. This is where we will write the two
hexadecimal digits (the first byte also is where we will read the input). The third byte
is a space.</p>
<p>The code section consists of four parts: Reading the byte, converting it to a
hexadecimal number, writing the result, and eventually exiting the program.</p>
<p>To read the byte, we ask the system to read one byte from <tt class="filename">stdin</tt>, and store it in the first byte of the <var class="varname">buffer</var>. The system returns the number of bytes read in <var class="varname">EAX</var>. This will be <code class="constant">1</code> while data is
coming, or <code class="constant">0</code>, when no more input data is available.
Therefore, we check the value of <var class="varname">EAX</var>. If it is <code class="constant">0</code>, we jump to <var class="varname">.done</var>, otherwise we
continue.</p>
<blockquote class="note">
<p><b>Note:</b> For simplicity sake, we are ignoring the possibility of an error
condition at this time.</p>
</blockquote>
<p>The hexadecimal conversion reads the byte from the <var class="varname">buffer</var>
into <var class="varname">EAX</var>, or actually just <var class="varname">AL</var>,
while clearing the remaining bits of <var class="varname">EAX</var> to zeros. We also
copy the byte to <var class="varname">EDX</var> because we need to convert the upper four
bits (nibble) separately from the lower four bits. We store the result in the first two
bytes of the buffer.</p>
<p>Next, we ask the system to write the three bytes of the buffer, i.e., the two
hexadecimal digits and the blank space, to <tt class="filename">stdout</tt>. We then jump
back to the beginning of the program and process the next byte.</p>
<p>Once there is no more input left, we ask the system to exit our program, returning a
zero, which is the traditional value meaning the program was successful.</p>
<p>Go ahead, and save the code in a file named <tt class="filename">hex.asm</tt>, then
type the following (the <kbd class="userinput">^D</kbd> means press the control key and
type <kbd class="userinput">D</kbd> while holding the control key down):</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">nasm -f elf hex.asm</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">ld -s -o hex hex.o</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">./hex</kbd>
<kbd class="userinput">Hello, World!</kbd>
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A <kbd class="userinput">Here I come!</kbd>
48 65 72 65 20 49 20 63 6F 6D 65 21 0A <kbd class="userinput">^D</kbd> <samp class="prompt">%</samp>
</pre>
<blockquote class="note">
<p><b>Note:</b> If you are migrating to <span class="trademark">UNIX</span> from <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym>, you may be wondering why
each line ends with <code class="constant">0A</code> instead of <code class="constant">0D
0A</code>. This is because <span class="trademark">UNIX</span> does not use the cr/lf
convention, but a "new line" convention, which is <code class="constant">0A</code> in
hexadecimal.</p>
</blockquote>
<p>Can we improve this? Well, for one, it is a bit confusing because once we have
converted a line of text, our input no longer starts at the beginning of the line. We can
modify it to print a new line instead of a space after each <code class="constant">0A</code>:</p>
<pkg:outlineMarker OutlineName="code_63" id="code_63" visible="false" copy="true">
<pre class="programlisting">%include 'system.inc'
section .data
hex db '0123456789ABCDEF'
buffer db 0, 0, ' '
section .text
global _start
_start:
mov cl, ' '
.loop:
; read a byte from stdin
push dword 1
push dword buffer
push dword stdin
sys.read
add esp, byte 12
or eax, eax
je .done
; convert it to hex
movzx eax, byte [buffer]
mov [buffer+2], cl
cmp al, 0Ah
jne .hex
mov [buffer+2], al
.hex:
mov edx, eax
shr dl, 4
mov dl, [hex+edx]
mov [buffer], dl
and al, 0Fh
mov al, [hex+eax]
mov [buffer+1], al
; print it
push dword 3
push dword buffer
push dword stdout
sys.write
add esp, byte 12
jmp short .loop
.done:
push dword 0
sys.exit
</pre>
</pkg:outlineMarker>
<p>We have stored the space in the <var class="varname">CL</var> register. We can do this
safely because, unlike <span class="trademark">Microsoft</span> <span class="trademark">Windows</span>, <span class="trademark">UNIX</span> system calls do not
modify the value of any register they do not use to return a value in.</p>
<p>That means we only need to set <var class="varname">CL</var> once. We have, therefore,
added a new label <var class="varname">.loop</var> and jump to it for the next byte
instead of jumping at <var class="varname">_start</var>. We have also added the <var class="varname">.hex</var> label so we can either have a blank space or a new line as the
third byte of the <var class="varname">buffer</var>.</p>
<p>Once you have changed <tt class="filename">hex.asm</tt> to reflect these changes,
type:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">nasm -f elf hex.asm</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">ld -s -o hex hex.o</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">./hex</kbd>
<kbd class="userinput">Hello, World!</kbd>
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A
<kbd class="userinput">Here I come!</kbd>
48 65 72 65 20 49 20 63 6F 6D 65 21 0A
<kbd class="userinput">^D</kbd> <samp class="prompt">%</samp>
</pre>
<p>That looks better. But this code is quite inefficient! We are making a system call for
every single byte twice (once to read it, another time to write the output).</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.8 Buffered Input and Output" id="X86-BUFFERED-IO">
<div class="sect2">
<h2 class="title">16.8 Buffered Input and
Output</h2>
<p>We can improve the efficiency of our code by buffering our input and output. We create
an input buffer and read a whole sequence of bytes at one time. Then we fetch them one by
one from the buffer.</p>
<p>We also create an output buffer. We store our output in it until it is full. At that
time we ask the kernel to write the contents of the buffer to <tt class="filename">stdout</tt>.</p>
<p>The program ends when there is no more input. But we still need to ask the kernel to
write the contents of our output buffer to <tt class="filename">stdout</tt> one last
time, otherwise some of our output would make it to the output buffer, but never be sent
out. Do not forget that, or you will be wondering why some of your output is missing.</p>
<pkg:outlineMarker OutlineName="code_64" id="code_64" visible="false" copy="true">
<pre class="programlisting">%include 'system.inc'
%define BUFSIZE 2048
section .data
hex db '0123456789ABCDEF'
section .bss
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
section .text
global _start
_start:
sub eax, eax
sub ebx, ebx
sub ecx, ecx
mov edi, obuffer
.loop:
; read a byte from stdin
call getchar
; convert it to hex
mov dl, al
shr al, 4
mov al, [hex+eax]
call putchar
mov al, dl
and al, 0Fh
mov al, [hex+eax]
call putchar
mov al, ' '
cmp dl, 0Ah
jne .put
mov al, dl
.put:
call putchar
jmp short .loop
align 4
getchar:
or ebx, ebx
jne .fetch
call read
.fetch:
lodsb
dec ebx
ret
read:
push dword BUFSIZE
mov esi, ibuffer
push esi
push dword stdin
sys.read
add esp, byte 12
mov ebx, eax
or eax, eax
je .done
sub eax, eax
ret
align 4
.done:
call write ; flush output buffer
push dword 0
sys.exit
align 4
putchar:
stosb
inc ecx
cmp ecx, BUFSIZE
je write
ret
align 4
write:
sub edi, ecx ; start of buffer
push ecx
push edi
push dword stdout
sys.write
add esp, byte 12
sub eax, eax
sub ecx, ecx ; buffer is empty now
ret
</pre>
</pkg:outlineMarker>
<p>We now have a third section in the source code, named <var class="varname">.bss</var>.
This section is not included in our executable file, and, therefore, cannot be
initialized. We use <code class="function">resb</code> instead of <code class="function">db</code>. It simply reserves the requested size of uninitialized memory
for our use.</p>
<p>We take advantage of the fact that the system does not modify the registers: We use
registers for what, otherwise, would have to be global variables stored in the <var class="varname">.data</var> section. This is also why the <span class="trademark">UNIX</span> convention of passing parameters to system calls on the
stack is superior to the Microsoft convention of passing them in the registers: We can
keep the registers for our own use.</p>
<p>We use <var class="varname">EDI</var> and <var class="varname">ESI</var> as pointers
to the next byte to be read from or written to. We use <var class="varname">EBX</var> and
<var class="varname">ECX</var> to keep count of the number of bytes in the two buffers,
so we know when to dump the output to, or read more input from, the system.</p>
<p>Let us see how it works now:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">nasm -f elf hex.asm</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">ld -s -o hex hex.o</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">./hex</kbd>
<kbd class="userinput">Hello, World!</kbd>
<kbd class="userinput">Here I come!</kbd>
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A
48 65 72 65 20 49 20 63 6F 6D 65 21 0A
<kbd class="userinput">^D</kbd> <samp class="prompt">%</samp>
</pre>
<p>Not what you expected? The program did not print the output until we pressed <kbd class="userinput">^D</kbd>. That is easy to fix by inserting three lines of code to write
the output every time we have converted a new line to <code class="constant">0A</code>. I
have marked the three lines with > (do not copy the > in your <tt class="filename">hex.asm</tt>).</p>
<pkg:outlineMarker OutlineName="code_65" id="code_65" visible="false" copy="true">
<pre class="programlisting">%include 'system.inc'
%define BUFSIZE 2048
section .data
hex db '0123456789ABCDEF'
section .bss
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
section .text
global _start
_start:
sub eax, eax
sub ebx, ebx
sub ecx, ecx
mov edi, obuffer
.loop:
; read a byte from stdin
call getchar
; convert it to hex
mov dl, al
shr al, 4
mov al, [hex+eax]
call putchar
mov al, dl
and al, 0Fh
mov al, [hex+eax]
call putchar
mov al, ' '
cmp dl, 0Ah
jne .put
mov al, dl
.put:
call putchar
> cmp al, 0Ah
> jne .loop
> call write
jmp short .loop
align 4
getchar:
or ebx, ebx
jne .fetch
call read
.fetch:
lodsb
dec ebx
ret
read:
push dword BUFSIZE
mov esi, ibuffer
push esi
push dword stdin
sys.read
add esp, byte 12
mov ebx, eax
or eax, eax
je .done
sub eax, eax
ret
align 4
.done:
call write ; flush output buffer
push dword 0
sys.exit
align 4
putchar:
stosb
inc ecx
cmp ecx, BUFSIZE
je write
ret
align 4
write:
sub edi, ecx ; start of buffer
push ecx
push edi
push dword stdout
sys.write
add esp, byte 12
sub eax, eax
sub ecx, ecx ; buffer is empty now
ret
</pre>
</pkg:outlineMarker>
<p>Now, let us see how it works:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">nasm -f elf hex.asm</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">ld -s -o hex hex.o</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">./hex</kbd>
<kbd class="userinput">Hello, World!</kbd>
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A
<kbd class="userinput">Here I come!</kbd>
48 65 72 65 20 49 20 63 6F 6D 65 21 0A
<kbd class="userinput">^D</kbd> <samp class="prompt">%</samp>
</pre>
<p>Not bad for a 644-byte executable, is it!</p>
<blockquote class="note">
<p><b>Note:</b> This approach to buffered input/output still contains a hidden danger. I
will discuss--and fix--it later, when I talk about the <a href="pkg://FreeBSD Developers' Handbook/X86-BUFFERED-DARK-SIDE">dark side of buffering</a>.</p>
</blockquote>
<hr />
<pkg:outlineMarker OutlineName="16.8.1 How to Unread a Character" id="X86-UNGETC">
<div class="sect3">
<h3 class="title">16.8.1 How to Unread a
Character</h3>
<blockquote class="warning">
<p><b>Warning:</b> This may be a somewhat advanced topic, mostly of interest to
programmers familiar with the theory of compilers. If you wish, you may <a href="pkg://FreeBSD Developers' Handbook/X86-COMMAND-LINE">skip to the next section</a>, and perhaps read this later.</p>
</blockquote>
<p>While our sample program does not require it, more sophisticated filters often need to
look ahead. In other words, they may need to see what the next character is (or even
several characters). If the next character is of a certain value, it is part of the token
currently being processed. Otherwise, it is not.</p>
<p>For example, you may be parsing the input stream for a textual string (e.g., when
implementing a language compiler): If a character is followed by another character, or
perhaps a digit, it is part of the token you are processing. If it is followed by white
space, or some other value, then it is not part of the current token.</p>
<p>This presents an interesting problem: How to return the next character back to the
input stream, so it can be read again later?</p>
<p>One possible solution is to store it in a character variable, then set a flag. We can
modify <code class="function">getchar</code> to check the flag, and if it is set, fetch
the byte from that variable instead of the input buffer, and reset the flag. But, of
course, that slows us down.</p>
<p>The C language has an <code class="function">ungetc()</code> function, just for that
purpose. Is there a quick way to implement it in our code? I would like you to scroll
back up and take a look at the <code class="function">getchar</code> procedure and see if
you can find a nice and fast solution before reading the next paragraph. Then come back
here and see my own solution.</p>
<p>The key to returning a character back to the stream is in how we are getting the
characters to start with:</p>
<p>First we check if the buffer is empty by testing the value of <var class="varname">EBX</var>. If it is zero, we call the <code class="function">read</code>
procedure.</p>
<p>If we do have a character available, we use <code class="function">lodsb</code>, then
decrease the value of <var class="varname">EBX</var>. The <code class="function">lodsb</code> instruction is effectively identical to:</p>
<pkg:outlineMarker OutlineName="code_66" id="code_66" visible="false" copy="true">
<pre class="programlisting"> mov al, [esi]
inc esi
</pre>
</pkg:outlineMarker>
<p>The byte we have fetched remains in the buffer until the next time <code class="function">read</code> is called. We do not know when that happens, but we do know
it will not happen until the next call to <code class="function">getchar</code>. Hence,
to "return" the last-read byte back to the stream, all we have to do is decrease the
value of <var class="varname">ESI</var> and increase the value of <var class="varname">EBX</var>:</p>
<pkg:outlineMarker OutlineName="code_67" id="code_67" visible="false" copy="true">
<pre class="programlisting">ungetc:
dec esi
inc ebx
ret
</pre>
</pkg:outlineMarker>
<p>But, be careful! We are perfectly safe doing this if our look-ahead is at most one
character at a time. If we are examining more than one upcoming character and call <code class="function">ungetc</code> several times in a row, it will work most of the time, but
not all the time (and will be tough to debug). Why?</p>
<p>Because as long as <code class="function">getchar</code> does not have to call <code class="function">read</code>, all of the pre-read bytes are still in the buffer, and our
<code class="function">ungetc</code> works without a glitch. But the moment <code class="function">getchar</code> calls <code class="function">read</code>, the contents of
the buffer change.</p>
<p>We can always rely on <code class="function">ungetc</code> working properly on the
last character we have read with <code class="function">getchar</code>, but not on
anything we have read before that.</p>
<p>If your program reads more than one byte ahead, you have at least two choices:</p>
<p>If possible, modify the program so it only reads one byte ahead. This is the simplest
solution.</p>
<p>If that option is not available, first of all determine the maximum number of
characters your program needs to return to the input stream at one time. Increase that
number slightly, just to be sure, preferably to a multiple of 16--so it aligns nicely.
Then modify the <var class="varname">.bss</var> section of your code, and create a small
"spare" buffer right before your input buffer, something like this:</p>
<pkg:outlineMarker OutlineName="code_68" id="code_68" visible="false" copy="true">
<pre class="programlisting">section .bss
resb 16 ; or whatever the value you came up with
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
</pre>
</pkg:outlineMarker>
<p>You also need to modify your <code class="function">ungetc</code> to pass the value of
the byte to unget in <var class="varname">AL</var>:</p>
<pkg:outlineMarker OutlineName="code_69" id="code_69" visible="false" copy="true">
<pre class="programlisting">ungetc:
dec esi
inc ebx
mov [esi], al
ret
</pre>
</pkg:outlineMarker>
<p>With this modification, you can call <code class="function">ungetc</code> up to 17
times in a row safely (the first call will still be within the buffer, the remaining 16
may be either within the buffer or within the "spare").</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.9 Command Line Arguments" id="X86-COMMAND-LINE">
<div class="sect2">
<h2 class="title">16.9 Command Line
Arguments</h2>
<p>Our <b class="application">hex</b> program will be more useful if it can read the
names of an input and output file from its command line, i.e., if it can process the
command line arguments. But... Where are they?</p>
<p>Before a <span class="trademark">UNIX</span> system starts a program, it <code class="function">push</code>es some data on the stack, then jumps at the <var class="varname">_start</var> label of the program. Yes, I said jumps, not calls. That
means the data can be accessed by reading <var class="varname">[esp+offset]</var>, or by
simply <code class="function">pop</code>ping it.</p>
<p>The value at the top of the stack contains the number of command line arguments. It is
traditionally called <var class="varname">argc</var>, for "argument count."</p>
<p>Command line arguments follow next, all <var class="varname">argc</var> of them. These
are typically referred to as <var class="varname">argv</var>, for "argument value(s)."
That is, we get <var class="varname">argv[0]</var>, <var class="varname">argv[1]</var>,
<var class="varname">...</var>, <var class="varname">argv[argc-1]</var>. These are not
the actual arguments, but pointers to arguments, i.e., memory addresses of the actual
arguments. The arguments themselves are NUL-terminated character strings.</p>
<p>The <var class="varname">argv</var> list is followed by a NULL pointer, which is
simply a <code class="constant">0</code>. There is more, but this is enough for our
purposes right now.</p>
<blockquote class="note">
<p><b>Note:</b> If you have come from the <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym> programming environment, the main difference is
that each argument is in a separate string. The second difference is that there is no
practical limit on how many arguments there can be.</p>
</blockquote>
<p>Armed with this knowledge, we are almost ready for the next version of <tt class="filename">hex.asm</tt>. First, however, we need to add a few lines to <tt class="filename">system.inc</tt>:</p>
<p>First, we need to add two new entries to our list of system call numbers:</p>
<pkg:outlineMarker OutlineName="code_70" id="code_70" visible="false" copy="true">
<pre class="programlisting">%define SYS_open 5
%define SYS_close 6
</pre>
</pkg:outlineMarker>
<p>Then we add two new macros at the end of the file:</p>
<pkg:outlineMarker OutlineName="code_71" id="code_71" visible="false" copy="true">
<pre class="programlisting">%macro sys.open 0
system SYS_open
%endmacro
%macro sys.close 0
system SYS_close
%endmacro
</pre>
</pkg:outlineMarker>
<p>Here, then, is our modified source code:</p>
<pkg:outlineMarker OutlineName="code_72" id="code_72" visible="false" copy="true">
<pre class="programlisting">%include 'system.inc'
%define BUFSIZE 2048
section .data
fd.in dd stdin
fd.out dd stdout
hex db '0123456789ABCDEF'
section .bss
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
section .text
align 4
err:
push dword 1 ; return failure
sys.exit
align 4
global _start
_start:
add esp, byte 8 ; discard argc and argv[0]
pop ecx
jecxz .init ; no more arguments
; ECX contains the path to input file
push dword 0 ; O_RDONLY
push ecx
sys.open
jc err ; open failed
add esp, byte 8
mov [fd.in], eax
pop ecx
jecxz .init ; no more arguments
; ECX contains the path to output file
push dword 420 ; file mode (644 octal)
push dword 0200h | 0400h | 01h
; O_CREAT | O_TRUNC | O_WRONLY
push ecx
sys.open
jc err
add esp, byte 12
mov [fd.out], eax
.init:
sub eax, eax
sub ebx, ebx
sub ecx, ecx
mov edi, obuffer
.loop:
; read a byte from input file or stdin
call getchar
; convert it to hex
mov dl, al
shr al, 4
mov al, [hex+eax]
call putchar
mov al, dl
and al, 0Fh
mov al, [hex+eax]
call putchar
mov al, ' '
cmp dl, 0Ah
jne .put
mov al, dl
.put:
call putchar
cmp al, dl
jne .loop
call write
jmp short .loop
align 4
getchar:
or ebx, ebx
jne .fetch
call read
.fetch:
lodsb
dec ebx
ret
read:
push dword BUFSIZE
mov esi, ibuffer
push esi
push dword [fd.in]
sys.read
add esp, byte 12
mov ebx, eax
or eax, eax
je .done
sub eax, eax
ret
align 4
.done:
call write ; flush output buffer
; close files
push dword [fd.in]
sys.close
push dword [fd.out]
sys.close
; return success
push dword 0
sys.exit
align 4
putchar:
stosb
inc ecx
cmp ecx, BUFSIZE
je write
ret
align 4
write:
sub edi, ecx ; start of buffer
push ecx
push edi
push dword [fd.out]
sys.write
add esp, byte 12
sub eax, eax
sub ecx, ecx ; buffer is empty now
ret
</pre>
</pkg:outlineMarker>
<p>In our <var class="varname">.data</var> section we now have two new variables, <var class="varname">fd.in</var> and <var class="varname">fd.out</var>. We store the input and
output file descriptors here.</p>
<p>In the <var class="varname">.text</var> section we have replaced the references to
<var class="varname">stdin</var> and <var class="varname">stdout</var> with <var class="varname">[fd.in]</var> and <var class="varname">[fd.out]</var>.</p>
<p>The <var class="varname">.text</var> section now starts with a simple error handler,
which does nothing but exit the program with a return value of <code class="constant">1</code>. The error handler is before <var class="varname">_start</var>
so we are within a short distance from where the errors occur.</p>
<p>Naturally, the program execution still begins at <var class="varname">_start</var>.
First, we remove <var class="varname">argc</var> and <var class="varname">argv[0]</var>
from the stack: They are of no interest to us (in this program, that is).</p>
<p>We pop <var class="varname">argv[1]</var> to <var class="varname">ECX</var>. This
register is particularly suited for pointers, as we can handle NULL pointers with <code class="function">jecxz</code>. If <var class="varname">argv[1]</var> is not NULL, we try
to open the file named in the first argument. Otherwise, we continue the program as
before: Reading from <var class="varname">stdin</var>, writing to <var class="varname">stdout</var>. If we fail to open the input file (e.g., it does not
exist), we jump to the error handler and quit.</p>
<p>If all went well, we now check for the second argument. If it is there, we open the
output file. Otherwise, we send the output to <var class="varname">stdout</var>. If we
fail to open the output file (e.g., it exists and we do not have the write permission),
we, again, jump to the error handler.</p>
<p>The rest of the code is the same as before, except we close the input and output files
before exiting, and, as mentioned, we use <var class="varname">[fd.in]</var> and <var class="varname">[fd.out]</var>.</p>
<p>Our executable is now a whopping 768 bytes long.</p>
<p>Can we still improve it? Of course! Every program can be improved. Here are a few
ideas of what we could do:</p>
<ul>
<li>
<p>Have our error handler print a message to <var class="varname">stderr</var>.</p>
</li>
<li>
<p>Add error handlers to the <code class="function">read</code> and <code class="function">write</code> functions.</p>
</li>
<li>
<p>Close <var class="varname">stdin</var> when we open an input file, <var class="varname">stdout</var> when we open an output file.</p>
</li>
<li>
<p>Add command line switches, such as <var class="parameter">-i</var> and <var class="parameter">-o</var>, so we can list the input and output files in any order, or
perhaps read from <var class="varname">stdin</var> and write to a file.</p>
</li>
<li>
<p>Print a usage message if command line arguments are incorrect.</p>
</li>
</ul>
<p>I shall leave these enhancements as an exercise to the reader: You already know
everything you need to know to implement them.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.10 UNIX Environment" id="X86-ENVIRONMENT">
<div class="sect2">
<h2 class="title">16.10 <span class="trademark">UNIX</span> Environment</h2>
<p>An important <span class="trademark">UNIX</span> concept is the environment, which is
defined by <span class="emphasis"><i class="emphasis">environment variables</i></span>.
Some are set by the system, others by you, yet others by the <b class="application">shell</b>, or any program that loads another program.</p>
<hr />
<pkg:outlineMarker OutlineName="16.10.1 How to Find Environment Variables" id="X86-FIND-ENVIRONMENT">
<div class="sect3">
<h3 class="title">16.10.1 How to
Find Environment Variables</h3>
<p>I said earlier that when a program starts executing, the stack contains <var class="varname">argc</var> followed by the NULL-terminated <var class="varname">argv</var> array, followed by something else. The "something else" is the
<span class="emphasis"><i class="emphasis">environment</i></span>, or, to be more
precise, a NULL-terminated array of pointers to <span class="emphasis"><i class="emphasis">environment variables</i></span>. This is often referred to as <var class="varname">env</var>.</p>
<p>The structure of <var class="varname">env</var> is the same as that of <var class="varname">argv</var>, a list of memory addresses followed by a NULL (<code class="constant">0</code>). In this case, there is no <var class="varname">"envc"</var>--we figure out where the array ends by searching for the
final NULL.</p>
<p>The variables usually come in the <var class="varname">name=value</var> format, but
sometimes the <var class="varname">=value</var> part may be missing. We need to account
for that possibility.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.10.2 webvars" id="X86-WEBVAR">
<div class="sect3">
<h3 class="title">16.10.2 webvars</h3>
<p>I could just show you some code that prints the environment the same way the <span class="trademark">UNIX</span> <b class="application">env</b> command does. But I thought
it would be more interesting to write a simple assembly language CGI utility.</p>
<hr />
<pkg:outlineMarker OutlineName="16.10.2.1 CGI: A Quick Overview" id="X86-CGI">
<div class="sect3">
<h4 class="title">16.10.2.1 CGI: A Quick Overview</h4>
<p>I have a <a href="http://www.whizkidtech.redprince.net/cgi-bin/tutorial" target="_top">detailed <acronym class="acronym">CGI</acronym> tutorial</a> on my web
site, but here is a very quick overview of <acronym class="acronym">CGI</acronym>:</p>
<ul>
<li>
<p>The web server communicates with the <acronym class="acronym">CGI</acronym> program by
setting <span class="emphasis"><i class="emphasis">environment variables</i></span>.</p>
</li>
<li>
<p>The <acronym class="acronym">CGI</acronym> program sends its output to <tt class="filename">stdout</tt>. The web server reads it from there.</p>
</li>
<li>
<p>It must start with an <acronym class="acronym">HTTP</acronym> header followed by two
blank lines.</p>
</li>
<li>
<p>It then prints the <acronym class="acronym">HTML</acronym> code, or whatever other
type of data it is producing.</p>
</li>
</ul>
<blockquote class="note">
<p><b>Note:</b> While certain <span class="emphasis"><i class="emphasis">environment
variables</i></span> use standard names, others vary, depending on the web server. That
makes <b class="application">webvars</b> quite a useful diagnostic tool.</p>
</blockquote>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.10.2.2 The Code" id="X86-WEBVARS-THE-CODE">
<div class="sect3">
<h4 class="title">16.10.2.2 The
Code</h4>
<p>Our <b class="application">webvars</b> program, then, must send out the <acronym class="acronym">HTTP</acronym> header followed by some <acronym class="acronym">HTML</acronym> mark-up. It then must read the <span class="emphasis"><i class="emphasis">environment variables</i></span> one by one and send them out as part of
the <acronym class="acronym">HTML</acronym> page.</p>
<p>The code follows. I placed comments and explanations right inside the code:</p>
<pkg:outlineMarker OutlineName="code_73" id="code_73" visible="false" copy="true">
<pre class="programlisting">;;;;;;; webvars.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Copyright (c) 2000 G. Adam Stanislav
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions
; are met:
; 1. Redistributions of source code must retain the above copyright
; notice, this list of conditions and the following disclaimer.
; 2. Redistributions in binary form must reproduce the above copyright
; notice, this list of conditions and the following disclaimer in the
; documentation and/or other materials provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
; SUCH DAMAGE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Version 1.0
;
; Started: 8-Dec-2000
; Updated: 8-Dec-2000
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%include 'system.inc'
section .data
http db 'Content-type: text/html', 0Ah, 0Ah
db '<?xml version="1.0" encoding="UTF-8"?>', 0Ah
db '<!DOCTYPE html PUBLIC "-//W3C/DTD XHTML Strict//EN" '
db '"DTD/xhtml1-strict.dtd">', 0Ah
db '<html xmlns="http://www.w3.org/1999/xhtml" '
db 'xml.lang="en" lang="en">', 0Ah
db '<head>', 0Ah
db '<title>Web Environment</title>', 0Ah
db '<meta name="author" content="G. Adam Stanislav" />', 0Ah
db '</head>', 0Ah, 0Ah
db '<body bgcolor="pkg://FreeBSD Developers' Handbook/ffffff" text="pkg://FreeBSD Developers' Handbook/000000" link="pkg://FreeBSD Developers' Handbook/0000ff" '
db 'vlink="pkg://FreeBSD Developers' Handbook/840084" alink="pkg://FreeBSD Developers' Handbook/0000ff">', 0Ah
db '<div class="webvars">', 0Ah
db '<h1>Web Environment</h1>', 0Ah
db '<p>The following <b>environment variables</b> are defined '
db 'on this web server:</p>', 0Ah, 0Ah
db '<table align="center" width="80" border="0" cellpadding="10" '
db 'cellspacing="0" class="webvars">', 0Ah
httplen equ $-http
left db '<tr>', 0Ah
db '<td class="name"><tt>'
leftlen equ $-left
middle db '</tt></td>', 0Ah
db '<td class="value"><tt><b>'
midlen equ $-middle
undef db '<i>(undefined)</i>'
undeflen equ $-undef
right db '</b></tt></td>', 0Ah
db '</tr>', 0Ah
rightlen equ $-right
wrap db '</table>', 0Ah
db '</div>', 0Ah
db '</body>', 0Ah
db '</html>', 0Ah, 0Ah
wraplen equ $-wrap
section .text
global _start
_start:
; First, send out all the http and xhtml stuff that is
; needed before we start showing the environment
push dword httplen
push dword http
push dword stdout
sys.write
; Now find how far on the stack the environment pointers
; are. We have 12 bytes we have pushed before "argc"
mov eax, [esp+12]
; We need to remove the following from the stack:
;
; The 12 bytes we pushed for sys.write
; The 4 bytes of argc
; The EAX*4 bytes of argv
; The 4 bytes of the NULL after argv
;
; Total:
; 20 + eax * 4
;
; Because stack grows down, we need to ADD that many bytes
; to ESP.
lea esp, [esp+20+eax*4]
cld ; This should already be the case, but let's be sure.
; Loop through the environment, printing it out
.loop:
pop edi
or edi, edi ; Done yet?
je near .wrap
; Print the left part of HTML
push dword leftlen
push dword left
push dword stdout
sys.write
; It may be tempting to search for the '=' in the env string next.
; But it is possible there is no '=', so we search for the
; terminating NUL first.
mov esi, edi ; Save start of string
sub ecx, ecx
not ecx ; ECX = FFFFFFFF
sub eax, eax
repne scasb
not ecx ; ECX = string length + 1
mov ebx, ecx ; Save it in EBX
; Now is the time to find '='
mov edi, esi ; Start of string
mov al, '='
repne scasb
not ecx
add ecx, ebx ; Length of name
push ecx
push esi
push dword stdout
sys.write
; Print the middle part of HTML table code
push dword midlen
push dword middle
push dword stdout
sys.write
; Find the length of the value
not ecx
lea ebx, [ebx+ecx-1]
; Print "undefined" if 0
or ebx, ebx
jne .value
mov ebx, undeflen
mov edi, undef
.value:
push ebx
push edi
push dword stdout
sys.write
; Print the right part of the table row
push dword rightlen
push dword right
push dword stdout
sys.write
; Get rid of the 60 bytes we have pushed
add esp, byte 60
; Get the next variable
jmp .loop
.wrap:
; Print the rest of HTML
push dword wraplen
push dword wrap
push dword stdout
sys.write
; Return success
push dword 0
sys.exit
</pre>
</pkg:outlineMarker>
<p>This code produces a 1,396-byte executable. Most of it is data, i.e., the <acronym class="acronym">HTML</acronym> mark-up we need to send out.</p>
<p>Assemble and link it as usual:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">nasm -f elf webvars.asm</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">ld -s -o webvars webvars.o</kbd>
</pre>
<p>To use it, you need to upload <tt class="filename">webvars</tt> to your web server.
Depending on how your web server is set up, you may have to store it in a special <tt class="filename">cgi-bin</tt> directory, or perhaps rename it with a <tt class="filename">.cgi</tt> extension.</p>
<p>Then you need to use your browser to view its output. To see its output on my web
server, please go to <a href="http://www.int80h.org/webvars/" target="_top"><tt class="filename">http://www.int80h.org/webvars/</tt></a>. If curious about the additional
environment variables present in a password protected web directory, go to <a href="http://www.int80h.org/private/" target="_top"><tt class="filename">http://www.int80h.org/private/</tt></a>, using the name <kbd class="userinput">asm</kbd> and password <kbd class="userinput">programmer</kbd>.</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.11 Working with Files" id="X86-FILES">
<div class="sect2">
<h2 class="title">16.11 Working with Files</h2>
<p>We have already done some basic file work: We know how to open and close them, how to
read and write them using buffers. But <span class="trademark">UNIX</span> offers much
more functionality when it comes to files. We will examine some of it in this section,
and end up with a nice file conversion utility.</p>
<p>Indeed, let us start at the end, that is, with the file conversion utility. It always
makes programming easier when we know from the start what the end product is supposed to
do.</p>
<p>One of the first programs I wrote for <span class="trademark">UNIX</span> was <a href="ftp://ftp.int80h.org/unix/tuc/" target="_top"><b class="application">tuc</b></a>, a
text-to-<span class="trademark">UNIX</span> file converter. It converts a text file from
other operating systems to a <span class="trademark">UNIX</span> text file. In other
words, it changes from different kind of line endings to the newline convention of <span class="trademark">UNIX</span>. It saves the output in a different file. Optionally, it
converts a <span class="trademark">UNIX</span> text file to a <acronym class="acronym">DOS</acronym> text file.</p>
<p>I have used <b class="application">tuc</b> extensively, but always only to convert
from some other <acronym class="acronym">OS</acronym> to <span class="trademark">UNIX</span>, never the other way. I have always wished it would just
overwrite the file instead of me having to send the output to a different file. Most of
the time, I end up using it like this:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">tuc <var class="replaceable">myfile tempfile</var></kbd>
<samp class="prompt">%</samp> <kbd class="userinput">mv <var class="replaceable">tempfile myfile</var></kbd>
</pre>
<p>It would be nice to have a <b class="application">ftuc</b>, i.e., <span class="emphasis"><i class="emphasis">fast tuc</i></span>, and use it like this:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">ftuc <var class="replaceable">myfile</var></kbd>
</pre>
<p>In this chapter, then, we will write <b class="application">ftuc</b> in assembly
language (the original <b class="application">tuc</b> is in C), and study various
file-oriented kernel services in the process.</p>
<p>At first sight, such a file conversion is very simple: All you have to do is strip the
carriage returns, right?</p>
<p>If you answered yes, think again: That approach will work most of the time (at least
with <acronym class="acronym">MS DOS</acronym> text files), but will fail
occasionally.</p>
<p>The problem is that not all non <span class="trademark">UNIX</span> text files end
their line with the carriage return / line feed sequence. Some use carriage returns
without line feeds. Others combine several blank lines into a single carriage return
followed by several line feeds. And so on.</p>
<p>A text file converter, then, must be able to handle any possible line endings:</p>
<ul>
<li>
<p>carriage return / line feed</p>
</li>
<li>
<p>carriage return</p>
</li>
<li>
<p>line feed / carriage return</p>
</li>
<li>
<p>line feed</p>
</li>
</ul>
<p>It should also handle files that use some kind of a combination of the above (e.g.,
carriage return followed by several line feeds).</p>
<hr />
<pkg:outlineMarker OutlineName="16.11.1 Finite State Machine" id="X86-FINITE-STATE-MACHINE">
<div class="sect3">
<h3 class="title">16.11.1 Finite State Machine</h3>
<p>The problem is easily solved by the use of a technique called <span class="emphasis"><i class="emphasis">finite state machine</i></span>, originally
developed by the designers of digital electronic circuits. A <span class="emphasis"><i class="emphasis">finite state machine</i></span> is a digital circuit whose output is
dependent not only on its input but on its previous input, i.e., on its state. The
microprocessor is an example of a <span class="emphasis"><i class="emphasis">finite state
machine</i></span>: Our assembly language code is assembled to machine language in which
some assembly language code produces a single byte of machine language, while others
produce several bytes. As the microprocessor fetches the bytes from the memory one by
one, some of them simply change its state rather than produce some output. When all the
bytes of the op code are fetched, the microprocessor produces some output, or changes the
value of a register, etc.</p>
<p>Because of that, all software is essentially a sequence of state instructions for the
microprocessor. Nevertheless, the concept of <span class="emphasis"><i class="emphasis">finite state machine</i></span> is useful in software design as
well.</p>
<p>Our text file converter can be designed as a <span class="emphasis"><i class="emphasis">finite state machine</i></span> with three possible states. We could
call them states 0-2, but it will make our life easier if we give them symbolic
names:</p>
<ul>
<li>
<p><var class="symbol">ordinary</var></p>
</li>
<li>
<p><var class="symbol">cr</var></p>
</li>
<li>
<p><var class="symbol">lf</var></p>
</li>
</ul>
<p>Our program will start in the <var class="symbol">ordinary</var> state. During this
state, the program action depends on its input as follows:</p>
<ul>
<li>
<p>If the input is anything other than a carriage return or line feed, the input is
simply passed on to the output. The state remains unchanged.</p>
</li>
<li>
<p>If the input is a carriage return, the state is changed to <var class="symbol">cr</var>. The input is then discarded, i.e., no output is made.</p>
</li>
<li>
<p>If the input is a line feed, the state is changed to <var class="symbol">lf</var>. The
input is then discarded.</p>
</li>
</ul>
<p>Whenever we are in the <var class="symbol">cr</var> state, it is because the last
input was a carriage return, which was unprocessed. What our software does in this state
again depends on the current input:</p>
<ul>
<li>
<p>If the input is anything other than a carriage return or line feed, output a line
feed, then output the input, then change the state to <var class="symbol">ordinary</var>.</p>
</li>
<li>
<p>If the input is a carriage return, we have received two (or more) carriage returns in
a row. We discard the input, we output a line feed, and leave the state unchanged.</p>
</li>
<li>
<p>If the input is a line feed, we output the line feed and change the state to <var class="symbol">ordinary</var>. Note that this is not the same as the first case above -
if we tried to combine them, we would be outputting two line feeds instead of one.</p>
</li>
</ul>
<p>Finally, we are in the <var class="symbol">lf</var> state after we have received a
line feed that was not preceded by a carriage return. This will happen when our file
already is in <span class="trademark">UNIX</span> format, or whenever several lines in a
row are expressed by a single carriage return followed by several line feeds, or when
line ends with a line feed / carriage return sequence. Here is how we need to handle our
input in this state:</p>
<ul>
<li>
<p>If the input is anything other than a carriage return or line feed, we output a line
feed, then output the input, then change the state to <var class="symbol">ordinary</var>.
This is exactly the same action as in the <var class="symbol">cr</var> state upon
receiving the same kind of input.</p>
</li>
<li>
<p>If the input is a carriage return, we discard the input, we output a line feed, then
change the state to <var class="symbol">ordinary</var>.</p>
</li>
<li>
<p>If the input is a line feed, we output the line feed, and leave the state
unchanged.</p>
</li>
</ul>
<hr />
<pkg:outlineMarker OutlineName="16.11.1.1 The Final State" id="X86-FINAL-STATE">
<div class="sect3">
<h4 class="title">16.11.1.1 The Final
State</h4>
<p>The above <span class="emphasis"><i class="emphasis">finite state machine</i></span>
works for the entire file, but leaves the possibility that the final line end will be
ignored. That will happen whenever the file ends with a single carriage return or a
single line feed. I did not think of it when I wrote <b class="application">tuc</b>, just
to discover that occasionally it strips the last line ending.</p>
<p>This problem is easily fixed by checking the state after the entire file was
processed. If the state is not <var class="symbol">ordinary</var>, we simply need to
output one last line feed.</p>
<blockquote class="note">
<p><b>Note:</b> Now that we have expressed our algorithm as a <span class="emphasis"><i class="emphasis">finite state machine</i></span>, we could easily design a dedicated
digital electronic circuit (a "chip") to do the conversion for us. Of course, doing so
would be considerably more expensive than writing an assembly language program.</p>
</blockquote>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.11.1.2 The Output Counter" id="X86-TUC-COUNTER">
<div class="sect3">
<h4 class="title">16.11.1.2 The Output
Counter</h4>
<p>Because our file conversion program may be combining two characters into one, we need
to use an output counter. We initialize it to <code class="constant">0</code>, and
increase it every time we send a character to the output. At the end of the program, the
counter will tell us what size we need to set the file to.</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.11.2 Implementing FSM in Software" id="X86-SOFTWARE-FSM">
<div class="sect3">
<h3 class="title">16.11.2 Implementing
FSM in Software</h3>
<p>The hardest part of working with a <span class="emphasis"><i class="emphasis">finite
state machine</i></span> is analyzing the problem and expressing it as a <span class="emphasis"><i class="emphasis">finite state machine</i></span>. That accomplished,
the software almost writes itself.</p>
<p>In a high-level language, such as C, there are several main approaches. One is to use
a <code class="function">switch</code> statement which chooses what function should be
run. For example,</p>
<pkg:outlineMarker OutlineName="code_74" id="code_74" visible="false" copy="true">
<pre class="programlisting"> switch (state) {
default:
case REGULAR:
regular(inputchar);
break;
case CR:
cr(inputchar);
break;
case LF:
lf(inputchar);
break;
}
</pre>
</pkg:outlineMarker>
<p>Another approach is by using an array of function pointers, something like this:</p>
<pkg:outlineMarker OutlineName="code_75" id="code_75" visible="false" copy="true">
<pre class="programlisting"> (output[state])(inputchar);
</pre>
</pkg:outlineMarker>
<p>Yet another is to have <var class="varname">state</var> be a function pointer, set to
point at the appropriate function:</p>
<pkg:outlineMarker OutlineName="code_76" id="code_76" visible="false" copy="true">
<pre class="programlisting"> (*state)(inputchar);
</pre>
</pkg:outlineMarker>
<p>This is the approach we will use in our program because it is very easy to do in
assembly language, and very fast, too. We will simply keep the address of the right
procedure in <var class="varname">EBX</var>, and then just issue:</p>
<pkg:outlineMarker OutlineName="code_77" id="code_77" visible="false" copy="true">
<pre class="programlisting"> call ebx
</pre>
</pkg:outlineMarker>
<p>This is possibly faster than hardcoding the address in the code because the
microprocessor does not have to fetch the address from the memory--it is already stored
in one of its registers. I said <span class="emphasis"><i class="emphasis">possibly</i></span> because with the caching modern microprocessors do,
either way may be equally fast.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.11.3 Memory Mapped Files" id="MEMORY-MAPPED-FILES">
<div class="sect3">
<h3 class="title">16.11.3 Memory
Mapped Files</h3>
<p>Because our program works on a single file, we cannot use the approach that worked for
us before, i.e., to read from an input file and to write to an output file.</p>
<p><span class="trademark">UNIX</span> allows us to map a file, or a section of a file,
into memory. To do that, we first need to open the file with the appropriate read/write
flags. Then we use the <code class="function">mmap</code> system call to map it into the
memory. One nice thing about <code class="function">mmap</code> is that it automatically
works with virtual memory: We can map more of the file into the memory than we have
physical memory available, yet still access it through regular memory op codes, such as
<code class="function">mov</code>, <code class="function">lods</code>, and <code class="function">stos</code>. Whatever changes we make to the memory image of the file
will be written to the file by the system. We do not even have to keep the file open: As
long as it stays mapped, we can read from it and write to it.</p>
<p>The 32-bit Intel microprocessors can access up to four gigabytes of memory - physical
or virtual. The FreeBSD system allows us to use up to a half of it for file mapping.</p>
<p>For simplicity sake, in this tutorial we will only convert files that can be mapped
into the memory in their entirety. There are probably not too many text files that exceed
two gigabytes in size. If our program encounters one, it will simply display a message
suggesting we use the original <b class="application">tuc</b> instead.</p>
<p>If you examine your copy of <tt class="filename">syscalls.master</tt>, you will find
two separate syscalls named <code class="function">mmap</code>. This is because of
evolution of <span class="trademark">UNIX</span>: There was the traditional <acronym class="acronym">BSD</acronym> <code class="function">mmap</code>, syscall 71. That one
was superceded by the <acronym class="acronym"><span class="trademark">POSIX</span></acronym> <code class="function">mmap</code>, syscall 197.
The FreeBSD system supports both because older programs were written by using the
original <acronym class="acronym">BSD</acronym> version. But new software uses the
<acronym class="acronym"><span class="trademark">POSIX</span></acronym> version, which is
what we will use.</p>
<p>The <tt class="filename">syscalls.master</tt> file lists the <acronym class="acronym"><span class="trademark">POSIX</span></acronym> version like this:</p>
<pkg:outlineMarker OutlineName="code_78" id="code_78" visible="false" copy="true">
<pre class="programlisting">197 STD BSD { caddr_t mmap(caddr_t addr, size_t len, int prot, \
int flags, int fd, long pad, off_t pos); }
</pre>
</pkg:outlineMarker>
<p>This differs slightly from what <a href="http://www.freebsd.org/cgi/man.cgi?query=mmap&sektion=2"><span class="citerefentry"><span class="refentrytitle">mmap</span>(2)</span></a> says. That is
because <a href="http://www.freebsd.org/cgi/man.cgi?query=mmap&sektion=2"><span class="citerefentry"><span class="refentrytitle">mmap</span>(2)</span></a> describes the
C version.</p>
<p>The difference is in the <var class="varname">long pad</var> argument, which is not
present in the C version. However, the FreeBSD syscalls add a 32-bit pad after <code class="function">push</code>ing a 64-bit argument. In this case, <var class="varname">off_t</var> is a 64-bit value.</p>
<p>When we are finished working with a memory-mapped file, we unmap it with the <code class="function">munmap</code> syscall:</p>
<blockquote class="tip">
<p><b>Tip:</b> For an in-depth treatment of <code class="function">mmap</code>, see W.
Richard Stevens' <a href="http://www.int80h.org/cgi-bin/isbn?isbn=0130810819" target="_top">Unix Network Programming, Volume 2, Chapter 12</a>.</p>
</blockquote>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.11.4 Determining File Size" id="X86-FILE-SIZE">
<div class="sect3">
<h3 class="title">16.11.4 Determining File
Size</h3>
<p>Because we need to tell <code class="function">mmap</code> how many bytes of the file
to map into the memory, and because we want to map the entire file, we need to determine
the size of the file.</p>
<p>We can use the <code class="function">fstat</code> syscall to get all the information
about an open file that the system can give us. That includes the file size.</p>
<p>Again, <tt class="filename">syscalls.master</tt> lists two versions of <code class="function">fstat</code>, a traditional one (syscall 62), and a <acronym class="acronym"><span class="trademark">POSIX</span></acronym> one (syscall 189).
Naturally, we will use the <acronym class="acronym"><span class="trademark">POSIX</span></acronym> version:</p>
<pkg:outlineMarker OutlineName="code_79" id="code_79" visible="false" copy="true">
<pre class="programlisting">189 STD POSIX { int fstat(int fd, struct stat *sb); }
</pre>
</pkg:outlineMarker>
<p>This is a very straightforward call: We pass to it the address of a <code class="structname">stat</code> structure and the descriptor of an open file. It will fill
out the contents of the <code class="structname">stat</code> structure.</p>
<p>I do, however, have to say that I tried to declare the <code class="structname">stat</code> structure in the <var class="varname">.bss</var> section,
and <code class="function">fstat</code> did not like it: It set the carry flag indicating
an error. After I changed the code to allocate the structure on the stack, everything was
working fine.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.11.5 Changing the File Size" id="X86-FTRUNCATE">
<div class="sect3">
<h3 class="title">16.11.5 Changing the File
Size</h3>
<p>Because our program may combine carriage return / line feed sequences into straight
line feeds, our output may be smaller than our input. However, since we are placing our
output into the same file we read the input from, we may have to change the size of the
file.</p>
<p>The <code class="function">ftruncate</code> system call allows us to do just that.
Despite its somewhat misleading name, the <code class="function">ftruncate</code> system
call can be used to both truncate the file (make it smaller) and to grow it.</p>
<p>And yes, we will find two versions of <code class="function">ftruncate</code> in <tt class="filename">syscalls.master</tt>, an older one (130), and a newer one (201). We will
use the newer one:</p>
<pkg:outlineMarker OutlineName="code_80" id="code_80" visible="false" copy="true">
<pre class="programlisting">201 STD BSD { int ftruncate(int fd, int pad, off_t length); }
</pre>
</pkg:outlineMarker>
<p>Please note that this one contains a <var class="varname">int pad</var> again.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.11.6 ftuc" id="X86-FTUC">
<div class="sect3">
<h3 class="title">16.11.6 ftuc</h3>
<p>We now know everything we need to write <b class="application">ftuc</b>. We start by
adding some new lines in <tt class="filename">system.inc</tt>. First, we define some
constants and structures, somewhere at or near the beginning of the file:</p>
<pkg:outlineMarker OutlineName="code_81" id="code_81" visible="false" copy="true">
<pre class="programlisting">;;;;;;; open flags
%define O_RDONLY 0
%define O_WRONLY 1
%define O_RDWR 2
;;;;;;; mmap flags
%define PROT_NONE 0
%define PROT_READ 1
%define PROT_WRITE 2
%define PROT_EXEC 4
;;
%define MAP_SHARED 0001h
%define MAP_PRIVATE 0002h
;;;;;;; stat structure
struc stat
st_dev resd 1 ; = 0
st_ino resd 1 ; = 4
st_mode resw 1 ; = 8, size is 16 bits
st_nlink resw 1 ; = 10, ditto
st_uid resd 1 ; = 12
st_gid resd 1 ; = 16
st_rdev resd 1 ; = 20
st_atime resd 1 ; = 24
st_atimensec resd 1 ; = 28
st_mtime resd 1 ; = 32
st_mtimensec resd 1 ; = 36
st_ctime resd 1 ; = 40
st_ctimensec resd 1 ; = 44
st_size resd 2 ; = 48, size is 64 bits
st_blocks resd 2 ; = 56, ditto
st_blksize resd 1 ; = 64
st_flags resd 1 ; = 68
st_gen resd 1 ; = 72
st_lspare resd 1 ; = 76
st_qspare resd 4 ; = 80
endstruc
</pre>
</pkg:outlineMarker>
<p>We define the new syscalls:</p>
<pkg:outlineMarker OutlineName="code_82" id="code_82" visible="false" copy="true">
<pre class="programlisting">%define SYS_mmap 197
%define SYS_munmap 73
%define SYS_fstat 189
%define SYS_ftruncate 201
</pre>
</pkg:outlineMarker>
<p>We add the macros for their use:</p>
<pkg:outlineMarker OutlineName="code_83" id="code_83" visible="false" copy="true">
<pre class="programlisting">%macro sys.mmap 0
system SYS_mmap
%endmacro
%macro sys.munmap 0
system SYS_munmap
%endmacro
%macro sys.ftruncate 0
system SYS_ftruncate
%endmacro
%macro sys.fstat 0
system SYS_fstat
%endmacro
</pre>
</pkg:outlineMarker>
<p>And here is our code:</p>
<pkg:outlineMarker OutlineName="code_84" id="code_84" visible="false" copy="true">
<pre class="programlisting">;;;;;;; Fast Text-to-Unix Conversion (ftuc.asm) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Started: 21-Dec-2000
;; Updated: 22-Dec-2000
;;
;; Copyright 2000 G. Adam Stanislav.
;; All rights reserved.
;;
;;;;;;; v.1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%include 'system.inc'
section .data
db 'Copyright 2000 G. Adam Stanislav.', 0Ah
db 'All rights reserved.', 0Ah
usg db 'Usage: ftuc filename', 0Ah
usglen equ $-usg
co db "ftuc: Can't open file.", 0Ah
colen equ $-co
fae db 'ftuc: File access error.', 0Ah
faelen equ $-fae
ftl db 'ftuc: File too long, use regular tuc instead.', 0Ah
ftllen equ $-ftl
mae db 'ftuc: Memory allocation error.', 0Ah
maelen equ $-mae
section .text
align 4
memerr:
push dword maelen
push dword mae
jmp short error
align 4
toolong:
push dword ftllen
push dword ftl
jmp short error
align 4
facerr:
push dword faelen
push dword fae
jmp short error
align 4
cantopen:
push dword colen
push dword co
jmp short error
align 4
usage:
push dword usglen
push dword usg
error:
push dword stderr
sys.write
push dword 1
sys.exit
align 4
global _start
_start:
pop eax ; argc
pop eax ; program name
pop ecx ; file to convert
jecxz usage
pop eax
or eax, eax ; Too many arguments?
jne usage
; Open the file
push dword O_RDWR
push ecx
sys.open
jc cantopen
mov ebp, eax ; Save fd
sub esp, byte stat_size
mov ebx, esp
; Find file size
push ebx
push ebp ; fd
sys.fstat
jc facerr
mov edx, [ebx + st_size + 4]
; File is too long if EDX != 0 ...
or edx, edx
jne near toolong
mov ecx, [ebx + st_size]
; ... or if it is above 2 GB
or ecx, ecx
js near toolong
; Do nothing if the file is 0 bytes in size
jecxz .quit
; Map the entire file in memory
push edx
push edx ; starting at offset 0
push edx ; pad
push ebp ; fd
push dword MAP_SHARED
push dword PROT_READ | PROT_WRITE
push ecx ; entire file size
push edx ; let system decide on the address
sys.mmap
jc near memerr
mov edi, eax
mov esi, eax
push ecx ; for SYS_munmap
push edi
; Use EBX for state machine
mov ebx, ordinary
mov ah, 0Ah
cld
.loop:
lodsb
call ebx
loop .loop
cmp ebx, ordinary
je .filesize
; Output final lf
mov al, ah
stosb
inc edx
.filesize:
; truncate file to new size
push dword 0 ; high dword
push edx ; low dword
push eax ; pad
push ebp
sys.ftruncate
; close it (ebp still pushed)
sys.close
add esp, byte 16
sys.munmap
.quit:
push dword 0
sys.exit
align 4
ordinary:
cmp al, 0Dh
je .cr
cmp al, ah
je .lf
stosb
inc edx
ret
align 4
.cr:
mov ebx, cr
ret
align 4
.lf:
mov ebx, lf
ret
align 4
cr:
cmp al, 0Dh
je .cr
cmp al, ah
je .lf
xchg al, ah
stosb
inc edx
xchg al, ah
; fall through
.lf:
stosb
inc edx
mov ebx, ordinary
ret
align 4
.cr:
mov al, ah
stosb
inc edx
ret
align 4
lf:
cmp al, ah
je .lf
cmp al, 0Dh
je .cr
xchg al, ah
stosb
inc edx
xchg al, ah
stosb
inc edx
mov ebx, ordinary
ret
align 4
.cr:
mov ebx, ordinary
mov al, ah
; fall through
.lf:
stosb
inc edx
ret
</pre>
</pkg:outlineMarker>
<blockquote class="warning">
<p><b>Warning:</b> Do not use this program on files stored on a disk formated by <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym> or <span class="trademark">Windows</span>. There seems to be a subtle bug in the FreeBSD code when
using <code class="function">mmap</code> on these drives mounted under FreeBSD: If the
file is over a certain size, <code class="function">mmap</code> will just fill the memory
with zeros, and then copy them to the file overwriting its contents.</p>
</blockquote>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.12 One-Pointed Mind" id="X86-ONE-POINTED-MIND">
<div class="sect2">
<h2 class="title">16.12
One-Pointed Mind</h2>
<p>As a student of Zen, I like the idea of a one-pointed mind: Do one thing at a time,
and do it well.</p>
<p>This, indeed, is very much how <span class="trademark">UNIX</span> works as well.
While a typical <span class="trademark">Windows</span> application is attempting to do
everything imaginable (and is, therefore, riddled with bugs), a typical <span class="trademark">UNIX</span> program does only one thing, and it does it well.</p>
<p>The typical <span class="trademark">UNIX</span> user then essentially assembles his
own applications by writing a shell script which combines the various existing programs
by piping the output of one program to the input of another.</p>
<p>When writing your own <span class="trademark">UNIX</span> software, it is generally a
good idea to see what parts of the problem you need to solve can be handled by existing
programs, and only write your own programs for that part of the problem that you do not
have an existing solution for.</p>
<hr />
<pkg:outlineMarker OutlineName="16.12.1 CSV" id="X86-CSV">
<div class="sect3">
<h3 class="title">16.12.1 CSV</h3>
<p>I will illustrate this principle with a specific real-life example I was faced with
recently:</p>
<p>I needed to extract the 11th field of each record from a database I downloaded from a
web site. The database was a <acronym class="acronym">CSV</acronym> file, i.e., a list of
<span class="emphasis"><i class="emphasis">comma-separated values</i></span>. That is
quite a standard format for sharing data among people who may be using different database
software.</p>
<p>The first line of the file contains the list of various fields separated by commas.
The rest of the file contains the data listed line by line, with values separated by
commas.</p>
<p>I tried <b class="application">awk</b>, using the comma as a separator. But because
several lines contained a quoted comma, <b class="application">awk</b> was extracting the
wrong field from those lines.</p>
<p>Therefore, I needed to write my own software to extract the 11th field from the
<acronym class="acronym">CSV</acronym> file. However, going with the <span class="trademark">UNIX</span> spirit, I only needed to write a simple filter that would
do the following:</p>
<ul>
<li>
<p>Remove the first line from the file;</p>
</li>
<li>
<p>Change all unquoted commas to a different character;</p>
</li>
<li>
<p>Remove all quotation marks.</p>
</li>
</ul>
<p>Strictly speaking, I could use <b class="application">sed</b> to remove the first line
from the file, but doing so in my own program was very easy, so I decided to do it and
reduce the size of the pipeline.</p>
<p>At any rate, writing a program like this took me about 20 minutes. Writing a program
that extracts the 11th field from the <acronym class="acronym">CSV</acronym> file would
take a lot longer, and I could not reuse it to extract some other field from some other
database.</p>
<p>This time I decided to let it do a little more work than a typical tutorial program
would:</p>
<ul>
<li>
<p>It parses its command line for options;</p>
</li>
<li>
<p>It displays proper usage if it finds wrong arguments;</p>
</li>
<li>
<p>It produces meaningful error messages.</p>
</li>
</ul>
<p>Here is its usage message:</p>
<pre class="screen">Usage: csv [-t<delim>] [-c<comma>] [-p] [-o <outfile>] [-i <infile>]
</pre>
<p>All parameters are optional, and can appear in any order.</p>
<p>The <var class="parameter">-t</var> parameter declares what to replace the commas
with. The <code class="constant">tab</code> is the default here. For example, <var class="parameter">-t;</var> will replace all unquoted commas with semicolons.</p>
<p>I did not need the <var class="parameter">-c</var> option, but it may come in handy in
the future. It lets me declare that I want a character other than a comma replaced with
something else. For example, <var class="parameter">-c@</var> will replace all at signs
(useful if you want to split a list of email addresses to their user names and
domains).</p>
<p>The <var class="parameter">-p</var> option preserves the first line, i.e., it does not
delete it. By default, we delete the first line because in a <acronym class="acronym">CSV</acronym> file it contains the field names rather than data.</p>
<p>The <var class="parameter">-i</var> and <var class="parameter">-o</var> options let me
specify the input and the output files. Defaults are <tt class="filename">stdin</tt> and
<tt class="filename">stdout</tt>, so this is a regular <span class="trademark">UNIX</span> filter.</p>
<p>I made sure that both <var class="parameter">-i filename</var> and <var class="parameter">-ifilename</var> are accepted. I also made sure that only one input and
one output files may be specified.</p>
<p>To get the 11th field of each record, I can now do:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">csv '-t;' <var class="replaceable">data.csv</var> | awk '-F;' '{print $11}'</kbd>
</pre>
<p>The code stores the options (except for the file descriptors) in <var class="varname">EDX</var>: The comma in <var class="varname">DH</var>, the new separator
in <var class="varname">DL</var>, and the flag for the <var class="parameter">-p</var>
option in the highest bit of <var class="varname">EDX</var>, so a check for its sign will
give us a quick decision what to do.</p>
<p>Here is the code:</p>
<pkg:outlineMarker OutlineName="code_85" id="code_85" visible="false" copy="true">
<pre class="programlisting">;;;;;;; csv.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Convert a comma-separated file to a something-else separated file.
;
; Started: 31-May-2001
; Updated: 1-Jun-2001
;
; Copyright (c) 2001 G. Adam Stanislav
; All rights reserved.
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%include 'system.inc'
%define BUFSIZE 2048
section .data
fd.in dd stdin
fd.out dd stdout
usg db 'Usage: csv [-t<delim>] [-c<comma>] [-p] [-o <outfile>] [-i <infile>]', 0Ah
usglen equ $-usg
iemsg db "csv: Can't open input file", 0Ah
iemlen equ $-iemsg
oemsg db "csv: Can't create output file", 0Ah
oemlen equ $-oemsg
section .bss
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
section .text
align 4
ierr:
push dword iemlen
push dword iemsg
push dword stderr
sys.write
push dword 1 ; return failure
sys.exit
align 4
oerr:
push dword oemlen
push dword oemsg
push dword stderr
sys.write
push dword 2
sys.exit
align 4
usage:
push dword usglen
push dword usg
push dword stderr
sys.write
push dword 3
sys.exit
align 4
global _start
_start:
add esp, byte 8 ; discard argc and argv[0]
mov edx, (',' << 8) | 9
.arg:
pop ecx
or ecx, ecx
je near .init ; no more arguments
; ECX contains the pointer to an argument
cmp byte [ecx], '-'
jne usage
inc ecx
mov ax, [ecx]
.o:
cmp al, 'o'
jne .i
; Make sure we are not asked for the output file twice
cmp dword [fd.out], stdout
jne usage
; Find the path to output file - it is either at [ECX+1],
; i.e., -ofile --
; or in the next argument,
; i.e., -o file
inc ecx
or ah, ah
jne .openoutput
pop ecx
jecxz usage
.openoutput:
push dword 420 ; file mode (644 octal)
push dword 0200h | 0400h | 01h
; O_CREAT | O_TRUNC | O_WRONLY
push ecx
sys.open
jc near oerr
add esp, byte 12
mov [fd.out], eax
jmp short .arg
.i:
cmp al, 'i'
jne .p
; Make sure we are not asked twice
cmp dword [fd.in], stdin
jne near usage
; Find the path to the input file
inc ecx
or ah, ah
jne .openinput
pop ecx
or ecx, ecx
je near usage
.openinput:
push dword 0 ; O_RDONLY
push ecx
sys.open
jc near ierr ; open failed
add esp, byte 8
mov [fd.in], eax
jmp .arg
.p:
cmp al, 'p'
jne .t
or ah, ah
jne near usage
or edx, 1 << 31
jmp .arg
.t:
cmp al, 't' ; redefine output delimiter
jne .c
or ah, ah
je near usage
mov dl, ah
jmp .arg
.c:
cmp al, 'c'
jne near usage
or ah, ah
je near usage
mov dh, ah
jmp .arg
align 4
.init:
sub eax, eax
sub ebx, ebx
sub ecx, ecx
mov edi, obuffer
; See if we are to preserve the first line
or edx, edx
js .loop
.firstline:
; get rid of the first line
call getchar
cmp al, 0Ah
jne .firstline
.loop:
; read a byte from stdin
call getchar
; is it a comma (or whatever the user asked for)?
cmp al, dh
jne .quote
; Replace the comma with a tab (or whatever the user wants)
mov al, dl
.put:
call putchar
jmp short .loop
.quote:
cmp al, '"'
jne .put
; Print everything until you get another quote or EOL. If it
; is a quote, skip it. If it is EOL, print it.
.qloop:
call getchar
cmp al, '"'
je .loop
cmp al, 0Ah
je .put
call putchar
jmp short .qloop
align 4
getchar:
or ebx, ebx
jne .fetch
call read
.fetch:
lodsb
dec ebx
ret
read:
jecxz .read
call write
.read:
push dword BUFSIZE
mov esi, ibuffer
push esi
push dword [fd.in]
sys.read
add esp, byte 12
mov ebx, eax
or eax, eax
je .done
sub eax, eax
ret
align 4
.done:
call write ; flush output buffer
; close files
push dword [fd.in]
sys.close
push dword [fd.out]
sys.close
; return success
push dword 0
sys.exit
align 4
putchar:
stosb
inc ecx
cmp ecx, BUFSIZE
je write
ret
align 4
write:
jecxz .ret ; nothing to write
sub edi, ecx ; start of buffer
push ecx
push edi
push dword [fd.out]
sys.write
add esp, byte 12
sub eax, eax
sub ecx, ecx ; buffer is empty now
.ret:
ret
</pre>
</pkg:outlineMarker>
<p>Much of it is taken from <tt class="filename">hex.asm</tt> above. But there is one
important difference: I no longer call <code class="function">write</code> whenever I am
outputting a line feed. Yet, the code can be used interactively.</p>
<p>I have found a better solution for the interactive problem since I first started
writing this chapter. I wanted to make sure each line is printed out separately only when
needed. After all, there is no need to flush out every line when used
non-interactively.</p>
<p>The new solution I use now is to call <code class="function">write</code> every time I
find the input buffer empty. That way, when running in the interactive mode, the program
reads one line from the user's keyboard, processes it, and sees its input buffer is
empty. It flushes its output and reads the next line.</p>
<hr />
<pkg:outlineMarker OutlineName="16.12.1.1 The Dark Side of Buffering" id="X86-BUFFERED-DARK-SIDE">
<div class="sect3">
<h4 class="title">16.12.1.1
The Dark Side of Buffering</h4>
<p>This change prevents a mysterious lockup in a very specific case. I refer to it as the
<span class="emphasis"><i class="emphasis">dark side of buffering</i></span>, mostly
because it presents a danger that is not quite obvious.</p>
<p>It is unlikely to happen with a program like the <b class="application">csv</b> above,
so let us consider yet another filter: In this case we expect our input to be raw data
representing color values, such as the <span class="emphasis"><i class="emphasis">red</i></span>, <span class="emphasis"><i class="emphasis">green</i></span>, and <span class="emphasis"><i class="emphasis">blue</i></span> intensities of a pixel. Our output will be the negative
of our input.</p>
<p>Such a filter would be very simple to write. Most of it would look just like all the
other filters we have written so far, so I am only going to show you its inner loop:</p>
<pkg:outlineMarker OutlineName="code_86" id="code_86" visible="false" copy="true">
<pre class="programlisting">.loop:
call getchar
not al ; Create a negative
call putchar
jmp short .loop
</pre>
</pkg:outlineMarker>
<p>Because this filter works with raw data, it is unlikely to be used interactively.</p>
<p>But it could be called by image manipulation software. And, unless it calls <code class="function">write</code> before each call to <code class="function">read</code>,
chances are it will lock up.</p>
<p>Here is what might happen:</p>
<ol type="1">
<li>
<p>The image editor will load our filter using the C function <code class="function">popen()</code>.</p>
</li>
<li>
<p>It will read the first row of pixels from a bitmap or pixmap.</p>
</li>
<li>
<p>It will write the first row of pixels to the <span class="emphasis"><i class="emphasis">pipe</i></span> leading to the <var class="varname">fd.in</var> of our
filter.</p>
</li>
<li>
<p>Our filter will read each pixel from its input, turn it to a negative, and write it to
its output buffer.</p>
</li>
<li>
<p>Our filter will call <code class="function">getchar</code> to fetch the next
pixel.</p>
</li>
<li>
<p><code class="function">getchar</code> will find an empty input buffer, so it will call
<code class="function">read</code>.</p>
</li>
<li>
<p><code class="function">read</code> will call the <code class="function">SYS_read</code> system call.</p>
</li>
<li>
<p>The <span class="emphasis"><i class="emphasis">kernel</i></span> will suspend our
filter until the image editor sends more data to the pipe.</p>
</li>
<li>
<p>The image editor will read from the other pipe, connected to the <var class="varname">fd.out</var> of our filter so it can set the first row of the output
image <span class="emphasis"><i class="emphasis">before</i></span> it sends us the second
row of the input.</p>
</li>
<li>
<p>The <span class="emphasis"><i class="emphasis">kernel</i></span> suspends the image
editor until it receives some output from our filter, so it can pass it on to the image
editor.</p>
</li>
</ol>
<p>At this point our filter waits for the image editor to send it more data to process,
while the image editor is waiting for our filter to send it the result of the processing
of the first row. But the result sits in our output buffer.</p>
<p>The filter and the image editor will continue waiting for each other forever (or, at
least, until they are killed). Our software has just entered a <a href="pkg://FreeBSD Developers' Handbook/SECURE-RACE-CONDITIONS">race condition</a>.</p>
<p>This problem does not exist if our filter flushes its output buffer <span class="emphasis"><i class="emphasis">before</i></span> asking the <span class="emphasis"><i class="emphasis">kernel</i></span> for more input data.</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13 Using the FPU" id="X86-FPU">
<div class="sect2">
<h2 class="title">16.13 Using the <acronym class="acronym">FPU</acronym></h2>
<p>Strangely enough, most of assembly language literature does not even mention the
existence of the <acronym class="acronym">FPU</acronym>, or <span class="emphasis"><i class="emphasis">floating point unit</i></span>, let alone discuss programming it.</p>
<p>Yet, never does assembly language shine more than when we create highly optimized
<acronym class="acronym">FPU</acronym> code by doing things that can be done <span class="emphasis"><i class="emphasis">only</i></span> in assembly language.</p>
<hr />
<pkg:outlineMarker OutlineName="16.13.1 Organization of the FPU" id="X86-FPU-ORGANIZATION">
<div class="sect3">
<h3 class="title">16.13.1
Organization of the <acronym class="acronym">FPU</acronym></h3>
<p>The <acronym class="acronym">FPU</acronym> consists of 8 80-bit floating-point
registers. These are organized in a stack fashion--you can <code class="function">push</code> a value on <acronym class="acronym">TOS</acronym> (<span class="emphasis"><i class="emphasis">top of stack</i></span>) and you can <code class="function">pop</code> it.</p>
<p>That said, the assembly language op codes are not <code class="function">push</code>
and <code class="function">pop</code> because those are already taken.</p>
<p>You can <code class="function">push</code> a value on <acronym class="acronym">TOS</acronym> by using <code class="function">fld</code>, <code class="function">fild</code>, and <code class="function">fbld</code>. Several other op
codes let you <code class="function">push</code> many common <span class="emphasis"><i class="emphasis">constants</i></span>--such as <span class="emphasis"><i class="emphasis">pi</i></span>--on the <acronym class="acronym">TOS</acronym>.</p>
<p>Similarly, you can <code class="function">pop</code> a value by using <code class="function">fst</code>, <code class="function">fstp</code>, <code class="function">fist</code>, <code class="function">fistp</code>, and <code class="function">fbstp</code>. Actually, only the op codes that end with a <span class="emphasis"><i class="emphasis">p</i></span> will literally <code class="function">pop</code> the value, the rest will <code class="function">store</code>
it somewhere else without removing it from the <acronym class="acronym">TOS</acronym>.</p>
<p>We can transfer the data between the <acronym class="acronym">TOS</acronym> and the
computer memory either as a 32-bit, 64-bit, or 80-bit <span class="emphasis"><i class="emphasis">real</i></span>, a 16-bit, 32-bit, or 64-bit <span class="emphasis"><i class="emphasis">integer</i></span>, or an 80-bit <span class="emphasis"><i class="emphasis">packed decimal</i></span>.</p>
<p>The 80-bit <span class="emphasis"><i class="emphasis">packed decimal</i></span> is a
special case of <span class="emphasis"><i class="emphasis">binary coded
decimal</i></span> which is very convenient when converting between the <acronym class="acronym">ASCII</acronym> representation of data and the internal data of the
<acronym class="acronym">FPU</acronym>. It allows us to use 18 significant digits.</p>
<p>No matter how we represent data in the memory, the <acronym class="acronym">FPU</acronym> always stores it in the 80-bit <span class="emphasis"><i class="emphasis">real</i></span> format in its registers.</p>
<p>Its internal precision is at least 19 decimal digits, so even if we choose to display
results as <acronym class="acronym">ASCII</acronym> in the full 18-digit precision, we
are still showing correct results.</p>
<p>We can perform mathematical operations on the <acronym class="acronym">TOS</acronym>:
We can calculate its <span class="emphasis"><i class="emphasis">sine</i></span>, we can
<span class="emphasis"><i class="emphasis">scale</i></span> it (i.e., we can multiply or
divide it by a power of 2), we can calculate its base-2 <span class="emphasis"><i class="emphasis">logarithm</i></span>, and many other things.</p>
<p>We can also <span class="emphasis"><i class="emphasis">multiply</i></span> or <span class="emphasis"><i class="emphasis">divide</i></span> it by, <span class="emphasis"><i class="emphasis">add</i></span> it to, or <span class="emphasis"><i class="emphasis">subtract</i></span> it from, any of the <acronym class="acronym">FPU</acronym> registers (including itself).</p>
<p>The official Intel op code for the <acronym class="acronym">TOS</acronym> is <var class="varname">st</var>, and for the <span class="emphasis"><i class="emphasis">registers</i></span> <var class="varname">st(0)</var>-<var class="varname">st(7)</var>. <var class="varname">st</var> and <var class="varname">st(0)</var>, then, refer to the same register.</p>
<p>For whatever reasons, the original author of <b class="application">nasm</b> has
decided to use different op codes, namely <var class="varname">st0</var>-<var class="varname">st7</var>. In other words, there are no parentheses, and the <acronym class="acronym">TOS</acronym> is always <var class="varname">st0</var>, never just <code class="function">st</code>.</p>
<hr />
<pkg:outlineMarker OutlineName="16.13.1.1 The Packed Decimal Format" id="X86-FPU-PACKED-DECIMAL">
<div class="sect3">
<h4 class="title">16.13.1.1
The Packed Decimal Format</h4>
<p>The <span class="emphasis"><i class="emphasis">packed decimal</i></span> format uses
10 bytes (80 bits) of memory to represent 18 digits. The number represented there is
always an <span class="emphasis"><i class="emphasis">integer</i></span>.</p>
<blockquote class="tip">
<p><b>Tip:</b> You can use it to get decimal places by multiplying the <acronym class="acronym">TOS</acronym> by a power of 10 first.</p>
</blockquote>
<p>The highest bit of the highest byte (byte 9) is the <span class="emphasis"><i class="emphasis">sign bit</i></span>: If it is set, the number is <span class="emphasis"><i class="emphasis">negative</i></span>, otherwise, it is <span class="emphasis"><i class="emphasis">positive</i></span>. The rest of the bits of this
byte are unused/ignored.</p>
<p>The remaining 9 bytes store the 18 digits of the number: 2 digits per byte.</p>
<p>The <span class="emphasis"><i class="emphasis">more significant digit</i></span> is
stored in the high <span class="emphasis"><i class="emphasis">nibble</i></span> (4 bits),
the <span class="emphasis"><i class="emphasis">less significant digit</i></span> in the
low <span class="emphasis"><i class="emphasis">nibble</i></span>.</p>
<p>That said, you might think that <code class="constant">-1234567</code> would be stored
in the memory like this (using hexadecimal notation):</p>
<pkg:outlineMarker OutlineName="code_87" id="code_87" visible="false" copy="true">
<pre class="programlisting">80 00 00 00 00 00 01 23 45 67
</pre>
</pkg:outlineMarker>
<p>Alas it is not! As with everything else of Intel make, even the <span class="emphasis"><i class="emphasis">packed decimal</i></span> is <span class="emphasis"><i class="emphasis">little-endian</i></span>.</p>
<p>That means our <code class="constant">-1234567</code> is stored like this:</p>
<pkg:outlineMarker OutlineName="code_88" id="code_88" visible="false" copy="true">
<pre class="programlisting">67 45 23 01 00 00 00 00 00 80
</pre>
</pkg:outlineMarker>
<p>Remember that, or you will be pulling your hair out in desperation!</p>
<blockquote class="note">
<p><b>Note:</b> The book to read--if you can find it--is Richard Startz' <a href="http://www.int80h.org/cgi-bin/isbn?isbn=013246604X" target="_top">8087/80287/80387
for the IBM PC & Compatibles</a>. Though it does seem to take the fact about the
little-endian storage of the <span class="emphasis"><i class="emphasis">packed
decimal</i></span> for granted. I kid you not about the desperation of trying to figure
out what was wrong with the filter I show below <span class="emphasis"><i class="emphasis">before</i></span> it occurred to me I should try the little-endian order
even for this type of data.</p>
</blockquote>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.2 Excursion to Pinhole Photography" id="X86-PINHOLE-PHOTOGRAPHY">
<div class="sect3">
<h3 class="title">16.13.2
Excursion to Pinhole Photography</h3>
<p>To write meaningful software, we must not only understand our programming tools, but
also the field we are creating software for.</p>
<p>Our next filter will help us whenever we want to build a <span class="emphasis"><i class="emphasis">pinhole camera</i></span>, so, we need some background in <span class="emphasis"><i class="emphasis">pinhole photography</i></span> before we can
continue.</p>
<hr />
<pkg:outlineMarker OutlineName="16.13.2.1 The Camera" id="X86-CAMERA">
<div class="sect3">
<h4 class="title">16.13.2.1 The Camera</h4>
<p>The easiest way to describe any camera ever built is as some empty space enclosed in
some lightproof material, with a small hole in the enclosure.</p>
<p>The enclosure is usually sturdy (e.g., a box), though sometimes it is flexible (the
bellows). It is quite dark inside the camera. However, the hole lets light rays in
through a single point (though in some cases there may be several). These light rays form
an image, a representation of whatever is outside the camera, in front of the hole.</p>
<p>If some light sensitive material (such as film) is placed inside the camera, it can
capture the image.</p>
<p>The hole often contains a <span class="emphasis"><i class="emphasis">lens</i></span>,
or a lens assembly, often called the <span class="emphasis"><i class="emphasis">objective</i></span>.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.2.2 The Pinhole" id="X86-THE-PINHOLE">
<div class="sect3">
<h4 class="title">16.13.2.2 The
Pinhole</h4>
<p>But, strictly speaking, the lens is not necessary: The original cameras did not use a
lens but a <span class="emphasis"><i class="emphasis">pinhole</i></span>. Even today,
<span class="emphasis"><i class="emphasis">pinholes</i></span> are used, both as a tool
to study how cameras work, and to achieve a special kind of image.</p>
<p>The image produced by the <span class="emphasis"><i class="emphasis">pinhole</i></span> is all equally sharp. Or <span class="emphasis"><i class="emphasis">blurred</i></span>. There is an ideal size for a pinhole: If it is
either larger or smaller, the image loses its sharpness.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.2.3 Focal Length" id="X86-FOCAL-LENGTH">
<div class="sect3">
<h4 class="title">16.13.2.3 Focal
Length</h4>
<p>This ideal pinhole diameter is a function of the square root of <span class="emphasis"><i class="emphasis">focal length</i></span>, which is the distance of
the pinhole from the film.</p>
<pkg:outlineMarker OutlineName="code_89" id="code_89" visible="false" copy="true">
<pre class="programlisting"> D = PC * sqrt(FL)
</pre>
</pkg:outlineMarker>
<p>In here, <var class="varname">D</var> is the ideal diameter of the pinhole, <var class="varname">FL</var> is the focal length, and <code class="constant">PC</code> is a
pinhole constant. According to Jay Bender, its value is <code class="constant">0.04</code>, while Kenneth Connors has determined it to be <code class="constant">0.037</code>. Others have proposed other values. Plus, this value is for
the daylight only: Other types of light will require a different constant, whose value
can only be determined by experimentation.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.2.4 The F-Number" id="X86-F-NUMBER">
<div class="sect3">
<h4 class="title">16.13.2.4 The
F-Number</h4>
<p>The f-number is a very useful measure of how much light reaches the film. A light
meter can determine that, for example, to expose a film of specific sensitivity with f5.6
may require the exposure to last 1/1000 sec.</p>
<p>It does not matter whether it is a 35-mm camera, or a 6x9cm camera, etc. As long as we
know the f-number, we can determine the proper exposure.</p>
<p>The f-number is easy to calculate:</p>
<pkg:outlineMarker OutlineName="code_90" id="code_90" visible="false" copy="true">
<pre class="programlisting"> F = FL / D
</pre>
</pkg:outlineMarker>
<p>In other words, the f-number equals the focal length divided by the diameter of the
pinhole. It also means a higher f-number either implies a smaller pinhole or a larger
focal distance, or both. That, in turn, implies, the higher the f-number, the longer the
exposure has to be.</p>
<p>Furthermore, while pinhole diameter and focal distance are one-dimensional
measurements, both, the film and the pinhole, are two-dimensional. That means that if you
have measured the exposure at f-number <var class="varname">A</var> as <var class="varname">t</var>, then the exposure at f-number <var class="varname">B</var>
is:</p>
<pkg:outlineMarker OutlineName="code_91" id="code_91" visible="false" copy="true">
<pre class="programlisting"> t * (B / A)²
</pre>
</pkg:outlineMarker>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.2.5 Normalized F-Number" id="X86-NORMALIZED-F-NUMBER">
<div class="sect3">
<h4 class="title">16.13.2.5 Normalized F-Number</h4>
<p>While many modern cameras can change the diameter of their pinhole, and thus their
f-number, quite smoothly and gradually, such was not always the case.</p>
<p>To allow for different f-numbers, cameras typically contained a metal plate with
several holes of different sizes drilled to them.</p>
<p>Their sizes were chosen according to the above formula in such a way that the
resultant f-number was one of standard f-numbers used on all cameras everywhere. For
example, a very old Kodak Duaflex IV camera in my possession has three such holes for
f-numbers 8, 11, and 16.</p>
<p>A more recently made camera may offer f-numbers of 2.8, 4, 5.6, 8, 11, 16, 22, and 32
(as well as others). These numbers were not chosen arbitrarily: They all are powers of
the square root of 2, though they may be rounded somewhat.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.2.6 The F-Stop" id="X86-F-STOP">
<div class="sect3">
<h4 class="title">16.13.2.6 The F-Stop</h4>
<p>A typical camera is designed in such a way that setting any of the normalized
f-numbers changes the feel of the dial. It will naturally <span class="emphasis"><i class="emphasis">stop</i></span> in that position. Because of that, these positions of
the dial are called f-stops.</p>
<p>Since the f-numbers at each stop are powers of the square root of 2, moving the dial
by 1 stop will double the amount of light required for proper exposure. Moving it by 2
stops will quadruple the required exposure. Moving the dial by 3 stops will require the
increase in exposure 8 times, etc.</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.3 Designing the Pinhole Software" id="X86-PINHOLE-SOFTWARE">
<div class="sect3">
<h3 class="title">16.13.3
Designing the Pinhole Software</h3>
<p>We are now ready to decide what exactly we want our pinhole software to do.</p>
<hr />
<pkg:outlineMarker OutlineName="16.13.3.1 Processing Program Input" id="XPINHOLE-PROCESSING-INPUT">
<div class="sect3">
<h4 class="title">16.13.3.1 Processing Program Input</h4>
<p>Since its main purpose is to help us design a working pinhole camera, we will use the
<span class="emphasis"><i class="emphasis">focal length</i></span> as the input to the
program. This is something we can determine without software: Proper focal length is
determined by the size of the film and by the need to shoot "regular" pictures, wide
angle pictures, or telephoto pictures.</p>
<p>Most of the programs we have written so far worked with individual characters, or
bytes, as their input: The <b class="application">hex</b> program converted individual
bytes into a hexadecimal number, the <b class="application">csv</b> program either let a
character through, or deleted it, or changed it to a different character, etc.</p>
<p>One program, <b class="application">ftuc</b> used the state machine to consider at
most two input bytes at a time.</p>
<p>But our <b class="application">pinhole</b> program cannot just work with individual
characters, it has to deal with larger syntactic units.</p>
<p>For example, if we want the program to calculate the pinhole diameter (and other
values we will discuss later) at the focal lengths of <code class="constant">100
mm</code>, <code class="constant">150 mm</code>, and <code class="constant">210
mm</code>, we may want to enter something like this:</p>
<pre class="screen"><kbd class="userinput">100, 150, 210</kbd>
</pre>
<p>Our program needs to consider more than a single byte of input at a time. When it sees
the first <code class="constant">1</code>, it must understand it is seeing the first
digit of a decimal number. When it sees the <code class="constant">0</code> and the other
<code class="constant">0</code>, it must know it is seeing more digits of the same
number.</p>
<p>When it encounters the first comma, it must know it is no longer receiving the digits
of the first number. It must be able to convert the digits of the first number into the
value of <code class="constant">100</code>. And the digits of the second number into the
value of <code class="constant">150</code>. And, of course, the digits of the third
number into the numeric value of <code class="constant">210</code>.</p>
<p>We need to decide what delimiters to accept: Do the input numbers have to be separated
by a comma? If so, how do we treat two numbers separated by something else?</p>
<p>Personally, I like to keep it simple. Something either is a number, so I process it.
Or it is not a number, so I discard it. I do not like the computer complaining about me
typing in an extra character when it is <span class="emphasis"><i class="emphasis">obvious</i></span> that it is an extra character. Duh!</p>
<p>Plus, it allows me to break up the monotony of computing and type in a query instead
of just a number:</p>
<pre class="screen"><kbd class="userinput">What is the best pinhole diameter for the focal length of 150?</kbd>
</pre>
<p>There is no reason for the computer to spit out a number of complaints:</p>
<pre class="screen">Syntax error: What
Syntax error: is
Syntax error: the
Syntax error: best
</pre>
<p>Et cetera, et cetera, et cetera.</p>
<p>Secondly, I like the <code class="constant">#</code> character to denote the start of
a comment which extends to the end of the line. This does not take too much effort to
code, and lets me treat input files for my software as executable scripts.</p>
<p>In our case, we also need to decide what units the input should come in: We choose
<span class="emphasis"><i class="emphasis">millimeters</i></span> because that is how
most photographers measure the focus length.</p>
<p>Finally, we need to decide whether to allow the use of the decimal point (in which
case we must also consider the fact that much of the world uses a decimal <span class="emphasis"><i class="emphasis">comma</i></span>).</p>
<p>In our case allowing for the decimal point/comma would offer a false sense of
precision: There is little if any noticeable difference between the focus lengths of
<code class="constant">50</code> and <code class="constant">51</code>, so allowing the
user to input something like <code class="constant">50.5</code> is not a good idea. This
is my opinion, mind you, but I am the one writing this program. You can make other
choices in yours, of course.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.3.2 Offering Options" id="X86-PINHOLE-OPTIONS">
<div class="sect3">
<h4 class="title">16.13.3.2
Offering Options</h4>
<p>The most important thing we need to know when building a pinhole camera is the
diameter of the pinhole. Since we want to shoot sharp images, we will use the above
formula to calculate the pinhole diameter from focal length. As experts are offering
several different values for the <code class="constant">PC</code> constant, we will need
to have the choice.</p>
<p>It is traditional in <span class="trademark">UNIX</span> programming to have two main
ways of choosing program parameters, plus to have a default for the time the user does
not make a choice.</p>
<p>Why have two ways of choosing?</p>
<p>One is to allow a (relatively) <span class="emphasis"><i class="emphasis">permanent</i></span> choice that applies automatically each time the
software is run without us having to tell it over and over what we want it to do.</p>
<p>The permanent choices may be stored in a configuration file, typically found in the
user's home directory. The file usually has the same name as the application but is
started with a dot. Often <span class="emphasis"><i class="emphasis">"rc"</i></span> is
added to the file name. So, ours could be <tt class="filename">~/.pinhole</tt> or <tt class="filename">~/.pinholerc</tt>. (The <tt class="filename">~/</tt> means current
user's home directory.)</p>
<p>The configuration file is used mostly by programs that have many configurable
parameters. Those that have only one (or a few) often use a different method: They expect
to find the parameter in an <span class="emphasis"><i class="emphasis">environment
variable</i></span>. In our case, we might look at an environment variable named <var class="varname">PINHOLE</var>.</p>
<p>Usually, a program uses one or the other of the above methods. Otherwise, if a
configuration file said one thing, but an environment variable another, the program might
get confused (or just too complicated).</p>
<p>Because we only need to choose <span class="emphasis"><i class="emphasis">one</i></span> such parameter, we will go with the second method and
search the environment for a variable named <var class="varname">PINHOLE</var>.</p>
<p>The other way allows us to make <span class="emphasis"><i class="emphasis">ad
hoc</i></span> decisions: <span class="emphasis"><i class="emphasis">"Though I usually
want you to use 0.039, this time I want 0.03872."</i></span> In other words, it allows us
to <span class="emphasis"><i class="emphasis">override</i></span> the permanent
choice.</p>
<p>This type of choice is usually done with command line parameters.</p>
<p>Finally, a program <span class="emphasis"><i class="emphasis">always</i></span> needs
a <span class="emphasis"><i class="emphasis">default</i></span>. The user may not make
any choices. Perhaps he does not know what to choose. Perhaps he is "just browsing."
Preferably, the default will be the value most users would choose anyway. That way they
do not need to choose. Or, rather, they can choose the default without an additional
effort.</p>
<p>Given this system, the program may find conflicting options, and handle them this
way:</p>
<ol type="1">
<li>
<p>If it finds an <span class="emphasis"><i class="emphasis">ad hoc</i></span> choice
(e.g., command line parameter), it should accept that choice. It must ignore any
permanent choice and any default.</p>
</li>
<li>
<p><span class="emphasis"><i class="emphasis">Otherwise</i></span>, if it finds a
permanent option (e.g., an environment variable), it should accept it, and ignore the
default.</p>
</li>
<li>
<p><span class="emphasis"><i class="emphasis">Otherwise</i></span>, it should use the
default.</p>
</li>
</ol>
<p>We also need to decide what <span class="emphasis"><i class="emphasis">format</i></span> our <code class="constant">PC</code> option should
have.</p>
<p>At first site, it seems obvious to use the <var class="varname">PINHOLE=0.04</var>
format for the environment variable, and <var class="parameter">-p0.04</var> for the
command line.</p>
<p>Allowing that is actually a security risk. The <code class="constant">PC</code>
constant is a very small number. Naturally, we will test our software using various small
values of <code class="constant">PC</code>. But what will happen if someone runs the
program choosing a huge value?</p>
<p>It may crash the program because we have not designed it to handle huge numbers.</p>
<p>Or, we may spend more time on the program so it can handle huge numbers. We might do
that if we were writing commercial software for computer illiterate audience.</p>
<p>Or, we might say, <span class="emphasis"><i class="emphasis">"Tough! The user should
know better.""</i></span></p>
<p>Or, we just may make it impossible for the user to enter a huge number. This is the
approach we will take: We will use an <span class="emphasis"><i class="emphasis">implied
0.</i></span> prefix.</p>
<p>In other words, if the user wants <code class="constant">0.04</code>, we will expect
him to type <var class="parameter">-p04</var>, or set <var class="varname">PINHOLE=04</var> in his environment. So, if he says <var class="parameter">-p9999999</var>, we will interpret it as <code class="constant">0.9999999</code>--still ridiculous but at least safer.</p>
<p>Secondly, many users will just want to go with either Bender's constant or Connors'
constant. To make it easier on them, we will interpret <var class="parameter">-b</var> as
identical to <var class="parameter">-p04</var>, and <var class="parameter">-c</var> as
identical to <var class="parameter">-p037</var>.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.3.3 The Output" id="X86-PINHOLE-OUTPUT">
<div class="sect3">
<h4 class="title">16.13.3.3 The
Output</h4>
<p>We need to decide what we want our software to send to the output, and in what
format.</p>
<p>Since our input allows for an unspecified number of focal length entries, it makes
sense to use a traditional database-style output of showing the result of the calculation
for each focal length on a separate line, while separating all values on one line by a
<code class="constant">tab</code> character.</p>
<p>Optionally, we should also allow the user to specify the use of the <acronym class="acronym">CSV</acronym> format we have studied earlier. In this case, we will print
out a line of comma-separated names describing each field of every line, then show our
results as before, but substituting a <code class="constant">comma</code> for the <code class="constant">tab</code>.</p>
<p>We need a command line option for the <acronym class="acronym">CSV</acronym> format.
We cannot use <var class="parameter">-c</var> because that already means <span class="emphasis"><i class="emphasis">use Connors' constant</i></span>. For some strange
reason, many web sites refer to <acronym class="acronym">CSV</acronym> files as <span class="emphasis"><i class="emphasis">"Excel spreadsheet"</i></span> (though the <acronym class="acronym">CSV</acronym> format predates Excel). We will, therefore, use the <var class="parameter">-e</var> switch to inform our software we want the output in the
<acronym class="acronym">CSV</acronym> format.</p>
<p>We will start each line of the output with the focal length. This may sound
repetitious at first, especially in the interactive mode: The user types in the focal
length, and we are repeating it.</p>
<p>But the user can type several focal lengths on one line. The input can also come in
from a file or from the output of another program. In that case the user does not see the
input at all.</p>
<p>By the same token, the output can go to a file which we will want to examine later, or
it could go to the printer, or become the input of another program.</p>
<p>So, it makes perfect sense to start each line with the focal length as entered by the
user.</p>
<p>No, wait! Not as entered by the user. What if the user types in something like
this:</p>
<pre class="screen"><kbd class="userinput">00000000150</kbd>
</pre>
<p>Clearly, we need to strip those leading zeros.</p>
<p>So, we might consider reading the user input as is, converting it to binary inside the
<acronym class="acronym">FPU</acronym>, and printing it out from there.</p>
<p>But...</p>
<p>What if the user types something like this:</p>
<pre class="screen"><kbd class="userinput">17459765723452353453534535353530530534563507309676764423</kbd>
</pre>
<p>Ha! The packed decimal <acronym class="acronym">FPU</acronym> format lets us input
18-digit numbers. But the user has entered more than 18 digits. How do we handle
that?</p>
<p>Well, we <span class="emphasis"><i class="emphasis">could</i></span> modify our code
to read the first 18 digits, enter it to the <acronym class="acronym">FPU</acronym>, then
read more, multiply what we already have on the <acronym class="acronym">TOS</acronym> by
10 raised to the number of additional digits, then <code class="function">add</code> to
it.</p>
<p>Yes, we could do that. But in <span class="emphasis"><i class="emphasis">this</i></span> program it would be ridiculous (in a different one it
may be just the thing to do): Even the circumference of the Earth expressed in
millimeters only takes 11 digits. Clearly, we cannot build a camera that large (not yet,
anyway).</p>
<p>So, if the user enters such a huge number, he is either bored, or testing us, or
trying to break into the system, or playing games--doing anything but designing a pinhole
camera.</p>
<p>What will we do?</p>
<p>We will slap him in the face, in a manner of speaking:</p>
<pre class="screen">17459765723452353453534535353530530534563507309676764423 ??? ??? ??? ??? ???
</pre>
<p>To achieve that, we will simply ignore any leading zeros. Once we find a non-zero
digit, we will initialize a counter to <code class="constant">0</code> and start taking
three steps:</p>
<ol type="1">
<li>
<p>Send the digit to the output.</p>
</li>
<li>
<p>Append the digit to a buffer we will use later to produce the packed decimal we can
send to the <acronym class="acronym">FPU</acronym>.</p>
</li>
<li>
<p>Increase the counter.</p>
</li>
</ol>
<p>Now, while we are taking these three steps, we also need to watch out for one of two
conditions:</p>
<ul>
<li>
<p>If the counter grows above 18, we stop appending to the buffer. We continue reading
the digits and sending them to the output.</p>
</li>
<li>
<p>If, or rather <span class="emphasis"><i class="emphasis">when</i></span>, the next
input character is not a digit, we are done inputting for now.</p>
<p>Incidentally, we can simply discard the non-digit, unless it is a <code class="constant">#</code>, which we must return to the input stream. It starts a comment,
so we must see it after we are done producing output and start looking for more
input.</p>
</li>
</ul>
<p>That still leaves one possibility uncovered: If all the user enters is a zero (or
several zeros), we will never find a non-zero to display.</p>
<p>We can determine this has happened whenever our counter stays at <code class="constant">0</code>. In that case we need to send <code class="constant">0</code>
to the output, and perform another "slap in the face":</p>
<pre class="screen">0 ??? ??? ??? ??? ???
</pre>
<p>Once we have displayed the focal length and determined it is valid (greater than <code class="constant">0</code> but not exceeding 18 digits), we can calculate the pinhole
diameter.</p>
<p>It is not by coincidence that <span class="emphasis"><i class="emphasis">pinhole</i></span> contains the word <span class="emphasis"><i class="emphasis">pin</i></span>. Indeed, many a pinhole literally is a <span class="emphasis"><i class="emphasis">pin hole</i></span>, a hole carefully punched with
the tip of a pin.</p>
<p>That is because a typical pinhole is very small. Our formula gets the result in
millimeters. We will multiply it by <code class="constant">1000</code>, so we can output
the result in <span class="emphasis"><i class="emphasis">microns</i></span>.</p>
<p>At this point we have yet another trap to face: <span class="emphasis"><i class="emphasis">Too much precision.</i></span></p>
<p>Yes, the <acronym class="acronym">FPU</acronym> was designed for high precision
mathematics. But we are not dealing with high precision mathematics. We are dealing with
physics (optics, specifically).</p>
<p>Suppose we want to convert a truck into a pinhole camera (we would not be the first
ones to do that!). Suppose its box is <code class="constant">12</code> meters long, so we
have the focal length of <code class="constant">12000</code>. Well, using Bender's
constant, it gives us square root of <code class="constant">12000</code> multiplied by
<code class="constant">0.04</code>, which is <code class="constant">4.381780460</code>
millimeters, or <code class="constant">4381.780460</code> microns.</p>
<p>Put either way, the result is absurdly precise. Our truck is not <span class="emphasis"><i class="emphasis">exactly</i></span> <code class="constant">12000</code> millimeters long. We did not measure its length with such a
precision, so stating we need a pinhole with the diameter of <code class="constant">4.381780460</code> millimeters is, well, deceiving. <code class="constant">4.4</code> millimeters would do just fine.</p>
<blockquote class="note">
<p><b>Note:</b> I "only" used ten digits in the above example. Imagine the absurdity of
going for all 18!</p>
</blockquote>
<p>We need to limit the number of significant digits of our result. One way of doing it
is by using an integer representing microns. So, our truck would need a pinhole with the
diameter of <code class="constant">4382</code> microns. Looking at that number, we still
decide that <code class="constant">4400</code> microns, or <code class="constant">4.4</code> millimeters is close enough.</p>
<p>Additionally, we can decide that no matter how big a result we get, we only want to
display four significant digits (or any other number of them, of course). Alas, the
<acronym class="acronym">FPU</acronym> does not offer rounding to a specific number of
digits (after all, it does not view the numbers as decimal but as binary).</p>
<p>We, therefore, must devise an algorithm to reduce the number of significant
digits.</p>
<p>Here is mine (I think it is awkward--if you know a better one, <span class="emphasis"><i class="emphasis">please</i></span>, let me know):</p>
<ol type="1">
<li>
<p>Initialize a counter to <code class="constant">0</code>.</p>
</li>
<li>
<p>While the number is greater than or equal to <code class="constant">10000</code>,
divide it by <code class="constant">10</code> and increase the counter.</p>
</li>
<li>
<p>Output the result.</p>
</li>
<li>
<p>While the counter is greater than <code class="constant">0</code>, output <code class="constant">0</code> and decrease the counter.</p>
</li>
</ol>
<blockquote class="note">
<p><b>Note:</b> The <code class="constant">10000</code> is only good if you want <span class="emphasis"><i class="emphasis">four</i></span> significant digits. For any other
number of significant digits, replace <code class="constant">10000</code> with <code class="constant">10</code> raised to the number of significant digits.</p>
</blockquote>
<p>We will, then, output the pinhole diameter in microns, rounded off to four significant
digits.</p>
<p>At this point, we know the <span class="emphasis"><i class="emphasis">focal
length</i></span> and the <span class="emphasis"><i class="emphasis">pinhole
diameter</i></span>. That means we have enough information to also calculate the <span class="emphasis"><i class="emphasis">f-number</i></span>.</p>
<p>We will display the f-number, rounded to four significant digits. Chances are the
f-number will tell us very little. To make it more meaningful, we can find the nearest
<span class="emphasis"><i class="emphasis">normalized f-number</i></span>, i.e., the
nearest power of the square root of 2.</p>
<p>We do that by multiplying the actual f-number by itself, which, of course, will give
us its <code class="function">square</code>. We will then calculate its base-2 logarithm,
which is much easier to do than calculating the base-square-root-of-2 logarithm! We will
round the result to the nearest integer. Next, we will raise 2 to the result. Actually,
the <acronym class="acronym">FPU</acronym> gives us a good shortcut to do that: We can
use the <code class="function">fscale</code> op code to "scale" 1, which is analogous to
<code class="function">shift</code>ing an integer left. Finally, we calculate the square
root of it all, and we have the nearest normalized f-number.</p>
<p>If all that sounds overwhelming--or too much work, perhaps--it may become much clearer
if you see the code. It takes 9 op codes altogether:</p>
<pkg:outlineMarker OutlineName="code_92" id="code_92" visible="false" copy="true">
<pre class="programlisting"> fmul st0, st0
fld1
fld st1
fyl2x
frndint
fld1
fscale
fsqrt
fstp st1
</pre>
</pkg:outlineMarker>
<p>The first line, <code class="function">fmul st0, st0</code>, squares the contents of
the <acronym class="acronym">TOS</acronym> (top of the stack, same as <var class="varname">st</var>, called <var class="varname">st0</var> by <b class="application">nasm</b>). The <code class="function">fld1</code> pushes <code class="constant">1</code> on the <acronym class="acronym">TOS</acronym>.</p>
<p>The next line, <code class="function">fld st1</code>, pushes the square back to the
<acronym class="acronym">TOS</acronym>. At this point the square is both in <var class="varname">st</var> and <var class="varname">st(2)</var> (it will become clear why
we leave a second copy on the stack in a moment). <var class="varname">st(1)</var>
contains <code class="constant">1</code>.</p>
<p>Next, <code class="function">fyl2x</code> calculates base-2 logarithm of <var class="varname">st</var> multiplied by <var class="varname">st(1)</var>. That is why we
placed <code class="constant">1</code> on <var class="varname">st(1)</var> before.</p>
<p>At this point, <var class="varname">st</var> contains the logarithm we have just
calculated, <var class="varname">st(1)</var> contains the square of the actual f-number
we saved for later.</p>
<p><code class="function">frndint</code> rounds the <acronym class="acronym">TOS</acronym> to the nearest integer. <code class="function">fld1</code>
pushes a <code class="constant">1</code>. <code class="function">fscale</code> shifts the
<code class="constant">1</code> we have on the <acronym class="acronym">TOS</acronym> by
the value in <var class="varname">st(1)</var>, effectively raising 2 to <var class="varname">st(1)</var>.</p>
<p>Finally, <code class="function">fsqrt</code> calculates the square root of the result,
i.e., the nearest normalized f-number.</p>
<p>We now have the nearest normalized f-number on the <acronym class="acronym">TOS</acronym>, the base-2 logarithm rounded to the nearest integer in
<var class="varname">st(1)</var>, and the square of the actual f-number in <var class="varname">st(2)</var>. We are saving the value in <var class="varname">st(2)</var>
for later.</p>
<p>But we do not need the contents of <var class="varname">st(1)</var> anymore. The last
line, <code class="function">fstp st1</code>, places the contents of <var class="varname">st</var> to <var class="varname">st(1)</var>, and pops. As a result, what
was <var class="varname">st(1)</var> is now <var class="varname">st</var>, what was <var class="varname">st(2)</var> is now <var class="varname">st(1)</var>, etc. The new <var class="varname">st</var> contains the normalized f-number. The new <var class="varname">st(1)</var> contains the square of the actual f-number we have stored
there for posterity.</p>
<p>At this point, we are ready to output the normalized f-number. Because it is
normalized, we will not round it off to four significant digits, but will send it out in
its full precision.</p>
<p>The normalized f-number is useful as long as it is reasonably small and can be found
on our light meter. Otherwise we need a different method of determining proper
exposure.</p>
<p>Earlier we have figured out the formula of calculating proper exposure at an arbitrary
f-number from that measured at a different f-number.</p>
<p>Every light meter I have ever seen can determine proper exposure at f5.6. We will,
therefore, calculate an <span class="emphasis"><i class="emphasis">"f5.6
multiplier,"</i></span> i.e., by how much we need to multiply the exposure measured at
f5.6 to determine the proper exposure for our pinhole camera.</p>
<p>From the above formula we know this factor can be calculated by dividing our f-number
(the actual one, not the normalized one) by <code class="constant">5.6</code>, and
squaring the result.</p>
<p>Mathematically, dividing the square of our f-number by the square of <code class="constant">5.6</code> will give us the same result.</p>
<p>Computationally, we do not want to square two numbers when we can only square one. So,
the first solution seems better at first.</p>
<p>But...</p>
<p><code class="constant">5.6</code> is a <span class="emphasis"><i class="emphasis">constant</i></span>. We do not have to have our <acronym class="acronym">FPU</acronym> waste precious cycles. We can just tell it to divide the
square of the f-number by whatever <code class="constant">5.6²</code> equals to. Or we
can divide the f-number by <code class="constant">5.6</code>, and then square the result.
The two ways now seem equal.</p>
<p>But, they are not!</p>
<p>Having studied the principles of photography above, we remember that the <code class="constant">5.6</code> is actually square root of 2 raised to the fifth power. An
<span class="emphasis"><i class="emphasis">irrational</i></span> number. The square of
this number is <span class="emphasis"><i class="emphasis">exactly</i></span> <code class="constant">32</code>.</p>
<p>Not only is <code class="constant">32</code> an integer, it is a power of 2. We do not
need to divide the square of the f-number by <code class="constant">32</code>. We only
need to use <code class="function">fscale</code> to shift it right by five positions. In
the <acronym class="acronym">FPU</acronym> lingo it means we will <code class="function">fscale</code> it with <var class="varname">st(1)</var> equal to <code class="constant">-5</code>. That is <span class="emphasis"><i class="emphasis">much
faster</i></span> than a division.</p>
<p>So, now it has become clear why we have saved the square of the f-number on the top of
the <acronym class="acronym">FPU</acronym> stack. The calculation of the f5.6 multiplier
is the easiest calculation of this entire program! We will output it rounded to four
significant digits.</p>
<p>There is one more useful number we can calculate: The number of stops our f-number is
from f5.6. This may help us if our f-number is just outside the range of our light meter,
but we have a shutter which lets us set various speeds, and this shutter uses stops.</p>
<p>Say, our f-number is 5 stops from f5.6, and the light meter says we should use 1/1000
sec. Then we can set our shutter speed to 1/1000 first, then move the dial by 5
stops.</p>
<p>This calculation is quite easy as well. All we have to do is to calculate the base-2
logarithm of the f5.6 multiplier we had just calculated (though we need its value from
before we rounded it off). We then output the result rounded to the nearest integer. We
do not need to worry about having more than four significant digits in this one: The
result is most likely to have only one or two digits anyway.</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.4 FPU Optimizations" id="X86-FPU-OPTIMIZATIONS">
<div class="sect3">
<h3 class="title">16.13.4 FPU
Optimizations</h3>
<p>In assembly language we can optimize the <acronym class="acronym">FPU</acronym> code
in ways impossible in high languages, including C.</p>
<p>Whenever a C function needs to calculate a floating-point value, it loads all
necessary variables and constants into <acronym class="acronym">FPU</acronym> registers.
It then does whatever calculation is required to get the correct result. Good C compilers
can optimize that part of the code really well.</p>
<p>It "returns" the value by leaving the result on the <acronym class="acronym">TOS</acronym>. However, before it returns, it cleans up. Any variables
and constants it used in its calculation are now gone from the <acronym class="acronym">FPU</acronym>.</p>
<p>It cannot do what we just did above: We calculated the square of the f-number and kept
it on the stack for later use by another function.</p>
<p>We <span class="emphasis"><i class="emphasis">knew</i></span> we would need that value
later on. We also knew we had enough room on the stack (which only has room for 8
numbers) to store it there.</p>
<p>A C compiler has no way of knowing that a value it has on the stack will be required
again in the very near future.</p>
<p>Of course, the C programmer may know it. But the only recourse he has is to store the
value in a memory variable.</p>
<p>That means, for one, the value will be changed from the 80-bit precision used
internally by the <acronym class="acronym">FPU</acronym> to a C <span class="emphasis"><i class="emphasis">double</i></span> (64 bits) or even <span class="emphasis"><i class="emphasis">single</i></span> (32 bits).</p>
<p>That also means that the value must be moved from the <acronym class="acronym">TOS</acronym> into the memory, and then back again. Alas, of all <acronym class="acronym">FPU</acronym> operations, the ones that access the computer memory are
the slowest.</p>
<p>So, whenever programming the <acronym class="acronym">FPU</acronym> in assembly
language, look for the ways of keeping intermediate results on the <acronym class="acronym">FPU</acronym> stack.</p>
<p>We can take that idea even further! In our program we are using a <span class="emphasis"><i class="emphasis">constant</i></span> (the one we named <code class="constant">PC</code>).</p>
<p>It does not matter how many pinhole diameters we are calculating: 1, 10, 20, 1000, we
are always using the same constant. Therefore, we can optimize our program by keeping the
constant on the stack all the time.</p>
<p>Early on in our program, we are calculating the value of the above constant. We need
to divide our input by <code class="constant">10</code> for every digit in the
constant.</p>
<p>It is much faster to multiply than to divide. So, at the start of our program, we
divide <code class="constant">10</code> into <code class="constant">1</code> to obtain
<code class="constant">0.1</code>, which we then keep on the stack: Instead of dividing
the input by <code class="constant">10</code> for every digit, we multiply it by <code class="constant">0.1</code>.</p>
<p>By the way, we do not input <code class="constant">0.1</code> directly, even though we
could. We have a reason for that: While <code class="constant">0.1</code> can be
expressed with just one decimal place, we do not know how many <span class="emphasis"><i class="emphasis">binary</i></span> places it takes. We, therefore, let the <acronym class="acronym">FPU</acronym> calculate its binary value to its own high precision.</p>
<p>We are using other constants: We multiply the pinhole diameter by <code class="constant">1000</code> to convert it from millimeters to microns. We compare
numbers to <code class="constant">10000</code> when we are rounding them off to four
significant digits. So, we keep both, <code class="constant">1000</code> and <code class="constant">10000</code>, on the stack. And, of course, we reuse the <code class="constant">0.1</code> when rounding off numbers to four digits.</p>
<p>Last but not least, we keep <code class="constant">-5</code> on the stack. We need it
to scale the square of the f-number, instead of dividing it by <code class="constant">32</code>. It is not by coincidence we load this constant last. That
makes it the top of the stack when only the constants are on it. So, when the square of
the f-number is being scaled, the <code class="constant">-5</code> is at <var class="varname">st(1)</var>, precisely where <code class="function">fscale</code> expects
it to be.</p>
<p>It is common to create certain constants from scratch instead of loading them from the
memory. That is what we are doing with <code class="constant">-5</code>:</p>
<pkg:outlineMarker OutlineName="code_93" id="code_93" visible="false" copy="true">
<pre class="programlisting"> fld1 ; TOS = 1
fadd st0, st0 ; TOS = 2
fadd st0, st0 ; TOS = 4
fld1 ; TOS = 1
faddp st1, st0 ; TOS = 5
fchs ; TOS = -5
</pre>
</pkg:outlineMarker>
<p>We can generalize all these optimizations into one rule: <span class="emphasis"><i class="emphasis">Keep repeat values on the stack!</i></span></p>
<blockquote class="tip">
<p><b>Tip:</b> <span class="emphasis"><i class="emphasis"><span class="trademark">PostScript</span>®</i></span> is a stack-oriented programming
language. There are many more books available about <span class="trademark">PostScript</span> than about the <acronym class="acronym">FPU</acronym>
assembly language: Mastering <span class="trademark">PostScript</span> will help you
master the <acronym class="acronym">FPU</acronym>.</p>
</blockquote>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.5 pinhole--The Code" id="X86-PINHOLE-THE-CODE">
<div class="sect3">
<h3 class="title">16.13.5 <b class="application">pinhole</b>--The Code</h3>
<pkg:outlineMarker OutlineName="code_94" id="code_94" visible="false" copy="true">
<pre class="programlisting">;;;;;;; pinhole.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Find various parameters of a pinhole camera construction and use
;
; Started: 9-Jun-2001
; Updated: 10-Jun-2001
;
; Copyright (c) 2001 G. Adam Stanislav
; All rights reserved.
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%include 'system.inc'
%define BUFSIZE 2048
section .data
align 4
ten dd 10
thousand dd 1000
tthou dd 10000
fd.in dd stdin
fd.out dd stdout
envar db 'PINHOLE=' ; Exactly 8 bytes, or 2 dwords long
pinhole db '04,', ; Bender's constant (0.04)
connors db '037', 0Ah ; Connors' constant
usg db 'Usage: pinhole [-b] [-c] [-e] [-p <value>] [-o <outfile>] [-i <infile>]', 0Ah
usglen equ $-usg
iemsg db "pinhole: Can't open input file", 0Ah
iemlen equ $-iemsg
oemsg db "pinhole: Can't create output file", 0Ah
oemlen equ $-oemsg
pinmsg db "pinhole: The PINHOLE constant must not be 0", 0Ah
pinlen equ $-pinmsg
toobig db "pinhole: The PINHOLE constant may not exceed 18 decimal places", 0Ah
biglen equ $-toobig
huhmsg db 9, '???'
separ db 9, '???'
sep2 db 9, '???'
sep3 db 9, '???'
sep4 db 9, '???', 0Ah
huhlen equ $-huhmsg
header db 'focal length in millimeters,pinhole diameter in microns,'
db 'F-number,normalized F-number,F-5.6 multiplier,stops '
db 'from F-5.6', 0Ah
headlen equ $-header
section .bss
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
dbuffer resb 20 ; decimal input buffer
bbuffer resb 10 ; BCD buffer
section .text
align 4
huh:
call write
push dword huhlen
push dword huhmsg
push dword [fd.out]
sys.write
add esp, byte 12
ret
align 4
perr:
push dword pinlen
push dword pinmsg
push dword stderr
sys.write
push dword 4 ; return failure
sys.exit
align 4
consttoobig:
push dword biglen
push dword toobig
push dword stderr
sys.write
push dword 5 ; return failure
sys.exit
align 4
ierr:
push dword iemlen
push dword iemsg
push dword stderr
sys.write
push dword 1 ; return failure
sys.exit
align 4
oerr:
push dword oemlen
push dword oemsg
push dword stderr
sys.write
push dword 2
sys.exit
align 4
usage:
push dword usglen
push dword usg
push dword stderr
sys.write
push dword 3
sys.exit
align 4
global _start
_start:
add esp, byte 8 ; discard argc and argv[0]
sub esi, esi
.arg:
pop ecx
or ecx, ecx
je near .getenv ; no more arguments
; ECX contains the pointer to an argument
cmp byte [ecx], '-'
jne usage
inc ecx
mov ax, [ecx]
inc ecx
.o:
cmp al, 'o'
jne .i
; Make sure we are not asked for the output file twice
cmp dword [fd.out], stdout
jne usage
; Find the path to output file - it is either at [ECX+1],
; i.e., -ofile --
; or in the next argument,
; i.e., -o file
or ah, ah
jne .openoutput
pop ecx
jecxz usage
.openoutput:
push dword 420 ; file mode (644 octal)
push dword 0200h | 0400h | 01h
; O_CREAT | O_TRUNC | O_WRONLY
push ecx
sys.open
jc near oerr
add esp, byte 12
mov [fd.out], eax
jmp short .arg
.i:
cmp al, 'i'
jne .p
; Make sure we are not asked twice
cmp dword [fd.in], stdin
jne near usage
; Find the path to the input file
or ah, ah
jne .openinput
pop ecx
or ecx, ecx
je near usage
.openinput:
push dword 0 ; O_RDONLY
push ecx
sys.open
jc near ierr ; open failed
add esp, byte 8
mov [fd.in], eax
jmp .arg
.p:
cmp al, 'p'
jne .c
or ah, ah
jne .pcheck
pop ecx
or ecx, ecx
je near usage
mov ah, [ecx]
.pcheck:
cmp ah, '0'
jl near usage
cmp ah, '9'
ja near usage
mov esi, ecx
jmp .arg
.c:
cmp al, 'c'
jne .b
or ah, ah
jne near usage
mov esi, connors
jmp .arg
.b:
cmp al, 'b'
jne .e
or ah, ah
jne near usage
mov esi, pinhole
jmp .arg
.e:
cmp al, 'e'
jne near usage
or ah, ah
jne near usage
mov al, ','
mov [huhmsg], al
mov [separ], al
mov [sep2], al
mov [sep3], al
mov [sep4], al
jmp .arg
align 4
.getenv:
; If ESI = 0, we did not have a -p argument,
; and need to check the environment for "PINHOLE="
or esi, esi
jne .init
sub ecx, ecx
.nextenv:
pop esi
or esi, esi
je .default ; no PINHOLE envar found
; check if this envar starts with 'PINHOLE='
mov edi, envar
mov cl, 2 ; 'PINHOLE=' is 2 dwords long
rep cmpsd
jne .nextenv
; Check if it is followed by a digit
mov al, [esi]
cmp al, '0'
jl .default
cmp al, '9'
jbe .init
; fall through
align 4
.default:
; We got here because we had no -p argument,
; and did not find the PINHOLE envar.
mov esi, pinhole
; fall through
align 4
.init:
sub eax, eax
sub ebx, ebx
sub ecx, ecx
sub edx, edx
mov edi, dbuffer+1
mov byte [dbuffer], '0'
; Convert the pinhole constant to real
.constloop:
lodsb
cmp al, '9'
ja .setconst
cmp al, '0'
je .processconst
jb .setconst
inc dl
.processconst:
inc cl
cmp cl, 18
ja near consttoobig
stosb
jmp short .constloop
align 4
.setconst:
or dl, dl
je near perr
finit
fild dword [tthou]
fld1
fild dword [ten]
fdivp st1, st0
fild dword [thousand]
mov edi, obuffer
mov ebp, ecx
call bcdload
.constdiv:
fmul st0, st2
loop .constdiv
fld1
fadd st0, st0
fadd st0, st0
fld1
faddp st1, st0
fchs
; If we are creating a CSV file,
; print header
cmp byte [separ], ','
jne .bigloop
push dword headlen
push dword header
push dword [fd.out]
sys.write
.bigloop:
call getchar
jc near done
; Skip to the end of the line if you got '#'
cmp al, '#'
jne .num
call skiptoeol
jmp short .bigloop
.num:
; See if you got a number
cmp al, '0'
jl .bigloop
cmp al, '9'
ja .bigloop
; Yes, we have a number
sub ebp, ebp
sub edx, edx
.number:
cmp al, '0'
je .number0
mov dl, 1
.number0:
or dl, dl ; Skip leading 0's
je .nextnumber
push eax
call putchar
pop eax
inc ebp
cmp ebp, 19
jae .nextnumber
mov [dbuffer+ebp], al
.nextnumber:
call getchar
jc .work
cmp al, '#'
je .ungetc
cmp al, '0'
jl .work
cmp al, '9'
ja .work
jmp short .number
.ungetc:
dec esi
inc ebx
.work:
; Now, do all the work
or dl, dl
je near .work0
cmp ebp, 19
jae near .toobig
call bcdload
; Calculate pinhole diameter
fld st0 ; save it
fsqrt
fmul st0, st3
fld st0
fmul st5
sub ebp, ebp
; Round off to 4 significant digits
.diameter:
fcom st0, st7
fstsw ax
sahf
jb .printdiameter
fmul st0, st6
inc ebp
jmp short .diameter
.printdiameter:
call printnumber ; pinhole diameter
; Calculate F-number
fdivp st1, st0
fld st0
sub ebp, ebp
.fnumber:
fcom st0, st6
fstsw ax
sahf
jb .printfnumber
fmul st0, st5
inc ebp
jmp short .fnumber
.printfnumber:
call printnumber ; F number
; Calculate normalized F-number
fmul st0, st0
fld1
fld st1
fyl2x
frndint
fld1
fscale
fsqrt
fstp st1
sub ebp, ebp
call printnumber
; Calculate time multiplier from F-5.6
fscale
fld st0
; Round off to 4 significant digits
.fmul:
fcom st0, st6
fstsw ax
sahf
jb .printfmul
inc ebp
fmul st0, st5
jmp short .fmul
.printfmul:
call printnumber ; F multiplier
; Calculate F-stops from 5.6
fld1
fxch st1
fyl2x
sub ebp, ebp
call printnumber
mov al, 0Ah
call putchar
jmp .bigloop
.work0:
mov al, '0'
call putchar
align 4
.toobig:
call huh
jmp .bigloop
align 4
done:
call write ; flush output buffer
; close files
push dword [fd.in]
sys.close
push dword [fd.out]
sys.close
finit
; return success
push dword 0
sys.exit
align 4
skiptoeol:
; Keep reading until you come to cr, lf, or eof
call getchar
jc done
cmp al, 0Ah
jne .cr
ret
.cr:
cmp al, 0Dh
jne skiptoeol
ret
align 4
getchar:
or ebx, ebx
jne .fetch
call read
.fetch:
lodsb
dec ebx
clc
ret
read:
jecxz .read
call write
.read:
push dword BUFSIZE
mov esi, ibuffer
push esi
push dword [fd.in]
sys.read
add esp, byte 12
mov ebx, eax
or eax, eax
je .empty
sub eax, eax
ret
align 4
.empty:
add esp, byte 4
stc
ret
align 4
putchar:
stosb
inc ecx
cmp ecx, BUFSIZE
je write
ret
align 4
write:
jecxz .ret ; nothing to write
sub edi, ecx ; start of buffer
push ecx
push edi
push dword [fd.out]
sys.write
add esp, byte 12
sub eax, eax
sub ecx, ecx ; buffer is empty now
.ret:
ret
align 4
bcdload:
; EBP contains the number of chars in dbuffer
push ecx
push esi
push edi
lea ecx, [ebp+1]
lea esi, [dbuffer+ebp-1]
shr ecx, 1
std
mov edi, bbuffer
sub eax, eax
mov [edi], eax
mov [edi+4], eax
mov [edi+2], ax
.loop:
lodsw
sub ax, 3030h
shl al, 4
or al, ah
mov [edi], al
inc edi
loop .loop
fbld [bbuffer]
cld
pop edi
pop esi
pop ecx
sub eax, eax
ret
align 4
printnumber:
push ebp
mov al, [separ]
call putchar
; Print the integer at the TOS
mov ebp, bbuffer+9
fbstp [bbuffer]
; Check the sign
mov al, [ebp]
dec ebp
or al, al
jns .leading
; We got a negative number (should never happen)
mov al, '-'
call putchar
.leading:
; Skip leading zeros
mov al, [ebp]
dec ebp
or al, al
jne .first
cmp ebp, bbuffer
jae .leading
; We are here because the result was 0.
; Print '0' and return
mov al, '0'
jmp putchar
.first:
; We have found the first non-zero.
; But it is still packed
test al, 0F0h
jz .second
push eax
shr al, 4
add al, '0'
call putchar
pop eax
and al, 0Fh
.second:
add al, '0'
call putchar
.next:
cmp ebp, bbuffer
jb .done
mov al, [ebp]
push eax
shr al, 4
add al, '0'
call putchar
pop eax
and al, 0Fh
add al, '0'
call putchar
dec ebp
jmp short .next
.done:
pop ebp
or ebp, ebp
je .ret
.zeros:
mov al, '0'
call putchar
dec ebp
jne .zeros
.ret:
ret
</pre>
</pkg:outlineMarker>
<p>The code follows the same format as all the other filters we have seen before, with
one subtle exception:</p>
<a name="AEN6187"></a>
<blockquote class="blockquote">
<p>We are no longer assuming that the end of input implies the end of things to do,
something we took for granted in the <span class="emphasis"><i class="emphasis">character-oriented</i></span> filters.</p>
<p>This filter does not process characters. It processes a <span class="emphasis"><i class="emphasis">language</i></span> (albeit a very simple one, consisting only of
numbers).</p>
<p>When we have no more input, it can mean one of two things:</p>
<ul>
<li>
<p>We are done and can quit. This is the same as before.</p>
</li>
<li>
<p>The last character we have read was a digit. We have stored it at the end of our
<acronym class="acronym">ASCII</acronym>-to-float conversion buffer. We now need to
convert the contents of that buffer into a number and write the last line of our
output.</p>
</li>
</ul>
<p>For that reason, we have modified our <code class="function">getchar</code> and our
<code class="function">read</code> routines to return with the <var class="varname">carry
flag</var> <span class="emphasis"><i class="emphasis">clear</i></span> whenever we are
fetching another character from the input, or the <var class="varname">carry flag</var>
<span class="emphasis"><i class="emphasis">set</i></span> whenever there is no more
input.</p>
<p>Of course, we are still using assembly language magic to do that! Take a good look at
<code class="function">getchar</code>. It <span class="emphasis"><i class="emphasis">always</i></span> returns with the <var class="varname">carry flag</var>
<span class="emphasis"><i class="emphasis">clear</i></span>.</p>
<p>Yet, our main code relies on the <var class="varname">carry flag</var> to tell it when
to quit--and it works.</p>
<p>The magic is in <code class="function">read</code>. Whenever it receives more input
from the system, it just returns to <code class="function">getchar</code>, which fetches
a character from the input buffer, <span class="emphasis"><i class="emphasis">clears</i></span> the <var class="varname">carry flag</var> and
returns.</p>
<p>But when <code class="function">read</code> receives no more input from the system, it
does <span class="emphasis"><i class="emphasis">not</i></span> return to <code class="function">getchar</code> at all. Instead, the <code class="function">add esp, byte
4</code> op code adds <code class="constant">4</code> to <var class="varname">ESP</var>,
<span class="emphasis"><i class="emphasis">sets</i></span> the <var class="varname">carry
flag</var>, and returns.</p>
<p>So, where does it return to? Whenever a program uses the <code class="function">call</code> op code, the microprocessor <code class="function">push</code>es the return address, i.e., it stores it on the top of the
stack (not the <acronym class="acronym">FPU</acronym> stack, the system stack, which is
in the memory). When a program uses the <code class="function">ret</code> op code, the
microprocessor <code class="function">pop</code>s the return value from the stack, and
jumps to the address that was stored there.</p>
<p>But since we added <code class="constant">4</code> to <var class="varname">ESP</var>
(which is the stack pointer register), we have effectively given the microprocessor a
minor case of <span class="emphasis"><i class="emphasis">amnesia</i></span>: It no longer
remembers it was <code class="function">getchar</code> that <code class="function">call</code>ed <code class="function">read</code>.</p>
<p>And since <code class="function">getchar</code> never <code class="function">push</code>ed anything before <code class="function">call</code>ing
<code class="function">read</code>, the top of the stack now contains the return address
to whatever or whoever <code class="function">call</code>ed <code class="function">getchar</code>. As far as that caller is concerned, he <code class="function">call</code>ed <code class="function">getchar</code>, which <code class="function">ret</code>urned with the <var class="varname">carry flag</var> set!</p>
</blockquote>
<p>Other than that, the <code class="function">bcdload</code> routine is caught up in the
middle of a Lilliputian conflict between the Big-Endians and the Little-Endians.</p>
<p>It is converting the text representation of a number into that number: The text is
stored in the big-endian order, but the <span class="emphasis"><i class="emphasis">packed
decimal</i></span> is little-endian.</p>
<p>To solve the conflict, we use the <code class="function">std</code> op code early on.
We cancel it with <code class="function">cld</code> later on: It is quite important we do
not <code class="function">call</code> anything that may depend on the default setting of
the <span class="emphasis"><i class="emphasis">direction flag</i></span> while <code class="function">std</code> is active.</p>
<p>Everything else in this code should be quite clear, providing you have read the entire
chapter that precedes it.</p>
<p>It is a classical example of the adage that programming requires a lot of thought and
only a little coding. Once we have thought through every tiny detail, the code almost
writes itself.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.6 Using pinhole" id="X86-PINHOLE-USING">
<div class="sect3">
<h3 class="title">16.13.6 Using <b class="application">pinhole</b></h3>
<p>Because we have decided to make the program <span class="emphasis"><i class="emphasis">ignore</i></span> any input except for numbers (and even those inside a
comment), we can actually perform <span class="emphasis"><i class="emphasis">textual
queries</i></span>. We do not <span class="emphasis"><i class="emphasis">have
to</i></span>, but we <span class="emphasis"><i class="emphasis">can</i></span>.</p>
<p>In my humble opinion, forming a textual query, instead of having to follow a very
strict syntax, makes software much more user friendly.</p>
<p>Suppose we want to build a pinhole camera to use the 4x5 inch film. The standard focal
length for that film is about 150mm. We want to <span class="emphasis"><i class="emphasis">fine-tune</i></span> our focal length so the pinhole diameter is as
round a number as possible. Let us also suppose we are quite comfortable with cameras but
somewhat intimidated by computers. Rather than just have to type in a bunch of numbers,
we want to <span class="emphasis"><i class="emphasis">ask</i></span> a couple of
questions.</p>
<p>Our session might look like this:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">pinhole
Computer,
What size pinhole do I need for the focal length of 150?</kbd>
150 490 306 362 2930 12
<kbd class="userinput">Hmmm... How about 160?</kbd>
160 506 316 362 3125 12
<kbd class="userinput">Let's make it 155, please.</kbd>
155 498 311 362 3027 12
<kbd class="userinput">Ah, let's try 157...</kbd>
157 501 313 362 3066 12
<kbd class="userinput">156?</kbd>
156 500 312 362 3047 12
<kbd class="userinput">That's it! Perfect! Thank you very much!
^D</kbd>
</pre>
<p>We have found that while for the focal length of 150, our pinhole diameter should be
490 microns, or 0.49 mm, if we go with the almost identical focal length of 156 mm, we
can get away with a pinhole diameter of exactly one half of a millimeter.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.13.7 Scripting" id="X86-PINHOLE-SCRIPTING">
<div class="sect3">
<h3 class="title">16.13.7
Scripting</h3>
<p>Because we have chosen the <code class="constant">#</code> character to denote the
start of a comment, we can treat our <b class="application">pinhole</b> software as a
<span class="emphasis"><i class="emphasis">scripting language</i></span>.</p>
<p>You have probably seen <b class="application">shell</b> <span class="emphasis"><i class="emphasis">scripts</i></span> that start with:</p>
<pkg:outlineMarker OutlineName="code_95" id="code_95" visible="false" copy="true">
<pre class="programlisting">#! /bin/sh
</pre>
</pkg:outlineMarker>
<p>...or...</p>
<pkg:outlineMarker OutlineName="code_96" id="code_96" visible="false" copy="true">
<pre class="programlisting">#!/bin/sh
</pre>
</pkg:outlineMarker>
<p>...because the blank space after the <code class="function">#!</code> is optional.</p>
<p>Whenever <span class="trademark">UNIX</span> is asked to run an executable file which
starts with the <code class="function">#!</code>, it assumes the file is a script. It
adds the command to the rest of the first line of the script, and tries to execute
that.</p>
<p>Suppose now that we have installed <b class="application">pinhole</b> in <b class="application">/usr/local/bin/</b>, we can now write a script to calculate various
pinhole diameters suitable for various focal lengths commonly used with the 120 film.</p>
<p>The script might look something like this:</p>
<pkg:outlineMarker OutlineName="code_97" id="code_97" visible="false" copy="true">
<pre class="programlisting">#! /usr/local/bin/pinhole -b -i
# Find the best pinhole diameter
# for the 120 film
### Standard
80
### Wide angle
30, 40, 50, 60, 70
### Telephoto
100, 120, 140
</pre>
</pkg:outlineMarker>
<p>Because 120 is a medium size film, we may name this file <b class="application">medium</b>.</p>
<p>We can set its permissions to execute, and run it as if it were a program:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">chmod 755 medium</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">./medium</kbd>
</pre>
<p><span class="trademark">UNIX</span> will interpret that last command as:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">/usr/local/bin/pinhole -b -i ./medium</kbd>
</pre>
<p>It will run that command and display:</p>
<pre class="screen">80 358 224 256 1562 11
30 219 137 128 586 9
40 253 158 181 781 10
50 283 177 181 977 10
60 310 194 181 1172 10
70 335 209 181 1367 10
100 400 250 256 1953 11
120 438 274 256 2344 11
140 473 296 256 2734 11
</pre>
<p>
Now, let us enter:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">./medium -c</kbd>
</pre>
<p><span class="trademark">UNIX</span> will treat that as:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">/usr/local/bin/pinhole -b -i ./medium -c</kbd>
</pre>
<p>That gives it two conflicting options: <var class="parameter">-b</var> and <var class="parameter">-c</var> (Use Bender's constant and use Connors' constant). We have
programmed it so later options override early ones--our program will calculate everything
using Connors' constant:</p>
<pre class="screen">80 331 242 256 1826 11
30 203 148 128 685 9
40 234 171 181 913 10
50 262 191 181 1141 10
60 287 209 181 1370 10
70 310 226 256 1598 11
100 370 270 256 2283 11
120 405 296 256 2739 11
140 438 320 362 3196 12
</pre>
<p>We decide we want to go with Bender's constant after all. We want to save its values
as a comma-separated file:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">./medium -b -e > bender</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">cat bender</kbd>
focal length in millimeters,pinhole diameter in microns,F-number,normalized F-number,F-5.6 multiplier,stops from F-5.6
80,358,224,256,1562,11
30,219,137,128,586,9
40,253,158,181,781,10
50,283,177,181,977,10
60,310,194,181,1172,10
70,335,209,181,1367,10
100,400,250,256,1953,11
120,438,274,256,2344,11
140,473,296,256,2734,11
<samp class="prompt">%</samp>
</pre>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.14 Caveats" id="X86-CAVEATS">
<div class="sect2">
<h2 class="title">16.14 Caveats</h2>
<p>Assembly language programmers who "grew up" under <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym> and <span class="trademark">Windows</span>
often tend to take shortcuts. Reading the keyboard scan codes and writing directly to
video memory are two classical examples of practices which, under <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym> are not frowned upon but
considered the right thing to do.</p>
<p>The reason? Both the <acronym class="acronym">PC BIOS</acronym> and <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym> are notoriously slow when
performing these operations.</p>
<p>You may be tempted to continue similar practices in the <span class="trademark">UNIX</span> environment. For example, I have seen a web site which
explains how to access the keyboard scan codes on a popular <span class="trademark">UNIX</span> clone.</p>
<p>That is generally a <span class="emphasis"><i class="emphasis">very bad
idea</i></span> in <span class="trademark">UNIX</span> environment! Let me explain
why.</p>
<hr />
<pkg:outlineMarker OutlineName="16.14.1 UNIX Is Protected" id="X86-PROTECTED">
<div class="sect3">
<h3 class="title">16.14.1 <span class="trademark">UNIX</span> Is Protected</h3>
<p>For one thing, it may simply not be possible. <span class="trademark">UNIX</span> runs
in protected mode. Only the kernel and device drivers are allowed to access hardware
directly. Perhaps a particular <span class="trademark">UNIX</span> clone will let you
read the keyboard scan codes, but chances are a real <span class="trademark">UNIX</span>
operating system will not. And even if one version may let you do it, the next one may
not, so your carefully crafted software may become a dinosaur overnight.</p>
<hr />
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.14.2 UNIX Is an Abstraction" id="X86-ABSTRACTION">
<div class="sect3">
<h3 class="title">16.14.2 <span class="trademark">UNIX</span> Is an Abstraction</h3>
<p>But there is a much more important reason not to try accessing the hardware directly
(unless, of course, you are writing a device driver), even on the <span class="trademark">UNIX</span> like systems that let you do it:</p>
<p><span class="emphasis"><i class="emphasis"><span class="trademark">UNIX</span> is an
abstraction!</i></span></p>
<p>There is a major difference in the philosophy of design between <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym> and <span class="trademark">UNIX</span>. <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym> was designed as a single-user system. It is run
on a computer with a keyboard and a video screen attached directly to that computer. User
input is almost guaranteed to come from that keyboard. Your program's output virtually
always ends up on that screen.</p>
<p>This is NEVER guaranteed under <span class="trademark">UNIX</span>. It is quite common
for a <span class="trademark">UNIX</span> user to pipe and redirect program input and
output:</p>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">program1 | program2 | program3 > file1</kbd>
</pre>
<p>If you have written <b class="application">program2</b>, your input does not come from
the keyboard but from the output of <b class="application">program1</b>. Similarly, your
output does not go to the screen but becomes the input for <b class="application">program3</b> whose output, in turn, goes to <tt class="filename">file1</tt>.</p>
<p>But there is more! Even if you made sure that your input comes from, and your output
goes to, the terminal, there is no guarantee the terminal is a PC: It may not have its
video memory where you expect it, nor may its keyboard be producing <acronym class="acronym">PC</acronym>-style scan codes. It may be a <span class="trademark">Macintosh</span>, or any other computer.</p>
<p>Now you may be shaking your head: My software is in <acronym class="acronym">PC</acronym> assembly language, how can it run on a <span class="trademark">Macintosh</span>? But I did not say your software would be running on a
<span class="trademark">Macintosh</span>, only that its terminal may be a <span class="trademark">Macintosh</span>.</p>
<p>Under <span class="trademark">UNIX</span>, the terminal does not have to be directly
attached to the computer that runs your software, it can even be on another continent,
or, for that matter, on another planet. It is perfectly possible that a <span class="trademark">Macintosh</span> user in Australia connects to a <span class="trademark">UNIX</span> system in North America (or anywhere else) via <b class="application">telnet</b>. The software then runs on one computer, while the
terminal is on a different computer: If you try to read the scan codes, you will get the
wrong input!</p>
<p>Same holds true about any other hardware: A file you are reading may be on a disk you
have no direct access to. A camera you are reading images from may be on a space shuttle,
connected to you via satellites.</p>
<p>That is why under <span class="trademark">UNIX</span> you must never make any
assumptions about where your data is coming from and going to. Always let the system
handle the physical access to the hardware.</p>
<blockquote class="note">
<p><b>Note:</b> These are caveats, not absolute rules. Exceptions are possible. For
example, if a text editor has determined it is running on a local machine, it may want to
read the scan codes directly for improved control. I am not mentioning these caveats to
tell you what to do or what not to do, just to make you aware of certain pitfalls that
await you if you have just arrived to <span class="trademark">UNIX</span> form <acronym class="acronym"><span class="trademark">MS-DOS</span></acronym>. Of course, creative
people often break rules, and it is OK as long as they know they are breaking them and
why.</p>
</blockquote>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="16.15 Acknowledgements" id="X86-ACKNOWLEDGEMENTS">
<div class="sect2">
<h2 class="title">16.15
Acknowledgements</h2>
<p>This tutorial would never have been possible without the help of many experienced
FreeBSD programmers from the <a href="http://lists.freebsd.org/mailman/listinfo/freebsd-hackers" target="_top">FreeBSD
technical discussions mailing list</a>, many of whom have patiently answered my
questions, and pointed me in the right direction in my attempts to explore the inner
workings of <span class="trademark">UNIX</span> system programming in general and FreeBSD
in particular.</p>
<p>Thomas M. Sommers opened the door for me. His <a href="http://home.ptd.net/%7Etms2/hello.html" target="_top">How do I write "Hello, world"
in FreeBSD assembler?</a> web page was my first encounter with an example of assembly
language programming under FreeBSD.</p>
<p>Jake Burkholder has kept the door open by willingly answering all of my questions and
supplying me with example assembly language source code.</p>
<p>Copyright © 2000-2001 G. Adam Stanislav. All rights reserved.</p>
<hr />
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="V. Appendices" id="APPENDICES" visible="true" renderchildren="false">
<div class="sect1">
<h1 class="title">V. Appendices</h1>
<dl>
<dt><b>Table of Contents</b></dt>
<dt><a href="pkg://FreeBSD Developers' Handbook/APPENDICES/#AEN6428">Bibliography</a></dt>
<dt><a href="pkg://FreeBSD Developers' Handbook/DOC-INDEX">Index</a></dt>
</dl>
<h3><a name="AEN6428">Bibliography</a></h3>
<a name="COD"></a>
<p>[1] <span class="author">Dave A Patterson</span> <span class="author">and John L
Hennessy</span>, 1998, 1-55860-428-6, Morgan Kaufmann Publishers, Inc., <i>Computer
Organization and Design</i><i>:</i> <i>The Hardware / Software Interface</i>, 1-2.</p>
<a name="AEN6448"></a>
<p>[2] <span class="author">W. Richard Stevens</span>, 1993, 0-201-56317-7, Addison
Wesley Longman, Inc., <i>Advanced Programming in the Unix Environment</i>, 1-2.</p>
<a name="AEN6462"></a>
<p>[3] <span class="author">Marshall Kirk McKusick,</span> <span class="author">Keith Bostic,</span> <span class="author">Michael J Karels,</span> <span class="author">and John S Quarterman</span>, 1996, 0-201-54979-4, Addison-Wesley
Publishing Company, Inc., <i>The Design and Implementation of the 4.4 BSD Operating
System</i>, 1-2.</p>
<a name="PHRACK"></a>
<p>[4] <span class="author">Aleph One</span>, <i>Phrack 49; "Smashing the Stack for
Fun and Profit"</i>.</p>
<a name="STACKGUARD"></a>
<p>[5] <span class="author">Chrispin Cowan,</span> <span class="author">Calton
Pu,</span> <span class="author">and Dave Maier</span>, <i>StackGuard; Automatic Adaptive
Detection and Prevention of Buffer-Overflow Attacks</i>.</p>
<a name="OPENBSD"></a>
<p>[6] <span class="author">Todd Miller</span> <span class="author">and Theo de
Raadt</span>, <i>strlcpy and strlcat -- consistent, safe string copy and
concatenation.</i>.</p>
<hr />
<pkg:outlineMarker OutlineName="Index" id="DOC-INDEX">
<div class="sect1">
<h1 class="title">Index</h1>
<h2 class="indexdiv"><a name="AEN6515">A</a></h2>
<dl>
<dt>arguments, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6520">B</a></h2>
<dl>
<dt>bounds checking</dt>
<dd>
<dl>
<dt>compiler-based, <a href="pkg://FreeBSD Developers' Handbook/AEN1388">Compiler based run-time bounds checking</a></dt>
<dt>library-based, <a href="pkg://FreeBSD Developers' Handbook/AEN1407">Library based run-time bounds checking</a></dt>
</dl>
</dd>
<dt>buffer overflow, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a>, <a href="pkg://FreeBSD Developers' Handbook/AEN1388">Compiler based run-time bounds checking</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6532">C</a></h2>
<dl>
<dt>CERT</dt>
<dd>
<dl>
<dt>security advisories, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
</dl>
</dd>
<dt>chroot(), <a href="pkg://FreeBSD Developers' Handbook/SECURE-CHROOT">Limiting your program's environment</a></dt>
<dt>contributed software, <a href="pkg://FreeBSD Developers' Handbook/POLICIES-CONTRIBUTED">Contributed Software</a></dt>
<dt>core team, <a href="pkg://FreeBSD Developers' Handbook/POLICIES-ENCUMBERED">Encumbered Files</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6547">D</a></h2>
<dl>
<dt>data validation, <a href="pkg://FreeBSD Developers' Handbook/SECURE-TRUST">Trust</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6552">F</a></h2>
<dl>
<dt>frame pointer, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6557">G</a></h2>
<dl>
<dt>gcc, <a href="pkg://FreeBSD Developers' Handbook/AEN1388">Compiler based run-time bounds checking</a></dt>
<dt>GTK, <a href="pkg://FreeBSD Developers' Handbook/L10N-PROGRAMMING">Programming I18N Compliant Applications</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6565">J</a></h2>
<dl>
<dt>jail, <a href="pkg://FreeBSD Developers' Handbook/AEN1454">FreeBSD's jail functionality</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6570">L</a></h2>
<dl>
<dt>LIFO, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6575">M</a></h2>
<dl>
<dt>Morris Internet worm, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6580">N</a></h2>
<dl>
<dt>NUL termination, <a href="pkg://FreeBSD Developers' Handbook/AEN1359">Avoiding Buffer Overflows</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6585">O</a></h2>
<dl>
<dt>OpenBSD, <a href="pkg://FreeBSD Developers' Handbook/AEN1359">Avoiding Buffer Overflows</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6590">P</a></h2>
<dl>
<dt>Perl, <a href="pkg://FreeBSD Developers' Handbook/AEN1558">Perl and Python</a></dt>
<dt>Perl Taint mode, <a href="pkg://FreeBSD Developers' Handbook/SECURE-TRUST">Trust</a></dt>
<dt>ports maintainer, <a href="pkg://FreeBSD Developers' Handbook/POLICIES-MAINTAINER">MAINTAINER on Makefiles</a></dt>
<dt>positive filtering, <a href="pkg://FreeBSD Developers' Handbook/SECURE-TRUST">Trust</a></dt>
<dt>POSIX.1e Process Capabilities, <a href="pkg://FreeBSD Developers' Handbook/AEN1495">POSIX.1e Process
Capabilities</a></dt>
<dt>process image</dt>
<dd>
<dl>
<dt>frame pointer, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
<dt>stack pointer, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
</dl>
</dd>
<dt>Python, <a href="pkg://FreeBSD Developers' Handbook/AEN1558">Perl and Python</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6616">Q</a></h2>
<dl>
<dt>Qt, <a href="pkg://FreeBSD Developers' Handbook/L10N-PROGRAMMING">Programming I18N Compliant Applications</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6621">R</a></h2>
<dl>
<dt>race conditions</dt>
<dd>
<dl>
<dt>access checks, <a href="pkg://FreeBSD Developers' Handbook/SECURE-RACE-CONDITIONS">Race Conditions</a></dt>
<dt>file opens, <a href="pkg://FreeBSD Developers' Handbook/SECURE-RACE-CONDITIONS">Race Conditions</a></dt>
<dt>signals, <a href="pkg://FreeBSD Developers' Handbook/SECURE-RACE-CONDITIONS">Race Conditions</a></dt>
</dl>
</dd>
<dt>release engineer, <a href="pkg://FreeBSD Developers' Handbook/POLICIES-ENCUMBERED">Encumbered Files</a></dt>
<dt>return address, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6637">S</a></h2>
<dl>
<dt>seteuid, <a href="pkg://FreeBSD Developers' Handbook/SECURE-SETUID">SetUID issues</a></dt>
<dt>stack, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
<dt>stack frame, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
<dt>stack pointer, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
<dt>stack-overflow, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
<dt>StackGuard, <a href="pkg://FreeBSD Developers' Handbook/AEN1388">Compiler based run-time bounds checking</a></dt>
<dt>string copy functions</dt>
<dd>
<dl>
<dt>strlcat, <a href="pkg://FreeBSD Developers' Handbook/AEN1359">Avoiding Buffer Overflows</a></dt>
<dt>strlcpy, <a href="pkg://FreeBSD Developers' Handbook/AEN1359">Avoiding Buffer Overflows</a></dt>
<dt>strncat, <a href="pkg://FreeBSD Developers' Handbook/AEN1359">Avoiding Buffer Overflows</a></dt>
<dt>strncpy, <a href="pkg://FreeBSD Developers' Handbook/AEN1359">Avoiding Buffer Overflows</a></dt>
</dl>
</dd>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6667">T</a></h2>
<dl>
<dt>TrustedBSD, <a href="pkg://FreeBSD Developers' Handbook/AEN1495">POSIX.1e Process Capabilities</a></dt>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6672">U</a></h2>
<dl>
<dt>user IDs</dt>
<dd>
<dl>
<dt>effective user ID, <a href="pkg://FreeBSD Developers' Handbook/SECURE-SETUID">SetUID issues</a></dt>
<dt>real user ID, <a href="pkg://FreeBSD Developers' Handbook/SECURE-SETUID">SetUID issues</a></dt>
</dl>
</dd>
</dl>
<hr />
<h2 class="indexdiv"><a name="AEN6680">V</a></h2>
<dl>
<dt>Von-Neuman, <a href="pkg://FreeBSD Developers' Handbook/SECURE-BUFFEROV">Buffer Overflows</a></dt>
</dl>
<h3 class="footnotes">Notes</h3>
<table class="footnotes" border="0" width="100%">
<tbody><tr>
<td align="left" valign="top" width="5%"><a name="FTNAEN305" href="pkg://FreeBSD Developers' Handbook/AEN305"><span class="footnote">[1]</span></a></td>
<td align="left" valign="top" width="95%">
<p>If you run it in the shell, you may get a core dump.</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%"><a name="FTNAEN331" href="pkg://FreeBSD Developers' Handbook/AEN331"><span class="footnote">[2]</span></a></td>
<td align="left" valign="top" width="95%">
<p>To be strictly accurate, <tt class="command">cc</tt> converts the source code into its
own, machine-independent <i class="firstterm">p-code</i> instead of assembly language at
this stage.</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%"><a name="FTNAEN361" href="pkg://FreeBSD Developers' Handbook/AEN361"><span class="footnote">[3]</span></a></td>
<td align="left" valign="top" width="95%">
<p>In case you did not know, a binary sort is an efficient way of sorting things into
order and a bubble sort is not.</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%"><a name="FTNAEN374" href="pkg://FreeBSD Developers' Handbook/AEN374"><span class="footnote">[4]</span></a></td>
<td align="left" valign="top" width="95%">
<p>The reasons for this are buried in the mists of history.</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%"><a name="FTNAEN413" href="pkg://FreeBSD Developers' Handbook/AEN413"><span class="footnote">[5]</span></a></td>
<td align="left" valign="top" width="95%">
<p>Note, we did not use the <var class="option">-o</var> flag to specify the executable
name, so we will get an executable called <tt class="filename">a.out</tt>. Producing a
debug version called <tt class="filename">foobar</tt> is left as an exercise for the
reader!</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%"><a name="FTNAEN743" href="pkg://FreeBSD Developers' Handbook/AEN743"><span class="footnote">[6]</span></a></td>
<td align="left" valign="top" width="95%">
<p>They do not use the <tt class="filename">MAKEFILE</tt> form as block capitals are
often used for documentation files like <tt class="filename">README</tt>.</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%"><a name="FTNAEN1064" href="pkg://FreeBSD Developers' Handbook/AEN1064"><span class="footnote">[7]</span></a></td>
<td align="left" valign="top" width="95%">
<p>Some powerful, free IDEs now exist, such as KDevelop in the ports collection.</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%"><a name="FTNAEN1175" href="pkg://FreeBSD Developers' Handbook/AEN1175"><span class="footnote">[8]</span></a></td>
<td align="left" valign="top" width="95%">
<p>Many Emacs users set their <tt class="envar">EDITOR</tt> environment to <var class="literal">emacsclient</var> so this happens every time they need to edit a
file.</p>
</td>
</tr>
</tbody></table>
<hr />
<p align="center"><small>This, and other documents, can be downloaded from <a href="ftp://ftp.freebsd.org/pub/FreeBSD/doc/">ftp://ftp.FreeBSD.org/pub/FreeBSD/doc/</a>.</small></p>
<p align="center"><small>For questions about FreeBSD, read the <a href="http://www.freebsd.org/docs.html">documentation</a> before contacting <<a href="mailto:questions@FreeBSD.org">questions@FreeBSD.org</a>>.<br />
For questions about this documentation, e-mail <<a href="mailto:doc@FreeBSD.org">doc@FreeBSD.org</a>>.</small></p>
<div align="right"><img align="right" src="wee.png" /></div>
</div>
</pkg:outlineMarker>
</div>
</pkg:outlineMarker>
</pkg:outlineMarker>
</pkg:content>
</pkg:package>