<?xml version="1.0"?>
<pkg:package name="FreeBSD Developers' Handbook" 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="bsd_big.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 Developers' Handbook. This manual is a <span class="emphasis"><i class="emphasis">work in progress</i></span> and is the work of many individuals. Many
sections do not yet exist and some of those that do exist need to be updated. If you are
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 this document is always available from the <a href="http://www.freebsd.org/index.html" target="_top">FreeBSD World Wide Web server</a>. It may
also be downloaded in a variety of formats and compression options from 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 ``&#8482;'' or the ``®'' symbol.</p>




<hr />



<dl>
<dt><b>Table of Contents</b></dt>

<dt>I. <a href="pkg://FreeBSD Developers' Handbook/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="bsd_sm.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. System all installed and you are ready to start programming. But where
to start? What does FreeBSD provide? What can it do for me, as a programmer?</p>

<p>These are some questions which this chapter tries to answer. Of course, programming
has different levels of proficiency like any other trade. For some it is a hobby, for
others it is their profession. The information in this chapter might be more aimed
towards the beginning programmer, but may also serve to be useful for the programmer
taking her first steps on the FreeBSD platform.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="1.2 The BSD Vision" id="INTRODUCTION-BSDVISION">
		<div class="sect2">
			<h2 class="title">1.2 The
BSD Vision</h2>

<p>To produce the best <span class="trademark">UNIX</span>® like operating system
package possible, with due respect to the original software tools ideology as well as
usability, performance and stability.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="1.3 Architectural Guidelines" id="INTRODUCTION-ARCHGUIDE">
		<div class="sect2">
			<h2 class="title">1.3
Architectural Guidelines</h2>

<p>Our ideology can be described by the following guidelines</p>

<ul>
<li>
<p>Do not add new functionality unless an implementor cannot complete a real application
without it.</p>
</li>

<li>
<p>It is as important to decide what a system is not as to decide what it is. Do not
serve all the world's needs; rather, make the system extensible so that additional needs
can be met in an upwardly compatible fashion.</p>
</li>

<li>
<p>The only thing worse than generalizing from one example is generalizing from no
examples at all.</p>
</li>

<li>
<p>If a problem is not completely understood, it is probably best to provide no solution
at all.</p>
</li>

<li>
<p>If you can get 90 percent of the desired effect for 10 percent of the work, use the
simpler solution.</p>
</li>

<li>
<p>Isolate complexity as much as possible.</p>
</li>

<li>
<p>Provide mechanism, rather than policy. In particular, place user interface policy in
the client's hands.</p>
</li>
</ul>

<p>From Scheifler &#38; Gettys: "X Window System"</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 complete source code to FreeBSD is available from our public CVS repository. The
source code is normally installed in <tt class="filename">/usr/src</tt> which contains
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 is an introduction to using some of the programming tools supplied with
FreeBSD, although much of it will be applicable to many other versions of <span class="trademark">UNIX</span>. It does <span class="emphasis"><i class="emphasis">not</i></span> attempt to describe coding in any detail. Most of the
chapter assumes little or no previous programming knowledge, although it is hoped that
most programmers will find something of value 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 an excellent development environment. Compilers for C, C++, and Fortran
and an assembler come with the basic system, not to mention a Perl interpreter and
classic <span class="trademark">UNIX</span> tools such as <tt class="command">sed</tt>
and <tt class="command">awk</tt>. If that is not enough, there are many more compilers
and interpreters in the Ports collection. FreeBSD is very compatible with standards such
as <acronym class="acronym"><span class="trademark">POSIX</span>®</acronym> and
<acronym class="acronym">ANSI</acronym> C, as well with its own BSD heritage, so it is
possible to write applications that will compile and run with little or no modification
on a wide range of platforms.</p>

<p>However, all this power can be rather overwhelming at first if you have never written
programs on a <span class="trademark">UNIX</span> platform before. This document aims to
help you get up and running, without getting too deeply into more advanced topics. The
intention is that this document should give you enough of the basics to be able to make
some sense of the documentation.</p>

<p>Most of the document requires little or no knowledge of programming, although it does
assume a basic competence with using <span class="trademark">UNIX</span> and a
willingness to learn!</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 of interpreters that are available as <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/" target="_top">FreeBSD
packages</a>, with a brief discussion of some of the more popular interpreted
languages.</p>

<p>To get one of these packages, all you need to do is to click on the hotlink for the
package, to download the package and then install the package by running:</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">pkg_add <var class="replaceable">package name</var></kbd>
</pre>

<p>as root. Obviously, you will need to have a fully functional FreeBSD 2.1.0 or later
system for the package to work!</p>


<dl>
<dt><acronym class="acronym">BASIC</acronym></dt>

<dd>
<p>Short for Beginner's All-purpose Symbolic Instruction Code. Developed in the 1950s for
teaching University students to program and provided with every self-respecting personal
computer in the 1980s, <acronym class="acronym">BASIC</acronym> has been the first
programming language for many programmers. It is also the foundation for Visual
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 that was developed in the late 1950s as an alternative to the
``number-crunching'' languages that were popular at the time. Instead of being based on
numbers, Lisp is based on lists; in fact the name is short for ``List Processing''. Very
popular in <acronym class="acronym">AI</acronym> (Artificial Intelligence) circles.</p>

<p>Lisp is an extremely powerful and sophisticated language, but can be rather large and
unwieldy.</p>

<p>Various implementations of Lisp that can run on <span class="trademark">UNIX</span>
systems are available as packages for FreeBSD. <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/gcl.tgz" target="_top">GNU
Common Lisp</a>, <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/clisp.tgz" target="_top">CLISP</a> by Bruno Haible and Michael Stoll, <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/cmucl.tgz" target="_top">CMUCL</a> which includes a highly-optimizing compiler too, or simpler Lisp
implementations, like <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/slisp.tgz" target="_top">SLisp</a> which implements most of the Common Lisp constructs in a few
hundred lines of C code.</p>
</dd>

<dt>Perl</dt>

<dd>
<p>Very popular with system administrators for writing scripts; also often used on World
Wide Web servers for writing <acronym class="acronym">CGI</acronym> scripts.</p>

<p>Perl is available as a <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/perl.tgz" target="_top">package</a> for all FreeBSD releases, and is installed as <tt class="command">/usr/bin/perl</tt> in the base system of 4.x releases.</p>
</dd>

<dt>Scheme</dt>

<dd>
<p>A dialect of Lisp that is rather more compact and cleaner than Common Lisp. Popular in
Universities as it is simple enough to teach to undergraduates as a first language, while
it has a high enough level of abstraction to be used in research work.</p>

<p>FreeBSD has packages of the <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/elk.tgz" target="_top">Elk
Scheme Interpreter</a>, the <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/mit-scheme.tgz" target="_top">MIT Scheme Interpreter</a> and the <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/scm.tgz" target="_top">SCM
Scheme Interpreter</a>.</p>
</dd>

<dt>Icon</dt>

<dd>
<p>Icon is a high-level language with extensive facilities for processing strings and
structures. A <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/icon.tgz" target="_top">package</a> is available for FreeBSD.</p>
</dd>

<dt>Logo</dt>

<dd>
<p>Logo is a language that is easy to learn, and has been used as an introductory
programming language in various courses. It is an excellent tool to work with when
teaching programming in small ages, as it makes the creation of elaborate geometric
shapes an easy task even for very small children.</p>

<p>A package is available for FreeBSD of Brian Harvey's <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/ucblogo.tgz" target="_top">LOGO Interpreter</a>.</p>
</dd>

<dt>Python</dt>

<dd>
<p>Python is an Object-Oriented, interpreted language. Its advocates argue that it is one
of the best languages to start programming with, since it is relatively easy to start
with, but is not limited in comparison to other popular interpreted languages that are
used for the development of large, complex applications (Perl and Tcl are two other
languages that are popular for such tasks).</p>

<p>A package of the latest version of Python for FreeBSD is available <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/python.tgz" target="_top">here</a>.</p>
</dd>

<dt>Tcl and Tk</dt>

<dd>
<p>Tcl is an embeddable, interpreted language, that has become widely used and became
popular mostly because of its portability to many platforms. It can be used both for
quickly writing small, prototype applications, or (when combined with Tk, a GUI toolkit)
fully-fledged, featureful programs.</p>

<p>Various versions of Tcl are available as packages for FreeBSD. The latest version is,
as of this writing, <a href="ftp://ftp.freebsd.org/pub/FreeBSD/ports/packages/Latest/tcl83.tgz" target="_top">Tcl version 8.3</a>.</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. First of all, you write your code in a file (or files)
using an editor. You then run the compiler and see if it accepts your program. If it did
not compile, grit your teeth and go back to the editor; if it did compile and gave you a
program, you can run it either at a shell command prompt or in a debugger to see if it
works properly. <a name="AEN305" href="pkg://FreeBSD Developers' Handbook/FTNAEN305"><span class="footnote">[1]</span></a></p>

<p>Obviously, this is not quite as direct as using an interpreter. However it allows you
to do a lot of things which are very difficult or even impossible with an interpreter,
such as writing code which interacts closely with the operating system--or even writing
your own operating system! It is also useful if you need to write very efficient code, as
the compiler can take its time and optimize the code, which would not be acceptable in an
interpreter. Moreover, distributing a program written for a compiler is usually more
straightforward than one written for an interpreter--you can just give them a copy of the
executable, assuming they have the same operating system as you.</p>

<p>Compiled languages include Pascal, C and C++. C and C++ are rather unforgiving
languages, and best suited to more experienced programmers; Pascal, on the other hand,
was designed as an educational language, and is quite a good language to start with.
FreeBSD does not include Pascal support in the base system, but both GNU Pascal Compiler
(GPC) and the Free Pascal Compiler are available in the ports collection as <a href="http://www.freebsd.org/cgi/url.cgi?ports/lang/gpc/pkg-descr"><tt class="filename">lang/gpc</tt></a> and <a href="http://www.freebsd.org/cgi/url.cgi?ports/lang/fpc/pkg-descr"><tt class="filename">lang/fpc</tt></a>.</p>

<p>As the edit-compile-run-debug cycle is rather tedious when using separate programs,
many commercial compiler makers have produced Integrated Development Environments
(<acronym class="acronym">IDE</acronym>s for short). FreeBSD does not include an IDE in
the base system, but <a href="http://www.freebsd.org/cgi/url.cgi?ports/devel/kdevelop/pkg-descr"><tt class="filename">devel/kdevelop</tt></a> is available in the ports tree and many use <b class="application">Emacs</b> for this purpose. Using <b class="application">Emacs</b> as
an IDE is discussed in <a href="pkg://FreeBSD Developers' Handbook/EMACS">Section 2.7</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>

<p>This section deals only with the GNU compiler for C and C++, since that comes with the
base FreeBSD system. It can be invoked by either <tt class="command">cc</tt> or <tt class="command">gcc</tt>. The details of producing a program with an interpreter vary
considerably between interpreters, and are usually well covered in the documentation and
on-line help for the interpreter.</p>

<p>Once you have written your masterpiece, the next step is to convert it into something
that will (hopefully!) run on FreeBSD. This usually involves several steps, each of which
is done by a separate program.</p>


<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>Convert the assembly language into machine code--yep, we are talking bits and bytes,
ones and zeros here.</p>
</li>

<li>
<p>Check that you have used things like functions and global variables in a consistent
way. For example, if you have called a non-existent function, it will complain.</p>
</li>

<li>
<p>If you are trying to produce an executable from several source code files, work out
how to fit them all together.</p>
</li>

<li>
<p>Work out how to produce something that the system's run-time loader will be able to
load into memory and run.</p>
</li>

<li>
<p>Finally, write the executable on the filesystem.</p>
</li>
</ol>


<p>The word <i class="firstterm">compiling</i> is often used to refer to just steps 1 to
4--the others are referred to as <i class="firstterm">linking</i>. Sometimes step 1 is
referred to as <i class="firstterm">pre-processing</i> and steps 3-4 as <i class="firstterm">assembling</i>.</p>

<p>Fortunately, almost all this detail is hidden from you, as <tt class="command">cc</tt>
is a front end that manages calling all these programs with the right arguments for you;
simply typing</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc foobar.c</kbd>
</pre>

<p>will cause <tt class="filename">foobar.c</tt> to be compiled by all the steps above.
If you have more than one file to compile, just do something like</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc foo.c bar.c</kbd>
</pre>

<p>Note that the syntax checking is just that--checking the syntax. It will not check for
any logical mistakes you may have made, like putting the program into an infinite loop,
or using a bubble sort when you meant to use a binary sort. <a name="AEN361" href="pkg://FreeBSD Developers' Handbook/FTNAEN361"><span class="footnote">[3]</span></a></p>

<p>There are lots and lots of options for <tt class="command">cc</tt>, which are all in
the manual page. Here are a few of the most important ones, with examples of how to use
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>

<dt><var class="option">-c</var></dt>

<dd>
<p>Just compile the file, do not link it. Useful for toy programs where you just want to
check the syntax, or if you are using a <tt class="filename">Makefile</tt>.</p>

<a name="AEN392"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc -c foobar.c</kbd>
       
</pre>


<p>This will produce an <i class="firstterm">object file</i> (not an executable) called
<tt class="filename">foobar.o</tt>. This can be linked together with other object files
into an executable.</p>
</dd>

<dt><var class="option">-g</var></dt>

<dd>
<p>Create a debug version of the executable. This makes the compiler put information into
the executable about which line of which source file corresponds to which function call.
A debugger can use this information to show the source code as you step through the
program, which is <span class="emphasis"><i class="emphasis">very</i></span> useful; the
disadvantage is that all this extra information makes the program much bigger. Normally,
you compile with <var class="option">-g</var> while you are developing a program and then
compile a ``release version'' without <var class="option">-g</var> when you are satisfied
it works properly.</p>

<a name="AEN408"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc -g foobar.c</kbd>
       
</pre>


<p>This will produce a debug version of the program. <a name="AEN413" href="pkg://FreeBSD Developers' Handbook/FTNAEN413"><span class="footnote">[5]</span></a></p>
</dd>

<dt><var class="option">-O</var></dt>

<dd>
<p>Create an optimized version of the executable. The compiler performs various clever
tricks to try to produce an executable that runs faster than normal. You can add a number
after the <var class="option">-O</var> to specify a higher level of optimization, but
this often exposes bugs in the compiler's optimizer. For instance, the version of <tt class="command">cc</tt> that comes with the 2.1.0 release of FreeBSD is known to produce
bad code with the <var class="option">-O2</var> option in some circumstances.</p>

<p>Optimization is usually only turned on when compiling a release version.</p>

<a name="AEN427"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc -O -o foobar foobar.c</kbd>
       
</pre>


<p>This will produce an optimized version of <tt class="filename">foobar</tt>.</p>
</dd>
</dl>


<p>The following three flags will force <tt class="command">cc</tt> to check that your
code complies to the relevant international standard, often referred to as the <acronym class="acronym">ANSI</acronym> standard, though strictly speaking it is an <acronym class="acronym">ISO</acronym> standard.</p>


<dl>
<dt><var class="option">-Wall</var></dt>

<dd>
<p>Enable all the warnings which the authors of <tt class="command">cc</tt> believe are
worthwhile. Despite the name, it will not enable all the warnings <tt class="command">cc</tt> is capable of.</p>
</dd>

<dt><var class="option">-ansi</var></dt>

<dd>
<p>Turn off most, but not all, of the non-<acronym class="acronym">ANSI</acronym>&#160;C
features provided by <tt class="command">cc</tt>. Despite the name, it does not guarantee
strictly that your code will comply to the standard.</p>
</dd>

<dt><var class="option">-pedantic</var></dt>

<dd>
<p>Turn off <span class="emphasis"><i class="emphasis">all</i></span> <tt class="command">cc</tt>'s non-<acronym class="acronym">ANSI</acronym>&#160;C
features.</p>
</dd>
</dl>


<p>Without these flags, <tt class="command">cc</tt> will allow you to use some of its
non-standard extensions to the standard. Some of these are very useful, but will not work
with other compilers--in fact, one of the main aims of the standard is to allow people to
write code that will work with any compiler on any system. This is known as <i class="firstterm">portable code</i>.</p>

<p>Generally, you should try to make your code as portable as possible, as otherwise you
may have to completely rewrite the program later to get it to work somewhere else--and
who knows what you may be using in a few years time?</p>

<a name="AEN464"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc -Wall -ansi -pedantic -o foobar foobar.c</kbd>
</pre>


<p>This will produce an executable <tt class="filename">foobar</tt> after checking <tt class="filename">foobar.c</tt> for standard compliance.</p>


<dl>
<dt><var class="option">-l<var class="replaceable">library</var></var></dt>

<dd>
<p>Specify a function library to be used at link time.</p>

<p>The most common example of this is when compiling a program that uses some of the
mathematical functions in C. Unlike most other platforms, these are in a separate library
from the standard C one and you have to tell the compiler to add it.</p>

<p>The rule is that if the library is called <tt class="filename">lib<var class="replaceable">something</var>.a</tt>, you give <tt class="command">cc</tt> the
argument <var class="option">-l<var class="replaceable">something</var></var>. For
example, the math library is <tt class="filename">libm.a</tt>, so you give <tt class="command">cc</tt> the argument <var class="option">-lm</var>. A common ``gotcha''
with the math library is that it has to be the last library on the command line.</p>

<a name="AEN489"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc -o foobar foobar.c -lm</kbd>
       
</pre>


<p>This will link the math library functions into <tt class="filename">foobar</tt>.</p>

<p>If you are compiling C++ code, you need to add <var class="option">-lg++</var>, or
<var class="option">-lstdc++</var> if you are using FreeBSD 2.2 or later, to the command
line argument to link the C++ library functions. Alternatively, you can run <tt class="command">c++</tt> instead of <tt class="command">cc</tt>, which does this for you.
<tt class="command">c++</tt> can also be invoked as <tt class="command">g++</tt> on
FreeBSD.</p>

<a name="AEN502"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc -o foobar foobar.cc -lg++</kbd>     For FreeBSD 2.1.6 and earlier
<samp class="prompt">%</samp> <kbd class="userinput">cc -o foobar foobar.cc -lstdc++</kbd>  For FreeBSD 2.2 and later
<samp class="prompt">%</samp> <kbd class="userinput">c++ -o foobar foobar.cc</kbd>
       
</pre>


<p>Each of these will both produce an executable <tt class="filename">foobar</tt> from
the C++ source file <tt class="filename">foobar.cc</tt>. Note that, on <span class="trademark">UNIX</span> systems, C++ source files traditionally end in <tt class="filename">.C</tt>, <tt class="filename">.cxx</tt> or <tt class="filename">.cc</tt>, rather than the <span class="trademark">MS-DOS</span>®
style <tt class="filename">.cpp</tt> (which was already used for something else). <tt class="command">gcc</tt> used to rely on this to work out what kind of compiler to use on
the source file; however, this restriction no longer applies, so you may now call your
C++ files <tt class="filename">.cpp</tt> with impunity!</p>
</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.1. <a href="pkg://FreeBSD Developers' Handbook/Q2411">I am trying to write a program which uses the <code class="function">sin()</code> function and I get an error like this. What does it
mean?</a></dt>

<dt>2.4.1.2. <a href="pkg://FreeBSD Developers' Handbook/Q2412">All right, I wrote this simple program to practice
using <var class="option">-lm</var>. All it does is raise 2.1 to the power of 6.</a></dt>

<dt>2.4.1.3. <a href="pkg://FreeBSD Developers' Handbook/Q2413">So how do I fix this?</a></dt>

<dt>2.4.1.4. <a href="pkg://FreeBSD Developers' Handbook/Q2414">I compiled a file called <tt class="filename">foobar.c</tt> and I cannot find an executable called <tt class="filename">foobar</tt>. Where has it gone?</a></dt>

<dt>2.4.1.5. <a href="pkg://FreeBSD Developers' Handbook/Q2415">OK, I have an executable called <tt class="filename">foobar</tt>, I can see it when I run <tt class="command">ls</tt>, but
when I type in <tt class="command">foobar</tt> at the command prompt it tells me there is
no such file. Why can it not find it?</a></dt>

<dt>2.4.1.6. <a href="pkg://FreeBSD Developers' Handbook/Q2416">I called my executable <tt class="filename">test</tt>,
but nothing happens when I run it. What is going on?</a></dt>

<dt>2.4.1.7. <a href="pkg://FreeBSD Developers' Handbook/Q2417">I compiled my program and it seemed to run all right at
first, then there was an error and it said something about ``<tt class="errorname">core
dumped</tt>''. What does that mean?</a></dt>

<dt>2.4.1.8. <a href="pkg://FreeBSD Developers' Handbook/Q2418">Fascinating stuff, but what I am supposed to do
now?</a></dt>

<dt>2.4.1.9. <a href="pkg://FreeBSD Developers' Handbook/Q2419">When my program dumped core, it said something about a
``<tt class="errorname">segmentation fault</tt>''. What is that?</a></dt>

<dt>2.4.1.10. <a href="pkg://FreeBSD Developers' Handbook/Q24110">Sometimes when I get a core dump it says ``<tt class="errorname">bus error</tt>''. It says in my <span class="trademark">UNIX</span>
book that this means a hardware problem, but the computer still seems to be working. Is
this true?</a></dt>

<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.1. I am trying to write a program which uses the sin() function and I get an error like this. What does it mean?" id="Q2411">
			<div class="sect4">
				<div class="title"><b>2.4.1.1.</b> I am trying to write a program
which uses the <code class="function">sin()</code> function and I get an error like this.
What does it mean?</div>
				

<a name="AEN531"></a>
<pre class="screen">/var/tmp/cc0143941.o: Undefined symbol `_sin' referenced from text segment
         
</pre>




<p><b></b>When using mathematical functions like <code class="function">sin()</code>, you
have to tell <tt class="command">cc</tt> to link in the math library, like so:</p>

<a name="AEN537"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc -o foobar foobar.c -lm</kbd>
         
</pre>







			</div>
		</pkg:outlineMarker>

		<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
program to practice using <var class="option">-lm</var>. All it does is raise 2.1 to the
power of 6.</div>
				

<a name="AEN545"></a>

		<pkg:outlineMarker OutlineName="code_1" id="code_1" visible="false" copy="true">
				<pre class="programlisting">#include &#60;stdio.h&#62;

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>


<p>This is <span class="emphasis"><i class="emphasis">not</i></span> the right answer!
What is going on?</p>



<p><b></b>When the compiler sees you call a function, it checks if it has already seen a
prototype for it. If it has not, it assumes the function returns an <span class="type">int</span>, which is definitely not what you want here.</p>






			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.4.1.3. So how do I fix this?" id="Q2413">
			<div class="sect4">
				<div class="title"><b>2.4.1.3.</b> So how do I fix this?</div>
				



<p><b></b>The prototypes for the mathematical functions are in <tt class="filename">math.h</tt>. If you include this file, the compiler will be able to find
the prototype and it will stop doing strange things to your calculation!</p>

<a name="AEN568"></a>

		<pkg:outlineMarker OutlineName="code_2" id="code_2" visible="false" copy="true">
				<pre class="programlisting">#include &#60;math.h&#62;
#include &#60;stdio.h&#62;

int main() {
...
         
</pre>
		</pkg:outlineMarker>



<p>After recompiling it as you did before, run it:</p>

<a name="AEN571"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">./a.out</kbd>
2.1 ^ 6 = 85.766121
         
</pre>


<p>If you are using any of the mathematical functions, <span class="emphasis"><i class="emphasis">always</i></span> include <tt class="filename">math.h</tt> and remember
to link in the math library.</p>






			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.4.1.4. I compiled a file called foobar.c and I cannot find an executable called foobar. Where has it gone?" id="Q2414">
			<div class="sect4">
				<div class="title"><b>2.4.1.4.</b> I compiled a file called <tt class="filename">foobar.c</tt> and I cannot find an executable called <tt class="filename">foobar</tt>. Where has it gone?</div>
				



<p><b></b>Remember, <tt class="command">cc</tt> will call the executable <tt class="filename">a.out</tt> unless you tell it differently. Use the <var class="option">-o&#160;<var class="replaceable">filename</var></var> option:</p>

<a name="AEN589"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc -o foobar foobar.c</kbd>
         
</pre>







			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.4.1.5. OK, I have an executable called foobar, I can see it when I run ls, but when I type in foobar at the command prompt it tells me there is no such file. Why can it not find it?" id="Q2415">
			<div class="sect4">
				<div class="title"><b>2.4.1.5.</b> OK, I have an executable called
<tt class="filename">foobar</tt>, I can see it when I run <tt class="command">ls</tt>,
but when I type in <tt class="command">foobar</tt> at the command prompt it tells me
there is no such file. Why can it not find it?</div>
				



<p><b></b>Unlike <span class="trademark">MS-DOS</span>, <span class="trademark">UNIX</span> does not look in the current directory when it is trying to
find out which executable you want it to run, unless you tell it to. Either type <tt class="command">./foobar</tt>, which means ``run the file called <tt class="filename">foobar</tt> in the current directory'', or change your <tt class="envar">PATH</tt> environment variable so that it looks something like</p>

<a name="AEN607"></a>
<pre class="screen">bin:/usr/bin:/usr/local/bin:.
         
</pre>


<p>The dot at the end means ``look in the current directory if it is not in any of the
others''.</p>






			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.4.1.6. I called my executable test, but nothing happens when I run it. What is going on?" id="Q2416">
			<div class="sect4">
				<div class="title"><b>2.4.1.6.</b> I called my executable <tt class="filename">test</tt>, but nothing happens when I run it. What is going on?</div>
				



<p><b></b>Most <span class="trademark">UNIX</span> systems have a program called <tt class="command">test</tt> in <tt class="filename">/usr/bin</tt> and the shell is picking
that one up before it gets to checking the current directory. Either type:</p>

<a name="AEN620"></a>
<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">./test</kbd>
         
</pre>


<p>or choose a better name for your program!</p>






			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.4.1.7. I compiled my program and it seemed to run all right at first, then there was an error and it said something about ``core dumped''. What does that mean?" id="Q2417">
			<div class="sect4">
				<div class="title"><b>2.4.1.7.</b> I compiled my program and it
seemed to run all right at first, then there was an error and it said something about
``<tt class="errorname">core dumped</tt>''. What does that mean?</div>
				



<p><b></b>The name <i class="firstterm">core dump</i> dates back to the very early days
of <span class="trademark">UNIX</span>, when the machines used core memory for storing
data. Basically, if the program failed under certain conditions, the system would write
the contents of core memory to disk in a file called <tt class="filename">core</tt>,
which the programmer could then pore over to find out what went wrong.</p>






			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.4.1.8. Fascinating stuff, but what I am supposed to do now?" id="Q2418">
			<div class="sect4">
				<div class="title"><b>2.4.1.8.</b> Fascinating stuff, but what I
am supposed to do now?</div>
				



<p><b></b>Use <tt class="command">gdb</tt> to analyze the core (see <a href="pkg://FreeBSD Developers' Handbook/DEBUGGING">Section 2.6</a>).</p>






			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.4.1.9. When my program dumped core, it said something about a ``segmentation fault''. What is that?" id="Q2419">
			<div class="sect4">
				<div class="title"><b>2.4.1.9.</b> When my program dumped core, it
said something about a ``<tt class="errorname">segmentation fault</tt>''. What is
that?</div>
				



<p><b></b>This basically means that your program tried to perform some sort of illegal
operation on memory; <span class="trademark">UNIX</span> is designed to protect the
operating system and other programs from rogue programs.</p>

<p>Common causes for this are:</p>

<ul>
<li>
<p>Trying to write to a <var class="symbol">NULL</var> pointer, eg</p>


		<pkg:outlineMarker OutlineName="code_3" id="code_3" visible="false" copy="true">
				<pre class="programlisting">char *foo = NULL;
strcpy(foo, "bang!");
       
</pre>
		</pkg:outlineMarker>

</li>

<li>
<p>Using a pointer that has not been initialized, eg</p>


		<pkg:outlineMarker OutlineName="code_4" id="code_4" visible="false" copy="true">
				<pre class="programlisting">char *foo;
strcpy(foo, "bang!");
       
</pre>
		</pkg:outlineMarker>


<p>The pointer will have some random value that, with luck, will point into an area of
memory that is not available to your program and the kernel will kill your program before
it can do any damage. If you are unlucky, it will point somewhere inside your own program
and corrupt one of your data structures, causing the program to fail mysteriously.</p>
</li>

<li>
<p>Trying to access past the end of an array, eg</p>


		<pkg:outlineMarker OutlineName="code_5" id="code_5" visible="false" copy="true">
				<pre class="programlisting">int bar[20];
bar[27] = 6;
       
</pre>
		</pkg:outlineMarker>

</li>

<li>
<p>Trying to store something in read-only memory, eg</p>


		<pkg:outlineMarker OutlineName="code_6" id="code_6" visible="false" copy="true">
				<pre class="programlisting">char *foo = "My string";
strcpy(foo, "bang!");
       
</pre>
		</pkg:outlineMarker>


<p><span class="trademark">UNIX</span> compilers often put string literals like <var class="literal">"My string"</var> into read-only areas of memory.</p>
</li>

<li>
<p>Doing naughty things with <code class="function">malloc()</code> and <code class="function">free()</code>, eg</p>


		<pkg:outlineMarker OutlineName="code_7" id="code_7" visible="false" copy="true">
				<pre class="programlisting">char bar[80];
free(bar);
       
</pre>
		</pkg:outlineMarker>


<p>or</p>


		<pkg:outlineMarker OutlineName="code_8" id="code_8" visible="false" copy="true">
				<pre class="programlisting">char *foo = malloc(27);
free(foo);
free(foo);
       
</pre>
		</pkg:outlineMarker>

</li>
</ul>

<p>Making one of these mistakes will not always lead to an error, but they are always bad
practice. Some systems and compilers are more tolerant than others, which is why programs
that ran well on one system can crash when you try them on an another.</p>






			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.4.1.10. Sometimes when I get a core dump it says ``bus error''. It says in my UNIX book that this means a hardware problem, but the computer still seems to be working. Is this true?" id="Q24110">
			<div class="sect4">
				<div class="title"><b>2.4.1.10.</b> Sometimes when I get a core
dump it says ``<tt class="errorname">bus error</tt>''. It says in my <span class="trademark">UNIX</span> book that this means a hardware problem, but the computer
still seems to be working. Is this true?</div>
				



<p><b></b>No, fortunately not (unless of course you really do have a hardware
problem...). This is usually another way of saying that you accessed memory in a way you
should not have.</p>






			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.4.1.11. 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?" id="Q24111">
			<div class="sect4">
				<div class="title"><b>2.4.1.11.</b> 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?</div>
				



<p><b></b>Yes, just go to another console or xterm, do</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">ps</kbd>
       
</pre>

<p>to find out the process ID of your program, and do</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">kill -ABRT <var class="replaceable">pid</var></kbd>
       
</pre>

<p>where <var class="parameter"><var class="replaceable">pid</var></var> is the process
ID you looked up.</p>

<p>This is useful if your program has got stuck in an infinite loop, for instance. If
your program happens to trap <var class="symbol">SIGABRT</var>, there are several other
signals which have a similar effect.</p>

<p>Alternatively, you can create a core dump from inside your program, by calling the
<code class="function">abort()</code> function. See the manual page of <a href="http://www.freebsd.org/cgi/man.cgi?query=abort&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">abort</span>(3)</span></a> to learn
more.</p>

<p>If you want to create a core dump from outside your program, but do not want the
process to terminate, you can use the <tt class="command">gcore</tt> program. See the
manual page of <a href="http://www.freebsd.org/cgi/man.cgi?query=gcore&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">gcore</span>(1)</span></a> for more
information.</p>







<hr />

		</div>
	</pkg:outlineMarker>

	
			</div>
		</pkg:outlineMarker>

			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="2.5 Make" id="TOOLS-MAKE">
		<div class="sect2">
			<h2 class="title">2.5 Make</h2>



		<pkg:outlineMarker OutlineName="2.5.1 What is make?" id="AEN712">
			<div class="sect3">
				<h3 class="title">2.5.1 What is <tt class="command">make</tt>?</h3>

<p>When you are working on a simple program with only one or two source files, typing
in</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc file1.c file2.c</kbd>
</pre>

<p>is not too bad, but it quickly becomes very tedious when there are several files--and
it can take a while to compile, too.</p>

<p>One way to get around this is to use object files and only recompile the source file
if the source code has changed. So we could have something like:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc file1.o file2.o</kbd> ... <kbd class="userinput">file37.c</kbd> ...
</pre>

<p>if we had changed <tt class="filename">file37.c</tt>, but not any of the others, since
the last time we compiled. This may speed up the compilation quite a bit, but does not
solve the typing problem.</p>

<p>Or we could write a shell script to solve the typing problem, but it would have to
re-compile everything, making it very inefficient on a large project.</p>

<p>What happens if we have hundreds of source files lying about? What if we are working
in a team with other people who forget to tell us when they have changed one of their
source files that we use?</p>

<p>Perhaps we could put the two solutions together and write something like a shell
script that would contain some kind of magic rule saying when a source file needs
compiling. Now all we need now is a program that can understand these rules, as it is a
bit too complicated for the shell.</p>

<p>This program is called <tt class="command">make</tt>. It reads in a file, called a <i class="firstterm">makefile</i>, that tells it how different files depend on each other,
and works out which files need to be re-compiled and which ones do not. For example, a
rule could say something like ``if <tt class="filename">fromboz.o</tt> is older than <tt class="filename">fromboz.c</tt>, that means someone must have changed <tt class="filename">fromboz.c</tt>, so it needs to be re-compiled.'' The makefile also has
rules telling make <span class="emphasis"><i class="emphasis">how</i></span> to
re-compile the source file, making it a much more powerful tool.</p>

<p>Makefiles are typically kept in the same directory as the source they apply to, and
can be called <tt class="filename">makefile</tt>, <tt class="filename">Makefile</tt> or
<tt class="filename">MAKEFILE</tt>. Most programmers use the name <tt class="filename">Makefile</tt>, as this puts it near the top of a directory listing,
where it can easily be seen. <a name="AEN743" href="pkg://FreeBSD Developers' Handbook/FTNAEN743"><span class="footnote">[6]</span></a></p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.5.2 Example of using make" id="AEN747">
			<div class="sect3">
				<h3 class="title">2.5.2 Example of using <tt class="command">make</tt></h3>

<p>Here is a very simple make file:</p>


		<pkg:outlineMarker OutlineName="code_9" id="code_9" visible="false" copy="true">
				<pre class="programlisting">foo: foo.c
    cc -o foo foo.c
</pre>
		</pkg:outlineMarker>


<p>It consists of two lines, a dependency line and a creation line.</p>

<p>The dependency line here consists of the name of the program (known as the <i class="firstterm">target</i>), followed by a colon, then whitespace, then the name of the
source file. When <tt class="command">make</tt> reads this line, it looks to see if <tt class="filename">foo</tt> exists; if it exists, it compares the time <tt class="filename">foo</tt> was last modified to the time <tt class="filename">foo.c</tt>
was last modified. If <tt class="filename">foo</tt> does not exist, or is older than <tt class="filename">foo.c</tt>, it then looks at the creation line to find out what to do.
In other words, this is the rule for working out when <tt class="filename">foo.c</tt>
needs to be re-compiled.</p>

<p>The creation line starts with a <span class="token">tab</span> (press the <b class="keycap">tab</b> key) and then the command you would type to create <tt class="filename">foo</tt> if you were doing it at a command prompt. If <tt class="filename">foo</tt> is out of date, or does not exist, <tt class="command">make</tt> then executes this command to create it. In other words, this
is the rule which tells make how to re-compile <tt class="filename">foo.c</tt>.</p>

<p>So, when you type <kbd class="userinput">make</kbd>, it will make sure that <tt class="filename">foo</tt> is up to date with respect to your latest changes to <tt class="filename">foo.c</tt>. This principle can be extended to <tt class="filename">Makefile</tt>s with hundreds of targets--in fact, on FreeBSD, it is
possible to compile the entire operating system just by typing <kbd class="userinput">make world</kbd> in the appropriate directory!</p>

<p>Another useful property of makefiles is that the targets do not have to be programs.
For instance, we could have a make file that looks like this:</p>


		<pkg:outlineMarker OutlineName="code_10" id="code_10" visible="false" copy="true">
				<pre class="programlisting">foo: foo.c
    cc -o foo foo.c

install:
    cp foo /home/me
</pre>
		</pkg:outlineMarker>


<p>We can tell make which target we want to make by typing:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">make <var class="replaceable">target</var></kbd>
</pre>

<p><tt class="command">make</tt> will then only look at that target and ignore any
others. For example, if we type <kbd class="userinput">make foo</kbd> with the makefile
above, make will ignore the <tt class="maketarget">install</tt> target.</p>

<p>If we just type <kbd class="userinput">make</kbd> on its own, make will always look at
the first target and then stop without looking at any others. So if we typed <kbd class="userinput">make</kbd> here, it will just go to the <tt class="maketarget">foo</tt>
target, re-compile <tt class="filename">foo</tt> if necessary, and then stop without
going on to the <tt class="maketarget">install</tt> target.</p>

<p>Notice that the <tt class="maketarget">install</tt> target does not actually depend on
anything! This means that the command on the following line is always executed when we
try to make that target by typing <kbd class="userinput">make install</kbd>. In this
case, it will copy <tt class="filename">foo</tt> into the user's home directory. This is
often used by application makefiles, so that the application can be installed in the
correct directory when it has been correctly compiled.</p>

<p>This is a slightly confusing subject to try to explain. If you do not quite understand
how <tt class="command">make</tt> works, the best thing to do is to write a simple
program like ``hello world'' and a make file like the one above and experiment. Then
progress to using more than one source file, or having the source file include a header
file. The <tt class="command">touch</tt> command is very useful here--it changes the date
on a file without you having to edit it.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.5.3 Make and include-files" id="AEN800">
			<div class="sect3">
				<h3 class="title">2.5.3 Make and include-files</h3>

<p>C code often starts with a list of files to include, for example stdio.h. Some of
these files are system-include files, some of them are from the project you are now
working on:</p>


		<pkg:outlineMarker OutlineName="code_11" id="code_11" visible="false" copy="true">
				<pre class="programlisting">#include &#60;stdio.h&#62;
#include "foo.h"

int main(....
</pre>
		</pkg:outlineMarker>


<p>To make sure that this file is recompiled the moment <tt class="filename">foo.h</tt>
is changed, you have to add it in your <tt class="filename">Makefile</tt>:</p>


		<pkg:outlineMarker OutlineName="code_12" id="code_12" visible="false" copy="true">
				<pre class="programlisting">foo: foo.c foo.h
</pre>
		</pkg:outlineMarker>


<p>The moment your project is getting bigger and you have more and more own include-files
to maintain, it will be a pain to keep track of all include files and the files which are
depending on it. If you change an include-file but forget to recompile all the files
which are depending on it, the results will be devastating. <tt class="command">gcc</tt>
has an option to analyze your files and to produce a list of include-files and their
dependencies: <var class="option">-MM</var>.</p>

<p>If you add this to your Makefile:</p>


		<pkg:outlineMarker OutlineName="code_13" id="code_13" visible="false" copy="true">
				<pre class="programlisting">depend:
    gcc -E -MM *.c &#62; .depend
</pre>
		</pkg:outlineMarker>


<p>and run <kbd class="userinput">make depend</kbd>, the file <tt class="filename">.depend</tt> will appear with a list of object-files, C-files and the
include-files:</p>


		<pkg:outlineMarker OutlineName="code_14" id="code_14" visible="false" copy="true">
				<pre class="programlisting">foo.o: foo.c foo.h
</pre>
		</pkg:outlineMarker>


<p>If you change <tt class="filename">foo.h</tt>, next time you run <tt class="command">make</tt> all files depending on <tt class="filename">foo.h</tt> will be
recompiled.</p>

<p>Do not forget to run <tt class="command">make depend</tt> each time you add an
include-file to one of your files.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.5.4 FreeBSD Makefiles" id="AEN823">
			<div class="sect3">
				<h3 class="title">2.5.4 FreeBSD Makefiles</h3>

<p>Makefiles can be rather complicated to write. Fortunately, BSD-based systems like
FreeBSD come with some very powerful ones as part of the system. One very good example of
this is the FreeBSD ports system. Here is the essential part of a typical ports <tt class="filename">Makefile</tt>:</p>


		<pkg:outlineMarker OutlineName="code_15" id="code_15" visible="false" copy="true">
				<pre class="programlisting">MASTER_SITES=   ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/
DISTFILES=      scheme-microcode+dist-7.3-freebsd.tgz

.include &#60;bsd.port.mk&#62;
</pre>
		</pkg:outlineMarker>


<p>Now, if we go to the directory for this port and type <kbd class="userinput">make</kbd>, the following happens:</p>


<ol type="1">
<li>
<p>A check is made to see if the source code for this port is already on the system.</p>
</li>

<li>
<p>If it is not, an FTP connection to the URL in <var class="symbol">MASTER_SITES</var>
is set up to download the source.</p>
</li>

<li>
<p>The checksum for the source is calculated and compared it with one for a known, good,
copy of the source. This is to make sure that the source was not corrupted while in
transit.</p>
</li>

<li>
<p>Any changes required to make the source work on FreeBSD are applied--this is known as
<i class="firstterm">patching</i>.</p>
</li>

<li>
<p>Any special configuration needed for the source is done. (Many <span class="trademark">UNIX</span> program distributions try to work out which version of
<span class="trademark">UNIX</span> they are being compiled on and which optional <span class="trademark">UNIX</span> features are present--this is where they are given the
information in the FreeBSD ports scenario).</p>
</li>

<li>
<p>The source code for the program is compiled. In effect, we change to the directory
where the source was unpacked and do <tt class="command">make</tt>--the program's own
make file has the necessary information to build the program.</p>
</li>

<li>
<p>We now have a compiled version of the program. If we wish, we can test it now; when we
feel confident about the program, we can type <kbd class="userinput">make install</kbd>.
This will cause the program and any supporting files it needs to be copied into the
correct location; an entry is also made into a <span class="database">package
database</span>, so that the port can easily be uninstalled later if we change our mind
about it.</p>
</li>
</ol>


<p>Now I think you will agree that is rather impressive for a four line script!</p>

<p>The secret lies in the last line, which tells <tt class="command">make</tt> to look in
the system makefile called <tt class="filename">bsd.port.mk</tt>. It is easy to overlook
this line, but this is where all the clever stuff comes from--someone has written a
makefile that tells <tt class="command">make</tt> to do all the things above (plus a
couple of other things I did not mention, including handling any errors that may occur)
and anyone can get access to that just by putting a single line in their own make
file!</p>

<p>If you want to have a look at these system makefiles, they are in <tt class="filename">/usr/share/mk</tt>, but it is probably best to wait until you have had a
bit of practice with makefiles, as they are very complicated (and if you do look at them,
make sure you have a flask of strong coffee handy!)</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.5.5 More advanced uses of make" id="AEN860">
			<div class="sect3">
				<h3 class="title">2.5.5 More advanced uses of <tt class="command">make</tt></h3>

<p><tt class="command">Make</tt> is a very powerful tool, and can do much more than the
simple example above shows. Unfortunately, there are several different versions of <tt class="command">make</tt>, and they all differ considerably. The best way to learn what
they can do is probably to read the documentation--hopefully this introduction will have
given you a base from which you can do this.</p>

<p>The version of make that comes with FreeBSD is the <b class="application">Berkeley
make</b>; there is a tutorial for it in <tt class="filename">/usr/share/doc/psd/12.make</tt>. To view it, do</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">zmore paper.ascii.gz</kbd>
</pre>

<p>in that directory.</p>

<p>Many applications in the ports use <b class="application">GNU make</b>, which has a
very good set of ``info'' pages. If you have installed any of these ports, <b class="application">GNU make</b> will automatically have been installed as <tt class="command">gmake</tt>. It is also available as a port and package in its own
right.</p>

<p>To view the info pages for <b class="application">GNU make</b>, you will have to edit
the <tt class="filename">dir</tt> file in the <tt class="filename">/usr/local/info</tt>
directory to add an entry for it. This involves adding a line like</p>


		<pkg:outlineMarker OutlineName="code_16" id="code_16" visible="false" copy="true">
				<pre class="programlisting"> * Make: (make).                 The GNU Make utility.
</pre>
		</pkg:outlineMarker>


<p>to the file. Once you have done this, you can type <kbd class="userinput">info</kbd>
and then select <span class="guimenuitem">make</span> from the menu (or in <b class="application">Emacs</b>, do <kbd class="userinput">C-h i</kbd>).</p>




<hr />

		</div>
	</pkg:outlineMarker>

	
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="2.6 Debugging" id="DEBUGGING">
		<div class="sect2">
			<h2 class="title">2.6 Debugging</h2>



		<pkg:outlineMarker OutlineName="2.6.1 The Debugger" id="AEN890">
			<div class="sect3">
				<h3 class="title">2.6.1 The Debugger</h3>

<p>The debugger that comes with FreeBSD is called <tt class="command">gdb</tt> (<b class="application">GNU debugger</b>). You start it up by typing</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">gdb <var class="replaceable">progname</var></kbd>
</pre>

<p>although most people prefer to run it inside <b class="application">Emacs</b>. You can
do this by:</p>

<pre class="screen"><kbd class="userinput">M-x gdb RET <var class="replaceable">progname</var> RET</kbd>
</pre>

<p>Using a debugger allows you to run the program under more controlled circumstances.
Typically, you can step through the program a line at a time, inspect the value of
variables, change them, tell the debugger to run up to a certain point and then stop, and
so on. You can even attach to a program that is already running, or load a core file to
investigate why the program crashed. It is even possible to debug the kernel, though that
is a little trickier than the user applications we will be discussing in this
section.</p>

<p><tt class="command">gdb</tt> has quite good on-line help, as well as a set of info
pages, so this section will concentrate on a few of the basic commands.</p>

<p>Finally, if you find its text-based command-prompt style off-putting, there is a
graphical front-end for it (<a href="http://www.freebsd.org/ports/devel.html" target="_top">xxgdb</a>) in the ports collection.</p>

<p>This section is intended to be an introduction to using <tt class="command">gdb</tt>
and does not cover specialized topics such as debugging the kernel.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.6.2 Running a program in the debugger" id="AEN911">
			<div class="sect3">
				<h3 class="title">2.6.2 Running a program in the
debugger</h3>

<p>You will need to have compiled the program with the <var class="option">-g</var>
option to get the most out of using <tt class="command">gdb</tt>. It will work without,
but you will only see the name of the function you are in, instead of the source code. If
you see a line like:</p>

<pre class="screen">... (no debugging symbols found) ...
</pre>

<p>when <tt class="command">gdb</tt> starts up, you will know that the program was not
compiled with the <var class="option">-g</var> option.</p>

<p>At the <tt class="command">gdb</tt> prompt, type <kbd class="userinput">break
main</kbd>. This will tell the debugger to skip over the preliminary set-up code in the
program and start at the beginning of your code. Now type <kbd class="userinput">run</kbd> to start the program--it will start at the beginning of the
set-up code and then get stopped by the debugger when it calls <code class="function">main()</code>. (If you have ever wondered where <code class="function">main()</code> gets called from, now you know!).</p>

<p>You can now step through the program, a line at a time, by pressing <tt class="command">n</tt>. If you get to a function call, you can step into it by pressing
<tt class="command">s</tt>. Once you are in a function call, you can return from stepping
into a function call by pressing <tt class="command">f</tt>. You can also use <tt class="command">up</tt> and <tt class="command">down</tt> to take a quick look at the
caller.</p>

<p>Here is a simple example of how to spot a mistake in a program with <tt class="command">gdb</tt>. This is our program (with a deliberate mistake):</p>


		<pkg:outlineMarker OutlineName="code_17" id="code_17" visible="false" copy="true">
				<pre class="programlisting">#include &#60;stdio.h&#62;

int bazz(int anint);

main() {
    int i;

    printf("This is my program\n");
    bazz(i);
    return 0;
}

int bazz(int anint) {
    printf("You gave me %d\n", anint);
    return anint;
}
</pre>
		</pkg:outlineMarker>


<p>This program sets <var class="symbol">i</var> to be <var class="literal">5</var> and
passes it to a function <code class="function">bazz()</code> which prints out the number
we gave it.</p>

<p>When we compile and run the program we get</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc -g -o temp temp.c</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">./temp</kbd>
This is my program
anint = 4231
</pre>

<p>That was not what we expected! Time to see what is going on!</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">gdb temp</kbd>
GDB is free software and you are welcome to distribute copies of it
 under certain conditions; type "show copying" to see the conditions.
There is absolutely no warranty for GDB; type "show warranty" for details.
GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.
(gdb) <kbd class="userinput">break main</kbd>               Skip the set-up code
Breakpoint 1 at 0x160f: file temp.c, line 9.    <tt class="command">gdb</tt> puts breakpoint at <code class="function">main()</code>
(gdb) <kbd class="userinput">run</kbd>                   Run as far as <code class="function">main()</code>
Starting program: /home/james/tmp/temp      Program starts running

Breakpoint 1, main () at temp.c:9       <tt class="command">gdb</tt> stops at <code class="function">main()</code>
(gdb) <kbd class="userinput">n</kbd>                       Go to next line
This is my program              Program prints out
(gdb) <kbd class="userinput">s</kbd>                       step into <code class="function">bazz()</code>
bazz (anint=4231) at temp.c:17          <tt class="command">gdb</tt> displays stack frame
(gdb)
</pre>

<p>Hang on a minute! How did <var class="symbol">anint</var> get to be <var class="literal">4231</var>? Did we not we set it to be <var class="literal">5</var> in
<code class="function">main()</code>? Let's move up to <code class="function">main()</code> and have a look.</p>

<pre class="screen">(gdb) <kbd class="userinput">up</kbd>                   Move up call stack
#1  0x1625 in main () at temp.c:11      <tt class="command">gdb</tt> displays stack frame
(gdb) <kbd class="userinput">p i</kbd>                   Show us the value of <var class="symbol">i</var>
$1 = 4231                   <tt class="command">gdb</tt> displays <var class="literal">4231</var>
</pre>

<p>Oh dear! Looking at the code, we forgot to initialize <var class="symbol">i</var>. We
meant to put</p>


		<pkg:outlineMarker OutlineName="code_18" id="code_18" visible="false" copy="true">
				<pre class="programlisting">...
main() {
    int i;

    i = 5;
    printf("This is my program\n");
...
</pre>
		</pkg:outlineMarker>


<p>but we left the <var class="literal">i=5;</var> line out. As we did not initialize
<var class="symbol">i</var>, it had whatever number happened to be in that area of memory
when the program ran, which in this case happened to be <var class="literal">4231</var>.</p>


<blockquote class="note">
<p><b>Note:</b> <tt class="command">gdb</tt> displays the stack frame every time we go
into or out of a function, even if we are using <tt class="command">up</tt> and <tt class="command">down</tt> to move around the call stack. This shows the name of the
function and the values of its arguments, which helps us keep track of where we are and
what is going on. (The stack is a storage area where the program stores information about
the arguments passed to functions and where to go when it returns from a function
call).</p>
</blockquote>




<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.6.3 Examining a core file" id="AEN1000">
			<div class="sect3">
				<h3 class="title">2.6.3 Examining a core file</h3>

<p>A core file is basically a file which contains the complete state of the process when
it crashed. In ``the good old days'', programmers had to print out hex listings of core
files and sweat over machine code manuals, but now life is a bit easier. Incidentally,
under FreeBSD and other 4.4BSD systems, a core file is called <tt class="filename"><var class="replaceable">progname</var>.core</tt> instead of just <tt class="filename">core</tt>, to make it clearer which program a core file belongs to.</p>

<p>To examine a core file, start up <tt class="command">gdb</tt> in the usual way.
Instead of typing <tt class="command">break</tt> or <tt class="command">run</tt>,
type</p>

<pre class="screen">(gdb) <kbd class="userinput">core <var class="replaceable">progname</var>.core</kbd>
</pre>

<p>If you are not in the same directory as the core file, you will have to do <kbd class="userinput">dir /path/to/core/file</kbd> first.</p>

<p>You should see something like this:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">gdb a.out</kbd>
GDB is free software and you are welcome to distribute copies of it
 under certain conditions; type "show copying" to see the conditions.
There is absolutely no warranty for GDB; type "show warranty" for details.
GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.
(gdb) <kbd class="userinput">core a.out.core</kbd>
Core was generated by `a.out'.
Program terminated with signal 11, Segmentation fault.
Cannot access memory at address 0x7020796d.
#0  0x164a in bazz (anint=0x5) at temp.c:17
(gdb)
</pre>

<p>In this case, the program was called <tt class="filename">a.out</tt>, so the core file
is called <tt class="filename">a.out.core</tt>. We can see that the program crashed due
to trying to access an area in memory that was not available to it in a function called
<code class="function">bazz</code>.</p>

<p>Sometimes it is useful to be able to see how a function was called, as the problem
could have occurred a long way up the call stack in a complex program. The <tt class="command">bt</tt> command causes <tt class="command">gdb</tt> to print out a
back-trace of the call stack:</p>

<pre class="screen">(gdb) <kbd class="userinput">bt</kbd>
#0  0x164a in bazz (anint=0x5) at temp.c:17
#1  0xefbfd888 in end ()
#2  0x162c in main () at temp.c:11
(gdb)
</pre>

<p>The <code class="function">end()</code> function is called when a program crashes; in
this case, the <code class="function">bazz()</code> function was called from <code class="function">main()</code>.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.6.4 Attaching to a running program" id="AEN1034">
			<div class="sect3">
				<h3 class="title">2.6.4 Attaching to a running
program</h3>

<p>One of the neatest features about <tt class="command">gdb</tt> is that it can attach
to a program that is already running. Of course, that assumes you have sufficient
permissions to do so. A common problem is when you are stepping through a program that
forks, and you want to trace the child, but the debugger will only let you trace the
parent.</p>

<p>What you do is start up another <tt class="command">gdb</tt>, use <tt class="command">ps</tt> to find the process ID for the child, and do</p>

<pre class="screen">(gdb) <kbd class="userinput">attach <var class="replaceable">pid</var></kbd>
</pre>

<p>in <tt class="command">gdb</tt>, and then debug as usual.</p>

<p>``That is all very well,'' you are probably thinking, ``but by the time I have done
that, the child process will be over the hill and far away''. Fear not, gentle reader,
here is how to do it (courtesy of the <tt class="command">gdb</tt> info pages):</p>

<pre class="screen">...
if ((pid = fork()) &#60; 0)     /* _Always_ check this */
    error();
else if (pid == 0) {        /* child */
    int PauseMode = 1;

    while (PauseMode)
        sleep(10);  /* Wait until someone attaches to us */
    ...
} else {            /* parent */
    ...
</pre>

<p>Now all you have to do is attach to the child, set <var class="symbol">PauseMode</var>
to <var class="literal">0</var>, and wait for the <code class="function">sleep()</code>
call to return!</p>




<hr />

		</div>
	</pkg:outlineMarker>

	
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="2.7 Using Emacs as a Development Environment" id="EMACS">
		<div class="sect2">
			<h2 class="title">2.7 Using Emacs as a Development
Environment</h2>



		<pkg:outlineMarker OutlineName="2.7.1 Emacs" id="AEN1060">
			<div class="sect3">
				<h3 class="title">2.7.1 Emacs</h3>

<p>Unfortunately, <span class="trademark">UNIX</span> systems do not come with the kind
of everything-you-ever-wanted-and-lots-more-you-did-not-in-one-gigantic-package
integrated development environments that other systems have. <a name="AEN1064" href="pkg://FreeBSD Developers' Handbook/FTNAEN1064"><span class="footnote">[7]</span></a> However, it is
possible to set up your own environment. It may not be as pretty, and it may not be quite
as integrated, but you can set it up the way you want it. And it is free. And you have
the source to it.</p>

<p>The key to it all is Emacs. Now there are some people who loathe it, but many who love
it. If you are one of the former, I am afraid this section will hold little of interest
to you. Also, you will need a fair amount of memory to run it--I would recommend 8MB in
text mode and 16MB in X as the bare minimum to get reasonable performance.</p>

<p>Emacs is basically a highly customizable editor--indeed, it has been customized to the
point where it is more like an operating system than an editor! Many developers and
sysadmins do in fact spend practically all their time working inside Emacs, leaving it
only to log out.</p>

<p>It is impossible even to summarize everything Emacs can do here, but here are some of
the features of interest to developers:</p>

<ul>
<li>
<p>Very powerful editor, allowing search-and-replace on both strings and regular
expressions (patterns), jumping to start/end of block expression, etc, etc.</p>
</li>

<li>
<p>Pull-down menus and online help.</p>
</li>

<li>
<p>Language-dependent syntax highlighting and indentation.</p>
</li>

<li>
<p>Completely customizable.</p>
</li>

<li>
<p>You can compile and debug programs within Emacs.</p>
</li>

<li>
<p>On a compilation error, you can jump to the offending line of source code.</p>
</li>

<li>
<p>Friendly-ish front-end to the <tt class="command">info</tt> program used for reading
GNU hypertext documentation, including the documentation on Emacs itself.</p>
</li>

<li>
<p>Friendly front-end to <tt class="command">gdb</tt>, allowing you to look at the source
code as you step through your program.</p>
</li>

<li>
<p>You can read Usenet news and mail while your program is compiling.</p>
</li>
</ul>

<p>And doubtless many more that I have overlooked.</p>

<p>Emacs can be installed on FreeBSD using <a href="http://www.freebsd.org/ports/editors.html" target="_top">the Emacs port</a>.</p>

<p>Once it is installed, start it up and do <kbd class="userinput">C-h t</kbd> to read an
Emacs tutorial--that means hold down the <b class="keycap">control</b> key, press <b class="keycap">h</b>, let go of the <b class="keycap">control</b> key, and then press <b class="keycap">t</b>. (Alternatively, you can you use the mouse to select <span class="guimenuitem">Emacs Tutorial</span> from the <span class="guimenu">Help</span>
menu).</p>

<p>Although Emacs does have menus, it is well worth learning the key bindings, as it is
much quicker when you are editing something to press a couple of keys than to try to find
the mouse and then click on the right place. And, when you are talking to seasoned Emacs
users, you will find they often casually throw around expressions like ``<var class="literal">M-x replace-s RET foo RET bar RET</var>'' so it is useful to know what
they mean. And in any case, Emacs has far too many useful functions for them to all fit
on the menu bars.</p>

<p>Fortunately, it is quite easy to pick up the key-bindings, as they are displayed next
to the menu item. My advice is to use the menu item for, say, opening a file until you
understand how it works and feel confident with it, then try doing C-x C-f. When you are
happy with that, move on to another menu command.</p>

<p>If you can not remember what a particular combination of keys does, select <span class="guimenuitem">Describe Key</span> from the <span class="guimenu">Help</span> menu
and type it in--Emacs will tell you what it does. You can also use the <span class="guimenuitem">Command Apropos</span> menu item to find out all the commands which
contain a particular word in them, with the key binding next to it.</p>

<p>By the way, the expression above means hold down the <span class="keysym">Meta</span>
key, press <span class="keysym">x</span>, release the <span class="keysym">Meta</span>
key, type <kbd class="userinput">replace-s</kbd> (short for <var class="literal">replace-string</var>--another feature of Emacs is that you can abbreviate
commands), press the <span class="keysym">return</span> key, type <kbd class="userinput">foo</kbd> (the string you want replaced), press the <span class="keysym">return</span> key, type bar (the string you want to replace <var class="literal">foo</var> with) and press <span class="keysym">return</span> again. Emacs
will then do the search-and-replace operation you have just requested.</p>

<p>If you are wondering what on earth the <span class="keysym">Meta</span> key is, it is
a special key that many <span class="trademark">UNIX</span> workstations have.
Unfortunately, PC's do not have one, so it is usually the <b class="keycap">alt</b> key
(or if you are unlucky, the <span class="keysym">escape</span> key).</p>

<p>Oh, and to get out of Emacs, do <tt class="command">C-x C-c</tt> (that means hold down
the <span class="keysym">control</span> key, press <span class="keysym">x</span>, press
<span class="keysym">c</span> and release the <span class="keysym">control</span> key).
If you have any unsaved files open, Emacs will ask you if you want to save them. (Ignore
the bit in the documentation where it says <tt class="command">C-z</tt> is the usual way
to leave Emacs--that leaves Emacs hanging around in the background, and is only really
useful if you are on a system which does not have virtual terminals).</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.7.2 Configuring Emacs" id="AEN1132">
			<div class="sect3">
				<h3 class="title">2.7.2 Configuring Emacs</h3>

<p>Emacs does many wonderful things; some of them are built in, some of them need to be
configured.</p>

<p>Instead of using a proprietary macro language for configuration, Emacs uses a version
of Lisp specially adapted for editors, known as Emacs Lisp. Working with Emacs Lisp can
be quite helpful if you want to go on and learn something like Common Lisp. Emacs Lisp
has many features of Common Lisp, although it is considerably smaller (and thus easier to
master).</p>

<p>The best way to learn Emacs Lisp is to download the <a href="ftp://ftp.gnu.org/old-gnu/emacs/elisp-manual-19-2.4.tar.gz" target="_top">Emacs
Tutorial</a></p>

<p>However, there is no need to actually know any Lisp to get started with configuring
Emacs, as I have included a sample <tt class="filename">.emacs</tt> file, which should be
enough to get you started. Just copy it into your home directory and restart Emacs if it
is already running; it will read the commands from the file and (hopefully) give you a
useful basic setup.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.7.3 A sample .emacs file" id="AEN1140">
			<div class="sect3">
				<h3 class="title">2.7.3 A sample <tt class="filename">.emacs</tt> file</h3>

<p>Unfortunately, there is far too much here to explain it in detail; however there are
one or two points worth mentioning.</p>

<ul>
<li>
<p>Everything beginning with a <var class="literal">;</var> is a comment and is ignored
by Emacs.</p>
</li>

<li>
<p>In the first line, the <var class="literal">-*-&#160;Emacs-Lisp&#160;-*-</var> is so
that we can edit the <tt class="filename">.emacs</tt> file itself within Emacs and get
all the fancy features for editing Emacs Lisp. Emacs usually tries to guess this based on
the filename, and may not get it right for <tt class="filename">.emacs</tt>.</p>
</li>

<li>
<p>The <span class="keysym">tab</span> key is bound to an indentation function in some
modes, so when you press the tab key, it will indent the current line of code. If you
want to put a <span class="token">tab</span> character in whatever you are writing, hold
the <span class="keysym">control</span> key down while you are pressing the <span class="keysym">tab</span> key.</p>
</li>

<li>
<p>This file supports syntax highlighting for C, C++, Perl, Lisp and Scheme, by guessing
the language from the filename.</p>
</li>

<li>
<p>Emacs already has a pre-defined function called <code class="function">next-error</code>. In a compilation output window, this allows you to
move from one compilation error to the next by doing <tt class="command">M-n</tt>; we
define a complementary function, <code class="function">previous-error</code>, that
allows you to go to a previous error by doing <tt class="command">M-p</tt>. The nicest
feature of all is that <tt class="command">C-c C-c</tt> will open up the source file in
which the error occurred and jump to the appropriate line.</p>
</li>

<li>
<p>We enable Emacs's ability to act as a server, so that if you are doing something
outside Emacs and you want to edit a file, you can just type in</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">emacsclient <var class="replaceable">filename</var></kbd>
     
</pre>

<p>and then you can edit the file in your Emacs! <a name="AEN1175" href="pkg://FreeBSD Developers' Handbook/FTNAEN1175"><span class="footnote">[8]</span></a></p>
</li>
</ul>

<a name="AEN1179"></a>
<p><b>Example 2-1. A sample <tt class="filename">.emacs</tt> file</b></p>


		<pkg:outlineMarker OutlineName="code_19" id="code_19" visible="false" copy="true">
				<pre class="programlisting">;; -*-Emacs-Lisp-*-

;; This file is designed to be re-evaled; use the variable first-time
;; to avoid any problems with this.
(defvar first-time t
  "Flag signifying this is the first time that .emacs has been evaled")

;; Meta
(global-set-key "\M- " 'set-mark-command)
(global-set-key "\M-\C-h" 'backward-kill-word)
(global-set-key "\M-\C-r" 'query-replace)
(global-set-key "\M-r" 'replace-string)
(global-set-key "\M-g" 'goto-line)
(global-set-key "\M-h" 'help-command)

;; Function keys
(global-set-key [f1] 'manual-entry)
(global-set-key [f2] 'info)
(global-set-key [f3] 'repeat-complex-command)
(global-set-key [f4] 'advertised-undo)
(global-set-key [f5] 'eval-current-buffer)
(global-set-key [f6] 'buffer-menu)
(global-set-key [f7] 'other-window)
(global-set-key [f8] 'find-file)
(global-set-key [f9] 'save-buffer)
(global-set-key [f10] 'next-error)
(global-set-key [f11] 'compile)
(global-set-key [f12] 'grep)
(global-set-key [C-f1] 'compile)
(global-set-key [C-f2] 'grep)
(global-set-key [C-f3] 'next-error)
(global-set-key [C-f4] 'previous-error)
(global-set-key [C-f5] 'display-faces)
(global-set-key [C-f8] 'dired)
(global-set-key [C-f10] 'kill-compilation)

;; Keypad bindings
(global-set-key [up] "\C-p")
(global-set-key [down] "\C-n")
(global-set-key [left] "\C-b")
(global-set-key [right] "\C-f")
(global-set-key [home] "\C-a")
(global-set-key [end] "\C-e")
(global-set-key [prior] "\M-v")
(global-set-key [next] "\C-v")
(global-set-key [C-up] "\M-\C-b")
(global-set-key [C-down] "\M-\C-f")
(global-set-key [C-left] "\M-b")
(global-set-key [C-right] "\M-f")
(global-set-key [C-home] "\M-&#60;")
(global-set-key [C-end] "\M-&#62;")
(global-set-key [C-prior] "\M-&#60;")
(global-set-key [C-next] "\M-&#62;")

;; Mouse
(global-set-key [mouse-3] 'imenu)

;; Misc
(global-set-key [C-tab] "\C-q\t")   ; Control tab quotes a tab.
(setq backup-by-copying-when-mismatch t)

;; Treat 'y' or &#60;CR&#62; as yes, 'n' as no.
(fset 'yes-or-no-p 'y-or-n-p)
(define-key query-replace-map [return] 'act)
(define-key query-replace-map [?\C-m] 'act)

;; Load packages
(require 'desktop)
(require 'tar-mode)

;; Pretty diff mode
(autoload 'ediff-buffers "ediff" "Intelligent Emacs interface to diff" t)
(autoload 'ediff-files "ediff" "Intelligent Emacs interface to diff" t)
(autoload 'ediff-files-remote "ediff"
  "Intelligent Emacs interface to diff")

(if first-time
    (setq auto-mode-alist
      (append '(("\\.cpp$" . c++-mode)
            ("\\.hpp$" . c++-mode)
            ("\\.lsp$" . lisp-mode)
            ("\\.scm$" . scheme-mode)
            ("\\.pl$" . perl-mode)
            ) auto-mode-alist)))

;; Auto font lock mode
(defvar font-lock-auto-mode-list
  (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'lisp-mode 'perl-mode 'scheme-mode)
  "List of modes to always start in font-lock-mode")

(defvar font-lock-mode-keyword-alist
  '((c++-c-mode . c-font-lock-keywords)
    (perl-mode . perl-font-lock-keywords))
  "Associations between modes and keywords")

(defun font-lock-auto-mode-select ()
  "Automatically select font-lock-mode if the current major mode is in font-lock-auto-mode-list"
  (if (memq major-mode font-lock-auto-mode-list)
      (progn
    (font-lock-mode t))
    )
  )

(global-set-key [M-f1] 'font-lock-fontify-buffer)

;; New dabbrev stuff
;(require 'new-dabbrev)
(setq dabbrev-always-check-other-buffers t)
(setq dabbrev-abbrev-char-regexp "\\sw\\|\\s_")
(add-hook 'emacs-lisp-mode-hook
      '(lambda ()
         (set (make-local-variable 'dabbrev-case-fold-search) nil)
         (set (make-local-variable 'dabbrev-case-replace) nil)))
(add-hook 'c-mode-hook
      '(lambda ()
         (set (make-local-variable 'dabbrev-case-fold-search) nil)
         (set (make-local-variable 'dabbrev-case-replace) nil)))
(add-hook 'text-mode-hook
      '(lambda ()
         (set (make-local-variable 'dabbrev-case-fold-search) t)
         (set (make-local-variable 'dabbrev-case-replace) t)))

;; C++ and C mode...
(defun my-c++-mode-hook ()
  (setq tab-width 4)
  (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent)
  (define-key c++-mode-map "\C-ce" 'c-comment-edit)
  (setq c++-auto-hungry-initial-state 'none)
  (setq c++-delete-function 'backward-delete-char)
  (setq c++-tab-always-indent t)
  (setq c-indent-level 4)
  (setq c-continued-statement-offset 4)
  (setq c++-empty-arglist-indent 4))

(defun my-c-mode-hook ()
  (setq tab-width 4)
  (define-key c-mode-map "\C-m" 'reindent-then-newline-and-indent)
  (define-key c-mode-map "\C-ce" 'c-comment-edit)
  (setq c-auto-hungry-initial-state 'none)
  (setq c-delete-function 'backward-delete-char)
  (setq c-tab-always-indent t)
;; BSD-ish indentation style
  (setq c-indent-level 4)
  (setq c-continued-statement-offset 4)
  (setq c-brace-offset -4)
  (setq c-argdecl-indent 0)
  (setq c-label-offset -4))

;; Perl mode
(defun my-perl-mode-hook ()
  (setq tab-width 4)
  (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent)
  (setq perl-indent-level 4)
  (setq perl-continued-statement-offset 4))

;; Scheme mode...
(defun my-scheme-mode-hook ()
  (define-key scheme-mode-map "\C-m" 'reindent-then-newline-and-indent))

;; Emacs-Lisp mode...
(defun my-lisp-mode-hook ()
  (define-key lisp-mode-map "\C-m" 'reindent-then-newline-and-indent)
  (define-key lisp-mode-map "\C-i" 'lisp-indent-line)
  (define-key lisp-mode-map "\C-j" 'eval-print-last-sexp))

;; Add all of the hooks...
(add-hook 'c++-mode-hook 'my-c++-mode-hook)
(add-hook 'c-mode-hook 'my-c-mode-hook)
(add-hook 'scheme-mode-hook 'my-scheme-mode-hook)
(add-hook 'emacs-lisp-mode-hook 'my-lisp-mode-hook)
(add-hook 'lisp-mode-hook 'my-lisp-mode-hook)
(add-hook 'perl-mode-hook 'my-perl-mode-hook)

;; Complement to next-error
(defun previous-error (n)
  "Visit previous compilation error message and corresponding source code."
  (interactive "p")
  (next-error (- n)))

;; Misc...
(transient-mark-mode 1)
(setq mark-even-if-inactive t)
(setq visible-bell nil)
(setq next-line-add-newlines nil)
(setq compile-command "make")
(setq suggest-key-bindings nil)
(put 'eval-expression 'disabled nil)
(put 'narrow-to-region 'disabled nil)
(put 'set-goal-column 'disabled nil)
(if (&#62;= emacs-major-version 21)
    (setq show-trailing-whitespace t))

;; Elisp archive searching
(autoload 'format-lisp-code-directory "lispdir" nil t)
(autoload 'lisp-dir-apropos "lispdir" nil t)
(autoload 'lisp-dir-retrieve "lispdir" nil t)
(autoload 'lisp-dir-verify "lispdir" nil t)

;; Font lock mode
(defun my-make-face (face color &#38;optional bold)
  "Create a face from a color and optionally make it bold"
  (make-face face)
  (copy-face 'default face)
  (set-face-foreground face color)
  (if bold (make-face-bold face))
  )

(if (eq window-system 'x)
    (progn
      (my-make-face 'blue "blue")
      (my-make-face 'red "red")
      (my-make-face 'green "dark green")
      (setq font-lock-comment-face 'blue)
      (setq font-lock-string-face 'bold)
      (setq font-lock-type-face 'bold)
      (setq font-lock-keyword-face 'bold)
      (setq font-lock-function-name-face 'red)
      (setq font-lock-doc-string-face 'green)
      (add-hook 'find-file-hooks 'font-lock-auto-mode-select)

      (setq baud-rate 1000000)
      (global-set-key "\C-cmm" 'menu-bar-mode)
      (global-set-key "\C-cms" 'scroll-bar-mode)
      (global-set-key [backspace] 'backward-delete-char)
                    ;      (global-set-key [delete] 'delete-char)
      (standard-display-european t)
      (load-library "iso-transl")))

;; X11 or PC using direct screen writes
(if window-system
    (progn
      ;;      (global-set-key [M-f1] 'hilit-repaint-command)
      ;;      (global-set-key [M-f2] [?\C-u M-f1])
      (setq hilit-mode-enable-list
        '(not text-mode c-mode c++-mode emacs-lisp-mode lisp-mode
          scheme-mode)
        hilit-auto-highlight nil
        hilit-auto-rehighlight 'visible
        hilit-inhibit-hooks nil
        hilit-inhibit-rebinding t)
      (require 'hilit19)
      (require 'paren))
  (setq baud-rate 2400)         ; For slow serial connections
  )

;; TTY type terminal
(if (and (not window-system)
     (not (equal system-type 'ms-dos)))
    (progn
      (if first-time
      (progn
        (keyboard-translate ?\C-h ?\C-?)
        (keyboard-translate ?\C-? ?\C-h)))))

;; Under UNIX
(if (not (equal system-type 'ms-dos))
    (progn
      (if first-time
      (server-start))))

;; Add any face changes here
(add-hook 'term-setup-hook 'my-term-setup-hook)
(defun my-term-setup-hook ()
  (if (eq window-system 'pc)
      (progn
;;  (set-face-background 'default "red")
    )))

;; Restore the "desktop" - do this as late as possible
(if first-time
    (progn
      (desktop-load-default)
      (desktop-read)))

;; Indicate that this file has been read at least once
(setq first-time nil)

;; No need to debug anything now

(setq debug-on-error nil)

;; All done
(message "All done, %s%s" (user-login-name) ".")
   
</pre>
		</pkg:outlineMarker>





<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="2.7.4 Extending the Range of Languages Emacs Understands" id="AEN1183">
			<div class="sect3">
				<h3 class="title">2.7.4 Extending the Range of Languages
Emacs Understands</h3>

<p>Now, this is all very well if you only want to program in the languages already
catered for in the <tt class="filename">.emacs</tt> file (C, C++, Perl, Lisp and Scheme),
but what happens if a new language called ``whizbang'' comes out, full of exciting
features?</p>

<p>The first thing to do is find out if whizbang comes with any files that tell Emacs
about the language. These usually end in <tt class="filename">.el</tt>, short for ``Emacs
Lisp''. For example, if whizbang is a FreeBSD port, we can locate these files by
doing</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">find /usr/ports/lang/whizbang -name "*.el" -print</kbd>
</pre>

<p>and install them by copying them into the Emacs site Lisp directory. On FreeBSD
2.1.0-RELEASE, this is <tt class="filename">/usr/local/share/emacs/site-lisp</tt>.</p>

<p>So for example, if the output from the find command was</p>

<pre class="screen">/usr/ports/lang/whizbang/work/misc/whizbang.el
</pre>

<p>we would do</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/share/emacs/site-lisp</kbd>
</pre>

<p>Next, we need to decide what extension whizbang source files have. Let's say for the
sake of argument that they all end in <tt class="filename">.wiz</tt>. We need to add an
entry to our <tt class="filename">.emacs</tt> file to make sure Emacs will be able to use
the information in <tt class="filename">whizbang.el</tt>.</p>

<p>Find the <var class="symbol">auto-mode-alist entry</var> in <tt class="filename">.emacs</tt> and add a line for whizbang, such as:</p>


		<pkg:outlineMarker OutlineName="code_20" id="code_20" visible="false" copy="true">
				<pre class="programlisting">...
("\\.lsp$" . lisp-mode)
("\\.wiz$" . whizbang-mode)
("\\.scm$" . scheme-mode)
...
</pre>
		</pkg:outlineMarker>


<p>This means that Emacs will automatically go into <code class="function">whizbang-mode</code> when you edit a file ending in <tt class="filename">.wiz</tt>.</p>

<p>Just below this, you will find the <var class="symbol">font-lock-auto-mode-list</var>
entry. Add <code class="function">whizbang-mode</code> to it like so:</p>


		<pkg:outlineMarker OutlineName="code_21" id="code_21" visible="false" copy="true">
				<pre class="programlisting">;; Auto font lock mode
(defvar font-lock-auto-mode-list
  (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'whizbang-mode 'lisp-mode 'perl-mode 'scheme-mode)
  "List of modes to always start in font-lock-mode")
</pre>
		</pkg:outlineMarker>


<p>This means that Emacs will always enable <code class="function">font-lock-mode</code>
(ie syntax highlighting) when editing a <tt class="filename">.wiz</tt> file.</p>

<p>And that is all that is needed. If there is anything else you want done automatically
when you open up a <tt class="filename">.wiz</tt> file, you can add a <code class="function">whizbang-mode hook</code> (see <code class="function">my-scheme-mode-hook</code> for a simple example that adds <code class="function">auto-indent</code>).</p>




<hr />

		</div>
	</pkg:outlineMarker>

	
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="2.8 Further Reading" id="TOOLS-READING">
		<div class="sect2">
			<h2 class="title">2.8 Further Reading</h2>

<p>For information about setting up a development environment for contributing fixes to
FreeBSD itself, please see <a href="http://www.freebsd.org/cgi/man.cgi?query=development&#38;sektion=7"><span class="citerefentry"><span class="refentrytitle">development</span>(7)</span></a>.</p>

<ul>
<li>
<p>Brian Harvey and Matthew Wright <span class="emphasis"><i class="emphasis">Simply
Scheme</i></span> MIT 1994. ISBN 0-262-08226-8</p>
</li>

<li>
<p>Randall Schwartz <span class="emphasis"><i class="emphasis">Learning Perl</i></span>
O'Reilly 1993 ISBN 1-56592-042-2</p>
</li>

<li>
<p>Patrick Henry Winston and Berthold Klaus Paul Horn <span class="emphasis"><i class="emphasis">Lisp (3rd Edition)</i></span> Addison-Wesley 1989 ISBN 0-201-08319-1</p>
</li>

<li>
<p>Brian W. Kernighan and Rob Pike <span class="emphasis"><i class="emphasis">The Unix
Programming Environment</i></span> Prentice-Hall 1984 ISBN 0-13-937681-X</p>
</li>

<li>
<p>Brian W. Kernighan and Dennis M. Ritchie <span class="emphasis"><i class="emphasis">The C Programming Language (2nd Edition)</i></span> Prentice-Hall 1988
ISBN 0-13-110362-8</p>
</li>

<li>
<p>Bjarne Stroustrup <span class="emphasis"><i class="emphasis">The C++ Programming
Language</i></span> Addison-Wesley 1991 ISBN 0-201-53992-6</p>
</li>

<li>
<p>W. Richard Stevens <span class="emphasis"><i class="emphasis">Advanced Programming in
the Unix Environment</i></span> Addison-Wesley 1992 ISBN 0-201-56317-7</p>
</li>

<li>
<p>W. Richard Stevens <span class="emphasis"><i class="emphasis">Unix Network
Programming</i></span> Prentice-Hall 1990 ISBN 0-13-949876-1</p>
</li>
</ul>




<hr />

	</div>
</pkg:outlineMarker>


		</div>
	</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="Chapter 3 Secure Programming" id="SECURE">
	<div class="sect1">
		<h1 class="title">Chapter 3 Secure Programming</h1>

<i class="authorgroup"><span class="contrib">Contributed by</span> Murray Stockely.</i> 



	<pkg:outlineMarker OutlineName="3.1 Synopsis" id="SECURE-SYNOPSIS">
		<div class="sect2">
			<h2 class="title">3.1 Synopsis</h2>

<p>This chapter describes some of the security issues that have plagued <span class="trademark">UNIX</span> programmers for decades and some of the new tools available
to help programmers avoid writing exploitable code.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="3.2 Secure Design Methodology" id="SECURE-PHILOSOPHY">
		<div class="sect2">
			<h2 class="title">3.2 Secure Design
Methodology</h2>

<p>Writing secure applications takes a very scrutinous and pessimistic outlook on life.
Applications should be run with the principle of ``least privilege'' so that no process
is ever running with more than the bare minimum access that it needs to accomplish its
function. Previously tested code should be reused whenever possible to avoid common
mistakes that others may have already fixed.</p>

<p>One of the pitfalls of the <span class="trademark">UNIX</span> environment is how easy
it is to make assumptions about the sanity of the environment. Applications should never
trust user input (in all its forms), system resources, inter-process communication, or
the timing of events. <span class="trademark">UNIX</span> processes do not execute
synchronously so logical operations are rarely atomic.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="3.3 Buffer Overflows" id="SECURE-BUFFEROV">
		<div class="sect2">
			<h2 class="title">3.3 Buffer
Overflows</h2>

<p>Buffer Overflows have been around since the very beginnings of the Von-Neuman <a href="pkg://FreeBSD Developers' Handbook/APPENDICES/#COD">1</a> architecture. They first gained widespread notoriety in 1988 with the
Morris Internet worm. Unfortunately, the same basic attack remains effective today. Of
the 17 CERT security advisories of 1999, 10 of them were directly caused by
buffer-overflow software bugs. By far the most common type of buffer overflow attack is
based on corrupting the stack.</p>

<p>Most modern computer systems use a stack to pass arguments to procedures and to store
local variables. A stack is a last in first out (LIFO) buffer in the high memory area of
a process image. When a program invokes a function a new "stack frame" is created. This
stack frame consists of the arguments passed to the function as well as a dynamic amount
of local variable space. The "stack pointer" is a register that holds the current
location of the top of the stack. Since this value is constantly changing as new values
are pushed onto the top of the stack, many implementations also provide a "frame pointer"
that is located near the beginning of a stack frame so that local variables can more
easily be addressed relative to this value. <a href="pkg://FreeBSD Developers' Handbook/APPENDICES/#COD">1</a> The return address for
function calls is also stored on the stack, and this is the cause of stack-overflow
exploits since overflowing a local variable in a function can overwrite the return
address of that function, potentially allowing a malicious user to execute any code he or
she wants.</p>

<p>Although stack-based attacks are by far the most common, it would also be possible to
overrun the stack with a heap-based (malloc/free) attack.</p>

<p>The C programming language does not perform automatic bounds checking on arrays or
pointers as many other languages do. In addition, the standard C library is filled with a
handful of very dangerous functions.</p>

<a name="AEN1316"></a>
<table class="calstable" border="0" frame="void" width="100%">
<col />
<col />
<tbody>
<tr>
<td><code class="function">strcpy</code>(char *dest, const char *src)</td>
<td>
<p>May overflow the dest buffer</p>
</td>
</tr>

<tr>
<td><code class="function">strcat</code>(char *dest, const char *src)</td>
<td>
<p>May overflow the dest buffer</p>
</td>
</tr>

<tr>
<td><code class="function">getwd</code>(char *buf)</td>
<td>
<p>May overflow the buf buffer</p>
</td>
</tr>

<tr>
<td><code class="function">gets</code>(char *s)</td>
<td>
<p>May overflow the s buffer</p>
</td>
</tr>

<tr>
<td><code class="function">[vf]scanf</code>(const char *format, ...)</td>
<td>
<p>May overflow its arguments.</p>
</td>
</tr>

<tr>
<td><code class="function">realpath</code>(char *path, char resolved_path[])</td>
<td>
<p>May overflow the path buffer</p>
</td>
</tr>

<tr>
<td><code class="function">[v]sprintf</code>(char *str, const char *format, ...)</td>
<td>
<p>May overflow the str buffer.</p>
</td>
</tr>
</tbody>
</table>



<hr />

		<pkg:outlineMarker OutlineName="3.3.1 Example Buffer Overflow" id="AEN1354">
			<div class="sect3">
				<h3 class="title">3.3.1 Example Buffer Overflow</h3>

<p>The following example code contains a buffer overflow designed to overwrite the return
address and skip the instruction immediately following the function call. (Inspired by <a href="pkg://FreeBSD Developers' Handbook/APPENDICES/#PHRACK">4</a>)</p>


		<pkg:outlineMarker OutlineName="code_22" id="code_22" visible="false" copy="true">
				<pre class="programlisting">#include <tt class="sgmltag">&#60;stdio.h&#62;</tt>

void manipulate(char *buffer) {
  char newbuffer[80];
  strcpy(newbuffer,buffer);
}

int main() {
  char ch,buffer[4096];
  int i=0;

  while ((buffer[i++] = getchar()) != '\n') {};
  
  i=1;
  manipulate(buffer);
  i=2;
  printf("The value of i is : %d\n",i);
  return 0;
}
</pre>
		</pkg:outlineMarker>


<p>Let us examine what the memory image of this process would look like if we were to
input 160 spaces into our little program before hitting return.</p>

<p>[XXX figure here!]</p>

<p>Obviously more malicious input can be devised to execute actual compiled instructions
(such as exec(/bin/sh)).</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="3.3.2 Avoiding Buffer Overflows" id="AEN1363">
			<div class="sect3">
				<h3 class="title">3.3.2 Avoiding Buffer Overflows</h3>

<p>The most straightforward solution to the problem of stack-overflows is to always use
length restricted memory and string copy functions. <code class="function">strncpy</code>
and <code class="function">strncat</code> are part of the standard C library. These
functions accept a length value as a parameter which should be no larger than the size of
the destination buffer. These functions will then copy up to `length' bytes from the
source to the destination. However there are a number of problems with these functions.
Neither function guarantees NUL termination if the size of the input buffer is as large
as the destination. The length parameter is also used inconsistently between strncpy and
strncat so it is easy for programmers to get confused as to their proper usage. There is
also a significant performance loss compared to <code class="function">strcpy</code> when
copying a short string into a large buffer since <code class="function">strncpy</code>
NUL fills up the size specified.</p>

<p>In OpenBSD, another memory copy implementation has been created to get around these
problem. The <code class="function">strlcpy</code> and <code class="function">strlcat</code> functions guarantee that they will always null terminate
the destination string when given a non-zero length argument. For more information about
these functions see <a href="pkg://FreeBSD Developers' Handbook/APPENDICES/#OPENBSD">6</a>. The OpenBSD <code class="function">strlcpy</code> and <code class="function">strlcat</code> instructions
have been in FreeBSD since 3.3.</p>


<hr />

		<pkg:outlineMarker OutlineName="3.3.2.1 Compiler based run-time bounds checking" id="AEN1392">
			<div class="sect3">
				<h4 class="title">3.3.2.1 Compiler based run-time bounds
checking</h4>

<p>Unfortunately there is still a very large assortment of code in public use which
blindly copies memory around without using any of the bounded copy routines we just
discussed. Fortunately, there is another solution. Several compiler add-ons and libraries
exist to do Run-time bounds checking in C/C++.</p>

<p>StackGuard is one such add-on that is implemented as a small patch to the gcc code
generator. From the <a href="http://immunix.org/stackguard.html" target="_top">StackGuard
website</a>: <a name="AEN1404"></a></p>

<blockquote class="blockquote">
<p>"StackGuard detects and defeats stack smashing attacks by protecting the return
address on the stack from being altered. StackGuard places a "canary" word next to the
return address when a function is called. If the canary word has been altered when the
function returns, then a stack smashing attack has been attempted, and the program
responds by emitting an intruder alert into syslog, and then halts."</p>
</blockquote>

<a name="AEN1406"></a>
<blockquote class="blockquote">
<p>"StackGuard is implemented as a small patch to the gcc code generator, specifically
the function_prolog() and function_epilog() routines. function_prolog() has been enhanced
to lay down canaries on the stack when functions start, and function_epilog() checks
canary integrity when the function exits. Any attempt at corrupting the return address is
thus detected before the function returns."</p>
</blockquote>

<br />
<br />
<p>Recompiling your application with StackGuard is an effective means of stopping most
buffer-overflow attacks, but it can still be compromised.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="3.3.2.2 Library based run-time bounds checking" id="AEN1411">
			<div class="sect3">
				<h4 class="title">3.3.2.2 Library based run-time bounds
checking</h4>

<p>Compiler-based mechanisms are completely useless for binary-only software for which
you cannot recompile. For these situations there are a number of libraries which
re-implement the unsafe functions of the C-library (<code class="function">strcpy</code>,
<code class="function">fscanf</code>, <code class="function">getwd</code>, etc..) and
ensure that these functions can never write past the stack pointer.</p>

<ul>
<li>
<p>libsafe</p>
</li>

<li>
<p>libverify</p>
</li>

<li>
<p>libparanoia</p>
</li>
</ul>

<p>Unfortunately these library-based defenses have a number of shortcomings. These
libraries only protect against a very small set of security related issues and they
neglect to fix the actual problem. These defenses may fail if the application was
compiled with -fomit-frame-pointer. Also, the LD_PRELOAD and LD_LIBRARY_PATH environment
variables can be overwritten/unset by the user.</p>





<hr />

		</div>
	</pkg:outlineMarker>

	
			</div>
		</pkg:outlineMarker>

			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="3.4 SetUID issues" id="SECURE-SETUID">
		<div class="sect2">
			<h2 class="title">3.4 SetUID issues</h2>

<p>There are at least 6 different IDs associated with any given process. Because of this
you have to be very careful with the access that your process has at any given time. In
particular, all seteuid applications should give up their privileges as soon as it is no
longer required.</p>

<p>The real user ID can only be changed by a superuser process. The <b class="application">login</b> program sets this when a user initially logs in and it is
seldom changed.</p>

<p>The effective user ID is set by the <code class="function">exec()</code> functions if
a program has its seteuid bit set. An application can call <code class="function">seteuid()</code> at any time to set the effective user ID to either the
real user ID or the saved set-user-ID. When the effective user ID is set by <code class="function">exec()</code> functions, the previous value is saved in the saved
set-user-ID.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="3.5 Limiting your program's environment" id="SECURE-CHROOT">
		<div class="sect2">
			<h2 class="title">3.5 Limiting your program's
environment</h2>

<p>The traditional method of restricting a process is with the <code class="function">chroot()</code> system call. This system call changes the root directory
from which all other paths are referenced for a process and any child processes. For this
call to succeed the process must have execute (search) permission on the directory being
referenced. The new environment does not actually take effect until you <code class="function">chdir()</code> into your new environment. It should also be noted that a
process can easily break out of a chroot environment if it has root privilege. This could
be accomplished by creating device nodes to read kernel memory, attaching a debugger to a
process outside of the jail, or in many other creative ways.</p>

<p>The behavior of the <code class="function">chroot()</code> system call can be
controlled somewhat with the kern.chroot_allow_open_directories <tt class="command">sysctl</tt> variable. When this value is set to 0, <code class="function">chroot()</code> will fail with EPERM if there are any directories open.
If set to the default value of 1, then <code class="function">chroot()</code> will fail
with EPERM if there are any directories open and the process is already subject to a
<code class="function">chroot()</code> call. For any other value, the check for open
directories will be bypassed completely.</p>


<hr />

		<pkg:outlineMarker OutlineName="3.5.1 FreeBSD's jail functionality" id="AEN1458">
			<div class="sect3">
				<h3 class="title">3.5.1 FreeBSD's jail
functionality</h3>

<p>The concept of a Jail extends upon the <code class="function">chroot()</code> by
limiting the powers of the superuser to create a true `virtual server'. Once a prison is
set up all network communication must take place through the specified IP address, and
the power of "root privilege" in this jail is severely constrained.</p>

<p>While in a prison, any tests of superuser power within the kernel using the <code class="function">suser()</code> call will fail. However, some calls to <code class="function">suser()</code> have been changed to a new interface <code class="function">suser_xxx()</code>. This function is responsible for recognizing or
denying access to superuser power for imprisoned processes.</p>

<p>A superuser process within a jailed environment has the power to:</p>

<ul>
<li>
<p>Manipulate credential with <code class="function">setuid</code>, <code class="function">seteuid</code>, <code class="function">setgid</code>, <code class="function">setegid</code>, <code class="function">setgroups</code>, <code class="function">setreuid</code>, <code class="function">setregid</code>, <code class="function">setlogin</code></p>
</li>

<li>
<p>Set resource limits with <code class="function">setrlimit</code></p>
</li>

<li>
<p>Modify some sysctl nodes (kern.hostname)</p>
</li>

<li>
<p><code class="function">chroot()</code></p>
</li>

<li>
<p>Set flags on a vnode: <code class="function">chflags</code>, <code class="function">fchflags</code></p>
</li>

<li>
<p>Set attributes of a vnode such as file permission, owner, group, size, access time,
and modification time.</p>
</li>

<li>
<p>Bind to privileged ports in the Internet domain (ports &#60; 1024)</p>
</li>
</ul>

<p><code class="function">Jail</code> is a very useful tool for running applications in a
secure environment but it does have some shortcomings. Currently, the IPC mechanisms have
not been converted to the <code class="function">suser_xxx</code> so applications such as
MySQL cannot be run within a jail. Superuser access may have a very limited meaning
within a jail, but there is no way to specify exactly what "very limited" means.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="3.5.2 POSIX.1e Process Capabilities" id="AEN1499">
			<div class="sect3">
				<h3 class="title">3.5.2 <span class="trademark">POSIX</span>®.1e Process Capabilities</h3>

<p><span class="trademark">POSIX</span> has released a working draft that adds event
auditing, access control lists, fine grained privileges, information labeling, and
mandatory access control.</p>

<p>This is a work in progress and is the focus of the <a href="http://www.trustedbsd.org/" target="_top">TrustedBSD</a> project. Some of the
initial work has been committed to FreeBSD-CURRENT (cap_set_proc(3)).</p>




<hr />

		</div>
	</pkg:outlineMarker>

	
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="3.6 Trust" id="SECURE-TRUST">
		<div class="sect2">
			<h2 class="title">3.6 Trust</h2>

<p>An application should never assume that anything about the users environment is sane.
This includes (but is certainly not limited to): user input, signals, environment
variables, resources, IPC, mmaps, the filesystem working directory, file descriptors, the
# of open files, etc.</p>

<p>You should never assume that you can catch all forms of invalid input that a user
might supply. Instead, your application should use positive filtering to only allow a
specific subset of inputs that you deem safe. Improper data validation has been the cause
of many exploits, especially with CGI scripts on the world wide web. For filenames you
need to be extra careful about paths ("../", "/"), symbolic links, and shell escape
characters.</p>

<p>Perl has a really cool feature called "Taint" mode which can be used to prevent
scripts from using data derived outside the program in an unsafe way. This mode will
check command line arguments, environment variables, locale information, the results of
certain syscalls (<code class="function">readdir()</code>, <code class="function">readlink()</code>, <code class="function">getpwxxx()</code>, and all
file input.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="3.7 Race Conditions" id="SECURE-RACE-CONDITIONS">
		<div class="sect2">
			<h2 class="title">3.7 Race
Conditions</h2>

<p>A race condition is anomalous behavior caused by the unexpected dependence on the
relative timing of events. In other words, a programmer incorrectly assumed that a
particular event would always happen before another.</p>

<p>Some of the common causes of race conditions are signals, access checks, and file
opens. Signals are asynchronous events by nature so special care must be taken in dealing
with them. Checking access with <code class="function">access(2)</code> then <code class="function">open(2)</code> is clearly non-atomic. Users can move files in between
the two calls. Instead, privileged applications should <code class="function">seteuid()</code> and then call <code class="function">open()</code>
directly. Along the same lines, an application should always set a proper umask before
<code class="function">open()</code> to obviate the need for spurious <code class="function">chmod()</code> calls.</p>




<hr />

	</div>
</pkg:outlineMarker>


		</div>
	</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="Chapter 4 Localization and Internationalization - L10Nand I18N" id="L10N">
	<div class="sect1">
		<h1 class="title">Chapter 4 Localization and Internationalization - L10N
and I18N</h1>



	<pkg:outlineMarker OutlineName="4.1 Programming I18N Compliant Applications" id="L10N-PROGRAMMING">
		<div class="sect2">
			<h2 class="title">4.1 Programming I18N
Compliant Applications</h2>

<p>To make your application more useful for speakers of other languages, we hope that you
will program I18N compliant. The GNU gcc compiler and GUI libraries like QT and GTK
support I18N through special handling of strings. Making a program I18N compliant is very
easy. It allows contributors to port your application to other languages quickly. Refer
to the library specific I18N documentation for more details.</p>

<p>In contrast with common perception, I18N compliant code is easy to write. Usually, it
only involves wrapping your strings with library specific functions. In addition, please
be sure to allow for wide or multibyte character support.</p>


<hr />

		<pkg:outlineMarker OutlineName="4.1.1 A Call to Unify the I18N Effort" id="AEN1553">
			<div class="sect3">
				<h3 class="title">4.1.1 A Call to Unify the I18N
Effort</h3>

<p>It has come to our attention that the individual I18N/L10N efforts for each country
has been repeating each others' efforts. Many of us have been reinventing the wheel
repeatedly and inefficiently. We hope that the various major groups in I18N could
congregate into a group effort similar to the Core Team's responsibility.</p>

<p>Currently, we hope that, when you write or port I18N programs, you would send it out
to each country's related FreeBSD mailing list for testing. In the future, we hope to
create applications that work in all the languages out-of-the-box without dirty
hacks.</p>

<p>The <a href="http://lists.freebsd.org/mailman/listinfo/freebsd-i18n" target="_top">FreeBSD internationalization mailing list</a> has been established. If you
are an I18N/L10N developer, please send your comments, ideas, questions, and anything you
deem related to it.</p>

<p>Michael C. Wu will be maintaining an I18N works in progress homepage at <a href="http://www.freebsd.org/%7Ekeichii/i18n/index.html" target="_top">http://www.FreeBSD.org/~keichii/i18n/index.html</a>. Please also read the
BSDCon2000 I18N paper and presentations by Clive Lin, Chia-Liang Kao, and Michael C. Wu
at <a href="http://www.freebsd.org/%7Ekeichii/papers/" target="_top">http://www.FreeBSD.org/~keichii/papers/</a></p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="4.1.2 Perl and Python" id="AEN1562">
			<div class="sect3">
				<h3 class="title">4.1.2 Perl and Python</h3>

<p>Perl and Python have I18N and wide character handling libraries. Please use them for
I18N compliance.</p>

<p>In older FreeBSD versions, Perl may give warnings about not having a wide character
locale installed on your system. You can set the environment variable <tt class="envar">LD_PRELOAD</tt> to <tt class="filename">/usr/lib/libxpg4.so</tt> in your
shell.</p>

<p>In <var class="literal">sh</var>-based shells:</p>


		<pkg:outlineMarker OutlineName="code_23" id="code_23" visible="false" copy="true">
				<pre class="programlisting"><tt class="envar">LD_PRELOAD=/usr/lib/libxpg4.so</tt>
</pre>
		</pkg:outlineMarker>


<p>In <var class="literal">C</var>-based shells:</p>


		<pkg:outlineMarker OutlineName="code_24" id="code_24" visible="false" copy="true">
				<pre class="programlisting"><tt class="envar">setenv LD_PRELOAD /usr/lib/libxpg4.so</tt>
</pre>
		</pkg:outlineMarker>






<hr />

	</div>
</pkg:outlineMarker>


		</div>
	</pkg:outlineMarker>

			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="Chapter 5 Source Tree Guidelines andPolicies" id="POLICIES">
	<div class="sect1">
		<h1 class="title">Chapter 5 Source Tree Guidelines and
Policies</h1>

<i class="authorgroup"><span class="contrib">Contributed by</span> Poul-Henning Kamp.</i>


<p>This chapter documents various guidelines and policies in force for the FreeBSD source
tree.</p>


<hr />

	<pkg:outlineMarker OutlineName="5.1 MAINTAINER on Makefiles" id="POLICIES-MAINTAINER">
		<div class="sect2">
			<h2 class="title">5.1 <tt class="makevar">MAINTAINER</tt> on Makefiles</h2>

<p>If a particular portion of the FreeBSD distribution is being maintained by a person or
group of persons, they can communicate this fact to the world by adding a</p>


		<pkg:outlineMarker OutlineName="code_25" id="code_25" visible="false" copy="true">
				<pre class="programlisting">MAINTAINER= email-addresses
</pre>
		</pkg:outlineMarker>


line to the <tt class="filename">Makefile</tt>s covering this portion of the source
tree.<br />
<br />
<p>The semantics of this are as follows:</p>

<p>The maintainer owns and is responsible for that code. This means that he is
responsible for fixing bugs and answering problem reports pertaining to that piece of the
code, and in the case of contributed software, for tracking new versions, as
appropriate.</p>

<p>Changes to directories which have a maintainer defined shall be sent to the maintainer
for review before being committed. Only if the maintainer does not respond for an
unacceptable period of time, to several emails, will it be acceptable to commit changes
without review by the maintainer. However, it is suggested that you try to have the
changes reviewed by someone else if at all possible.</p>

<p>It is of course not acceptable to add a person or group as maintainer unless they
agree to assume this duty. On the other hand it does not have to be a committer and it
can easily be a group of people.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="5.2 Contributed Software" id="POLICIES-CONTRIBUTED">
		<div class="sect2">
			<h2 class="title">5.2
Contributed Software</h2>

<i class="authorgroup"><span class="contrib">Contributed by</span> Poul-Henning Kamp and
David O'Brien.</i> 

<p>Some parts of the FreeBSD distribution consist of software that is actively being
maintained outside the FreeBSD project. For historical reasons, we call this <span class="emphasis"><i class="emphasis">contributed</i></span> software. Some examples are
<b class="application">sendmail</b>, <b class="application">gcc</b> and <b class="application">patch</b>.</p>

<p>Over the last couple of years, various methods have been used in dealing with this
type of software and all have some number of advantages and drawbacks. No clear winner
has emerged.</p>

<p>Since this is the case, after some debate one of these methods has been selected as
the ``official'' method and will be required for future imports of software of this kind.
Furthermore, it is strongly suggested that existing contributed software converge on this
model over time, as it has significant advantages over the old method, including the
ability to easily obtain diffs relative to the ``official'' versions of the source by
everyone (even without cvs access). This will make it significantly easier to return
changes to the primary developers of the contributed software.</p>

<p>Ultimately, however, it comes down to the people actually doing the work. If using
this model is particularly unsuited to the package being dealt with, exceptions to these
rules may be granted only with the approval of the core team and with the general
consensus of the other developers. The ability to maintain the package in the future will
be a key issue in the decisions.</p>


<blockquote class="note">
<p><b>Note:</b> Because of some unfortunate design limitations with the RCS file format
and CVS's use of vendor branches, minor, trivial and/or cosmetic changes are <span class="emphasis"><i class="emphasis">strongly discouraged</i></span> on files that are
still tracking the vendor branch. ``Spelling fixes'' are explicitly included here under
the ``cosmetic'' category and are to be avoided for files with revision 1.1.x.x. The
repository bloat impact from a single character change can be rather dramatic.</p>
</blockquote>


<p>The <b class="application">Tcl</b> embedded programming language will be used as
example of how this model works:</p>

<p><tt class="filename">src/contrib/tcl</tt> contains the source as distributed by the
maintainers of this package. Parts that are entirely not applicable for FreeBSD can be
removed. In the case of Tcl, the <tt class="filename">mac</tt>, <tt class="filename">win</tt> and <tt class="filename">compat</tt> subdirectories were
eliminated before the import.</p>

<p><tt class="filename">src/lib/libtcl</tt> contains only a <b class="application">bmake</b> style <tt class="filename">Makefile</tt> that uses the
standard <tt class="filename">bsd.lib.mk</tt> makefile rules to produce the library and
install the documentation.</p>

<p><tt class="filename">src/usr.bin/tclsh</tt> contains only a bmake style <tt class="filename">Makefile</tt> which will produce and install the <tt class="command">tclsh</tt> program and its associated man-pages using the standard <tt class="filename">bsd.prog.mk</tt> rules.</p>

<p><tt class="filename">src/tools/tools/tcl_bmake</tt> contains a couple of shell-scripts
that can be of help when the tcl software needs updating. These are not part of the built
or installed software.</p>

<p>The important thing here is that the <tt class="filename">src/contrib/tcl</tt>
directory is created according to the rules: it is supposed to contain the sources as
distributed (on a proper CVS vendor-branch and without RCS keyword expansion) with as few
FreeBSD-specific changes as possible. The 'easy-import' tool on <tt class="hostid">freefall</tt> will assist in doing the import, but if there are any doubts
on how to go about it, it is imperative that you ask first and not blunder ahead and hope
it ``works out''. CVS is not forgiving of import accidents and a fair amount of effort is
required to back out major mistakes.</p>

<p>Because of the previously mentioned design limitations with CVS's vendor branches, it
is required that ``official'' patches from the vendor be applied to the original
distributed sources and the result re-imported onto the vendor branch again. Official
patches should never be patched into the FreeBSD checked out version and ``committed'',
as this destroys the vendor branch coherency and makes importing future versions rather
difficult as there will be conflicts.</p>

<p>Since many packages contain files that are meant for compatibility with other
architectures and environments that FreeBSD, it is permissible to remove parts of the
distribution tree that are of no interest to FreeBSD in order to save space. Files
containing copyright notices and release-note kind of information applicable to the
remaining files shall <span class="emphasis"><i class="emphasis">not</i></span> be
removed.</p>

<p>If it seems easier, the <tt class="command">bmake</tt> <tt class="filename">Makefile</tt>s can be produced from the dist tree automatically by some
utility, something which would hopefully make it even easier to upgrade to a new version.
If this is done, be sure to check in such utilities (as necessary) in the <tt class="filename">src/tools</tt> directory along with the port itself so that it is
available to future maintainers.</p>

<p>In the <tt class="filename">src/contrib/tcl</tt> level directory, a file called <tt class="filename">FREEBSD-upgrade</tt> should be added and it should state things
like:</p>

<ul>
<li>
<p>Which files have been left out.</p>
</li>

<li>
<p>Where the original distribution was obtained from and/or the official master site.</p>
</li>

<li>
<p>Where to send patches back to the original authors.</p>
</li>

<li>
<p>Perhaps an overview of the FreeBSD-specific changes that have been made.</p>
</li>
</ul>

<p>However, please do not import <tt class="filename">FREEBSD-upgrade</tt> with the
contributed source. Rather you should <tt class="command">cvs add FREEBSD-upgrade ; cvs
ci</tt> after the initial import. Example wording from <tt class="filename">src/contrib/cpio</tt> is below:</p>


		<pkg:outlineMarker OutlineName="code_26" id="code_26" visible="false" copy="true">
				<pre class="programlisting">This directory contains virgin sources of the original distribution files
on a "vendor" branch.  Do not, under any circumstances, attempt to upgrade
the files in this directory via patches and a cvs commit.  New versions or
official-patch versions must be imported.  Please remember to import with
"-ko" to prevent CVS from corrupting any vendor RCS Ids.

For the import of GNU cpio 2.4.2, the following files were removed:

        INSTALL         cpio.info       mkdir.c             
        Makefile.in     cpio.texi       mkinstalldirs

To upgrade to a newer version of cpio, when it is available:
        1. Unpack the new version into an empty directory.
           [Do not make ANY changes to the files.]

        2. Remove the files listed above and any others that don't apply to
           FreeBSD.

        3. Use the command:
                cvs import -ko -m 'Virgin import of GNU cpio v&#60;version&#62;' \
                        src/contrib/cpio GNU cpio_&#60;version&#62;

           For example, to do the import of version 2.4.2, I typed:
                cvs import -ko -m 'Virgin import of GNU v2.4.2' \
                        src/contrib/cpio GNU cpio_2_4_2

        4. Follow the instructions printed out in step 3 to resolve any
           conflicts between local FreeBSD changes and the newer version.

Do not, under any circumstances, deviate from this procedure.

To make local changes to cpio, simply patch and commit to the main
branch (aka HEAD).  Never make local changes on the GNU branch.

All local changes should be submitted to "cpio@gnu.ai.mit.edu" for
inclusion in the next vendor release.

obrien@FreeBSD.org - 30 March 1997
</pre>
		</pkg:outlineMarker>




<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="5.3 Encumbered Files" id="POLICIES-ENCUMBERED">
		<div class="sect2">
			<h2 class="title">5.3 Encumbered
Files</h2>

<p>It might occasionally be necessary to include an encumbered file in the FreeBSD source
tree. For example, if a device requires a small piece of binary code to be loaded to it
before the device will operate, and we do not have the source to that code, then the
binary file is said to be encumbered. The following policies apply to including
encumbered files in the FreeBSD source tree.</p>

<ol type="1">
<li>
<p>Any file which is interpreted or executed by the system CPU(s) and not in source
format is encumbered.</p>
</li>

<li>
<p>Any file with a license more restrictive than BSD or GNU is encumbered.</p>
</li>

<li>
<p>A file which contains downloadable binary data for use by the hardware is not
encumbered, unless (1) or (2) apply to it. It must be stored in an architecture neutral
ASCII format (file2c or uuencoding is recommended).</p>
</li>

<li>
<p>Any encumbered file requires specific approval from the <a href="http://www.freebsd.org/doc/en_US.ISO8859-1/articles/contributors/staff-core.html" target="_top">Core team</a> before it is added to the CVS repository.</p>
</li>

<li>
<p>Encumbered files go in <tt class="filename">src/contrib</tt> or <tt class="filename">src/sys/contrib</tt>.</p>
</li>

<li>
<p>The entire module should be kept together. There is no point in splitting it, unless
there is code-sharing with non-encumbered code.</p>
</li>

<li>
<p>Object files are named <tt class="filename"><var class="replaceable">arch</var>/<var class="replaceable">filename</var>.o.uu&#62;</tt>.</p>
</li>

<li>
<p>Kernel files:</p>

<ol type="a">
<li>
<p>Should always be referenced in <tt class="filename">conf/files.*</tt> (for build
simplicity).</p>
</li>

<li>
<p>Should always be in <tt class="filename">LINT</tt>, but the <a href="http://www.freebsd.org/doc/en_US.ISO8859-1/articles/contributors/staff-core.html" target="_top">Core team</a> decides per case if it should be commented out or not. The <a href="http://www.freebsd.org/doc/en_US.ISO8859-1/articles/contributors/staff-core.html" target="_top">Core team</a> can, of course, change their minds later on.</p>
</li>

<li>
<p>The <i class="firstterm">Release Engineer</i> decides whether or not it goes into the
release.</p>
</li>
</ol>
</li>

<li>
<p>User-land files:</p>

<ol type="a">
<li>
<p>The <a href="http://www.freebsd.org/doc/en_US.ISO8859-1/articles/contributors/staff-core.html" target="_top">Core team</a> decides if the code should be part of <tt class="command">make world</tt>.</p>
</li>

<li>
<p>The <a href="http://www.freebsd.org/doc/en_US.ISO8859-1/articles/contributors/staff-who.html" target="_top">Release Engineer</a> decides if it goes into the release.</p>
</li>
</ol>
</li>
</ol>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="5.4 Shared Libraries" id="POLICIES-SHLIB">
		<div class="sect2">
			<h2 class="title">5.4 Shared
Libraries</h2>

<i class="authorgroup"><span class="contrib">Contributed by</span> Satoshi Asami, Peter
Wemm, and David O'Brien.</i> 

<p>If you are adding shared library support to a port or other piece of software that
does not have one, the version numbers should follow these rules. Generally, the
resulting numbers will have nothing to do with the release version of the software.</p>

<p>The three principles of shared library building are:</p>

<ul>
<li>
<p>Start from <var class="literal">1.0</var></p>
</li>

<li>
<p>If there is a change that is backwards compatible, bump minor number (note that ELF
systems ignore the minor number)</p>
</li>

<li>
<p>If there is an incompatible change, bump major number</p>
</li>
</ul>

<p>For instance, added functions and bugfixes result in the minor version number being
bumped, while deleted functions, changed function call syntax, etc. will force the major
version number to change.</p>

<p>Stick to version numbers of the form major.minor (<var class="replaceable">x</var>.<var class="replaceable">y</var>). Our a.out dynamic linker
does not handle version numbers of the form <var class="replaceable">x</var>.<var class="replaceable">y</var>.<var class="replaceable">z</var> well. Any version number
after the <var class="replaceable">y</var> (i.e. the third digit) is totally ignored when
comparing shared lib version numbers to decide which library to link with. Given two
shared libraries that differ only in the ``micro'' revision, <tt class="command">ld.so</tt> will link with the higher one. That is, if you link with <tt class="filename">libfoo.so.3.3.3</tt>, the linker only records <var class="literal">3.3</var> in the headers, and will link with anything starting with <var class="replaceable">libfoo.so.3</var>.<var class="replaceable">(anything &#62;=
3)</var>.<var class="replaceable">(highest available)</var>.</p>


<blockquote class="note">
<p><b>Note:</b> <tt class="command">ld.so</tt> will always use the highest ``minor''
revision. For instance, it will use <tt class="filename">libc.so.2.2</tt> in preference
to <tt class="filename">libc.so.2.0</tt>, even if the program was initially linked with
<tt class="filename">libc.so.2.0</tt>.</p>
</blockquote>


<p>In addition, our ELF dynamic linker does not handle minor version numbers at all.
However, one should still specify a major and minor version number as our <tt class="filename">Makefile</tt>s ``do the right thing'' based on the type of system.</p>

<p>For non-port libraries, it is also our policy to change the shared library version
number only once between releases. In addition, it is our policy to change the major
shared library version number only once between major OS releases (i.e. from 3.0 to 4.0).
When you make a change to a system library that requires the version number to be bumped,
check the <tt class="filename">Makefile</tt>'s commit logs. It is the responsibility of
the committer to ensure that the first such change since the release will result in the
shared library version number in the <tt class="filename">Makefile</tt> to be updated,
and any subsequent changes will not.</p>




<hr />

	</div>
</pkg:outlineMarker>


		</div>
	</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="Chapter 6 Regression and Performance Testing" id="TESTING">
	<div class="sect1">
		<h1 class="title">Chapter 6 Regression and Performance Testing</h1>

<p>Regression tests are used to exercise a particular bit of the system to check that it
works as expected, and to make sure that old bugs are not reintroduced.</p>

<p>The FreeBSD regression testing tools can be found in the FreeBSD source tree in the
directory <tt class="filename">src/tools/regression</tt>.</p>


<hr />
<h2 class="section"><a name="TESTING-MICRO-BENCHMARK">6.1.
Micro Benchmark Checklist</a></h2>

<p>This section contains hints for doing proper micro-benchmarking on FreeBSD or of
FreeBSD itself.</p>

<p>It is not possible to use all of the suggestions below every single time, but the more
used, the better the benchmark's ability to test small differences will be.</p>

<ul>
<li>
<p>Disable <acronym class="acronym">APM</acronym> and any other kind of clock fiddling
(<acronym class="acronym">ACPI</acronym> ?).</p>
</li>

<li>
<p>Run in single user mode. E.g. <a href="http://www.freebsd.org/cgi/man.cgi?query=cron&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">cron</span>(8)</span></a>, and and other
daemons only add noise. The <a href="http://www.freebsd.org/cgi/man.cgi?query=sshd&#38;sektion=8&#38;manpath=OpenBSD+3.4">
<span class="citerefentry"><span class="refentrytitle">sshd</span>(8)</span></a> daemon
can also cause problems. If ssh access is required during test either disable the SSHv1
key regeneration, or kill the parent <tt class="command">sshd</tt> daemon during the
tests.</p>
</li>

<li>
<p>Do not run <a href="http://www.freebsd.org/cgi/man.cgi?query=ntpd&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">ntpd</span>(8)</span></a>.</p>
</li>

<li>
<p>If <a href="http://www.freebsd.org/cgi/man.cgi?query=syslog&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">syslog</span>(3)</span></a> events are
generated, run <a href="http://www.freebsd.org/cgi/man.cgi?query=syslogd&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">syslogd</span>(8)</span></a> with an
empty <tt class="filename">/etc/syslogd.conf</tt>, otherwise, do not run it.</p>
</li>

<li>
<p>Minimize disk-I/O, avoid it entirely if possible.</p>
</li>

<li>
<p>Do not mount file systems that are not needed.</p>
</li>

<li>
<p>Mount <tt class="filename">/</tt>, <tt class="filename">/usr</tt>, and any other file
system as read-only if possible. This removes atime updates to disk (etc.) from the I/O
picture.</p>
</li>

<li>
<p>Reinitialize the read/write test file system with <a href="http://www.freebsd.org/cgi/man.cgi?query=newfs&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">newfs</span>(8)</span></a> and populate
it from a <a href="http://www.freebsd.org/cgi/man.cgi?query=tar&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">tar</span>(1)</span></a> or <a href="http://www.freebsd.org/cgi/man.cgi?query=dump&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">dump</span>(8)</span></a> file before
every run. Unmount and mount it before starting the test. This results in a consistent
file system layout. For a worldstone test this would apply to <tt class="filename">/usr/obj</tt> (just reinitialize with <tt class="command">newfs</tt> and
mount). To get 100% reproducibility, populate the file system from a <a href="http://www.freebsd.org/cgi/man.cgi?query=dd&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">dd</span>(1)</span></a> file (i.e.: <tt class="command">dd if=<tt class="filename">myimage</tt> of=<tt class="filename">/dev/ad0s1h</tt> bs=1m</tt>)</p>
</li>

<li>
<p>Use malloc backed or preloaded <a href="http://www.freebsd.org/cgi/man.cgi?query=md&#38;sektion=4"><span class="citerefentry"><span class="refentrytitle">md</span>(4)</span></a> partitions.</p>
</li>

<li>
<p>Reboot between individual iterations of the test, this gives a more consistent
state.</p>
</li>

<li>
<p>Remove all non-essential device drivers from the kernel. For instance if USB is not
needed for the test, do not put USB in the kernel. Drivers which attach often have
timeouts ticking away.</p>
</li>

<li>
<p>Unconfigure hardware that are not in use. Detach disks with <a href="http://www.freebsd.org/cgi/man.cgi?query=atacontrol&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">atacontrol</span>(8)</span></a> and <a href="http://www.freebsd.org/cgi/man.cgi?query=camcontrol&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">camcontrol</span>(8)</span></a> if the
disks are not used for the test.</p>
</li>

<li>
<p>Do not configure the network unless it is being tested, or wait until after the test
has been performed to ship the results off to another computer.</p>

<p>If the system must be connected to a public network, watch out for spikes of broadcast
traffic. Even though it is hardly noticeable, it will take up CPU cycles. Multicast has
similar caveats.</p>
</li>

<li>
<p>Put each file system on its own disk. This minimizes jitter from head-seek
optimizations.</p>
</li>

<li>
<p>Minimize output to serial or VGA consoles. Running output into files gives less
jitter. (Serial consoles easily become a bottleneck.) Do not touch keyboard while the
test is running, even <b class="keycap">space</b> or <b class="keycap">back-space</b>
shows up in the numbers.</p>
</li>

<li>
<p>Make sure the test is long enough, but not too long. If the test is too short,
timestamping is a problem. If it is too long temperature changes and drift will affect
the frequency of the quartz crystals in the computer. Rule of thumb: more than a minute,
less than an hour.</p>
</li>

<li>
<p>Try to keep the temperature as stable as possible around the machine. This affects
both quartz crystals and disk drive algorithms. To get real stable clock, consider
stabilized clock injection. E.g. get a OCXO + PLL, inject output into clock circuits
instead of motherboard xtal. Contact Poul-Henning Kamp <code class="email">&#60;<a href="mailto:phk@FreeBSD.org">phk@FreeBSD.org</a>&#62;</code> for more information about
this.</p>
</li>

<li>
<p>Run the test at least 3 times but it is better to run more than 20 times both for
``before'' and ``after'' code. Try to interleave if possible (i.e.: do not run 20 times
before then 20 times after), this makes it possible to spot environmental effects. Do not
interleave 1:1, but 3:3, this makes it possible to spot interaction effects.</p>

<p>A good pattern is: <var class="literal">bababa{bbbaaa}*</var>. This gives hint after
the first 1+1 runs (so it is possible to stop the test if it goes entirely the wrong
way), a standard deviation after the first 3+3 (gives a good indication if it is going to
be worth a long run) and trending and interaction numbers later on.</p>
</li>

<li>
<p>Use <tt class="filename">usr/src/tools/tools/ministat</tt> to see if the numbers are
significant. Consider buying ``Cartoon guide to statistics'' ISBN: 0062731025, highly
recommended, if you have forgotten or never learned about standard deviation and
Student's T.</p>
</li>

<li>
<p>Do not use background <a href="http://www.freebsd.org/cgi/man.cgi?query=fsck&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">fsck</span>(8)</span></a> unless the
test is a benchmark of background <tt class="command">fsck</tt>. Also, disable <var class="varname">background_fsck</var> in <tt class="filename">/etc/rc.conf</tt> unless
the benchmark is not started at least 60+``<tt class="command">fsck</tt> runtime''
seconds after the boot, as <a href="http://www.freebsd.org/cgi/man.cgi?query=rc&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">rc</span>(8)</span></a> wakes up and
checks if <tt class="command">fsck</tt> needs to run on any file systems when background
<tt class="command">fsck</tt> is enabled. Likewise, make sure there are no snapshots
lying around unless the benchmark is a test with snapshots.</p>
</li>

<li>
<p>If the benchmark show unexpected bad performance, check for things like high interrupt
volume from an unexpected source. Some versions of <acronym class="acronym">ACPI</acronym> have been reported to ``misbehave'' and generate excess
interrupts. To help diagnose odd test results, take a few snapshots of <tt class="command">vmstat -i</tt> and look for anything unusual.</p>
</li>

<li>
<p>Make sure to be careful about optimization parameters for kernel and userspace,
likewise debugging. It is easy to let something slip through and realize later the test
was not comparing the same thing.</p>
</li>

<li>
<p>Do not ever benchmark with the <var class="literal">WITNESS</var> and <var class="literal">INVARIANTS</var> kernel options enabled unless the test is interested to
benchmarking those features. <var class="literal">WITNESS</var> can cause 400%+ drops in
performance. Likewise, userspace <a href="http://www.freebsd.org/cgi/man.cgi?query=malloc&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">malloc</span>(3)</span></a> parameters
default differently in -CURRENT from the way they ship in production releases.</p>
</li>
</ul>





				<div align="right"><img align="right" src="bsd_sm.png"  /></div>
		</div>
</pkg:outlineMarker>



	</div>
</pkg:outlineMarker>
    <pkg:outlineMarker OutlineName="II. Interprocess Communication" id="IPC" visible="true" renderchildren="false">
		<div class="sect1">
				

<h1 class="title">II. Interprocess Communication</h1>


<dl>
<dt><b>Table of Contents</b></dt>

<dt>7 <a href="pkg://FreeBSD Developers' Handbook/SIGNALS">* Signals</a></dt>

<dt>8 <a href="pkg://FreeBSD Developers' Handbook/SOCKETS">Sockets</a></dt>

<dt>9 <a href="pkg://FreeBSD Developers' Handbook/IPV6">IPv6 Internals</a></dt>
</dl>




<hr />

<pkg:outlineMarker OutlineName="Chapter 7 * Signals" id="SIGNALS">
	<div class="sect1">
		<h1 class="title">Chapter 7 * Signals</h1>

<p>Signals, pipes, semaphores, message queues, shared memory, ports, sockets, doors</p>



<hr />

	</div>
</pkg:outlineMarker>

<pkg:outlineMarker OutlineName="Chapter 8 Sockets" id="SOCKETS">
	<div class="sect1">
		<h1 class="title">Chapter 8 Sockets</h1>

<i class="authorgroup"><span class="contrib">Contributed by</span> G. Adam Stanislav.</i>




	<pkg:outlineMarker OutlineName="8.1 Synopsis" id="SOCKETS-SYNOPSIS">
		<div class="sect2">
			<h2 class="title">8.1 Synopsis</h2>

<p><acronym class="acronym">BSD</acronym> sockets take interprocess communications to a
new level. It is no longer necessary for the communicating processes to run on the same
machine. They still <span class="emphasis"><i class="emphasis">can</i></span>, but they
do not have to.</p>

<p>Not only do these processes not have to run on the same machine, they do not have to
run under the same operating system. Thanks to <acronym class="acronym">BSD</acronym>
sockets, your FreeBSD software can smoothly cooperate with a program running on a <span class="trademark">Macintosh</span>®, another one running on a <span class="trademark">Sun</span>&#8482; workstation, yet another one running under <span class="trademark">Windows</span>® 2000, all connected with an Ethernet-based local
area network.</p>

<p>But your software can equally well cooperate with processes running in another
building, or on another continent, inside a submarine, or a space shuttle.</p>

<p>It can also cooperate with processes that are not part of a computer (at least not in
the strict sense of the word), but of such devices as printers, digital cameras, medical
equipment. Just about anything capable of digital communications.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="8.2 Networking and Diversity" id="SOCKETS-DIVERSITY">
		<div class="sect2">
			<h2 class="title">8.2 Networking and
Diversity</h2>

<p>We have already hinted on the <span class="emphasis"><i class="emphasis">diversity</i></span> of networking. Many different systems have to talk
to each other. And they have to speak the same language. They also have to <span class="emphasis"><i class="emphasis">understand</i></span> the same language the same
way.</p>

<p>People often think that <span class="emphasis"><i class="emphasis">body
language</i></span> is universal. But it is not. Back in my early teens, my father took
me to Bulgaria. We were sitting at a table in a park in Sofia, when a vendor approached
us trying to sell us some roasted almonds.</p>

<p>I had not learned much Bulgarian by then, so, instead of saying no, I shook my head
from side to side, the ``universal'' body language for <span class="emphasis"><i class="emphasis">no</i></span>. The vendor quickly started serving us some almonds.</p>

<p>I then remembered I had been told that in Bulgaria shaking your head sideways meant
<span class="emphasis"><i class="emphasis">yes</i></span>. Quickly, I started nodding my
head up and down. The vendor noticed, took his almonds, and walked away. To an uninformed
observer, I did not change the body language: I continued using the language of shaking
and nodding my head. What changed was the <span class="emphasis"><i class="emphasis">meaning</i></span> of the body language. At first, the vendor and I
interpreted the same language as having completely different meaning. I had to adjust my
own interpretation of that language so the vendor would understand.</p>

<p>It is the same with computers: The same symbols may have different, even outright
opposite meaning. Therefore, for two computers to understand each other, they must not
only agree on the same <span class="emphasis"><i class="emphasis">language</i></span>,
but on the same <span class="emphasis"><i class="emphasis">interpretation</i></span> of
the language.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="8.3 Protocols" id="SOCKETS-PROTOCOLS">
		<div class="sect2">
			<h2 class="title">8.3
Protocols</h2>

<p>While various programming languages tend to have complex syntax and use a number of
multi-letter reserved words (which makes them easy for the human programmer to
understand), the languages of data communications tend to be very terse. Instead of
multi-byte words, they often use individual <span class="emphasis"><i class="emphasis">bits</i></span>. There is a very convincing reason for it: While data
travels <span class="emphasis"><i class="emphasis">inside</i></span> your computer at
speeds approaching the speed of light, it often travels considerably slower between two
computers.</p>

<p>Because the languages used in data communications are so terse, we usually refer to
them as <span class="emphasis"><i class="emphasis">protocols</i></span> rather than
languages.</p>

<p>As data travels from one computer to another, it always uses more than one protocol.
These protocols are <span class="emphasis"><i class="emphasis">layered</i></span>. The
data can be compared to the inside of an onion: You have to peel off several layers of
``skin'' to get to the data. This is best illustrated with a picture:</p>

<p><img src="FreeBSDDevelopersHandbook_files/layers.png" /></p>

<p>In this example, we are trying to get an image from a web page we are connected to via
an Ethernet.</p>

<p>The image consists of raw data, which is simply a sequence of <acronym class="acronym">RGB</acronym> values that our software can process, i.e., convert into an
image and display on our monitor.</p>

<p>Alas, our software has no way of knowing how the raw data is organized: Is it a
sequence of <acronym class="acronym">RGB</acronym> values, or a sequence of grayscale
intensities, or perhaps of <acronym class="acronym">CMYK</acronym> encoded colors? Is the
data represented by 8-bit quanta, or are they 16 bits in size, or perhaps 4 bits? How
many rows and columns does the image consist of? Should certain pixels be
transparent?</p>

<p>I think you get the picture...</p>

<p>To inform our software how to handle the raw data, it is encoded as a <acronym class="acronym">PNG</acronym> file. It could be a <acronym class="acronym">GIF</acronym>,
or a <acronym class="acronym">JPEG</acronym>, but it is a <acronym class="acronym">PNG</acronym>.</p>

<p>And <acronym class="acronym">PNG</acronym> is a protocol.</p>

<p>At this point, I can hear some of you yelling, <span class="emphasis"><i class="emphasis">``No, it is not! It is a file format!''</i></span></p>

<p>Well, of course it is a file format. But from the perspective of data communications,
a file format is a protocol: The file structure is a <span class="emphasis"><i class="emphasis">language</i></span>, a terse one at that, communicating to our <span class="emphasis"><i class="emphasis">process</i></span> how the data is organized. Ergo,
it is a <span class="emphasis"><i class="emphasis">protocol</i></span>.</p>

<p>Alas, if all we received was the <acronym class="acronym">PNG</acronym> file, our
software would be facing a serious problem: How is it supposed to know the data is
representing an image, as opposed to some text, or perhaps a sound, or what not?
Secondly, how is it supposed to know the image is in the <acronym class="acronym">PNG</acronym> format as opposed to <acronym class="acronym">GIF</acronym>, or <acronym class="acronym">JPEG</acronym>, or some other
image format?</p>

<p>To obtain that information, we are using another protocol: <acronym class="acronym">HTTP</acronym>. This protocol can tell us exactly that the data
represents an image, and that it uses the <acronym class="acronym">PNG</acronym>
protocol. It can also tell us some other things, but let us stay focused on protocol
layers here.</p>

<p>So, now we have some data wrapped in the <acronym class="acronym">PNG</acronym>
protocol, wrapped in the <acronym class="acronym">HTTP</acronym> protocol. How did we get
it from the server?</p>

<p>By using <acronym class="acronym">TCP/IP</acronym> over Ethernet, that is how. Indeed,
that is three more protocols. Instead of continuing inside out, I am now going to talk
about Ethernet, simply because it is easier to explain the rest that way.</p>

<p>Ethernet is an interesting system of connecting computers in a <span class="emphasis"><i class="emphasis">local area network</i></span> (<acronym class="acronym">LAN</acronym>). Each computer has a <span class="emphasis"><i class="emphasis">network interface card</i></span> (<acronym class="acronym">NIC</acronym>), which has a unique 48-bit <acronym class="acronym">ID</acronym> called its <span class="emphasis"><i class="emphasis">address</i></span>. No two Ethernet <acronym class="acronym">NIC</acronym>s in the world have the same address.</p>

<p>These <acronym class="acronym">NIC</acronym>s are all connected with each other.
Whenever one computer wants to communicate with another in the same Ethernet <acronym class="acronym">LAN</acronym>, it sends a message over the network. Every <acronym class="acronym">NIC</acronym> sees the message. But as part of the Ethernet <span class="emphasis"><i class="emphasis">protocol</i></span>, the data contains the address
of the destination <acronym class="acronym">NIC</acronym> (among other things). So, only
one of all the network interface cards will pay attention to it, the rest will ignore
it.</p>

<p>But not all computers are connected to the same network. Just because we have received
the data over our Ethernet does not mean it originated in our own local area network. It
could have come to us from some other network (which may not even be Ethernet based)
connected with our own network via the Internet.</p>

<p>All data is transferred over the Internet using <acronym class="acronym">IP</acronym>,
which stands for <span class="emphasis"><i class="emphasis">Internet Protocol</i></span>.
Its basic role is to let us know where in the world the data has arrived from, and where
it is supposed to go to. It does not <span class="emphasis"><i class="emphasis">guarantee</i></span> we will receive the data, only that we will know
where it came from <span class="emphasis"><i class="emphasis">if</i></span> we do receive
it.</p>

<p>Even if we do receive the data, <acronym class="acronym">IP</acronym> does not
guarantee we will receive various chunks of data in the same order the other computer has
sent it to us. So, we can receive the center of our image before we receive the upper
left corner and after the lower right, for example.</p>

<p>It is <acronym class="acronym">TCP</acronym> (<span class="emphasis"><i class="emphasis">Transmission Control Protocol</i></span>) that asks the sender to resend
any lost data and that places it all into the proper order.</p>

<p>All in all, it took <span class="emphasis"><i class="emphasis">five</i></span>
different protocols for one computer to communicate to another what an image looks like.
We received the data wrapped into the <acronym class="acronym">PNG</acronym> protocol,
which was wrapped into the <acronym class="acronym">HTTP</acronym> protocol, which was
wrapped into the <acronym class="acronym">TCP</acronym> protocol, which was wrapped into
the <acronym class="acronym">IP</acronym> protocol, which was wrapped into the <acronym class="acronym">Ethernet</acronym> protocol.</p>

<p>Oh, and by the way, there probably were several other protocols involved somewhere on
the way. For example, if our <acronym class="acronym">LAN</acronym> was connected to the
Internet through a dial-up call, it used the <acronym class="acronym">PPP</acronym>
protocol over the modem which used one (or several) of the various modem protocols, et
cetera, et cetera, et cetera...</p>

<p>As a developer you should be asking by now, <span class="emphasis"><i class="emphasis">``How am I supposed to handle it all?''</i></span></p>

<p>Luckily for you, you are <span class="emphasis"><i class="emphasis">not</i></span>
supposed to handle it all. You <span class="emphasis"><i class="emphasis">are</i></span>
supposed to handle some of it, but not all of it. Specifically, you need not worry about
the physical connection (in our case Ethernet and possibly <acronym class="acronym">PPP</acronym>, etc). Nor do you need to handle the Internet Protocol, or
the Transmission Control Protocol.</p>

<p>In other words, you do not have to do anything to receive the data from the other
computer. Well, you do have to <span class="emphasis"><i class="emphasis">ask</i></span>
for it, but that is almost as simple as opening a file.</p>

<p>Once you have received the data, it is up to you to figure out what to do with it. In
our case, you would need to understand the <acronym class="acronym">HTTP</acronym>
protocol and the <acronym class="acronym">PNG</acronym> file structure.</p>

<p>To use an analogy, all the internetworking protocols become a gray area: Not so much
because we do not understand how it works, but because we are no longer concerned about
it. The sockets interface takes care of this gray area for us:</p>

<p><img src="FreeBSDDevelopersHandbook_files/slayers.png" /></p>

<p>We only need to understand any protocols that tell us how to <span class="emphasis"><i class="emphasis">interpret the data</i></span>, not how to <span class="emphasis"><i class="emphasis">receive</i></span> it from another process, nor how to <span class="emphasis"><i class="emphasis">send</i></span> it to another process.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="8.4 The Sockets Model" id="SOCKETS-MODEL">
		<div class="sect2">
			<h2 class="title">8.4 The Sockets
Model</h2>

<p><acronym class="acronym">BSD</acronym> sockets are built on the basic <span class="trademark">UNIX</span> model: <span class="emphasis"><i class="emphasis">Everything is a file.</i></span> In our example, then, sockets would let
us receive an <span class="emphasis"><i class="emphasis">HTTP file</i></span>, so to
speak. It would then be up to us to extract the <span class="emphasis"><i class="emphasis"><acronym class="acronym">PNG</acronym> file</i></span> from it.</p>

<p>Because of the complexity of internetworking, we cannot just use the <code class="function">open</code> system call, or the <code class="function">open()</code> C
function. Instead, we need to take several steps to ``opening'' a socket.</p>

<p>Once we do, however, we can start treating the <span class="emphasis"><i class="emphasis">socket</i></span> the same way we treat any <span class="emphasis"><i class="emphasis">file descriptor</i></span>: We can <code class="function">read</code>
from it, <code class="function">write</code> to it, <code class="function">pipe</code>
it, and, eventually, <code class="function">close</code> it.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="8.5 Essential Socket Functions" id="SOCKETS-ESSENTIAL-FUNCTIONS">
		<div class="sect2">
			<h2 class="title">8.5 Essential Socket Functions</h2>

<p>While FreeBSD offers different functions to work with sockets, we only <span class="emphasis"><i class="emphasis">need</i></span> four to ``open'' a socket. And in
some cases we only need two.</p>


<hr />

		<pkg:outlineMarker OutlineName="8.5.1 The Client-Server Difference" id="SOCKETS-CLIENT-SERVER">
			<div class="sect3">
				<h3 class="title">8.5.1 The
Client-Server Difference</h3>

<p>Typically, one of the ends of a socket-based data communication is a <span class="emphasis"><i class="emphasis">server</i></span>, the other is a <span class="emphasis"><i class="emphasis">client</i></span>.</p>


<hr />

		<pkg:outlineMarker OutlineName="8.5.1.1 The Common Elements" id="SOCKETS-COMMON-ELEMENTS">
			<div class="sect3">
				<h4 class="title">8.5.1.1
The Common Elements</h4>



		<pkg:outlineMarker OutlineName="8.5.1.1.1 socket" id="SOCKETS-SOCKET">
			<div class="sect3">
				<h5 class="title">8.5.1.1.1 <code class="function">socket</code></h5>

<p>The one function used by both, clients and servers, is <a href="http://www.freebsd.org/cgi/man.cgi?query=socket&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">socket</span>(2)</span></a>. It is
declared this way:</p>


		<pkg:outlineMarker OutlineName="code_27" id="code_27" visible="false" copy="true">
				<pre class="programlisting">int socket(int domain, int type, int protocol);
</pre>
		</pkg:outlineMarker>


<p>The return value is of the same type as that of <code class="function">open</code>, an
integer. FreeBSD allocates its value from the same pool as that of file handles. That is
what allows sockets to be treated the same way as files.</p>

<p>The <var class="varname">domain</var> argument tells the system what <span class="emphasis"><i class="emphasis">protocol family</i></span> you want it to use. Many
of them exist, some are vendor specific, others are very common. They are declared in <tt class="filename">sys/socket.h</tt>.</p>

<p>Use <code class="constant">PF_INET</code> for <acronym class="acronym">UDP</acronym>,
<acronym class="acronym">TCP</acronym> and other Internet protocols (<acronym class="acronym">IP</acronym>v4).</p>

<p>Five values are defined for the <var class="varname">type</var> argument, again, in
<tt class="filename">sys/socket.h</tt>. All of them start with ``<code class="constant">SOCK_</code>''. The most common one is <code class="constant">SOCK_STREAM</code>, which tells the system you are asking for a <span class="emphasis"><i class="emphasis">reliable stream delivery service</i></span> (which
is <acronym class="acronym">TCP</acronym> when used with <code class="constant">PF_INET</code>).</p>

<p>If you asked for <code class="constant">SOCK_DGRAM</code>, you would be requesting a
<span class="emphasis"><i class="emphasis">connectionless datagram delivery
service</i></span> (in our case, <acronym class="acronym">UDP</acronym>).</p>

<p>If you wanted to be in charge of the low-level protocols (such as <acronym class="acronym">IP</acronym>), or even network interfaces (e.g., the Ethernet), you would
need to specify <code class="constant">SOCK_RAW</code>.</p>

<p>Finally, the <var class="varname">protocol</var> argument depends on the previous two
arguments, and is not always meaningful. In that case, use <code class="constant">0</code> for its value.</p>


<blockquote class="note"><a name="SOCKETS-UNCONNECTED"></a>
<p><b>The Unconnected Socket:</b> Nowhere, in the <code class="function">socket</code>
function have we specified to what other system we should be connected. Our newly created
socket remains <span class="emphasis"><i class="emphasis">unconnected</i></span>.</p>

<p>This is on purpose: To use a telephone analogy, we have just attached a modem to the
phone line. We have neither told the modem to make a call, nor to answer if the phone
rings.</p>
</blockquote>




<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="8.5.1.1.2 sockaddr" id="SOCKETS-SOCKADDR">
			<div class="sect3">
				<h5 class="title">8.5.1.1.2 <var class="varname">sockaddr</var></h5>

<p>Various functions of the sockets family expect the address of (or pointer to, to use C
terminology) a small area of the memory. The various C declarations in the <tt class="filename">sys/socket.h</tt> refer to it as <var class="varname">struct
sockaddr</var>. This structure is declared in the same file:</p>


		<pkg:outlineMarker OutlineName="code_28" id="code_28" visible="false" copy="true">
				<pre class="programlisting">/*
 * Structure used by kernel to store most
 * addresses.
 */
struct sockaddr {
    u_char      sa_len;     /* total length */
    sa_family_t sa_family;  /* address family */
    char        sa_data[14];    /* actually longer; address value */
};
#define SOCK_MAXADDRLEN 255     /* longest possible addresses */
</pre>
		</pkg:outlineMarker>


<p>Please note the <span class="emphasis"><i class="emphasis">vagueness</i></span> with
which the <var class="varname">sa_data</var> field is declared, just as an array of <code class="constant">14</code> bytes, with the comment hinting there can be more than <code class="constant">14</code> of them.</p>

<p>This vagueness is quite deliberate. Sockets is a very powerful interface. While most
people perhaps think of it as nothing more than the Internet interface--and most
applications probably use it for that nowadays--sockets can be used for just about <span class="emphasis"><i class="emphasis">any</i></span> kind of interprocess communications,
of which the Internet (or, more precisely, <acronym class="acronym">IP</acronym>) is only
one.</p>

<p>The <tt class="filename">sys/socket.h</tt> refers to the various types of protocols
sockets will handle as <span class="emphasis"><i class="emphasis">address
families</i></span>, and lists them right before the definition of <var class="varname">sockaddr</var>:</p>


		<pkg:outlineMarker OutlineName="code_29" id="code_29" visible="false" copy="true">
				<pre class="programlisting">/*
 * Address families.
 */
#define AF_UNSPEC   0       /* unspecified */
#define AF_LOCAL    1       /* local to host (pipes, portals) */
#define AF_UNIX     AF_LOCAL    /* backward compatibility */
#define AF_INET     2       /* internetwork: UDP, TCP, etc. */
#define AF_IMPLINK  3       /* arpanet imp addresses */
#define AF_PUP      4       /* pup protocols: e.g. BSP */
#define AF_CHAOS    5       /* mit CHAOS protocols */
#define AF_NS       6       /* XEROX NS protocols */
#define AF_ISO      7       /* ISO protocols */
#define AF_OSI      AF_ISO
#define AF_ECMA     8       /* European computer manufacturers */
#define AF_DATAKIT  9       /* datakit protocols */
#define AF_CCITT    10      /* CCITT protocols, X.25 etc */
#define AF_SNA      11      /* IBM SNA */
#define AF_DECnet   12      /* DECnet */
#define AF_DLI      13      /* DEC Direct data link interface */
#define AF_LAT      14      /* LAT */
#define AF_HYLINK   15      /* NSC Hyperchannel */
#define AF_APPLETALK    16      /* Apple Talk */
#define AF_ROUTE    17      /* Internal Routing Protocol */
#define AF_LINK     18      /* Link layer interface */
#define pseudo_AF_XTP   19      /* eXpress Transfer Protocol (no AF) */
#define AF_COIP     20      /* connection-oriented IP, aka ST II */
#define AF_CNT      21      /* Computer Network Technology */
#define pseudo_AF_RTIP  22      /* Help Identify RTIP packets */
#define AF_IPX      23      /* Novell Internet Protocol */
#define AF_SIP      24      /* Simple Internet Protocol */
#define pseudo_AF_PIP   25      /* Help Identify PIP packets */
#define AF_ISDN     26      /* Integrated Services Digital Network*/
#define AF_E164     AF_ISDN     /* CCITT E.164 recommendation */
#define pseudo_AF_KEY   27      /* Internal key-management function */
#define AF_INET6    28      /* IPv6 */
#define AF_NATM     29      /* native ATM access */
#define AF_ATM      30      /* ATM */
#define pseudo_AF_HDRCMPLT 31       /* Used by BPF to not rewrite headers
                     * in interface output routine
                     */
#define AF_NETGRAPH 32      /* Netgraph sockets */

#define AF_MAX      33
</pre>
		</pkg:outlineMarker>


<p>The one used for <acronym class="acronym">IP</acronym> is <var class="symbol">AF_INET</var>. It is a symbol for the constant <code class="constant">2</code>.</p>

<p>It is the <span class="emphasis"><i class="emphasis">address family</i></span> listed
in the <var class="varname">sa_family</var> field of <var class="varname">sockaddr</var>
that decides how exactly the vaguely named bytes of <var class="varname">sa_data</var>
will be used.</p>

<p>Specifically, whenever the <span class="emphasis"><i class="emphasis">address
family</i></span> is <var class="symbol">AF_INET</var>, we can use <var class="varname">struct sockaddr_in</var> found in <tt class="filename">netinet/in.h</tt>,
wherever <var class="varname">sockaddr</var> is expected:</p>


		<pkg:outlineMarker OutlineName="code_30" id="code_30" visible="false" copy="true">
				<pre class="programlisting">/*
 * Socket address, internet style.
 */
struct sockaddr_in {
    u_char  sin_len;
    u_char  sin_family;
    u_short sin_port;
    struct  in_addr sin_addr;
    char    sin_zero[8];
};
</pre>
		</pkg:outlineMarker>


<p>We can visualize its organization this way:</p>

<p><img src="FreeBSDDevelopersHandbook_files/sain.png" /></p>

<p>The three important fields are <var class="varname">sin_family</var>, which is byte 1
of the structure, <var class="varname">sin_port</var>, a 16-bit value found in bytes 2
and 3, and <var class="varname">sin_addr</var>, a 32-bit integer representation of the
<acronym class="acronym">IP</acronym> address, stored in bytes 4-7.</p>

<p>Now, let us try to fill it out. Let us assume we are trying to write a client for the
<span class="emphasis"><i class="emphasis">daytime</i></span> protocol, which simply
states that its server will write a text string representing the current date and time to
port 13. We want to use <acronym class="acronym">TCP/IP</acronym>, so we need to specify
<code class="constant">AF_INET</code> in the address family field. <code class="constant">AF_INET</code> is defined as <code class="constant">2</code>. Let us use
the <acronym class="acronym">IP</acronym> address of <tt class="hostid">192.43.244.18</tt>, which is the time server of US federal government (<tt class="hostid">time.nist.gov</tt>).</p>

<p><img src="FreeBSDDevelopersHandbook_files/sainfill.png" /></p>

<p>By the way the <var class="varname">sin_addr</var> field is declared as being of the
<var class="varname">struct in_addr</var> type, which is defined in <tt class="filename">netinet/in.h</tt>:</p>


		<pkg:outlineMarker OutlineName="code_31" id="code_31" visible="false" copy="true">
				<pre class="programlisting">/*
 * Internet address (a structure for historical reasons)
 */
struct in_addr {
    in_addr_t s_addr;
};
</pre>
		</pkg:outlineMarker>


<p>In addition, <var class="varname">in_addr_t</var> is a 32-bit integer.</p>

<p>The <tt class="hostid">192.43.244.18</tt> is just a convenient notation of expressing
a 32-bit integer by listing all of its 8-bit bytes, starting with the <span class="emphasis"><i class="emphasis">most significant</i></span> one.</p>

<p>So far, we have viewed <var class="varname">sockaddr</var> as an abstraction. Our
computer does not store <var class="varname">short</var> integers as a single 16-bit
entity, but as a sequence of 2 bytes. Similarly, it stores 32-bit integers as a sequence
of 4 bytes.</p>

<p>Suppose we coded something like this:</p>


		<pkg:outlineMarker OutlineName="code_32" id="code_32" visible="false" copy="true">
				<pre class="programlisting">   sa.sin_family      = AF_INET;
    sa.sin_port        = 13;
    sa.sin_addr.s_addr = (((((192 &#60;&#60; 8) | 43) &#60;&#60; 8) | 244) &#60;&#60; 8) | 18;
</pre>
		</pkg:outlineMarker>


<p>What would the result look like?</p>

<p>Well, that depends, of course. On a <span class="trademark">Pentium</span>®, or
other x86, based computer, it would look like this:</p>

<p><img src="FreeBSDDevelopersHandbook_files/sainlsb.png" /></p>

<p>On a different system, it might look like this:</p>

<p><img src="FreeBSDDevelopersHandbook_files/sainmsb.png" /></p>

<p>And on a PDP it might look different yet. But the above two are the most common ways
in use today.</p>

<p>Ordinarily, wanting to write portable code, programmers pretend that these differences
do not exist. And they get away with it (except when they code in assembly language).
Alas, you cannot get away with it that easily when coding for sockets.</p>

<p>Why?</p>

<p>Because when communicating with another computer, you usually do not know whether it
stores data <span class="emphasis"><i class="emphasis">most significant byte</i></span>
(<acronym class="acronym">MSB</acronym>) or <span class="emphasis"><i class="emphasis">least significant byte</i></span> (<acronym class="acronym">LSB</acronym>) first.</p>

<p>You might be wondering, <span class="emphasis"><i class="emphasis">``So, will sockets
not handle it for me?''</i></span></p>

<p>It will not.</p>

<p>While that answer may surprise you at first, remember that the general sockets
interface only understands the <var class="varname">sa_len</var> and <var class="varname">sa_family</var> fields of the <var class="varname">sockaddr</var>
structure. You do not have to worry about the byte order there (of course, on FreeBSD
<var class="varname">sa_family</var> is only 1 byte anyway, but many other <span class="trademark">UNIX</span> systems do not have <var class="varname">sa_len</var> and
use 2 bytes for <var class="varname">sa_family</var>, and expect the data in whatever
order is native to the computer).</p>

<p>But the rest of the data is just <var class="varname">sa_data[14]</var> as far as
sockets goes. Depending on the <span class="emphasis"><i class="emphasis">address
family</i></span>, sockets just forwards that data to its destination.</p>

<p>Indeed, when we enter a port number, it is because we want the other computer to know
what service we are asking for. And, when we are the server, we read the port number so
we know what service the other computer is expecting from us. Either way, sockets only
has to forward the port number as data. It does not interpret it in any way.</p>

<p>Similarly, we enter the <acronym class="acronym">IP</acronym> address to tell everyone
on the way where to send our data to. Sockets, again, only forwards it as data.</p>

<p>That is why, we (the <span class="emphasis"><i class="emphasis">programmers</i></span>, not the <span class="emphasis"><i class="emphasis">sockets</i></span>) have to distinguish between the byte order used by
our computer and a conventional byte order to send the data in to the other computer.</p>

<p>We will call the byte order our computer uses the <span class="emphasis"><i class="emphasis">host byte order</i></span>, or just the <span class="emphasis"><i class="emphasis">host order</i></span>.</p>

<p>There is a convention of sending the multi-byte data over <acronym class="acronym">IP</acronym> <span class="emphasis"><i class="emphasis"><acronym class="acronym">MSB</acronym> first</i></span>. This, we will refer to as the <span class="emphasis"><i class="emphasis">network byte order</i></span>, or simply the <span class="emphasis"><i class="emphasis">network order</i></span>.</p>

<p>Now, if we compiled the above code for an Intel based computer, our <span class="emphasis"><i class="emphasis">host byte order</i></span> would produce:</p>

<p><img src="FreeBSDDevelopersHandbook_files/sainlsb.png" /></p>

<p>But the <span class="emphasis"><i class="emphasis">network byte order</i></span>
requires that we store the data <acronym class="acronym">MSB</acronym> first:</p>

<p><img src="FreeBSDDevelopersHandbook_files/sainmsb.png" /></p>

<p>Unfortunately, our <span class="emphasis"><i class="emphasis">host order</i></span> is
the exact opposite of the <span class="emphasis"><i class="emphasis">network
order</i></span>.</p>

<p>We have several ways of dealing with it. One would be to <span class="emphasis"><i class="emphasis">reverse</i></span> the values in our code:</p>


		<pkg:outlineMarker OutlineName="code_33" id="code_33" visible="false" copy="true">
				<pre class="programlisting">   sa.sin_family      = AF_INET;
    sa.sin_port        = 13 &#60;&#60; 8;
    sa.sin_addr.s_addr = (((((18 &#60;&#60; 8) | 244) &#60;&#60; 8) | 43) &#60;&#60; 8) | 192;
</pre>
		</pkg:outlineMarker>


<p>This will <span class="emphasis"><i class="emphasis">trick</i></span> our compiler
into storing the data in the <span class="emphasis"><i class="emphasis">network byte
order</i></span>. In some cases, this is exactly the way to do it (e.g., when programming
in assembly language). In most cases, however, it can cause a problem.</p>

<p>Suppose, you wrote a sockets-based program in C. You know it is going to run on a
<span class="trademark">Pentium</span>, so you enter all your constants in reverse and
force them to the <span class="emphasis"><i class="emphasis">network byte
order</i></span>. It works well.</p>

<p>Then, some day, your trusted old <span class="trademark">Pentium</span> becomes a
rusty old <span class="trademark">Pentium</span>. You replace it with a system whose
<span class="emphasis"><i class="emphasis">host order</i></span> is the same as the <span class="emphasis"><i class="emphasis">network order</i></span>. You need to recompile all
your software. All of your software continues to perform well, except the one program you
wrote.</p>

<p>You have since forgotten that you had forced all of your constants to the opposite of
the <span class="emphasis"><i class="emphasis">host order</i></span>. You spend some
quality time tearing out your hair, calling the names of all gods you ever heard of (and
some you made up), hitting your monitor with a nerf bat, and performing all the other
traditional ceremonies of trying to figure out why something that has worked so well is
suddenly not working at all.</p>

<p>Eventually, you figure it out, say a couple of swear words, and start rewriting your
code.</p>

<p>Luckily, you are not the first one to face the problem. Someone else has created the
<a href="http://www.freebsd.org/cgi/man.cgi?query=htons&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">htons</span>(3)</span></a> and <a href="http://www.freebsd.org/cgi/man.cgi?query=htonl&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">htonl</span>(3)</span></a> C functions
to convert a <var class="varname">short</var> and <var class="varname">long</var>
respectively from the <span class="emphasis"><i class="emphasis">host byte
order</i></span> to the <span class="emphasis"><i class="emphasis">network byte
order</i></span>, and the <a href="http://www.freebsd.org/cgi/man.cgi?query=ntohs&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">ntohs</span>(3)</span></a> and <a href="http://www.freebsd.org/cgi/man.cgi?query=ntohl&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">ntohl</span>(3)</span></a> C functions
to go the other way.</p>

<p>On <span class="emphasis"><i class="emphasis"><acronym class="acronym">MSB</acronym>-first</i></span> systems these functions do nothing. On
<span class="emphasis"><i class="emphasis"><acronym class="acronym">LSB</acronym>-first</i></span> systems they convert values to the proper
order.</p>

<p>So, regardless of what system your software is compiled on, your data will end up in
the correct order if you use these functions.</p>




<hr />

			</div>
		</pkg:outlineMarker>

		
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="8.5.1.2 Client Functions" id="SOCKETS-CLIENT-FUNCTIONS">
			<div class="sect3">
				<h4 class="title">8.5.1.2 Client Functions</h4>

<p>Typically, the client initiates the connection to the server. The client knows which
server it is about to call: It knows its <acronym class="acronym">IP</acronym> address,
and it knows the <span class="emphasis"><i class="emphasis">port</i></span> the server
resides at. It is akin to you picking up the phone and dialing the number (the <span class="emphasis"><i class="emphasis">address</i></span>), then, after someone answers,
asking for the person in charge of wingdings (the <span class="emphasis"><i class="emphasis">port</i></span>).</p>


<hr />

		<pkg:outlineMarker OutlineName="8.5.1.2.1 connect" id="SOCKETS-CONNECT">
			<div class="sect3">
				<h5 class="title">8.5.1.2.1 <code class="function">connect</code></h5>

<p>Once a client has created a socket, it needs to connect it to a specific port on a
remote system. It uses <a href="http://www.freebsd.org/cgi/man.cgi?query=connect&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">connect</span>(2)</span></a>:</p>


		<pkg:outlineMarker OutlineName="code_34" id="code_34" visible="false" copy="true">
				<pre class="programlisting">int connect(int s, const struct sockaddr *name, socklen_t namelen);
</pre>
		</pkg:outlineMarker>


<p>The <var class="varname">s</var> argument is the socket, i.e., the value returned by
the <code class="function">socket</code> function. The <var class="varname">name</var> is
a pointer to <var class="varname">sockaddr</var>, the structure we have talked about
extensively. Finaly, <var class="varname">namelen</var> informs the system how many bytes
are in our <var class="varname">sockaddr</var> structure.</p>

<p>If <code class="function">connect</code> is successful, it returns <code class="constant">0</code>. Otherwise it returns <code class="constant">-1</code> and
stores the error code in <var class="varname">errno</var>.</p>

<p>There are many reasons why <code class="function">connect</code> may fail. For
example, with an attempt to an Internet connection, the <acronym class="acronym">IP</acronym> address may not exist, or it may be down, or just too busy,
or it may not have a server listening at the specified port. Or it may outright <span class="emphasis"><i class="emphasis">refuse</i></span> any request for specific code.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="8.5.1.2.2 Our First Client" id="SOCKETS-FIRST-CLIENT">
			<div class="sect3">
				<h5 class="title">8.5.1.2.2 Our
First Client</h5>

<p>We now know enough to write a very simple client, one that will get current time from
<tt class="hostid">192.43.244.18</tt> and print it to <tt class="devicename">stdout</tt>.</p>


		<pkg:outlineMarker OutlineName="code_35" id="code_35" visible="false" copy="true">
				<pre class="programlisting">/*
 * daytime.c
 *
 * Programmed by G. Adam Stanislav
 */
#include &#60;stdio.h&#62;
#include &#60;sys/types.h&#62;
#include &#60;sys/socket.h&#62;
#include &#60;netinet/in.h&#62;

int main() {
  register int s;
  register int bytes;
  struct sockaddr_in sa;
  char buffer[BUFSIZ+1];

  if ((s = socket(PF_INET, SOCK_STREAM, 0)) &#60; 0) {
    perror("socket");
    return 1;
  }

  bzero(&#38;sa, sizeof sa);

  sa.sin_family = AF_INET;
  sa.sin_port = htons(13);
  sa.sin_addr.s_addr = htonl((((((192 &#60;&#60; 8) | 43) &#60;&#60; 8) | 244) &#60;&#60; 8) | 18);
  if (connect(s, (struct sockaddr *)&#38;sa, sizeof sa) &#60; 0) {
    perror("connect");
    close(s);
    return 2;
  }

  while ((bytes = read(s, buffer, BUFSIZ)) &#62; 0)
    write(1, buffer, bytes);

  close(s);
  return 0;
}
</pre>
		</pkg:outlineMarker>


<p>Go ahead, enter it in your editor, save it as <tt class="filename">daytime.c</tt>,
then compile and run it:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">cc -O3 -o daytime daytime.c</kbd>
<samp class="prompt">%</samp> <kbd class="userinput">./daytime</kbd>

52079 01-06-19 02:29:25 50 0 1 543.9 UTC(NIST) * 
<samp class="prompt">%</samp>
</pre>

<p>In this case, the date was June 19, 2001, the time was 02:29:25 <acronym class="acronym">UTC</acronym>. Naturally, your results will vary.</p>




<hr />

			</div>
		</pkg:outlineMarker>

		
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="8.5.1.3 Server Functions" id="SOCKETS-SERVER-FUNCTIONS">
			<div class="sect3">
				<h4 class="title">8.5.1.3 Server Functions</h4>

<p>The typical server does not initiate the connection. Instead, it waits for a client to
call it and request services. It does not know when the client will call, nor how many
clients will call. It may be just sitting there, waiting patiently, one moment, The next
moment, it can find itself swamped with requests from a number of clients, all calling in
at the same time.</p>

<p>The sockets interface offers three basic functions to handle this.</p>


<hr />

		<pkg:outlineMarker OutlineName="8.5.1.3.1 bind" id="SOCKETS-BIND">
			<div class="sect3">
				<h5 class="title">8.5.1.3.1 <code class="function">bind</code></h5>

<p>Ports are like extensions to a phone line: After you dial a number, you dial the
extension to get to a specific person or department.</p>

<p>There are 65535 <acronym class="acronym">IP</acronym> ports, but a server usually
processes requests that come in on only one of them. It is like telling the phone room
operator that we are now at work and available to answer the phone at a specific
extension. We use <a href="http://www.freebsd.org/cgi/man.cgi?query=bind&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">bind</span>(2)</span></a> to tell
sockets which port we want to serve.</p>


		<pkg:outlineMarker OutlineName="code_36" id="code_36" visible="false" copy="true">
				<pre class="programlisting">int bind(int s, const struct sockaddr *addr, socklen_t addrlen);
</pre>
		</pkg:outlineMarker>


<p>Beside specifying the port in <var class="varname">addr</var>, the server may include
its <acronym class="acronym">IP</acronym> address. However, it can just use the symbolic
constant <var class="symbol">INADDR_ANY</var> to indicate it will serve all requests to
the specified port regardless of what its <acronym class="acronym">IP</acronym> address
is. This symbol, along with several similar ones, is declared in <tt class="filename">netinet/in.h</tt></p>


		<pkg:outlineMarker OutlineName="code_37" id="code_37" visible="false" copy="true">
				<pre class="programlisting">#define    INADDR_ANY      (u_int32_t)0x00000000
</pre>
		</pkg:outlineMarker>


<p>Suppose we were writing a server for the <span class="emphasis"><i class="emphasis">daytime</i></span> protocol over <acronym class="acronym">TCP</acronym>/<acronym class="acronym">IP</acronym>. Recall that it uses
port 13. Our <var class="varname">sockaddr_in</var> structure would look like this:</p>

<p><img src="FreeBSDDevelopersHandbook_files/sainserv.png" /></p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="8.5.1.3.2 listen" id="SOCKETS-LISTEN">
			<div class="sect3">
				<h5 class="title">8.5.1.3.2 <code class="function">listen</code></h5>

<p>To continue our office phone analogy, after you have told the phone central operator
what extension you will be at, you now walk into your office, and make sure your own
phone is plugged in and the ringer is turned on. Plus, you make sure your call waiting is
activated, so you can hear the phone ring even while you are talking to someone.</p>

<p>The server ensures all of that with the <a href="http://www.freebsd.org/cgi/man.cgi?query=listen&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">listen</span>(2)</span></a>
function.</p>


		<pkg:outlineMarker OutlineName="code_38" id="code_38" visible="false" copy="true">
				<pre class="programlisting">int listen(int s, int backlog);
</pre>
		</pkg:outlineMarker>


<p>In here, the <var class="varname">backlog</var> variable tells sockets how many
incoming requests to accept while you are busy processing the last request. In other
words, it determines the maximum size of the queue of pending connections.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="8.5.1.3.3 accept" id="SOCKETS-ACCEPT">
			<div class="sect3">
				<h5 class="title">8.5.1.3.3 <code class="function">accept</code></h5>

<p>After you hear the phone ringing, you accept the call by answering the call. You have
now established a connection with your client. This connection remains active until
either you or your client hang up.</p>

<p>The server accepts the connection by using the <a href="http://www.freebsd.org/cgi/man.cgi?query=accept&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">accept</span>(2)</span></a>
function.</p>


		<pkg:outlineMarker OutlineName="code_39" id="code_39" visible="false" copy="true">
				<pre class="programlisting">int accept(int s, struct sockaddr *addr, socklen_t *addrlen);
</pre>
		</pkg:outlineMarker>


<p>Note that this time <var class="varname">addrlen</var> is a pointer. This is necessary
because in this case it is the socket that fills out <var class="varname">addr</var>, the
<var class="varname">sockaddr_in</var> structure.</p>

<p>The return value is an integer. Indeed, the <code class="function">accept</code>
returns a <span class="emphasis"><i class="emphasis">new socket</i></span>. You will use
this new socket to communicate with the client.</p>

<p>What happens to the old socket? It continues to listen for more requests (remember the
<var class="varname">backlog</var> variable we passed to <code class="function">listen</code>?) until we <code class="function">close</code> it.</p>

<p>Now, the new socket is meant only for communications. It is fully connected. We cannot
pass it to <code class="function">listen</code> again, trying to accept additional
connections.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="8.5.1.3.4 Our First Server" id="SOCKETS-FIRST-SERVER">
			<div class="sect3">
				<h5 class="title">8.5.1.3.4 Our
First Server</h5>

<p>Our first server will be somewhat more complex than our first client was: Not only do
we have more sockets functions to use, but we need to write it as a daemon.</p>

<p>This is best achieved by creating a <span class="emphasis"><i class="emphasis">child
process</i></span> after binding the port. The main process then exits and returns
control to the <b class="application">shell</b> (or whatever program invoked it).</p>

<p>The child calls <code class="function">listen</code>, then starts an endless loop,
which accepts a connection, serves it, and eventually closes its socket.</p>


		<pkg:outlineMarker OutlineName="code_40" id="code_40" visible="false" copy="true">
				<pre class="programlisting">/*
 * daytimed - a port 13 server
 *
 * Programmed by G. Adam Stanislav
 * June 19, 2001
 */
#include &#60;stdio.h&#62;
#include &#60;time.h&#62;
#include &#60;unistd.h&#62;
#include &#60;sys/types.h&#62;
#include &#60;sys/socket.h&#62;
#include &#60;netinet/in.h&#62;

#define BACKLOG 4

int main() {
    register int s, c;
    int b;
    struct sockaddr_in sa;
    time_t t;
    struct tm *tm;
    FILE *client;

    if ((s = socket(PF_INET, SOCK_STREAM, 0)) &#60; 0) {
        perror("socket");
        return 1;
    }

    bzero(&#38;sa, sizeof sa);

    sa.sin_family = AF_INET;
    sa.sin_port   = htons(13);

    if (INADDR_ANY)
        sa.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(s, (struct sockaddr *)&#38;sa, sizeof sa) &#60; 0) {
        perror("bind");
        return 2;
    }

    switch (fork()) {
        case -1:
            perror("fork");
            return 3;
            break;
        default:
            close(s);
            return 0;
            break;
        case 0:
            break;
    }

    listen(s, BACKLOG);

    for (;;) {
        b = sizeof sa;

        if ((c = accept(s, (struct sockaddr *)&#38;sa, &#38;b)) &#60; 0) {
            perror("daytimed accept");
            return 4;
        }

        if ((client = fdopen(c, "w")) == NULL) {
            perror("daytimed fdopen");
            return 5;
        }

        if ((t = time(NULL)) &#60; 0) {
            perror("daytimed time");

            return 6;
        }

        tm = gmtime(&#38;t);
        fprintf(client, "%.4i-%.2i-%.2iT%.2i:%.2i:%.2iZ\n",
            tm-&#62;tm_year + 1900,
            tm-&#62;tm_mon + 1,
            tm-&#62;tm_mday,
            tm-&#62;tm_hour,
            tm-&#62;tm_min,
            tm-&#62;tm_sec);

        fclose(client);
    }
}
</pre>
		</pkg:outlineMarker>


<p>We start by creating a socket. Then we fill out the <var class="varname">sockaddr_in</var> structure in <var class="varname">sa</var>. Note the
conditional use of <var class="symbol">INADDR_ANY</var>:</p>


		<pkg:outlineMarker OutlineName="code_41" id="code_41" visible="false" copy="true">
				<pre class="programlisting">    if (INADDR_ANY)
        sa.sin_addr.s_addr = htonl(INADDR_ANY);
</pre>
		</pkg:outlineMarker>


<p>Its value is <code class="constant">0</code>. Since we have just used <code class="function">bzero</code> on the entire structure, it would be redundant to set it to
<code class="constant">0</code> again. But if we port our code to some other system where
<var class="symbol">INADDR_ANY</var> is perhaps not a zero, we need to assign it to <var class="varname">sa.sin_addr.s_addr</var>. Most modern C compilers are clever enough to
notice that <var class="symbol">INADDR_ANY</var> is a constant. As long as it is a zero,
they will optimize the entire conditional statement out of the code.</p>

<p>After we have called <code class="function">bind</code> successfully, we are ready to
become a <span class="emphasis"><i class="emphasis">daemon</i></span>: We use <code class="function">fork</code> to create a child process. In both, the parent and the
child, the <var class="varname">s</var> variable is our socket. The parent process will
not need it, so it calls <code class="function">close</code>, then it returns <code class="constant">0</code> to inform its own parent it had terminated successfully.</p>

<p>Meanwhile, the child process continues working in the background. It calls <code class="function">listen</code> and sets its backlog to <code class="constant">4</code>.
It does not need a large value here because <span class="emphasis"><i class="emphasis">daytime</i></span> is not a protocol many clients request all the time,
and because it can process each request instantly anyway.</p>

<p>Finally, the daemon starts an endless loop, which performs the following steps:</p>


<ol type="1">
<li>
<p>Call <code class="function">accept</code>. It waits here until a client contacts it.
At that point, it receives a new socket, <var class="varname">c</var>, which it can use
to communicate with this particular client.</p>
</li>

<li>
<p>It uses the C function <code class="function">fdopen</code> to turn the socket from a
low-level <span class="emphasis"><i class="emphasis">file descriptor</i></span> to a
C-style <var class="varname">FILE</var> pointer. This will allow the use of <code class="function">fprintf</code> later on.</p>
</li>

<li>
<p>It checks the time, and prints it in the <span class="emphasis"><i class="emphasis"><acronym class="acronym">ISO</acronym> 8601</i></span> format to the
<var class="varname">client</var> ``file''. It then uses <code class="function">fclose</code> to close the file. That will automatically close the
socket as well.</p>
</li>
</ol>


<p>We can <span class="emphasis"><i class="emphasis">generalize</i></span> this, and use
it as a model for many other servers:</p>

<p><img src="FreeBSDDevelopersHandbook_files/serv.png" /></p>

<p>This flowchart is good for <span class="emphasis"><i class="emphasis">sequential
servers</i></span>, i.e., servers that can serve one client at a time, just as we were
able to with our <span class="emphasis"><i class="emphasis">daytime</i></span> server.
This is only possible whenever there is no real ``conversation'' going on between the
client and the server: As soon as the server detects a connection to the client, it sends
out some data and closes the connection. The entire operation may take nanoseconds, and
it is finished.</p>

<p>The advantage of this flowchart is that, except for the brief moment after the parent
<code class="function">fork</code>s and before it exits, there is always only one <span class="emphasis"><i class="emphasis">process</i></span> active: Our server does not take
up much memory and other system resources.</p>

<p>Note that we have added <span class="emphasis"><i class="emphasis">initialize
daemon</i></span> in our flowchart. We did not need to initialize our own daemon, but
this is a good place in the flow of the program to set up any <code class="function">signal</code> handlers, open any files we may need, etc.</p>

<p>Just about everything in the flow chart can be used literally on many different
servers. The <span class="emphasis"><i class="emphasis">serve</i></span> entry is the
exception. We think of it as a <span class="emphasis"><i class="emphasis">``black
box''</i></span>, i.e., something you design specifically for your own server, and just
``plug it into the rest.''</p>

<p>Not all protocols are that simple. Many receive a request from the client, reply to
it, then receive another request from the same client. Because of that, they do not know
in advance how long they will be serving the client. Such servers usually start a new
process for each client. While the new process is serving its client, the daemon can
continue listening for more connections.</p>

<p>Now, go ahead, save the above source code as <tt class="filename">daytimed.c</tt> (it
is customary to end the names of daemons with the letter <code class="constant">d</code>). After you have compiled it, try running it:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">./daytimed</kbd>
bind: Permission denied
<samp class="prompt">%</samp>
</pre>

<p>What happened here? As you will recall, the <span class="emphasis"><i class="emphasis">daytime</i></span> protocol uses port 13. But all ports below 1024 are
reserved to the superuser (otherwise, anyone could start a daemon pretending to serve a
commonly used port, while causing a security breach).</p>

<p>Try again, this time as the superuser:</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">./daytimed</kbd>
<samp class="prompt">#</samp>
</pre>

<p>What... Nothing? Let us try again:</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">./daytimed</kbd>

bind: Address already in use
<samp class="prompt">#</samp>
</pre>

<p>Every port can only be bound by one program at a time. Our first attempt was indeed
successful: It started the child daemon and returned quietly. It is still running and
will continue to run until you either kill it, or any of its system calls fail, or you
reboot the system.</p>

<p>Fine, we know it is running in the background. But is it working? How do we know it is
a proper <span class="emphasis"><i class="emphasis">daytime</i></span> server?
Simple:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">telnet localhost 13</kbd>

Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
2001-06-19T21:04:42Z
Connection closed by foreign host.
<samp class="prompt">%</samp>
</pre>

<p><b class="application">telnet</b> tried the new <acronym class="acronym">IP</acronym>v6, and failed. It retried with <acronym class="acronym">IP</acronym>v4 and succeeded. The daemon works.</p>

<p>If you have access to another <span class="trademark">UNIX</span> system via <b class="application">telnet</b>, you can use it to test accessing the server remotely. My
computer does not have a static <acronym class="acronym">IP</acronym> address, so this is
what I did:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">who</kbd>

whizkid          ttyp0   Jun 19 16:59   (216.127.220.143)
xxx              ttyp1   Jun 19 16:06   (xx.xx.xx.xx)
<samp class="prompt">%</samp> <kbd class="userinput">telnet 216.127.220.143 13</kbd>

Trying 216.127.220.143...
Connected to r47.bfm.org.
Escape character is '^]'.
2001-06-19T21:31:11Z
Connection closed by foreign host.
<samp class="prompt">%</samp>
</pre>

<p>Again, it worked. Will it work using the domain name?</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">telnet r47.bfm.org 13</kbd>

Trying 216.127.220.143...
Connected to r47.bfm.org.
Escape character is '^]'.
2001-06-19T21:31:40Z
Connection closed by foreign host.
<samp class="prompt">%</samp>
</pre>

<p>By the way, <b class="application">telnet</b> prints the <span class="emphasis"><i class="emphasis">Connection closed by foreign host</i></span> message after our daemon
has closed the socket. This shows us that, indeed, using <code class="function">fclose(client);</code> in our code works as advertised.</p>






<hr />

		</div>
	</pkg:outlineMarker>

	
			</div>
		</pkg:outlineMarker>

			</div>
		</pkg:outlineMarker>

			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="8.6 Helper Functions" id="SOCKETS-HELPER-FUNCTIONS">
		<div class="sect2">
			<h2 class="title">8.6
Helper Functions</h2>

<p>FreeBSD C library contains many helper functions for sockets programming. For example,
in our sample client we hard coded the <tt class="hostid">time.nist.gov</tt> <acronym class="acronym">IP</acronym> address. But we do not always know the <acronym class="acronym">IP</acronym> address. Even if we do, our software is more flexible if it
allows the user to enter the <acronym class="acronym">IP</acronym> address, or even the
domain name.</p>


<hr />

		<pkg:outlineMarker OutlineName="8.6.1 gethostbyname" id="SOCKETS-GETHOSTBYNAME">
			<div class="sect3">
				<h3 class="title">8.6.1 <code class="function">gethostbyname</code></h3>

<p>While there is no way to pass the domain name directly to any of the sockets
functions, the FreeBSD C library comes with the <a href="http://www.freebsd.org/cgi/man.cgi?query=gethostbyname&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">gethostbyname</span>(3)</span></a> and
<a href="http://www.freebsd.org/cgi/man.cgi?query=gethostbyname2&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">gethostbyname2</span>(3)</span></a>
functions, declared in <tt class="filename">netdb.h</tt>.</p>


		<pkg:outlineMarker OutlineName="code_42" id="code_42" visible="false" copy="true">
				<pre class="programlisting">struct hostent * gethostbyname(const char *name);
struct hostent * gethostbyname2(const char *name, int af);
</pre>
		</pkg:outlineMarker>


<p>Both return a pointer to the <var class="varname">hostent</var> structure, with much
information about the domain. For our purposes, the <var class="varname">h_addr_list[0]</var> field of the structure points at <var class="varname">h_length</var> bytes of the correct address, already stored in the <span class="emphasis"><i class="emphasis">network byte order</i></span>.</p>

<p>This allows us to create a much more flexible--and much more useful--version of our <b class="application">daytime</b> program:</p>


		<pkg:outlineMarker OutlineName="code_43" id="code_43" visible="false" copy="true">
				<pre class="programlisting">/*
 * daytime.c
 *
 * Programmed by G. Adam Stanislav
 * 19 June 2001
 */
#include &#60;stdio.h&#62;
#include &#60;string.h&#62;
#include &#60;sys/types.h&#62;
#include &#60;sys/socket.h&#62;
#include &#60;netinet/in.h&#62;
#include &#60;netdb.h&#62;

int main(int argc, char *argv[]) {
  register int s;
  register int bytes;
  struct sockaddr_in sa;
  struct hostent *he;
  char buf[BUFSIZ+1];
  char *host;

  if ((s = socket(PF_INET, SOCK_STREAM, 0)) &#60; 0) {
    perror("socket");
    return 1;
  }

  bzero(&#38;sa, sizeof sa);

  sa.sin_family = AF_INET;
  sa.sin_port = htons(13);

  host = (argc &#62; 1) ? (char *)argv[1] : "time.nist.gov";

  if ((he = gethostbyname(host)) == NULL) {
    herror(host);
    return 2;
  }

  bcopy(he-&#62;h_addr_list[0],&#38;sa.sin_addr, he-&#62;h_length);

  if (connect(s, (struct sockaddr *)&#38;sa, sizeof sa) &#60; 0) {
    perror("connect");
    return 3;
  }

  while ((bytes = read(s, buf, BUFSIZ)) &#62; 0)
    write(1, buf, bytes);

  close(s);
  return 0;
}
</pre>
		</pkg:outlineMarker>


<p>We now can type a domain name (or an <acronym class="acronym">IP</acronym> address, it
works both ways) on the command line, and the program will try to connect to its <span class="emphasis"><i class="emphasis">daytime</i></span> server. Otherwise, it will still
default to <tt class="hostid">time.nist.gov</tt>. However, even in this case we will use
<code class="function">gethostbyname</code> rather than hard coding <tt class="hostid">192.43.244.18</tt>. That way, even if its <acronym class="acronym">IP</acronym> address changes in the future, we will still find it.</p>

<p>Since it takes virtually no time to get the time from your local server, you could run
<b class="application">daytime</b> twice in a row: First to get the time from <tt class="hostid">time.nist.gov</tt>, the second time from your own system. You can then
compare the results and see how exact your system clock is:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">daytime ; daytime localhost</kbd>


52080 01-06-20 04:02:33 50 0 0 390.2 UTC(NIST) * 
2001-06-20T04:02:35Z
<samp class="prompt">%</samp>
</pre>

<p>As you can see, my system was two seconds ahead of the <acronym class="acronym">NIST</acronym> time.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="8.6.2 getservbyname" id="SOCKETS-GETSERVBYNAME">
			<div class="sect3">
				<h3 class="title">8.6.2 <code class="function">getservbyname</code></h3>

<p>Sometimes you may not be sure what port a certain service uses. The <a href="http://www.freebsd.org/cgi/man.cgi?query=getservbyname&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getservbyname</span>(3)</span></a>
function, also declared in <tt class="filename">netdb.h</tt> comes in very handy in those
cases:</p>


		<pkg:outlineMarker OutlineName="code_44" id="code_44" visible="false" copy="true">
				<pre class="programlisting">struct servent * getservbyname(const char *name, const char *proto);
</pre>
		</pkg:outlineMarker>


<p>The <var class="varname">servent</var> structure contains the <var class="varname">s_port</var>, which contains the proper port, already in <span class="emphasis"><i class="emphasis">network byte order</i></span>.</p>

<p>Had we not known the correct port for the <span class="emphasis"><i class="emphasis">daytime</i></span> service, we could have found it this way:</p>


		<pkg:outlineMarker OutlineName="code_45" id="code_45" visible="false" copy="true">
				<pre class="programlisting">  struct servent *se;
  ...
  if ((se = getservbyname("daytime", "tcp")) == NULL {
    fprintf(stderr, "Cannot determine which port to use.\n");
    return 7;
  }
  sa.sin_port = se-&#62;s_port;
</pre>
		</pkg:outlineMarker>


<p>You usually do know the port. But if you are developing a new protocol, you may be
testing it on an unofficial port. Some day, you will register the protocol and its port
(if nowhere else, at least in your <tt class="filename">/etc/services</tt>, which is
where <code class="function">getservbyname</code> looks). Instead of returning an error
in the above code, you just use the temporary port number. Once you have listed the
protocol in <tt class="filename">/etc/services</tt>, your software will find its port
without you having to rewrite the code.</p>




<hr />

		</div>
	</pkg:outlineMarker>

	
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="8.7 Concurrent Servers" id="SOCKETS-CONCURRENT-SERVERS">
		<div class="sect2">
			<h2 class="title">8.7 Concurrent Servers</h2>

<p>Unlike a sequential server, a <span class="emphasis"><i class="emphasis">concurrent
server</i></span> has to be able to serve more than one client at a time. For example, a
<span class="emphasis"><i class="emphasis">chat server</i></span> may be serving a
specific client for hours--it cannot wait till it stops serving a client before it serves
the next one.</p>

<p>This requires a significant change in our flowchart:</p>

<p><img src="FreeBSDDevelopersHandbook_files/serv2.png" /></p>

<p>We moved the <span class="emphasis"><i class="emphasis">serve</i></span> from the
<span class="emphasis"><i class="emphasis">daemon process</i></span> to its own <span class="emphasis"><i class="emphasis">server process</i></span>. However, because each
child process inherits all open files (and a socket is treated just like a file), the new
process inherits not only the <span class="emphasis"><i class="emphasis">``accepted
handle,''</i></span> i.e., the socket returned by the <code class="function">accept</code> call, but also the <span class="emphasis"><i class="emphasis">top socket</i></span>, i.e., the one opened by the top process right at
the beginning.</p>

<p>However, the <span class="emphasis"><i class="emphasis">server process</i></span> does
not need this socket and should <code class="function">close</code> it immediately.
Similarly, the <span class="emphasis"><i class="emphasis">daemon process</i></span> no
longer needs the <span class="emphasis"><i class="emphasis">accepted socket</i></span>,
and not only should, but <span class="emphasis"><i class="emphasis">must</i></span> <code class="function">close</code> it--otherwise, it will run out of available <span class="emphasis"><i class="emphasis">file descriptors</i></span> sooner or later.</p>

<p>After the <span class="emphasis"><i class="emphasis">server process</i></span> is done
serving, it should close the <span class="emphasis"><i class="emphasis">accepted
socket</i></span>. Instead of returning to <code class="function">accept</code>, it now
exits.</p>

<p>Under <span class="trademark">UNIX</span>, a process does not really <span class="emphasis"><i class="emphasis">exit</i></span>. Instead, it <span class="emphasis"><i class="emphasis">returns</i></span> to its parent. Typically, a
parent process <code class="function">wait</code>s for its child process, and obtains a
return value. However, our <span class="emphasis"><i class="emphasis">daemon
process</i></span> cannot simply stop and wait. That would defeat the whole purpose of
creating additional processes. But if it never does <code class="function">wait</code>,
its children will become <span class="emphasis"><i class="emphasis">zombies</i></span>--no longer functional but still roaming around.</p>

<p>For that reason, the <span class="emphasis"><i class="emphasis">daemon
process</i></span> needs to set <span class="emphasis"><i class="emphasis">signal
handlers</i></span> in its <span class="emphasis"><i class="emphasis">initialize
daemon</i></span> phase. At least a <var class="symbol">SIGCHLD</var> signal has to be
processed, so the daemon can remove the zombie return values from the system and release
the system resources they are taking up.</p>

<p>That is why our flowchart now contains a <span class="emphasis"><i class="emphasis">process signals</i></span> box, which is not connected to any other box.
By the way, many servers also process <var class="symbol">SIGHUP</var>, and typically
interpret as the signal from the superuser that they should reread their configuration
files. This allows us to change settings without having to kill and restart these
servers.</p>




<hr />

	</div>
</pkg:outlineMarker>


		</div>
	</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="Chapter 9 IPv6 Internals" id="IPV6">
	<div class="sect1">
		<h1 class="title">Chapter 9 IPv6 Internals</h1>



	<pkg:outlineMarker OutlineName="9.1 IPv6/IPsec Implementation" id="IPV6-IMPLEMENTATION">
		<div class="sect2">
			<h2 class="title">9.1 IPv6/IPsec
Implementation</h2>

<i class="authorgroup"><span class="contrib">Contributed by</span> Yoshinobu Inoue.</i> 

<p>This section should explain IPv6 and IPsec related implementation internals. These
functionalities are derived from <a href="http://www.kame.net/" target="_top">KAME
project</a></p>


<hr />

		<pkg:outlineMarker OutlineName="9.1.1 IPv6" id="IPV6DETAILS">
			<div class="sect3">
				<h3 class="title">9.1.1 IPv6</h3>



		<pkg:outlineMarker OutlineName="9.1.1.1 Conformance" id="AEN2706">
			<div class="sect3">
				<h4 class="title">9.1.1.1 Conformance</h4>

<p>The IPv6 related functions conforms, or tries to conform to the latest set of IPv6
specifications. For future reference we list some of the relevant documents below (<span class="emphasis"><i class="emphasis">NOTE</i></span>: this is not a complete list - this
is too hard to maintain...).</p>

<p>For details please refer to specific chapter in the document, RFCs, manual pages, or
comments in the source code.</p>

<p>Conformance tests have been performed on the KAME STABLE kit at TAHI project. Results
can be viewed at <a href="http://www.tahi.org/report/KAME/" target="_top">http://www.tahi.org/report/KAME/</a>. We also attended Univ. of New
Hampshire IOL tests (<a href="http://www.iol.unh.edu/" target="_top">http://www.iol.unh.edu/</a>) in the past, with our past snapshots.</p>

<ul>
<li>
<p>RFC1639: FTP Operation Over Big Address Records (FOOBAR)</p>

<ul>
<li>
<p>RFC2428 is preferred over RFC1639. FTP clients will first try RFC2428, then RFC1639 if
failed.</p>
</li>
</ul>
</li>

<li>
<p>RFC1886: DNS Extensions to support IPv6</p>
</li>

<li>
<p>RFC1933: Transition Mechanisms for IPv6 Hosts and Routers</p>

<ul>
<li>
<p>IPv4 compatible address is not supported.</p>
</li>

<li>
<p>automatic tunneling (described in 4.3 of this RFC) is not supported.</p>
</li>

<li>
<p><a href="http://www.freebsd.org/cgi/man.cgi?query=gif&#38;sektion=4"><span class="citerefentry"><span class="refentrytitle">gif</span>(4)</span></a> interface
implements IPv[46]-over-IPv[46] tunnel in a generic way, and it covers "configured
tunnel" described in the spec. See <a href="pkg://FreeBSD Developers' Handbook/GIF">23.5.1.5</a> in this document for
details.</p>
</li>
</ul>
</li>

<li>
<p>RFC1981: Path MTU Discovery for IPv6</p>
</li>

<li>
<p>RFC2080: RIPng for IPv6</p>

<ul>
<li>
<p>usr.sbin/route6d support this.</p>
</li>
</ul>
</li>

<li>
<p>RFC2292: Advanced Sockets API for IPv6</p>

<ul>
<li>
<p>For supported library functions/kernel APIs, see <tt class="filename">sys/netinet6/ADVAPI</tt>.</p>
</li>
</ul>
</li>

<li>
<p>RFC2362: Protocol Independent Multicast-Sparse Mode (PIM-SM)</p>

<ul>
<li>
<p>RFC2362 defines packet formats for PIM-SM. <tt class="filename">draft-ietf-pim-ipv6-01.txt</tt> is written based on this.</p>
</li>
</ul>
</li>

<li>
<p>RFC2373: IPv6 Addressing Architecture</p>

<ul>
<li>
<p>supports node required addresses, and conforms to the scope requirement.</p>
</li>
</ul>
</li>

<li>
<p>RFC2374: An IPv6 Aggregatable Global Unicast Address Format</p>

<ul>
<li>
<p>supports 64-bit length of Interface ID.</p>
</li>
</ul>
</li>

<li>
<p>RFC2375: IPv6 Multicast Address Assignments</p>

<ul>
<li>
<p>Userland applications use the well-known addresses assigned in the RFC.</p>
</li>
</ul>
</li>

<li>
<p>RFC2428: FTP Extensions for IPv6 and NATs</p>

<ul>
<li>
<p>RFC2428 is preferred over RFC1639. FTP clients will first try RFC2428, then RFC1639 if
failed.</p>
</li>
</ul>
</li>

<li>
<p>RFC2460: IPv6 specification</p>
</li>

<li>
<p>RFC2461: Neighbor discovery for IPv6</p>

<ul>
<li>
<p>See <a href="pkg://FreeBSD Developers' Handbook/NEIGHBOR-DISCOVERY">23.5.1.2</a> in this document for details.</p>
</li>
</ul>
</li>

<li>
<p>RFC2462: IPv6 Stateless Address Autoconfiguration</p>

<ul>
<li>
<p>See <a href="pkg://FreeBSD Developers' Handbook/IPV6-PNP">23.5.1.4</a> in this document for details.</p>
</li>
</ul>
</li>

<li>
<p>RFC2463: ICMPv6 for IPv6 specification</p>

<ul>
<li>
<p>See <a href="pkg://FreeBSD Developers' Handbook/ICMPV6">23.5.1.9</a> in this document for details.</p>
</li>
</ul>
</li>

<li>
<p>RFC2464: Transmission of IPv6 Packets over Ethernet Networks</p>
</li>

<li>
<p>RFC2465: MIB for IPv6: Textual Conventions and General Group</p>

<ul>
<li>
<p>Necessary statistics are gathered by the kernel. Actual IPv6 MIB support is provided
as a patchkit for ucd-snmp.</p>
</li>
</ul>
</li>

<li>
<p>RFC2466: MIB for IPv6: ICMPv6 group</p>

<ul>
<li>
<p>Necessary statistics are gathered by the kernel. Actual IPv6 MIB support is provided
as patchkit for ucd-snmp.</p>
</li>
</ul>
</li>

<li>
<p>RFC2467: Transmission of IPv6 Packets over FDDI Networks</p>
</li>

<li>
<p>RFC2497: Transmission of IPv6 packet over ARCnet Networks</p>
</li>

<li>
<p>RFC2553: Basic Socket Interface Extensions for IPv6</p>

<ul>
<li>
<p>IPv4 mapped address (3.7) and special behavior of IPv6 wildcard bind socket (3.8) are
supported. See <a href="pkg://FreeBSD Developers' Handbook/IPV6-WILDCARD-SOCKET">23.5.1.12</a> in this document for
details.</p>
</li>
</ul>
</li>

<li>
<p>RFC2675: IPv6 Jumbograms</p>

<ul>
<li>
<p>See <a href="pkg://FreeBSD Developers' Handbook/IPV6-JUMBO">23.5.1.7</a> in this document for details.</p>
</li>
</ul>
</li>

<li>
<p>RFC2710: Multicast Listener Discovery for IPv6</p>
</li>

<li>
<p>RFC2711: IPv6 router alert option</p>
</li>

<li>
<p><tt class="filename">draft-ietf-ipngwg-router-renum-08</tt>: Router renumbering for
IPv6</p>
</li>

<li>
<p><tt class="filename">draft-ietf-ipngwg-icmp-namelookups-02</tt>: IPv6 Name Lookups
Through ICMP</p>
</li>

<li>
<p><tt class="filename">draft-ietf-ipngwg-icmp-name-lookups-03</tt>: IPv6 Name Lookups
Through ICMP</p>
</li>

<li>
<p><tt class="filename">draft-ietf-pim-ipv6-01.txt</tt>: PIM for IPv6</p>

<ul>
<li>
<p><a href="http://www.freebsd.org/cgi/man.cgi?query=pim6dd&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">pim6dd</span>(8)</span></a> implements
dense mode. <a href="http://www.freebsd.org/cgi/man.cgi?query=pim6sd&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">pim6sd</span>(8)</span></a> implements
sparse mode.</p>
</li>
</ul>
</li>

<li>
<p><tt class="filename">draft-itojun-ipv6-tcp-to-anycast-00</tt>: Disconnecting TCP
connection toward IPv6 anycast address</p>
</li>

<li>
<p><tt class="filename">draft-yamamoto-wideipv6-comm-model-00</tt></p>

<ul>
<li>
<p>See <a href="pkg://FreeBSD Developers' Handbook/IPV6-SAS">23.5.1.6</a> in this document for details.</p>
</li>
</ul>
</li>

<li>
<p><tt class="filename">draft-ietf-ipngwg-scopedaddr-format-00.txt</tt> : An Extension of
Format for IPv6 Scoped Addresses</p>
</li>
</ul>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.2 Neighbor Discovery" id="NEIGHBOR-DISCOVERY">
			<div class="sect3">
				<h4 class="title">9.1.1.2 Neighbor
Discovery</h4>

<p>Neighbor Discovery is fairly stable. Currently Address Resolution, Duplicated Address
Detection, and Neighbor Unreachability Detection are supported. In the near future we
will be adding Proxy Neighbor Advertisement support in the kernel and Unsolicited
Neighbor Advertisement transmission command as admin tool.</p>

<p>If DAD fails, the address will be marked "duplicated" and message will be generated to
syslog (and usually to console). The "duplicated" mark can be checked with <a href="http://www.freebsd.org/cgi/man.cgi?query=ifconfig&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">ifconfig</span>(8)</span></a>. It is
administrators' responsibility to check for and recover from DAD failures. The behavior
should be improved in the near future.</p>

<p>Some of the network driver loops multicast packets back to itself, even if instructed
not to do so (especially in promiscuous mode). In such cases DAD may fail, because DAD
engine sees inbound NS packet (actually from the node itself) and considers it as a sign
of duplicate. You may want to look at #if condition marked "heuristics" in
sys/netinet6/nd6_nbr.c:nd6_dad_timer() as workaround (note that the code fragment in
"heuristics" section is not spec conformant).</p>

<p>Neighbor Discovery specification (RFC2461) does not talk about neighbor cache handling
in the following cases:</p>

<ol type="1">
<li>
<p>when there was no neighbor cache entry, node received unsolicited RS/NS/NA/redirect
packet without link-layer address</p>
</li>

<li>
<p>neighbor cache handling on medium without link-layer address (we need a neighbor cache
entry for IsRouter bit)</p>
</li>
</ol>

<p>For first case, we implemented workaround based on discussions on IETF ipngwg mailing
list. For more details, see the comments in the source code and email thread started from
(IPng 7155), dated Feb 6 1999.</p>

<p>IPv6 on-link determination rule (RFC2461) is quite different from assumptions in BSD
network code. At this moment, no on-link determination rule is supported where default
router list is empty (RFC2461, section 5.2, last sentence in 2nd paragraph - note that
the spec misuse the word "host" and "node" in several places in the section).</p>

<p>To avoid possible DoS attacks and infinite loops, only 10 options on ND packet is
accepted now. Therefore, if you have 20 prefix options attached to RA, only the first 10
prefixes will be recognized. If this troubles you, please ask it on FREEBSD-CURRENT
mailing list and/or modify nd6_maxndopt in <tt class="filename">sys/netinet6/nd6.c</tt>.
If there are high demands we may provide sysctl knob for the variable.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.3 Scope Index" id="IPV6-SCOPE-INDEX">
			<div class="sect3">
				<h4 class="title">9.1.1.3 Scope
Index</h4>

<p>IPv6 uses scoped addresses. Therefore, it is very important to specify scope index
(interface index for link-local address, or site index for site-local address) with an
IPv6 address. Without scope index, scoped IPv6 address is ambiguous to the kernel, and
kernel will not be able to determine the outbound interface for a packet.</p>

<p>Ordinary userland applications should use advanced API (RFC2292) to specify scope
index, or interface index. For similar purpose, sin6_scope_id member in sockaddr_in6
structure is defined in RFC2553. However, the semantics for sin6_scope_id is rather
vague. If you care about portability of your application, we suggest you to use advanced
API rather than sin6_scope_id.</p>

<p>In the kernel, an interface index for link-local scoped address is embedded into 2nd
16bit-word (3rd and 4th byte) in IPv6 address. For example, you may see something
like:</p>

<pre class="screen">   fe80:1::200:f8ff:fe01:6317
   
</pre>

<p>in the routing table and interface address structure (struct in6_ifaddr). The address
above is a link-local unicast address which belongs to a network interface whose
interface identifier is 1. The embedded index enables us to identify IPv6 link local
addresses over multiple interfaces effectively and with only a little code change.</p>

<p>Routing daemons and configuration programs, like <a href="http://www.freebsd.org/cgi/man.cgi?query=route6d&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">route6d</span>(8)</span></a> and <a href="http://www.freebsd.org/cgi/man.cgi?query=ifconfig&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">ifconfig</span>(8)</span></a>, will need
to manipulate the "embedded" scope index. These programs use routing sockets and ioctls
(like SIOCGIFADDR_IN6) and the kernel API will return IPv6 addresses with 2nd 16bit-word
filled in. The APIs are for manipulating kernel internal structure. Programs that use
these APIs have to be prepared about differences in kernels anyway.</p>

<p>When you specify scoped address to the command line, NEVER write the embedded form
(such as ff02:1::1 or fe80:2::fedc). This is not supposed to work. Always use standard
form, like ff02::1 or fe80::fedc, with command line option for specifying interface (like
<tt class="command">ping6 -I ne0 ff02::1</tt>). In general, if a command does not have
command line option to specify outgoing interface, that command is not ready to accept
scoped address. This may seem to be opposite from IPv6's premise to support "dentist
office" situation. We believe that specifications need some improvements for this.</p>

<p>Some of the userland tools support extended numeric IPv6 syntax, as documented in <tt class="filename">draft-ietf-ipngwg-scopedaddr-format-00.txt</tt>. You can specify
outgoing link, by using name of the outgoing interface like "fe80::1%ne0". This way you
will be able to specify link-local scoped address without much trouble.</p>

<p>To use this extension in your program, you will need to use <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getaddrinfo</span>(3)</span></a>, and <a href="http://www.freebsd.org/cgi/man.cgi?query=getnameinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getnameinfo</span>(3)</span></a> with
NI_WITHSCOPEID. The implementation currently assumes 1-to-1 relationship between a link
and an interface, which is stronger than what specs say.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.4 Plug and Play" id="IPV6-PNP">
			<div class="sect3">
				<h4 class="title">9.1.1.4 Plug and Play</h4>

<p>Most of the IPv6 stateless address autoconfiguration is implemented in the kernel.
Neighbor Discovery functions are implemented in the kernel as a whole. Router
Advertisement (RA) input for hosts is implemented in the kernel. Router Solicitation (RS)
output for endhosts, RS input for routers, and RA output for routers are implemented in
the userland.</p>


<hr />

		<pkg:outlineMarker OutlineName="9.1.1.4.1 Assignment of link-local, and special addresses" id="AEN2906">
			<div class="sect3">
				<h5 class="title">9.1.1.4.1 Assignment of link-local, and
special addresses</h5>

<p>IPv6 link-local address is generated from IEEE802 address (Ethernet MAC address). Each
of interface is assigned an IPv6 link-local address automatically, when the interface
becomes up (IFF_UP). Also, direct route for the link-local address is added to routing
table.</p>

<p>Here is an output of netstat command:</p>

<pre class="screen">Internet6:
Destination                   Gateway                   Flags      Netif Expire
fe80:1::%ed0/64               link#1                    UC          ed0
fe80:2::%ep0/64               link#2                    UC          ep0
</pre>

<p>Interfaces that has no IEEE802 address (pseudo interfaces like tunnel interfaces, or
ppp interfaces) will borrow IEEE802 address from other interfaces, such as Ethernet
interfaces, whenever possible. If there is no IEEE802 hardware attached, a last resort
pseudo-random value, MD5(hostname), will be used as source of link-local address. If it
is not suitable for your usage, you will need to configure the link-local address
manually.</p>

<p>If an interface is not capable of handling IPv6 (such as lack of multicast support),
link-local address will not be assigned to that interface. See section 2 for details.</p>

<p>Each interface joins the solicited multicast address and the link-local all-nodes
multicast addresses (e.g. fe80::1:ff01:6317 and ff02::1, respectively, on the link the
interface is attached). In addition to a link-local address, the loopback address (::1)
will be assigned to the loopback interface. Also, ::1/128 and ff01::/32 are automatically
added to routing table, and loopback interface joins node-local multicast group
ff01::1.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.4.2 Stateless address autoconfiguration on hosts" id="AEN2914">
			<div class="sect3">
				<h5 class="title">9.1.1.4.2 Stateless address
autoconfiguration on hosts</h5>

<p>In IPv6 specification, nodes are separated into two categories: <span class="emphasis"><i class="emphasis">routers</i></span> and <span class="emphasis"><i class="emphasis">hosts</i></span>. Routers forward packets addressed to others, hosts
does not forward the packets. net.inet6.ip6.forwarding defines whether this node is
router or host (router if it is 1, host if it is 0).</p>

<p>When a host hears Router Advertisement from the router, a host may autoconfigure
itself by stateless address autoconfiguration. This behavior can be controlled by
net.inet6.ip6.accept_rtadv (host autoconfigures itself if it is set to 1). By
autoconfiguration, network address prefix for the receiving interface (usually global
address prefix) is added. Default route is also configured. Routers periodically generate
Router Advertisement packets. To request an adjacent router to generate RA packet, a host
can transmit Router Solicitation. To generate a RS packet at any time, use the <span class="emphasis"><i class="emphasis">rtsol</i></span> command. <a href="http://www.freebsd.org/cgi/man.cgi?query=rtsold&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">rtsold</span>(8)</span></a> daemon is
also available. <a href="http://www.freebsd.org/cgi/man.cgi?query=rtsold&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">rtsold</span>(8)</span></a> generates
Router Solicitation whenever necessary, and it works great for nomadic usage
(notebooks/laptops). If one wishes to ignore Router Advertisements, use sysctl to set
net.inet6.ip6.accept_rtadv to 0.</p>

<p>To generate Router Advertisement from a router, use the <a href="http://www.freebsd.org/cgi/man.cgi?query=rtadvd&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">rtadvd</span>(8)</span></a> daemon.</p>

<p>Note that, IPv6 specification assumes the following items, and nonconforming cases are
left unspecified:</p>

<ul>
<li>
<p>Only hosts will listen to router advertisements</p>
</li>

<li>
<p>Hosts have single network interface (except loopback)</p>
</li>
</ul>

<p>Therefore, this is unwise to enable net.inet6.ip6.accept_rtadv on routers, or
multi-interface host. A misconfigured node can behave strange (nonconforming
configuration allowed for those who would like to do some experiments).</p>

<p>To summarize the sysctl knob:</p>

<pre class="screen">   accept_rtadv    forwarding  role of the node
    ---     ---     ---
    0       0       host (to be manually configured)
    0       1       router
    1       0       autoconfigured host
                    (spec assumes that host has single
                    interface only, autoconfigured host
                    with multiple interface is
                    out-of-scope)
    1       1       invalid, or experimental
                    (out-of-scope of spec)
</pre>

<p>RFC2462 has validation rule against incoming RA prefix information option, in 5.5.3
(e). This is to protect hosts from malicious (or misconfigured) routers that advertise
very short prefix lifetime. There was an update from Jim Bound to ipngwg mailing list
(look for "(ipng 6712)" in the archive) and it is implemented Jim's update.</p>

<p>See <a href="pkg://FreeBSD Developers' Handbook/NEIGHBOR-DISCOVERY">23.5.1.2</a> in the document for relationship
between DAD and autoconfiguration.</p>




<hr />

			</div>
		</pkg:outlineMarker>

		
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="9.1.1.5 Generic tunnel interface" id="GIF">
			<div class="sect3">
				<h4 class="title">9.1.1.5 Generic tunnel interface</h4>

<p>GIF (Generic InterFace) is a pseudo interface for configured tunnel. Details are
described in <a href="http://www.freebsd.org/cgi/man.cgi?query=gif&#38;sektion=4"><span class="citerefentry"><span class="refentrytitle">gif</span>(4)</span></a>. Currently</p>

<ul>
<li>
<p>v6 in v6</p>
</li>

<li>
<p>v6 in v4</p>
</li>

<li>
<p>v4 in v6</p>
</li>

<li>
<p>v4 in v4</p>
</li>
</ul>

<p>are available. Use <a href="http://www.freebsd.org/cgi/man.cgi?query=gifconfig&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">gifconfig</span>(8)</span></a> to assign
physical (outer) source and destination address to gif interfaces. Configuration that
uses same address family for inner and outer IP header (v4 in v4, or v6 in v6) is
dangerous. It is very easy to configure interfaces and routing tables to perform infinite
level of tunneling. <span class="emphasis"><i class="emphasis">Please be
warned</i></span>.</p>

<p>gif can be configured to be ECN-friendly. See <a href="pkg://FreeBSD Developers' Handbook/IPSEC-ECN">23.5.4.5</a> for
ECN-friendliness of tunnels, and <a href="http://www.freebsd.org/cgi/man.cgi?query=gif&#38;sektion=4"><span class="citerefentry"><span class="refentrytitle">gif</span>(4)</span></a> for how to
configure.</p>

<p>If you would like to configure an IPv4-in-IPv6 tunnel with gif interface, read <a href="http://www.freebsd.org/cgi/man.cgi?query=gif&#38;sektion=4"><span class="citerefentry"><span class="refentrytitle">gif</span>(4)</span></a> carefully. You
will need to remove IPv6 link-local address automatically assigned to the gif
interface.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.6 Source Address Selection" id="IPV6-SAS">
			<div class="sect3">
				<h4 class="title">9.1.1.6 Source Address
Selection</h4>

<p>Current source selection rule is scope oriented (there are some exceptions - see
below). For a given destination, a source IPv6 address is selected by the following
rule:</p>

<ol type="1">
<li>
<p>If the source address is explicitly specified by the user (e.g. via the advanced API),
the specified address is used.</p>
</li>

<li>
<p>If there is an address assigned to the outgoing interface (which is usually determined
by looking up the routing table) that has the same scope as the destination address, the
address is used.</p>

<p>This is the most typical case.</p>
</li>

<li>
<p>If there is no address that satisfies the above condition, choose a global address
assigned to one of the interfaces on the sending node.</p>
</li>

<li>
<p>If there is no address that satisfies the above condition, and destination address is
site local scope, choose a site local address assigned to one of the interfaces on the
sending node.</p>
</li>

<li>
<p>If there is no address that satisfies the above condition, choose the address
associated with the routing table entry for the destination. This is the last resort,
which may cause scope violation.</p>
</li>
</ol>

<p>For instance, ::1 is selected for ff01::1, fe80:1::200:f8ff:fe01:6317 for
fe80:1::2a0:24ff:feab:839b (note that embedded interface index - described in <a href="pkg://FreeBSD Developers' Handbook/IPV6-SCOPE-INDEX">23.5.1.3</a> - helps us choose the right source address. Those
embedded indices will not be on the wire). If the outgoing interface has multiple address
for the scope, a source is selected longest match basis (rule 3). Suppose
3ffe:501:808:1:200:f8ff:fe01:6317 and 3ffe:2001:9:124:200:f8ff:fe01:6317 are given to the
outgoing interface. 3ffe:501:808:1:200:f8ff:fe01:6317 is chosen as the source for the
destination 3ffe:501:800::1.</p>

<p>Note that the above rule is not documented in the IPv6 spec. It is considered "up to
implementation" item. There are some cases where we do not use the above rule. One
example is connected TCP session, and we use the address kept in tcb as the source.
Another example is source address for Neighbor Advertisement. Under the spec (RFC2461
7.2.2) NA's source should be the target address of the corresponding NS's target. In this
case we follow the spec rather than the above longest-match rule.</p>

<p>For new connections (when rule 1 does not apply), deprecated addresses (addresses with
preferred lifetime = 0) will not be chosen as source address if other choices are
available. If no other choices are available, deprecated address will be used as a last
resort. If there are multiple choice of deprecated addresses, the above scope rule will
be used to choose from those deprecated addresses. If you would like to prohibit the use
of deprecated address for some reason, configure net.inet6.ip6.use_deprecated to 0. The
issue related to deprecated address is described in RFC2462 5.5.4 (NOTE: there is some
debate underway in IETF ipngwg on how to use "deprecated" address).</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.7 Jumbo Payload" id="IPV6-JUMBO">
			<div class="sect3">
				<h4 class="title">9.1.1.7 Jumbo Payload</h4>

<p>The Jumbo Payload hop-by-hop option is implemented and can be used to send IPv6
packets with payloads longer than 65,535 octets. But currently no physical interface
whose MTU is more than 65,535 is supported, so such payloads can be seen only on the
loopback interface (i.e. lo0).</p>

<p>If you want to try jumbo payloads, you first have to reconfigure the kernel so that
the MTU of the loopback interface is more than 65,535 bytes; add the following to the
kernel configuration file:</p>

<p><var class="literal">options "LARGE_LOMTU" #To test jumbo payload</var></p>

<p>and recompile the new kernel.</p>

<p>Then you can test jumbo payloads by the <a href="http://www.freebsd.org/cgi/man.cgi?query=ping6&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">ping6</span>(8)</span></a> command with
-b and -s options. The -b option must be specified to enlarge the size of the socket
buffer and the -s option specifies the length of the packet, which should be more than
65,535. For example, type as follows:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">ping6 -b 70000 -s 68000 ::1</kbd>
</pre>

<p>The IPv6 specification requires that the Jumbo Payload option must not be used in a
packet that carries a fragment header. If this condition is broken, an ICMPv6 Parameter
Problem message must be sent to the sender. specification is followed, but you cannot
usually see an ICMPv6 error caused by this requirement.</p>

<p>When an IPv6 packet is received, the frame length is checked and compared to the
length specified in the payload length field of the IPv6 header or in the value of the
Jumbo Payload option, if any. If the former is shorter than the latter, the packet is
discarded and statistics are incremented. You can see the statistics as output of <a href="http://www.freebsd.org/cgi/man.cgi?query=netstat&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">netstat</span>(8)</span></a> command
with `-s -p ip6' option:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">netstat -s -p ip6</kbd>
      ip6:
        (snip)
        1 with data size &#60; data length
</pre>

<p>So, kernel does not send an ICMPv6 error unless the erroneous packet is an actual
Jumbo Payload, that is, its packet size is more than 65,535 bytes. As described above,
currently no physical interface with such a huge MTU is supported, so it rarely returns
an ICMPv6 error.</p>

<p>TCP/UDP over jumbogram is not supported at this moment. This is because we have no
medium (other than loopback) to test this. Contact us if you need this.</p>

<p>IPsec does not work on jumbograms. This is due to some specification twists in
supporting AH with jumbograms (AH header size influences payload length, and this makes
it real hard to authenticate inbound packet with jumbo payload option as well as AH).</p>

<p>There are fundamental issues in *BSD support for jumbograms. We would like to address
those, but we need more time to finalize these. To name a few:</p>

<ul>
<li>
<p>mbuf pkthdr.len field is typed as "int" in 4.4BSD, so it will not hold jumbogram with
len &#62; 2G on 32bit architecture CPUs. If we would like to support jumbogram properly,
the field must be expanded to hold 4G + IPv6 header + link-layer header. Therefore, it
must be expanded to at least int64_t (u_int32_t is NOT enough).</p>
</li>

<li>
<p>We mistakingly use "int" to hold packet length in many places. We need to convert them
into larger integral type. It needs a great care, as we may experience overflow during
packet length computation.</p>
</li>

<li>
<p>We mistakingly check for ip6_plen field of IPv6 header for packet payload length in
various places. We should be checking mbuf pkthdr.len instead. ip6_input() will perform
sanity check on jumbo payload option on input, and we can safely use mbuf pkthdr.len
afterwards.</p>
</li>

<li>
<p>TCP code needs a careful update in bunch of places, of course.</p>
</li>
</ul>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.8 Loop prevention in header processing" id="AEN3026">
			<div class="sect3">
				<h4 class="title">9.1.1.8 Loop prevention in header
processing</h4>

<p>IPv6 specification allows arbitrary number of extension headers to be placed onto
packets. If we implement IPv6 packet processing code in the way BSD IPv4 code is
implemented, kernel stack may overflow due to long function call chain. sys/netinet6 code
is carefully designed to avoid kernel stack overflow. Because of this, sys/netinet6 code
defines its own protocol switch structure, as "struct ip6protosw" (see <tt class="filename">netinet6/ip6protosw.h</tt>). There is no such update to IPv4 part
(sys/netinet) for compatibility, but small change is added to its pr_input() prototype.
So "struct ipprotosw" is also defined. Because of this, if you receive IPsec-over-IPv4
packet with massive number of IPsec headers, kernel stack may blow up. IPsec-over-IPv6 is
okay. (Off-course, for those all IPsec headers to be processed, each such IPsec header
must pass each IPsec check. So an anonymous attacker will not be able to do such an
attack.)</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.9 ICMPv6" id="ICMPV6">
			<div class="sect3">
				<h4 class="title">9.1.1.9 ICMPv6</h4>

<p>After RFC2463 was published, IETF ipngwg has decided to disallow ICMPv6 error packet
against ICMPv6 redirect, to prevent ICMPv6 storm on a network medium. This is already
implemented into the kernel.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.10 Applications" id="AEN3033">
			<div class="sect3">
				<h4 class="title">9.1.1.10 Applications</h4>

<p>For userland programming, we support IPv6 socket API as specified in RFC2553, RFC2292
and upcoming Internet drafts.</p>

<p>TCP/UDP over IPv6 is available and quite stable. You can enjoy <a href="http://www.freebsd.org/cgi/man.cgi?query=telnet&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">telnet</span>(1)</span></a>, <a href="http://www.freebsd.org/cgi/man.cgi?query=ftp&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">ftp</span>(1)</span></a>, <a href="http://www.freebsd.org/cgi/man.cgi?query=rlogin&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">rlogin</span>(1)</span></a>, <a href="http://www.freebsd.org/cgi/man.cgi?query=rsh&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">rsh</span>(1)</span></a>, <a href="http://www.freebsd.org/cgi/man.cgi?query=ssh&#38;sektion=1&#38;manpath=OpenBSD+3.4">
<span class="citerefentry"><span class="refentrytitle">ssh</span>(1)</span></a>, etc.
These applications are protocol independent. That is, they automatically chooses IPv4 or
IPv6 according to DNS.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.11 Kernel Internals" id="AEN3052">
			<div class="sect3">
				<h4 class="title">9.1.1.11 Kernel Internals</h4>

<p>While ip_forward() calls ip_output(), ip6_forward() directly calls if_output() since
routers must not divide IPv6 packets into fragments.</p>

<p>ICMPv6 should contain the original packet as long as possible up to 1280. UDP6/IP6
port unreach, for instance, should contain all extension headers and the *unchanged* UDP6
and IP6 headers. So, all IP6 functions except TCP never convert network byte order into
host byte order, to save the original packet.</p>

<p>tcp_input(), udp6_input() and icmp6_input() can not assume that IP6 header is
preceding the transport headers due to extension headers. So, in6_cksum() was implemented
to handle packets whose IP6 header and transport header is not continuous. TCP/IP6 nor
UDP6/IP6 header structures do not exist for checksum calculation.</p>

<p>To process IP6 header, extension headers and transport headers easily, network drivers
are now required to store packets in one internal mbuf or one or more external mbufs. A
typical old driver prepares two internal mbufs for 96 - 204 bytes data, however, now such
packet data is stored in one external mbuf.</p>

<p><tt class="command">netstat -s -p ip6</tt> tells you whether or not your driver
conforms such requirement. In the following example, "cce0" violates the requirement.
(For more information, refer to Section 2.)</p>

<pre class="screen">Mbuf statistics:
                317 one mbuf
                two or more mbuf::
                        lo0 = 8
            cce0 = 10
                3282 one ext mbuf
                0 two or more ext mbuf
   
</pre>

<p>Each input function calls IP6_EXTHDR_CHECK in the beginning to check if the region
between IP6 and its header is continuous. IP6_EXTHDR_CHECK calls m_pullup() only if the
mbuf has M_LOOP flag, that is, the packet comes from the loopback interface. m_pullup()
is never called for packets coming from physical network interfaces.</p>

<p>Both IP and IP6 reassemble functions never call m_pullup().</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.1.12 IPv4 mapped address and IPv6 wildcard socket" id="IPV6-WILDCARD-SOCKET">
			<div class="sect3">
				<h4 class="title">9.1.1.12 IPv4
mapped address and IPv6 wildcard socket</h4>

<p>RFC2553 describes IPv4 mapped address (3.7) and special behavior of IPv6 wildcard bind
socket (3.8). The spec allows you to:</p>

<ul>
<li>
<p>Accept IPv4 connections by AF_INET6 wildcard bind socket.</p>
</li>

<li>
<p>Transmit IPv4 packet over AF_INET6 socket by using special form of the address like
::ffff:10.1.1.1.</p>
</li>
</ul>

<p>but the spec itself is very complicated and does not specify how the socket layer
should behave. Here we call the former one "listening side" and the latter one
"initiating side", for reference purposes.</p>

<p>You can perform wildcard bind on both of the address families, on the same port.</p>

<p>The following table show the behavior of FreeBSD 4.x.</p>

<pre class="screen">listening side          initiating side
                (AF_INET6 wildcard      (connection to ::ffff:10.1.1.1)
                socket gets IPv4 conn.)
                ---                     ---
FreeBSD 4.x     configurable            supported
                default: enabled
   
</pre>

<p>The following sections will give you more details, and how you can configure the
behavior.</p>

<p>Comments on listening side:</p>

<p>It looks that RFC2553 talks too little on wildcard bind issue, especially on the port
space issue, failure mode and relationship between AF_INET/INET6 wildcard bind. There can
be several separate interpretation for this RFC which conform to it but behaves
differently. So, to implement portable application you should assume nothing about the
behavior in the kernel. Using <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getaddrinfo</span>(3)</span></a> is the
safest way. Port number space and wildcard bind issues were discussed in detail on
ipv6imp mailing list, in mid March 1999 and it looks that there is no concrete consensus
(means, up to implementers). You may want to check the mailing list archives.</p>

<p>If a server application would like to accept IPv4 and IPv6 connections, there will be
two alternatives.</p>

<p>One is using AF_INET and AF_INET6 socket (you will need two sockets). Use <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getaddrinfo</span>(3)</span></a> with
AI_PASSIVE into ai_flags, and <a href="http://www.freebsd.org/cgi/man.cgi?query=socket&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">socket</span>(2)</span></a> and <a href="http://www.freebsd.org/cgi/man.cgi?query=bind&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">bind</span>(2)</span></a> to all the
addresses returned. By opening multiple sockets, you can accept connections onto the
socket with proper address family. IPv4 connections will be accepted by AF_INET socket,
and IPv6 connections will be accepted by AF_INET6 socket.</p>

<p>Another way is using one AF_INET6 wildcard bind socket. Use <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getaddrinfo</span>(3)</span></a> with
AI_PASSIVE into ai_flags and with AF_INET6 into ai_family, and set the 1st argument
hostname to NULL. And <a href="http://www.freebsd.org/cgi/man.cgi?query=socket&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">socket</span>(2)</span></a> and <a href="http://www.freebsd.org/cgi/man.cgi?query=bind&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">bind</span>(2)</span></a> to the address
returned. (should be IPv6 unspecified addr). You can accept either of IPv4 and IPv6
packet via this one socket.</p>

<p>To support only IPv6 traffic on AF_INET6 wildcard binded socket portably, always check
the peer address when a connection is made toward AF_INET6 listening socket. If the
address is IPv4 mapped address, you may want to reject the connection. You can check the
condition by using IN6_IS_ADDR_V4MAPPED() macro.</p>

<p>To resolve this issue more easily, there is system dependent <a href="http://www.freebsd.org/cgi/man.cgi?query=setsockopt&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">setsockopt</span>(2)</span></a> option,
IPV6_BINDV6ONLY, used like below.</p>

<pre class="screen">   int on;

    setsockopt(s, IPPROTO_IPV6, IPV6_BINDV6ONLY,
           (char *)&#38;on, sizeof (on)) &#60; 0));
   
</pre>

<p>When this call succeed, then this socket only receive IPv6 packets.</p>

<p>Comments on initiating side:</p>

<p>Advise to application implementers: to implement a portable IPv6 application (which
works on multiple IPv6 kernels), we believe that the following is the key to the
success:</p>

<ul>
<li>
<p>NEVER hardcode AF_INET nor AF_INET6.</p>
</li>

<li>
<p>Use <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getaddrinfo</span>(3)</span></a> and <a href="http://www.freebsd.org/cgi/man.cgi?query=getnameinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getnameinfo</span>(3)</span></a>
throughout the system. Never use gethostby*(), getaddrby*(), inet_*() or getipnodeby*().
(To update existing applications to be IPv6 aware easily, sometime getipnodeby*() will be
useful. But if possible, try to rewrite the code to use <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getaddrinfo</span>(3)</span></a> and <a href="http://www.freebsd.org/cgi/man.cgi?query=getnameinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getnameinfo</span>(3)</span></a>.)</p>
</li>

<li>
<p>If you would like to connect to destination, use <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getaddrinfo</span>(3)</span></a> and try
all the destination returned, like <a href="http://www.freebsd.org/cgi/man.cgi?query=telnet&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">telnet</span>(1)</span></a> does.</p>
</li>

<li>
<p>Some of the IPv6 stack is shipped with buggy <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getaddrinfo</span>(3)</span></a>. Ship a
minimal working version with your application and use that as last resort.</p>
</li>
</ul>

<p>If you would like to use AF_INET6 socket for both IPv4 and IPv6 outgoing connection,
you will need to use <a href="http://www.freebsd.org/cgi/man.cgi?query=getipnodebyname&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getipnodebyname</span>(3)</span></a>.
When you would like to update your existing application to be IPv6 aware with minimal
effort, this approach might be chosen. But please note that it is a temporal solution,
because <a href="http://www.freebsd.org/cgi/man.cgi?query=getipnodebyname&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getipnodebyname</span>(3)</span></a>
itself is not recommended as it does not handle scoped IPv6 addresses at all. For IPv6
name resolution, <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getaddrinfo</span>(3)</span></a> is the
preferred API. So you should rewrite your application to use <a href="http://www.freebsd.org/cgi/man.cgi?query=getaddrinfo&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">getaddrinfo</span>(3)</span></a>, when
you get the time to do it.</p>

<p>When writing applications that make outgoing connections, story goes much simpler if
you treat AF_INET and AF_INET6 as totally separate address family. {set,get}sockopt issue
goes simpler, DNS issue will be made simpler. We do not recommend you to rely upon IPv4
mapped address.</p>


<hr />

		<pkg:outlineMarker OutlineName="9.1.1.12.1 unified tcp and inpcb code" id="AEN3155">
			<div class="sect3">
				<h5 class="title">9.1.1.12.1 unified tcp and inpcb
code</h5>

<p>FreeBSD 4.x uses shared tcp code between IPv4 and IPv6 (from sys/netinet/tcp*) and
separate udp4/6 code. It uses unified inpcb structure.</p>

<p>The platform can be configured to support IPv4 mapped address. Kernel configuration is
summarized as follows:</p>

<ul>
<li>
<p>By default, AF_INET6 socket will grab IPv4 connections in certain condition, and can
initiate connection to IPv4 destination embedded in IPv4 mapped IPv6 address.</p>
</li>

<li>
<p>You can disable it on entire system with sysctl like below.</p>

<p><tt class="command">sysctl net.inet6.ip6.mapped_addr=0</tt></p>
</li>
</ul>


<hr />
<h6 class="sect5"><a name="AEN3166">9.1.1.12.1.1 listening side</a></h6>

<p>Each socket can be configured to support special AF_INET6 wildcard bind (enabled by
default). You can disable it on each socket basis with <a href="http://www.freebsd.org/cgi/man.cgi?query=setsockopt&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">setsockopt</span>(2)</span></a> like
below.</p>

<pre class="screen">   int on;

    setsockopt(s, IPPROTO_IPV6, IPV6_BINDV6ONLY,
           (char *)&#38;on, sizeof (on)) &#60; 0));
   
</pre>

<p>Wildcard AF_INET6 socket grabs IPv4 connection if and only if the following conditions
are satisfied:</p>

<ul>
<li>
<p>there is no AF_INET socket that matches the IPv4 connection</p>
</li>

<li>
<p>the AF_INET6 socket is configured to accept IPv4 traffic, i.e.
getsockopt(IPV6_BINDV6ONLY) returns 0.</p>
</li>
</ul>

<p>There is no problem with open/close ordering.</p>



<hr />
<h6 class="sect5"><a name="AEN3180">9.1.1.12.1.2 initiating side</a></h6>

<p>FreeBSD 4.x supports outgoing connection to IPv4 mapped address (::ffff:10.1.1.1), if
the node is configured to support IPv4 mapped address.</p>





<hr />

			</div>
		</pkg:outlineMarker>

		
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="9.1.1.13 sockaddr_storage" id="AEN3183">
			<div class="sect3">
				<h4 class="title">9.1.1.13 sockaddr_storage</h4>

<p>When RFC2553 was about to be finalized, there was discussion on how struct
sockaddr_storage members are named. One proposal is to prepend "__" to the members (like
"__ss_len") as they should not be touched. The other proposal was not to prepend it (like
"ss_len") as we need to touch those members directly. There was no clear consensus on
it.</p>

<p>As a result, RFC2553 defines struct sockaddr_storage as follows:</p>

<pre class="screen">   struct sockaddr_storage {
        u_char  __ss_len;   /* address length */
        u_char  __ss_family;    /* address family */
        /* and bunch of padding */
    };
   
</pre>

<p>On the contrary, XNET draft defines as follows:</p>

<pre class="screen">   struct sockaddr_storage {
        u_char  ss_len;     /* address length */
        u_char  ss_family;  /* address family */
        /* and bunch of padding */
    };
   
</pre>

<p>In December 1999, it was agreed that RFC2553bis should pick the latter (XNET)
definition.</p>

<p>Current implementation conforms to XNET definition, based on RFC2553bis
discussion.</p>

<p>If you look at multiple IPv6 implementations, you will be able to see both
definitions. As an userland programmer, the most portable way of dealing with it is
to:</p>

<ol type="1">
<li>
<p>ensure ss_family and/or ss_len are available on the platform, by using GNU
autoconf,</p>
</li>

<li>
<p>have -Dss_family=__ss_family to unify all occurrences (including header file) into
__ss_family, or</p>
</li>

<li>
<p>never touch __ss_family. cast to sockaddr * and use sa_family like:</p>

<pre class="screen">   struct sockaddr_storage ss;
    family = ((struct sockaddr *)&#38;ss)-&#62;sa_family
       
</pre>
</li>
</ol>




<hr />

			</div>
		</pkg:outlineMarker>

		
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="9.1.2 Network Drivers" id="AEN3201">
			<div class="sect3">
				<h3 class="title">9.1.2 Network Drivers</h3>

<p>Now following two items are required to be supported by standard drivers:</p>

<ol type="1">
<li>
<p>mbuf clustering requirement. In this stable release, we changed MINCLSIZE into MHLEN+1
for all the operating systems in order to make all the drivers behave as we expect.</p>
</li>

<li>
<p>multicast. If <a href="http://www.freebsd.org/cgi/man.cgi?query=ifmcstat&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">ifmcstat</span>(8)</span></a> yields no
multicast group for a interface, that interface has to be patched.</p>
</li>
</ol>

<p>If any of the drivers do not support the requirements, then the drivers can not be
used for IPv6 and/or IPsec communication. If you find any problem with your card using
IPv6/IPsec, then, please report it to the <a href="http://lists.freebsd.org/mailman/listinfo/freebsd-bugs" target="_top">FreeBSD
problem reports mailing list</a>.</p>

<p>(NOTE: In the past we required all PCMCIA drivers to have a call to in6_ifattach(). We
have no such requirement any more)</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.3 Translator" id="AEN3215">
			<div class="sect3">
				<h3 class="title">9.1.3 Translator</h3>

<p>We categorize IPv4/IPv6 translator into 4 types:</p>

<ul>
<li>
<p><span class="emphasis"><i class="emphasis">Translator A</i></span> --- It is used in
the early stage of transition to make it possible to establish a connection from an IPv6
host in an IPv6 island to an IPv4 host in the IPv4 ocean.</p>
</li>

<li>
<p><span class="emphasis"><i class="emphasis">Translator B</i></span> --- It is used in
the early stage of transition to make it possible to establish a connection from an IPv4
host in the IPv4 ocean to an IPv6 host in an IPv6 island.</p>
</li>

<li>
<p><span class="emphasis"><i class="emphasis">Translator C</i></span> --- It is used in
the late stage of transition to make it possible to establish a connection from an IPv4
host in an IPv4 island to an IPv6 host in the IPv6 ocean.</p>
</li>

<li>
<p><span class="emphasis"><i class="emphasis">Translator D</i></span> --- It is used in
the late stage of transition to make it possible to establish a connection from an IPv6
host in the IPv6 ocean to an IPv4 host in an IPv4 island.</p>
</li>
</ul>

<p>TCP relay translator for category A is supported. This is called "FAITH". We also
provide IP header translator for category A. (The latter is not yet put into FreeBSD 4.x
yet.)</p>


<hr />

		<pkg:outlineMarker OutlineName="9.1.3.1 FAITH TCP relay translator" id="AEN3232">
			<div class="sect3">
				<h4 class="title">9.1.3.1 FAITH TCP relay
translator</h4>

<p>FAITH system uses TCP relay daemon called <a href="http://www.freebsd.org/cgi/man.cgi?query=faithd&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">faithd</span>(8)</span></a> helped by
the kernel. FAITH will reserve an IPv6 address prefix, and relay TCP connection toward
that prefix to IPv4 destination.</p>

<p>For example, if the reserved IPv6 prefix is 3ffe:0501:0200:ffff::, and the IPv6
destination for TCP connection is 3ffe:0501:0200:ffff::163.221.202.12, the connection
will be relayed toward IPv4 destination 163.221.202.12.</p>

<pre class="screen">   destination IPv4 node (163.221.202.12)
      ^
      | IPv4 tcp toward 163.221.202.12
    FAITH-relay dual stack node
      ^
      | IPv6 TCP toward 3ffe:0501:0200:ffff::163.221.202.12
    source IPv6 node
   
</pre>

<p><a href="http://www.freebsd.org/cgi/man.cgi?query=faithd&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">faithd</span>(8)</span></a> must be
invoked on FAITH-relay dual stack node.</p>

<p>For more details, consult <tt class="filename">src/usr.sbin/faithd/README</tt></p>




<hr />

			</div>
		</pkg:outlineMarker>

		
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="9.1.4 IPsec" id="IPSEC-IMPLEMENTATION">
			<div class="sect3">
				<h3 class="title">9.1.4
IPsec</h3>

<p>IPsec is mainly organized by three components.</p>

<ol type="1">
<li>
<p>Policy Management</p>
</li>

<li>
<p>Key Management</p>
</li>

<li>
<p>AH and ESP handling</p>
</li>
</ol>


<hr />

		<pkg:outlineMarker OutlineName="9.1.4.1 Policy Management" id="AEN3256">
			<div class="sect3">
				<h4 class="title">9.1.4.1 Policy Management</h4>

<p>The kernel implements experimental policy management code. There are two way to manage
security policy. One is to configure per-socket policy using <a href="http://www.freebsd.org/cgi/man.cgi?query=setsockopt&#38;sektion=2"><span class="citerefentry"><span class="refentrytitle">setsockopt</span>(2)</span></a>. In this
cases, policy configuration is described in <a href="http://www.freebsd.org/cgi/man.cgi?query=ipsec_set_policy&#38;sektion=3"><span class="citerefentry"><span class="refentrytitle">ipsec_set_policy</span>(3)</span></a>.
The other is to configure kernel packet filter-based policy using PF_KEY interface, via
<a href="http://www.freebsd.org/cgi/man.cgi?query=setkey&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">setkey</span>(8)</span></a>.</p>

<p>The policy entry is not re-ordered with its indexes, so the order of entry when you
add is very significant.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.4.2 Key Management" id="AEN3269">
			<div class="sect3">
				<h4 class="title">9.1.4.2 Key Management</h4>

<p>The key management code implemented in this kit (sys/netkey) is a home-brew PFKEY v2
implementation. This conforms to RFC2367.</p>

<p>The home-brew IKE daemon, "racoon" is included in the kit (kame/kame/racoon).
Basically you will need to run racoon as daemon, then set up a policy to require keys
(like <tt class="command">ping -P 'out ipsec esp/transport//use'</tt>). The kernel will
contact racoon daemon as necessary to exchange keys.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.4.3 AH and ESP handling" id="AEN3274">
			<div class="sect3">
				<h4 class="title">9.1.4.3 AH and ESP handling</h4>

<p>IPsec module is implemented as "hooks" to the standard IPv4/IPv6 processing. When
sending a packet, ip{,6}_output() checks if ESP/AH processing is required by checking if
a matching SPD (Security Policy Database) is found. If ESP/AH is needed,
{esp,ah}{4,6}_output() will be called and mbuf will be updated accordingly. When a packet
is received, {esp,ah}4_input() will be called based on protocol number, i.e.
(*inetsw[proto])(). {esp,ah}4_input() will decrypt/check authenticity of the packet, and
strips off daisy-chained header and padding for ESP/AH. It is safe to strip off the
ESP/AH header on packet reception, since we will never use the received packet in "as is"
form.</p>

<p>By using ESP/AH, TCP4/6 effective data segment size will be affected by extra
daisy-chained headers inserted by ESP/AH. Our code takes care of the case.</p>

<p>Basic crypto functions can be found in directory "sys/crypto". ESP/AH transform are
listed in {esp,ah}_core.c with wrapper functions. If you wish to add some algorithm, add
wrapper function in {esp,ah}_core.c, and add your crypto algorithm code into
sys/crypto.</p>

<p>Tunnel mode is partially supported in this release, with the following
restrictions:</p>

<ul>
<li>
<p>IPsec tunnel is not combined with GIF generic tunneling interface. It needs a great
care because we may create an infinite loop between ip_output() and
tunnelifp-&#62;if_output(). Opinion varies if it is better to unify them, or not.</p>
</li>

<li>
<p>MTU and Don't Fragment bit (IPv4) considerations need more checking, but basically
works fine.</p>
</li>

<li>
<p>Authentication model for AH tunnel must be revisited. We will need to improve the
policy management engine, eventually.</p>
</li>
</ul>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.4.4 Conformance to RFCs and IDs" id="AEN3287">
			<div class="sect3">
				<h4 class="title">9.1.4.4 Conformance to RFCs and
IDs</h4>

<p>The IPsec code in the kernel conforms (or, tries to conform) to the following
standards:</p>

<p>"old IPsec" specification documented in <tt class="filename">rfc182[5-9].txt</tt></p>

<p>"new IPsec" specification documented in <tt class="filename">rfc240[1-6].txt</tt>, <tt class="filename">rfc241[01].txt</tt>, <tt class="filename">rfc2451.txt</tt> and <tt class="filename">draft-mcdonald-simple-ipsec-api-01.txt</tt> (draft expired, but you can
take from <a href="ftp://ftp.kame.net/pub/internet-drafts/" target="_top">ftp://ftp.kame.net/pub/internet-drafts/</a>). (NOTE: IKE specifications,
<tt class="filename">rfc241[7-9].txt</tt> are implemented in userland, as "racoon" IKE
daemon)</p>

<p>Currently supported algorithms are:</p>

<ul>
<li>
<p>old IPsec AH</p>

<ul>
<li>
<p>null crypto checksum (no document, just for debugging)</p>
</li>

<li>
<p>keyed MD5 with 128bit crypto checksum (<tt class="filename">rfc1828.txt</tt>)</p>
</li>

<li>
<p>keyed SHA1 with 128bit crypto checksum (no document)</p>
</li>

<li>
<p>HMAC MD5 with 128bit crypto checksum (<tt class="filename">rfc2085.txt</tt>)</p>
</li>

<li>
<p>HMAC SHA1 with 128bit crypto checksum (no document)</p>
</li>
</ul>
</li>

<li>
<p>old IPsec ESP</p>

<ul>
<li>
<p>null encryption (no document, similar to <tt class="filename">rfc2410.txt</tt>)</p>
</li>

<li>
<p>DES-CBC mode (<tt class="filename">rfc1829.txt</tt>)</p>
</li>
</ul>
</li>

<li>
<p>new IPsec AH</p>

<ul>
<li>
<p>null crypto checksum (no document, just for debugging)</p>
</li>

<li>
<p>keyed MD5 with 96bit crypto checksum (no document)</p>
</li>

<li>
<p>keyed SHA1 with 96bit crypto checksum (no document)</p>
</li>

<li>
<p>HMAC MD5 with 96bit crypto checksum (<tt class="filename">rfc2403.txt</tt>)</p>
</li>

<li>
<p>HMAC SHA1 with 96bit crypto checksum (<tt class="filename">rfc2404.txt</tt>)</p>
</li>
</ul>
</li>

<li>
<p>new IPsec ESP</p>

<ul>
<li>
<p>null encryption (<tt class="filename">rfc2410.txt</tt>)</p>
</li>

<li>
<p>DES-CBC with derived IV (<tt class="filename">draft-ietf-ipsec-ciph-des-derived-01.txt</tt>, draft expired)</p>
</li>

<li>
<p>DES-CBC with explicit IV (<tt class="filename">rfc2405.txt</tt>)</p>
</li>

<li>
<p>3DES-CBC with explicit IV (<tt class="filename">rfc2451.txt</tt>)</p>
</li>

<li>
<p>BLOWFISH CBC (<tt class="filename">rfc2451.txt</tt>)</p>
</li>

<li>
<p>CAST128 CBC (<tt class="filename">rfc2451.txt</tt>)</p>
</li>

<li>
<p>RC5 CBC (<tt class="filename">rfc2451.txt</tt>)</p>
</li>

<li>
<p>each of the above can be combined with:</p>

<ul>
<li>
<p>ESP authentication with HMAC-MD5(96bit)</p>
</li>

<li>
<p>ESP authentication with HMAC-SHA1(96bit)</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>

<p>The following algorithms are NOT supported:</p>

<ul>
<li>
<p>old IPsec AH</p>

<ul>
<li>
<p>HMAC MD5 with 128bit crypto checksum + 64bit replay prevention (<tt class="filename">rfc2085.txt</tt>)</p>
</li>

<li>
<p>keyed SHA1 with 160bit crypto checksum + 32bit padding (<tt class="filename">rfc1852.txt</tt>)</p>
</li>
</ul>
</li>
</ul>

<p>IPsec (in kernel) and IKE (in userland as "racoon") has been tested at several
interoperability test events, and it is known to interoperate with many other
implementations well. Also, current IPsec implementation as quite wide coverage for IPsec
crypto algorithms documented in RFC (we cover algorithms without intellectual property
issues only).</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.4.5 ECN consideration on IPsec tunnels" id="IPSEC-ECN">
			<div class="sect3">
				<h4 class="title">9.1.4.5 ECN consideration on IPsec
tunnels</h4>

<p>ECN-friendly IPsec tunnel is supported as described in <tt class="filename">draft-ipsec-ecn-00.txt</tt>.</p>

<p>Normal IPsec tunnel is described in RFC2401. On encapsulation, IPv4 TOS field (or,
IPv6 traffic class field) will be copied from inner IP header to outer IP header. On
decapsulation outer IP header will be simply dropped. The decapsulation rule is not
compatible with ECN, since ECN bit on the outer IP TOS/traffic class field will be
lost.</p>

<p>To make IPsec tunnel ECN-friendly, we should modify encapsulation and decapsulation
procedure. This is described in <a href="http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt" target="_top">http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt</a>, chapter
3.</p>

<p>IPsec tunnel implementation can give you three behaviors, by setting
net.inet.ipsec.ecn (or net.inet6.ipsec6.ecn) to some value:</p>

<ul>
<li>
<p>RFC2401: no consideration for ECN (sysctl value -1)</p>
</li>

<li>
<p>ECN forbidden (sysctl value 0)</p>
</li>

<li>
<p>ECN allowed (sysctl value 1)</p>
</li>
</ul>

<p>Note that the behavior is configurable in per-node manner, not per-SA manner
(draft-ipsec-ecn-00 wants per-SA configuration, but it looks too much for me).</p>

<p>The behavior is summarized as follows (see source code for more detail):</p>

<pre class="screen">                encapsulate                     decapsulate
                ---                             ---
RFC2401         copy all TOS bits               drop TOS bits on outer
                from inner to outer.            (use inner TOS bits as is)

ECN forbidden   copy TOS bits except for ECN    drop TOS bits on outer
                (masked with 0xfc) from inner   (use inner TOS bits as is)
                to outer.  set ECN bits to 0.

ECN allowed     copy TOS bits except for ECN    use inner TOS bits with some
                CE (masked with 0xfe) from      change.  if outer ECN CE bit
                inner to outer.                 is 1, enable ECN CE bit on
                set ECN CE bit to 0.            the inner.

   
</pre>

<p>General strategy for configuration is as follows:</p>

<ul>
<li>
<p>if both IPsec tunnel endpoint are capable of ECN-friendly behavior, you should better
configure both end to ``ECN allowed'' (sysctl value 1).</p>
</li>

<li>
<p>if the other end is very strict about TOS bit, use "RFC2401" (sysctl value -1).</p>
</li>

<li>
<p>in other cases, use "ECN forbidden" (sysctl value 0).</p>
</li>
</ul>

<p>The default behavior is "ECN forbidden" (sysctl value 0).</p>

<p>For more information, please refer to:</p>

<p><a href="http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt" target="_top">http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt</a>, RFC2481
(Explicit Congestion Notification), src/sys/netinet6/{ah,esp}_input.c</p>

<p>(Thanks goes to Kenjiro Cho <code class="email">&#60;<a href="mailto:kjc@csl.sony.co.jp">kjc@csl.sony.co.jp</a>&#62;</code> for detailed
analysis)</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="9.1.4.6 Interoperability" id="AEN3416">
			<div class="sect3">
				<h4 class="title">9.1.4.6 Interoperability</h4>

<p>Here are (some of) platforms that KAME code have tested IPsec/IKE interoperability in
the past. Note that both ends may have modified their implementation, so use the
following list just for reference purposes.</p>

<p>Altiga, Ashley-laurent (vpcom.com), Data Fellows (F-Secure), Ericsson ACC, FreeS/WAN,
HITACHI, IBM <span class="trademark">AIX</span>®, IIJ, Intel, <span class="trademark">Microsoft</span>® <span class="trademark">Windows&#160;NT</span>®, NIST (linux IPsec + plutoplus), Netscreen,
OpenBSD, RedCreek, Routerware, SSH, Secure Computing, Soliton, Toshiba, VPNet, Yamaha
RT100i</p>







				<div align="right"><img align="right" src="bsd_sm.png"  /></div>
		</div>
</pkg:outlineMarker>



	</div>
</pkg:outlineMarker>

		</div>
	</pkg:outlineMarker>

			</div>
		</pkg:outlineMarker>

			</div>
    </pkg:outlineMarker>
    <pkg:outlineMarker OutlineName="III. Kernel" id="KERNEL" visible="true" renderchildren="false">
		<div class="sect1">
				

<h1 class="title">III. Kernel</h1>


<dl>
<dt><b>Table of Contents</b></dt>

<dt>10 <a href="pkg://FreeBSD Developers' Handbook/DMA">DMA</a></dt>

<dt>11 <a href="pkg://FreeBSD Developers' Handbook/KERNELDEBUG">Kernel Debugging</a></dt>

<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>
</dl>




<hr />

<pkg:outlineMarker OutlineName="Chapter 10 DMA" id="DMA">
	<div class="sect1">
		<h1 class="title">Chapter 10 DMA</h1>



	<pkg:outlineMarker OutlineName="10.1 DMA: What it is and How it Works" id="DMA-BASICS">
		<div class="sect2">
			<h2 class="title">10.1 DMA: What it is and How it
Works</h2>

<p><span class="emphasis"><i class="emphasis">Copyright © 1995,1997 Frank Durda IV
<code class="email">&#60;<a href="mailto:uhclem@FreeBSD.org">uhclem@FreeBSD.org</a>&#62;</code>, All Rights Reserved.
10 December 1996. Last Update 8 October 1997.</i></span></p>

<p>Direct Memory Access (DMA) is a method of allowing data to be moved from one location
to another in a computer without intervention from the central processor (CPU).</p>

<p>The way that the DMA function is implemented varies between computer architectures, so
this discussion will limit itself to the implementation and workings of the DMA subsystem
on the IBM Personal Computer (PC), the IBM PC/AT and all of its successors and
clones.</p>

<p>The PC DMA subsystem is based on the <span class="trademark">Intel</span>® 8237
DMA controller. The 8237 contains four DMA channels that can be programmed independently
and any one of the channels may be active at any moment. These channels are numbered 0,
1, 2 and 3. Starting with the PC/AT, IBM added a second 8237 chip, and numbered those
channels 4, 5, 6 and 7.</p>

<p>The original DMA controller (0, 1, 2 and 3) moves one byte in each transfer. The
second DMA controller (4, 5, 6, and 7) moves 16-bits from two adjacent memory locations
in each transfer, with the first byte always coming from an even-numbered address. The
two controllers are identical components and the difference in transfer size is caused by
the way the second controller is wired into the system.</p>

<p>The 8237 has two electrical signals for each channel, named DRQ and -DACK. There are
additional signals with the names HRQ (Hold Request), HLDA (Hold Acknowledge), -EOP (End
of Process), and the bus control signals -MEMR (Memory Read), -MEMW (Memory Write), -IOR
(I/O Read), and -IOW (I/O Write).</p>

<p>The 8237 DMA is known as a ``fly-by'' DMA controller. This means that the data being
moved from one location to another does not pass through the DMA chip and is not stored
in the DMA chip. Subsequently, the DMA can only transfer data between an I/O port and a
memory address, but not between two I/O ports or two memory locations.</p>


<blockquote class="note">
<p><b>Note:</b> The 8237 does allow two channels to be connected together to allow
memory-to-memory DMA operations in a non-``fly-by'' mode, but nobody in the PC industry
uses this scarce resource this way since it is faster to move data between memory
locations using the CPU.</p>
</blockquote>


<p>In the PC architecture, each DMA channel is normally activated only when the hardware
that uses a given DMA channel requests a transfer by asserting the DRQ line for that
channel.</p>


<hr />

		<pkg:outlineMarker OutlineName="10.1.1 A Sample DMA transfer" id="AEN3444">
			<div class="sect3">
				<h3 class="title">10.1.1 A Sample DMA transfer</h3>

<p>Here is an example of the steps that occur to cause and perform a DMA transfer. In
this example, the floppy disk controller (FDC) has just read a byte from a diskette and
wants the DMA to place it in memory at location 0x00123456. The process begins by the FDC
asserting the DRQ2 signal (the DRQ line for DMA channel 2) to alert the DMA
controller.</p>

<p>The DMA controller will note that the DRQ2 signal is asserted. The DMA controller will
then make sure that DMA channel 2 has been programmed and is unmasked (enabled). The DMA
controller also makes sure that none of the other DMA channels are active or want to be
active and have a higher priority. Once these checks are complete, the DMA asks the CPU
to release the bus so that the DMA may use the bus. The DMA requests the bus by asserting
the HRQ signal which goes to the CPU.</p>

<p>The CPU detects the HRQ signal, and will complete executing the current instruction.
Once the processor has reached a state where it can release the bus, it will. Now all of
the signals normally generated by the CPU (-MEMR, -MEMW, -IOR, -IOW and a few others) are
placed in a tri-stated condition (neither high or low) and then the CPU asserts the HLDA
signal which tells the DMA controller that it is now in charge of the bus.</p>

<p>Depending on the processor, the CPU may be able to execute a few additional
instructions now that it no longer has the bus, but the CPU will eventually have to wait
when it reaches an instruction that must read something from memory that is not in the
internal processor cache or pipeline.</p>

<p>Now that the DMA ``is in charge'', the DMA activates its -MEMR, -MEMW, -IOR, -IOW
output signals, and the address outputs from the DMA are set to 0x3456, which will be
used to direct the byte that is about to transferred to a specific memory location.</p>

<p>The DMA will then let the device that requested the DMA transfer know that the
transfer is commencing. This is done by asserting the -DACK signal, or in the case of the
floppy disk controller, -DACK2 is asserted.</p>

<p>The floppy disk controller is now responsible for placing the byte to be transferred
on the bus Data lines. Unless the floppy controller needs more time to get the data byte
on the bus (and if the peripheral does need more time it alerts the DMA via the READY
signal), the DMA will wait one DMA clock, and then de-assert the -MEMW and -IOR signals
so that the memory will latch and store the byte that was on the bus, and the FDC will
know that the byte has been transferred.</p>

<p>Since the DMA cycle only transfers a single byte at a time, the FDC now drops the DRQ2
signal, so the DMA knows that it is no longer needed. The DMA will de-assert the -DACK2
signal, so that the FDC knows it must stop placing data on the bus.</p>

<p>The DMA will now check to see if any of the other DMA channels have any work to do. If
none of the channels have their DRQ lines asserted, the DMA controller has completed its
work and will now tri-state the -MEMR, -MEMW, -IOR, -IOW and address signals.</p>

<p>Finally, the DMA will de-assert the HRQ signal. The CPU sees this, and de-asserts the
HOLDA signal. Now the CPU activates its -MEMR, -MEMW, -IOR, -IOW and address lines, and
it resumes executing instructions and accessing main memory and the peripherals.</p>

<p>For a typical floppy disk sector, the above process is repeated 512 times, once for
each byte. Each time a byte is transferred, the address register in the DMA is
incremented and the counter in the DMA that shows how many bytes are to be transferred is
decremented.</p>

<p>When the counter reaches zero, the DMA asserts the EOP signal, which indicates that
the counter has reached zero and no more data will be transferred until the DMA
controller is reprogrammed by the CPU. This event is also called the Terminal Count (TC).
There is only one EOP signal, and since only one DMA channel can be active at any
instant, the DMA channel that is currently active must be the DMA channel that just
completed its task.</p>

<p>If a peripheral wants to generate an interrupt when the transfer of a buffer is
complete, it can test for its -DACKn signal and the EOP signal both being asserted at the
same time. When that happens, it means the DMA will not transfer any more information for
that peripheral without intervention by the CPU. The peripheral can then assert one of
the interrupt signals to get the processors' attention. In the PC architecture, the DMA
chip itself is not capable of generating an interrupt. The peripheral and its associated
hardware is responsible for generating any interrupt that occurs. Subsequently, it is
possible to have a peripheral that uses DMA but does not use interrupts.</p>

<p>It is important to understand that although the CPU always releases the bus to the DMA
when the DMA makes the request, this action is invisible to both applications and the
operating system, except for slight changes in the amount of time the processor takes to
execute instructions when the DMA is active. Subsequently, the processor must poll the
peripheral, poll the registers in the DMA chip, or receive an interrupt from the
peripheral to know for certain when a DMA transfer has completed.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="10.1.2 DMA Page Registers and 16Meg address space limitations" id="AEN3461">
			<div class="sect3">
				<h3 class="title">10.1.2 DMA Page Registers and 16Meg
address space limitations</h3>

<p>You may have noticed earlier that instead of the DMA setting the address lines to
0x00123456 as we said earlier, the DMA only set 0x3456. The reason for this takes a bit
of explaining.</p>

<p>When the original IBM PC was designed, IBM elected to use both DMA and interrupt
controller chips that were designed for use with the 8085, an 8-bit processor with an
address space of 16 bits (64K). Since the IBM PC supported more than 64K of memory,
something had to be done to allow the DMA to read or write memory locations above the 64K
mark. What IBM did to solve this problem was to add an external data latch for each DMA
channel that holds the upper bits of the address to be read to or written from. Whenever
a DMA channel is active, the contents of that latch are written to the address bus and
kept there until the DMA operation for the channel ends. IBM called these latches ``Page
Registers''.</p>

<p>So for our example above, the DMA would put the 0x3456 part of the address on the bus,
and the Page Register for DMA channel 2 would put 0x0012xxxx on the bus. Together, these
two values form the complete address in memory that is to be accessed.</p>

<p>Because the Page Register latch is independent of the DMA chip, the area of memory to
be read or written must not span a 64K physical boundary. For example, if the DMA
accesses memory location 0xffff, after that transfer the DMA will then increment the
address register and the DMA will access the next byte at location 0x0000, not 0x10000.
The results of letting this happen are probably not intended.</p>


<blockquote class="note">
<p><b>Note:</b> ``Physical'' 64K boundaries should not be confused with 8086-mode 64K
``Segments'', which are created by mathematically adding a segment register with an
offset register. Page Registers have no address overlap and are mathematically OR-ed
together.</p>
</blockquote>


<p>To further complicate matters, the external DMA address latches on the PC/AT hold only
eight bits, so that gives us 8+16=24 bits, which means that the DMA can only point at
memory locations between 0 and 16Meg. For newer computers that allow more than 16Meg of
memory, the standard PC-compatible DMA cannot access memory locations above 16Meg.</p>

<p>To get around this restriction, operating systems will reserve a RAM buffer in an area
below 16Meg that also does not span a physical 64K boundary. Then the DMA will be
programmed to transfer data from the peripheral and into that buffer. Once the DMA has
moved the data into this buffer, the operating system will then copy the data from the
buffer to the address where the data is really supposed to be stored.</p>

<p>When writing data from an address above 16Meg to a DMA-based peripheral, the data must
be first copied from where it resides into a buffer located below 16Meg, and then the DMA
can copy the data from the buffer to the hardware. In FreeBSD, these reserved buffers are
called ``Bounce Buffers''. In the <span class="trademark">MS-DOS</span> world, they are
sometimes called ``Smart Buffers''.</p>


<blockquote class="note">
<p><b>Note:</b> A new implementation of the 8237, called the 82374, allows 16 bits of
page register to be specified and enables access to the entire 32 bit address space,
without the use of bounce buffers.</p>
</blockquote>




<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="10.1.3 DMA Operational Modes and Settings" id="AEN3480">
			<div class="sect3">
				<h3 class="title">10.1.3 DMA Operational Modes and
Settings</h3>

<p>The 8237 DMA can be operated in several modes. The main ones are:</p>


<dl>
<dt>Single</dt>

<dd>
<p>A single byte (or word) is transferred. The DMA must release and re-acquire the bus
for each additional byte. This is commonly-used by devices that cannot transfer the
entire block of data immediately. The peripheral will request the DMA each time it is
ready for another transfer.</p>

<p>The standard PC-compatible floppy disk controller (NEC 765) only has a one-byte
buffer, so it uses this mode.</p>
</dd>

<dt>Block/Demand</dt>

<dd>
<p>Once the DMA acquires the system bus, an entire block of data is transferred, up to a
maximum of 64K. If the peripheral needs additional time, it can assert the READY signal
to suspend the transfer briefly. READY should not be used excessively, and for slow
peripheral transfers, the Single Transfer Mode should be used instead.</p>

<p>The difference between Block and Demand is that once a Block transfer is started, it
runs until the transfer count reaches zero. DRQ only needs to be asserted until -DACK is
asserted. Demand Mode will transfer one more bytes until DRQ is de-asserted, at which
point the DMA suspends the transfer and releases the bus back to the CPU. When DRQ is
asserted later, the transfer resumes where it was suspended.</p>

<p>Older hard disk controllers used Demand Mode until CPU speeds increased to the point
that it was more efficient to transfer the data using the CPU, particularly if the memory
locations used in the transfer were above the 16Meg mark.</p>
</dd>

<dt>Cascade</dt>

<dd>
<p>This mechanism allows a DMA channel to request the bus, but then the attached
peripheral device is responsible for placing the addressing information on the bus
instead of the DMA. This is also used to implement a technique known as ``Bus
Mastering''.</p>

<p>When a DMA channel in Cascade Mode receives control of the bus, the DMA does not place
addresses and I/O control signals on the bus like the DMA normally does when it is
active. Instead, the DMA only asserts the -DACK signal for the active DMA channel.</p>

<p>At this point it is up to the peripheral connected to that DMA channel to provide
address and bus control signals. The peripheral has complete control over the system bus,
and can do reads and/or writes to any address below 16Meg. When the peripheral is
finished with the bus, it de-asserts the DRQ line, and the DMA controller can then return
control to the CPU or to some other DMA channel.</p>

<p>Cascade Mode can be used to chain multiple DMA controllers together, and this is
exactly what DMA Channel 4 is used for in the PC architecture. When a peripheral requests
the bus on DMA channels 0, 1, 2 or 3, the slave DMA controller asserts HLDREQ, but this
wire is actually connected to DRQ4 on the primary DMA controller instead of to the CPU.
The primary DMA controller, thinking it has work to do on Channel 4, requests the bus
from the CPU using HLDREQ signal. Once the CPU grants the bus to the primary DMA
controller, -DACK4 is asserted, and that wire is actually connected to the HLDA signal on
the slave DMA controller. The slave DMA controller then transfers data for the DMA
channel that requested it (0, 1, 2 or 3), or the slave DMA may grant the bus to a
peripheral that wants to perform its own bus-mastering, such as a SCSI controller.</p>

<p>Because of this wiring arrangement, only DMA channels 0, 1, 2, 3, 5, 6 and 7 are
usable with peripherals on PC/AT systems.</p>


<blockquote class="note">
<p><b>Note:</b> DMA channel 0 was reserved for refresh operations in early IBM PC
computers, but is generally available for use by peripherals in modern systems.</p>
</blockquote>


<p>When a peripheral is performing Bus Mastering, it is important that the peripheral
transmit data to or from memory constantly while it holds the system bus. If the
peripheral cannot do this, it must release the bus frequently so that the system can
perform refresh operations on main memory.</p>

<p>The Dynamic RAM used in all PCs for main memory must be accessed frequently to keep
the bits stored in the components ``charged''. Dynamic RAM essentially consists of
millions of capacitors with each one holding one bit of data. These capacitors are
charged with power to represent a <var class="literal">1</var> or drained to represent a
<var class="literal">0</var>. Because all capacitors leak, power must be added at regular
intervals to keep the <var class="literal">1</var> values intact. The RAM chips actually
handle the task of pumping power back into all of the appropriate locations in RAM, but
they must be told when to do it by the rest of the computer so that the refresh activity
will not interfere with the computer wanting to access RAM normally. If the computer is
unable to refresh memory, the contents of memory will become corrupted in just a few
milliseconds.</p>

<p>Since memory read and write cycles ``count'' as refresh cycles (a dynamic RAM refresh
cycle is actually an incomplete memory read cycle), as long as the peripheral controller
continues reading or writing data to sequential memory locations, that action will
refresh all of memory.</p>

<p>Bus-mastering is found in some SCSI host interfaces and other high-performance
peripheral controllers.</p>
</dd>

<dt>Autoinitialize</dt>

<dd>
<p>This mode causes the DMA to perform Byte, Block or Demand transfers, but when the DMA
transfer counter reaches zero, the counter and address are set back to where they were
when the DMA channel was originally programmed. This means that as long as the peripheral
requests transfers, they will be granted. It is up to the CPU to move new data into the
fixed buffer ahead of where the DMA is about to transfer it when doing output operations,
and to read new data out of the buffer behind where the DMA is writing when doing input
operations.</p>

<p>This technique is frequently used on audio devices that have small or no hardware
``sample'' buffers. There is additional CPU overhead to manage this ``circular'' buffer,
but in some cases this may be the only way to eliminate the latency that occurs when the
DMA counter reaches zero and the DMA stops transfers until it is reprogrammed.</p>
</dd>
</dl>




<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="10.1.4 Programming the DMA" id="AEN3522">
			<div class="sect3">
				<h3 class="title">10.1.4 Programming the DMA</h3>

<p>The DMA channel that is to be programmed should always be ``masked'' before loading
any settings. This is because the hardware might unexpectedly assert the DRQ for that
channel, and the DMA might respond, even though not all of the parameters have been
loaded or updated.</p>

<p>Once masked, the host must specify the direction of the transfer (memory-to-I/O or
I/O-to-memory), what mode of DMA operation is to be used for the transfer (Single, Block,
Demand, Cascade, etc), and finally the address and length of the transfer are loaded. The
length that is loaded is one less than the amount you expect the DMA to transfer. The LSB
and MSB of the address and length are written to the same 8-bit I/O port, so another port
must be written to first to guarantee that the DMA accepts the first byte as the LSB and
the second byte as the MSB of the length and address.</p>

<p>Then, be sure to update the Page Register, which is external to the DMA and is
accessed through a different set of I/O ports.</p>

<p>Once all the settings are ready, the DMA channel can be un-masked. That DMA channel is
now considered to be ``armed'', and will respond when the DRQ line for that channel is
asserted.</p>

<p>Refer to a hardware data book for precise programming details for the 8237. You will
also need to refer to the I/O port map for the PC system, which describes where the DMA
and Page Register ports are located. A complete port map table is located below.</p>



<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="10.1.5 DMA Port Map" id="AEN3531">
			<div class="sect3">
				<h3 class="title">10.1.5 DMA Port Map</h3>

<p>All systems based on the IBM-PC and PC/AT have the DMA hardware located at the same
I/O ports. The complete list is provided below. Ports assigned to DMA Controller #2 are
undefined on non-AT designs.</p>


<hr />

		<pkg:outlineMarker OutlineName="10.1.5.1 0x00-0x1f DMA Controller #1 (Channels 0, 1, 2 and 3)" id="AEN3534">
			<div class="sect3">
				<h4 class="title">10.1.5.1 0x00-0x1f DMA Controller #1
(Channels 0, 1, 2 and 3)</h4>

<p>DMA Address and Count Registers</p>

<a name="AEN3537"></a>
<table class="calstable" border="0" frame="void" width="100%">
<col />
<col />
<col />
<tbody>
<tr>
<td>0x00</td>
<td>write</td>
<td>Channel 0 starting address</td>
</tr>

<tr>
<td>0x00</td>
<td>read</td>
<td>Channel 0 current address</td>
</tr>

<tr>
<td>0x01</td>
<td>write</td>
<td>Channel 0 starting word count</td>
</tr>

<tr>
<td>0x01</td>
<td>read</td>
<td>Channel 0 remaining word count</td>
</tr>

<tr>
<td>0x02</td>
<td>write</td>
<td>Channel 1 starting address</td>
</tr>

<tr>
<td>0x02</td>
<td>read</td>
<td>Channel 1 current address</td>
</tr>

<tr>
<td>0x03</td>
<td>write</td>
<td>Channel 1 starting word count</td>
</tr>

<tr>
<td>0x03</td>
<td>read</td>
<td>Channel 1 remaining word count</td>
</tr>

<tr>
<td>0x04</td>
<td>write</td>
<td>Channel 2 starting address</td>
</tr>

<tr>
<td>0x04</td>
<td>read</td>
<td>Channel 2 current address</td>
</tr>

<tr>
<td>0x05</td>
<td>write</td>
<td>Channel 2 starting word count</td>
</tr>

<tr>
<td>0x05</td>
<td>read</td>
<td>Channel 2 remaining word count</td>
</tr>

<tr>
<td>0x06</td>
<td>write</td>
<td>Channel 3 starting address</td>
</tr>

<tr>
<td>0x06</td>
<td>read</td>
<td>Channel 3 current address</td>
</tr>

<tr>
<td>0x07</td>
<td>write</td>
<td>Channel 3 starting word count</td>
</tr>

<tr>
<td>0x07</td>
<td>read</td>
<td>Channel 3 remaining word count</td>
</tr>
</tbody>
</table>


<p>DMA Command Registers</p>

<a name="AEN3605"></a>
<table class="calstable" border="0" frame="void" width="100%">
<col />
<col />
<col />
<tbody>
<tr>
<td>0x08</td>
<td>write</td>
<td>Command Register</td>
</tr>

<tr>
<td>0x08</td>
<td>read</td>
<td>Status Register</td>
</tr>

<tr>
<td>0x09</td>
<td>write</td>
<td>Request Register</td>
</tr>

<tr>
<td>0x09</td>
<td>read</td>
<td>-</td>
</tr>

<tr>
<td>0x0a</td>
<td>write</td>
<td>Single Mask Register Bit</td>
</tr>

<tr>
<td>0x0a</td>
<td>read</td>
<td>-</td>
</tr>

<tr>
<td>0x0b</td>
<td>write</td>
<td>Mode Register</td>
</tr>

<tr>
<td>0x0b</td>
<td>read</td>
<td>-</td>
</tr>

<tr>
<td>0x0c</td>
<td>write</td>
<td>Clear LSB/MSB Flip-Flop</td>
</tr>

<tr>
<td>0x0c</td>
<td>read</td>
<td>-</td>
</tr>

<tr>
<td>0x0d</td>
<td>write</td>
<td>Master Clear/Reset</td>
</tr>

<tr>
<td>0x0d</td>
<td>read</td>
<td>Temporary Register (not available on newer versions)</td>
</tr>

<tr>
<td>0x0e</td>
<td>write</td>
<td>Clear Mask Register</td>
</tr>

<tr>
<td>0x0e</td>
<td>read</td>
<td>-</td>
</tr>

<tr>
<td>0x0f</td>
<td>write</td>
<td>Write All Mask Register Bits</td>
</tr>

<tr>
<td>0x0f</td>
<td>read</td>
<td>Read All Mask Register Bits (only in <span class="trademark">Intel</span> 82374)</td>
</tr>
</tbody>
</table>




<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="10.1.5.2 0xc0-0xdf DMA Controller #2 (Channels 4, 5, 6 and 7)" id="AEN3673">
			<div class="sect3">
				<h4 class="title">10.1.5.2 0xc0-0xdf DMA Controller #2
(Channels 4, 5, 6 and 7)</h4>

<p>DMA Address and Count Registers</p>

<a name="AEN3676"></a>
<table class="calstable" border="0" frame="void" width="100%">
<col />
<col />
<col />
<tbody>
<tr>
<td>0xc0</td>
<td>write</td>
<td>Channel 4 starting address</td>
</tr>

<tr>
<td>0xc0</td>
<td>read</td>
<td>Channel 4 current address</td>
</tr>

<tr>
<td>0xc2</td>
<td>write</td>
<td>Channel 4 starting word count</td>
</tr>

<tr>
<td>0xc2</td>
<td>read</td>
<td>Channel 4 remaining word count</td>
</tr>

<tr>
<td>0xc4</td>
<td>write</td>
<td>Channel 5 starting address</td>
</tr>

<tr>
<td>0xc4</td>
<td>read</td>
<td>Channel 5 current address</td>
</tr>

<tr>
<td>0xc6</td>
<td>write</td>
<td>Channel 5 starting word count</td>
</tr>

<tr>
<td>0xc6</td>
<td>read</td>
<td>Channel 5 remaining word count</td>
</tr>

<tr>
<td>0xc8</td>
<td>write</td>
<td>Channel 6 starting address</td>
</tr>

<tr>
<td>0xc8</td>
<td>read</td>
<td>Channel 6 current address</td>
</tr>

<tr>
<td>0xca</td>
<td>write</td>
<td>Channel 6 starting word count</td>
</tr>

<tr>
<td>0xca</td>
<td>read</td>
<td>Channel 6 remaining word count</td>
</tr>

<tr>
<td>0xcc</td>
<td>write</td>
<td>Channel 7 starting address</td>
</tr>

<tr>
<td>0xcc</td>
<td>read</td>
<td>Channel 7 current address</td>
</tr>

<tr>
<td>0xce</td>
<td>write</td>
<td>Channel 7 starting word count</td>
</tr>

<tr>
<td>0xce</td>
<td>read</td>
<td>Channel 7 remaining word count</td>
</tr>
</tbody>
</table>


<p>DMA Command Registers</p>

<a name="AEN3744"></a>
<table class="calstable" border="0" frame="void" width="100%">
<col />
<col />
<col />
<tbody>
<tr>
<td>0xd0</td>
<td>write</td>
<td>Command Register</td>
</tr>

<tr>
<td>0xd0</td>
<td>read</td>
<td>Status Register</td>
</tr>

<tr>
<td>0xd2</td>
<td>write</td>
<td>Request Register</td>
</tr>

<tr>
<td>0xd2</td>
<td>read</td>
<td>-</td>
</tr>

<tr>
<td>0xd4</td>
<td>write</td>
<td>Single Mask Register Bit</td>
</tr>

<tr>
<td>0xd4</td>
<td>read</td>
<td>-</td>
</tr>

<tr>
<td>0xd6</td>
<td>write</td>
<td>Mode Register</td>
</tr>

<tr>
<td>0xd6</td>
<td>read</td>
<td>-</td>
</tr>

<tr>
<td>0xd8</td>
<td>write</td>
<td>Clear LSB/MSB Flip-Flop</td>
</tr>

<tr>
<td>0xd8</td>
<td>read</td>
<td>-</td>
</tr>

<tr>
<td>0xda</td>
<td>write</td>
<td>Master Clear/Reset</td>
</tr>

<tr>
<td>0xda</td>
<td>read</td>
<td>Temporary Register (not present in <span class="trademark">Intel</span> 82374)</td>
</tr>

<tr>
<td>0xdc</td>
<td>write</td>
<td>Clear Mask Register</td>
</tr>

<tr>
<td>0xdc</td>
<td>read</td>
<td>-</td>
</tr>

<tr>
<td>0xde</td>
<td>write</td>
<td>Write All Mask Register Bits</td>
</tr>

<tr>
<td>0xdf</td>
<td>read</td>
<td>Read All Mask Register Bits (only in <span class="trademark">Intel</span> 82374)</td>
</tr>
</tbody>
</table>




<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="10.1.5.3 0x80-0x9f DMA Page Registers" id="AEN3813">
			<div class="sect3">
				<h4 class="title">10.1.5.3 0x80-0x9f DMA Page
Registers</h4>

<a name="AEN3815"></a>
<table class="calstable" border="0" frame="void" width="100%">
<col />
<col />
<col />
<tbody>
<tr>
<td>0x87</td>
<td>r/w</td>
<td>Channel 0 Low byte (23-16) page Register</td>
</tr>

<tr>
<td>0x83</td>
<td>r/w</td>
<td>Channel 1 Low byte (23-16) page Register</td>
</tr>

<tr>
<td>0x81</td>
<td>r/w</td>
<td>Channel 2 Low byte (23-16) page Register</td>
</tr>

<tr>
<td>0x82</td>
<td>r/w</td>
<td>Channel 3 Low byte (23-16) page Register</td>
</tr>

<tr>
<td>0x8b</td>
<td>r/w</td>
<td>Channel 5 Low byte (23-16) page Register</td>
</tr>

<tr>
<td>0x89</td>
<td>r/w</td>
<td>Channel 6 Low byte (23-16) page Register</td>
</tr>

<tr>
<td>0x8a</td>
<td>r/w</td>
<td>Channel 7 Low byte (23-16) page Register</td>
</tr>

<tr>
<td>0x8f</td>
<td>r/w</td>
<td>Low byte page Refresh</td>
</tr>
</tbody>
</table>




<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="10.1.5.4 0x400-0x4ff 82374 Enhanced DMA Registers" id="AEN3850">
			<div class="sect3">
				<h4 class="title">10.1.5.4 0x400-0x4ff 82374 Enhanced DMA
Registers</h4>

<p>The <span class="trademark">Intel</span> 82374 EISA System Component (ESC) was
introduced in early 1996 and includes a DMA controller that provides a superset of 8237
functionality as well as other PC-compatible core peripheral components in a single
package. This chip is targeted at both EISA and PCI platforms, and provides modern DMA
features like scatter-gather, ring buffers as well as direct access by the system DMA to
all 32 bits of address space.</p>

<p>If these features are used, code should also be included to provide similar
functionality in the previous 16 years worth of PC-compatible computers. For
compatibility reasons, some of the 82374 registers must be programmed <span class="emphasis"><i class="emphasis">after</i></span> programming the traditional 8237
registers for each transfer. Writing to a traditional 8237 register forces the contents
of some of the 82374 enhanced registers to zero to provide backward software
compatibility.</p>

<a name="AEN3856"></a>
<table class="calstable" border="0" frame="void" width="100%">
<col />
<col />
<col />
<tbody>
<tr>
<td>0x401</td>
<td>r/w</td>
<td>Channel 0 High byte (bits 23-16) word count</td>
</tr>

<tr>
<td>0x403</td>
<td>r/w</td>
<td>Channel 1 High byte (bits 23-16) word count</td>
</tr>

<tr>
<td>0x405</td>
<td>r/w</td>
<td>Channel 2 High byte (bits 23-16) word count</td>
</tr>

<tr>
<td>0x407</td>
<td>r/w</td>
<td>Channel 3 High byte (bits 23-16) word count</td>
</tr>

<tr>
<td>0x4c6</td>
<td>r/w</td>
<td>Channel 5 High byte (bits 23-16) word count</td>
</tr>

<tr>
<td>0x4ca</td>
<td>r/w</td>
<td>Channel 6 High byte (bits 23-16) word count</td>
</tr>

<tr>
<td>0x4ce</td>
<td>r/w</td>
<td>Channel 7 High byte (bits 23-16) word count</td>
</tr>

<tr>
<td>0x487</td>
<td>r/w</td>
<td>Channel 0 High byte (bits 31-24) page Register</td>
</tr>

<tr>
<td>0x483</td>
<td>r/w</td>
<td>Channel 1 High byte (bits 31-24) page Register</td>
</tr>

<tr>
<td>0x481</td>
<td>r/w</td>
<td>Channel 2 High byte (bits 31-24) page Register</td>
</tr>

<tr>
<td>0x482</td>
<td>r/w</td>
<td>Channel 3 High byte (bits 31-24) page Register</td>
</tr>

<tr>
<td>0x48b</td>
<td>r/w</td>
<td>Channel 5 High byte (bits 31-24) page Register</td>
</tr>

<tr>
<td>0x489</td>
<td>r/w</td>
<td>Channel 6 High byte (bits 31-24) page Register</td>
</tr>

<tr>
<td>0x48a</td>
<td>r/w</td>
<td>Channel 6 High byte (bits 31-24) page Register</td>
</tr>

<tr>
<td>0x48f</td>
<td>r/w</td>
<td>High byte page Refresh</td>
</tr>

<tr>
<td>0x4e0</td>
<td>r/w</td>
<td>Channel 0 Stop Register (bits 7-2)</td>
</tr>

<tr>
<td>0x4e1</td>
<td>r/w</td>
<td>Channel 0 Stop Register (bits 15-8)</td>
</tr>

<tr>
<td>0x4e2</td>
<td>r/w</td>
<td>Channel 0 Stop Register (bits 23-16)</td>
</tr>

<tr>
<td>0x4e4</td>
<td>r/w</td>
<td>Channel 1 Stop Register (bits 7-2)</td>
</tr>

<tr>
<td>0x4e5</td>
<td>r/w</td>
<td>Channel 1 Stop Register (bits 15-8)</td>
</tr>

<tr>
<td>0x4e6</td>
<td>r/w</td>
<td>Channel 1 Stop Register (bits 23-16)</td>
</tr>

<tr>
<td>0x4e8</td>
<td>r/w</td>
<td>Channel 2 Stop Register (bits 7-2)</td>
</tr>

<tr>
<td>0x4e9</td>
<td>r/w</td>
<td>Channel 2 Stop Register (bits 15-8)</td>
</tr>

<tr>
<td>0x4ea</td>
<td>r/w</td>
<td>Channel 2 Stop Register (bits 23-16)</td>
</tr>

<tr>
<td>0x4ec</td>
<td>r/w</td>
<td>Channel 3 Stop Register (bits 7-2)</td>
</tr>

<tr>
<td>0x4ed</td>
<td>r/w</td>
<td>Channel 3 Stop Register (bits 15-8)</td>
</tr>

<tr>
<td>0x4ee</td>
<td>r/w</td>
<td>Channel 3 Stop Register (bits 23-16)</td>
</tr>

<tr>
<td>0x4f4</td>
<td>r/w</td>
<td>Channel 5 Stop Register (bits 7-2)</td>
</tr>

<tr>
<td>0x4f5</td>
<td>r/w</td>
<td>Channel 5 Stop Register (bits 15-8)</td>
</tr>

<tr>
<td>0x4f6</td>
<td>r/w</td>
<td>Channel 5 Stop Register (bits 23-16)</td>
</tr>

<tr>
<td>0x4f8</td>
<td>r/w</td>
<td>Channel 6 Stop Register (bits 7-2)</td>
</tr>

<tr>
<td>0x4f9</td>
<td>r/w</td>
<td>Channel 6 Stop Register (bits 15-8)</td>
</tr>

<tr>
<td>0x4fa</td>
<td>r/w</td>
<td>Channel 6 Stop Register (bits 23-16)</td>
</tr>

<tr>
<td>0x4fc</td>
<td>r/w</td>
<td>Channel 7 Stop Register (bits 7-2)</td>
</tr>

<tr>
<td>0x4fd</td>
<td>r/w</td>
<td>Channel 7 Stop Register (bits 15-8)</td>
</tr>

<tr>
<td>0x4fe</td>
<td>r/w</td>
<td>Channel 7 Stop Register (bits 23-16)</td>
</tr>

<tr>
<td>0x40a</td>
<td>write</td>
<td>Channels 0-3 Chaining Mode Register</td>
</tr>

<tr>
<td>0x40a</td>
<td>read</td>
<td>Channel Interrupt Status Register</td>
</tr>

<tr>
<td>0x4d4</td>
<td>write</td>
<td>Channels 4-7 Chaining Mode Register</td>
</tr>

<tr>
<td>0x4d4</td>
<td>read</td>
<td>Chaining Mode Status</td>
</tr>

<tr>
<td>0x40c</td>
<td>read</td>
<td>Chain Buffer Expiration Control Register</td>
</tr>

<tr>
<td>0x410</td>
<td>write</td>
<td>Channel 0 Scatter-Gather Command Register</td>
</tr>

<tr>
<td>0x411</td>
<td>write</td>
<td>Channel 1 Scatter-Gather Command Register</td>
</tr>

<tr>
<td>0x412</td>
<td>write</td>
<td>Channel 2 Scatter-Gather Command Register</td>
</tr>

<tr>
<td>0x413</td>
<td>write</td>
<td>Channel 3 Scatter-Gather Command Register</td>
</tr>

<tr>
<td>0x415</td>
<td>write</td>
<td>Channel 5 Scatter-Gather Command Register</td>
</tr>

<tr>
<td>0x416</td>
<td>write</td>
<td>Channel 6 Scatter-Gather Command Register</td>
</tr>

<tr>
<td>0x417</td>
<td>write</td>
<td>Channel 7 Scatter-Gather Command Register</td>
</tr>

<tr>
<td>0x418</td>
<td>read</td>
<td>Channel 0 Scatter-Gather Status Register</td>
</tr>

<tr>
<td>0x419</td>
<td>read</td>
<td>Channel 1 Scatter-Gather Status Register</td>
</tr>

<tr>
<td>0x41a</td>
<td>read</td>
<td>Channel 2 Scatter-Gather Status Register</td>
</tr>

<tr>
<td>0x41b</td>
<td>read</td>
<td>Channel 3 Scatter-Gather Status Register</td>
</tr>

<tr>
<td>0x41d</td>
<td>read</td>
<td>Channel 5 Scatter-Gather Status Register</td>
</tr>

<tr>
<td>0x41e</td>
<td>read</td>
<td>Channel 5 Scatter-Gather Status Register</td>
</tr>

<tr>
<td>0x41f</td>
<td>read</td>
<td>Channel 7 Scatter-Gather Status Register</td>
</tr>

<tr>
<td>0x420-0x423</td>
<td>r/w</td>
<td>Channel 0 Scatter-Gather Descriptor Table Pointer Register</td>
</tr>

<tr>
<td>0x424-0x427</td>
<td>r/w</td>
<td>Channel 1 Scatter-Gather Descriptor Table Pointer Register</td>
</tr>

<tr>
<td>0x428-0x42b</td>
<td>r/w</td>
<td>Channel 2 Scatter-Gather Descriptor Table Pointer Register</td>
</tr>

<tr>
<td>0x42c-0x42f</td>
<td>r/w</td>
<td>Channel 3 Scatter-Gather Descriptor Table Pointer Register</td>
</tr>

<tr>
<td>0x434-0x437</td>
<td>r/w</td>
<td>Channel 5 Scatter-Gather Descriptor Table Pointer Register</td>
</tr>

<tr>
<td>0x438-0x43b</td>
<td>r/w</td>
<td>Channel 6 Scatter-Gather Descriptor Table Pointer Register</td>
</tr>

<tr>
<td>0x43c-0x43f</td>
<td>r/w</td>
<td>Channel 7 Scatter-Gather Descriptor Table Pointer Register</td>
</tr>
</tbody>
</table>







<hr />

	</div>
</pkg:outlineMarker>


		</div>
	</pkg:outlineMarker>

			</div>
		</pkg:outlineMarker>

			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="Chapter 11 Kernel Debugging" id="KERNELDEBUG">
	<div class="sect1">
		<h1 class="title">Chapter 11 Kernel Debugging</h1>

<i class="authorgroup"><span class="contrib">Contributed by</span> Paul Richards and Jörg
Wunsch.</i> 



	<pkg:outlineMarker OutlineName="11.1 Obtaining a Kernel Crash Dump" id="KERNELDEBUG-OBTAIN">
		<div class="sect2">
			<h2 class="title">11.1 Obtaining a
Kernel Crash Dump</h2>

<p>When running a development kernel (eg: FreeBSD-CURRENT), such as a kernel under
extreme conditions (eg: very high load averages, tens of thousands of connections,
exceedingly high number of concurrent users, hundreds of <a href="http://www.freebsd.org/cgi/man.cgi?query=jail&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">jail</span>(8)</span></a>s, etc.), or
using a new feature or device driver on FreeBSD-STABLE (eg: <acronym class="acronym">PAE</acronym>), sometimes a kernel will panic. In the event that it does,
this chapter will demonstrate how to extract useful information out of a crash.</p>

<p>A system reboot is inevitable once a kernel panics. Once a system is rebooted, the
contents of a system's physical memory (<acronym class="acronym">RAM</acronym>) is lost,
as well as any bits that are on the swap device before the panic. To preserve the bits in
physical memory, the kernel makes use of the swap device as a temporary place to store
the bits that are in RAM across a reboot after a crash. In doing this, when FreeBSD boots
after a crash, a kernel image can now be extracted and debugging can take place.</p>


<blockquote class="note">
<p><b>Note:</b> A swap device that has been configured as a dump device still acts as a
swap device. Dumps to non-swap devices (such as tapes or CDRWs, for example) are not
supported at this time. A ``swap device'' is synonymous with a ``swap partition.''</p>
</blockquote>


<p>To be able to extract a usable core, it is required that at least one swap partition
be large enough to hold all of the bits in physical memory. When a kernel panics, before
the system reboots, the kernel is smart enough to check to see if a swap device has been
configured as a dump device. If there is a valid dump device, the kernel dumps the
contents of what is in physical memory to the swap device.</p>


<hr />

		<pkg:outlineMarker OutlineName="11.1.1 Configuring the Dump Device" id="CONFIG-DUMPDEV">
			<div class="sect3">
				<h3 class="title">11.1.1 Configuring the
Dump Device</h3>

<p>Before the kernel will dump the contents of its physical memory to a dump device, a
dump device must be configured. A dump device is specified by using the <a href="http://www.freebsd.org/cgi/man.cgi?query=dumpon&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">dumpon</span>(8)</span></a> command to
tell the kernel where to save kernel crash dumps. The <a href="http://www.freebsd.org/cgi/man.cgi?query=dumpon&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">dumpon</span>(8)</span></a> program must
be called after the swap partition has been configured with <a href="http://www.freebsd.org/cgi/man.cgi?query=swapon&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">swapon</span>(8)</span></a>. This is
normally handled by setting the <var class="varname">dumpdev</var> variable in <a href="http://www.freebsd.org/cgi/man.cgi?query=rc.conf&#38;sektion=5"><span class="citerefentry"><span class="refentrytitle">rc.conf</span>(5)</span></a> to the path
of the swap device (the recommended way to extract a kernel dump).</p>

<p>Alternatively, the dump device can be hard-coded via the <var class="literal">dump</var> clause in the <a href="http://www.freebsd.org/cgi/man.cgi?query=config&#38;sektion=5"><span class="citerefentry"><span class="refentrytitle">config</span>(5)</span></a> line of a
kernel configuration file. This approach is deprecated and should be used only if a
kernel is crashing before <a href="http://www.freebsd.org/cgi/man.cgi?query=dumpon&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">dumpon</span>(8)</span></a> can be
executed.</p>


<blockquote class="tip">
<p><b>Tip:</b> Check <tt class="filename">/etc/fstab</tt> or <a href="http://www.freebsd.org/cgi/man.cgi?query=swapinfo&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">swapinfo</span>(8)</span></a> for a list
of swap devices.</p>
</blockquote>



<blockquote class="important">
<p><b>Important:</b> Make sure the <var class="varname">dumpdir</var> specified in <a href="http://www.freebsd.org/cgi/man.cgi?query=rc.conf&#38;sektion=5"><span class="citerefentry"><span class="refentrytitle">rc.conf</span>(5)</span></a> exists
before a kernel crash!</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">mkdir /var/crash</kbd>
<samp class="prompt">#</samp> <kbd class="userinput">chmod 700 /var/crash</kbd>
</pre>

<p>Also, remember that the contents of <tt class="filename">/var/crash</tt> is sensitive
and very likely contains confidential information such as passwords.</p>
</blockquote>




<hr />

			</div>
		</pkg:outlineMarker>

		<pkg:outlineMarker OutlineName="11.1.2 Extracting a Kernel Dump" id="EXTRACT-DUMP">
			<div class="sect3">
				<h3 class="title">11.1.2 Extracting a Kernel
Dump</h3>

<p>Once a dump has been written to a dump device, the dump must be extracted before the
swap device is mounted. To extract a dump from a dump device, use the <a href="http://www.freebsd.org/cgi/man.cgi?query=savecore&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">savecore</span>(8)</span></a> program.
If <var class="varname">dumpdev</var> has been set in <a href="http://www.freebsd.org/cgi/man.cgi?query=rc.conf&#38;sektion=5"><span class="citerefentry"><span class="refentrytitle">rc.conf</span>(5)</span></a>, <a href="http://www.freebsd.org/cgi/man.cgi?query=savecore&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">savecore</span>(8)</span></a> will be
called automatically on the first multi-user boot after the crash and before the swap
device is mounted. The location of the extracted core is placed in the <a href="http://www.freebsd.org/cgi/man.cgi?query=rc.conf&#38;sektion=5"><span class="citerefentry"><span class="refentrytitle">rc.conf</span>(5)</span></a> value <var class="varname">dumpdir</var>, by default <tt class="filename">/var/crash</tt> and will
be named <tt class="filename">vmcore.0</tt>.</p>

<p>In the event that there is already a file called <tt class="filename">vmcore.0</tt> in
<tt class="filename">/var/crash</tt> (or whatever <var class="varname">dumpdev</var> is
set to), the kernel will increment the trailing number for every crash to avoid
overwriting an existing <tt class="filename">vmcore</tt> (eg: <tt class="filename">vmcore.1</tt>). While debugging, it is highly likely that you will want
to use the highest version <tt class="filename">vmcore</tt> in <tt class="filename">/var/crash</tt> when searching for the right <tt class="filename">vmcore</tt>.</p>


<blockquote class="tip">
<p><b>Tip:</b> If you are testing a new kernel but need to boot a different one in order
to get your system up and running again, boot it only into single user mode using the
<var class="option">-s</var> flag at the boot prompt, and then perform the following
steps:</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">fsck -p</kbd>
<samp class="prompt">#</samp> <kbd class="userinput">mount -a -t ufs</kbd>       # make sure /var/crash is writable
<samp class="prompt">#</samp> <kbd class="userinput">savecore /var/crash /dev/ad0s1b</kbd>
<samp class="prompt">#</samp> <kbd class="userinput">exit</kbd>                  # exit to multi-user
</pre>

<p>This instructs <a href="http://www.freebsd.org/cgi/man.cgi?query=savecore&#38;sektion=8"><span class="citerefentry"><span class="refentrytitle">savecore</span>(8)</span></a> to extract
a kernel dump from <tt class="filename">/dev/ad0s1b</tt> and place the contents in <tt class="filename">/var/crash</tt>. Do not forget to make sure the destination directory
<tt class="filename">/var/crash</tt> has enough space for the dump. Also, do not forget
to specify the correct path to your swap device as it is likely different than <tt class="filename">/dev/ad0s1b</tt>!</p>
</blockquote>


<p>The recommended, and certainly the easiest way to automate obtaining crash dumps is to
use the <var class="varname">dumpdev</var> variable in <a href="http://www.freebsd.org/cgi/man.cgi?query=rc.conf&#38;sektion=5"><span class="citerefentry"><span class="refentrytitle">rc.conf</span>(5)</span></a>.</p>




<hr />

		</div>
	</pkg:outlineMarker>

	
			</div>
		</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="11.2 Debugging a Kernel Crash Dump with kgdb" id="KERNELDEBUG-GDB">
		<div class="sect2">
			<h2 class="title">11.2 Debugging a Kernel
Crash Dump with <tt class="command">kgdb</tt></h2>


<blockquote class="note">
<p><b>Note:</b> This section covers <a href="http://www.freebsd.org/cgi/man.cgi?query=kgdb&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">kgdb</span>(1)</span></a> as found in
FreeBSD&#160;5.3 and later. In previous versions, one must use <tt class="command">gdb
-k</tt> to read a core dump file.</p>
</blockquote>


<p>Once a dump has been obtained, getting useful information out of the dump is
relatively easy for simple problems. Before launching into the internals of <a href="http://www.freebsd.org/cgi/man.cgi?query=kgdb&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">kgdb</span>(1)</span></a> to debug the
crash dump, locate the debug version of your kernel (normally called <tt class="filename">kernel.debug</tt>) and the path to the source files used to build your
kernel (normally <tt class="filename">/usr/obj/usr/src/sys/<var class="replaceable">KERNCONF</var></tt>, where <tt class="filename"><var class="replaceable">KERNCONF</var></tt> is the <var class="varname">ident</var> specified
in a kernel <a href="http://www.freebsd.org/cgi/man.cgi?query=config&#38;sektion=5"><span class="citerefentry"><span class="refentrytitle">config</span>(5)</span></a>). With those
two pieces of info, let the debugging commence!</p>

<p>To enter into the debugger and begin getting information from the dump, the following
steps are required at a minimum:</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">cd /usr/obj/usr/src/sys/<var class="replaceable">KERNCONF</var></kbd>
<samp class="prompt">#</samp> <kbd class="userinput">kgdb /boot/kernel/kernel.debug /var/crash/vmcore.0</kbd>
</pre>

<p>You can debug the crash dump using the kernel sources just like you can for any other
program.</p>

<p>This first dump is from a 5.2-BETA kernel and the crash comes from deep within the
kernel. The output below has been modified to include line numbers on the left. This
first trace inspects the instruction pointer and obtains a back trace. The address that
is used on line 41 for the <tt class="command">list</tt> command is the instruction
pointer and can be found on line line 17. Most developers will request having at least
this information sent to them if you are unable to debug the problem yourself. If,
however, you do solve the problem, make sure that your patch winds its way into the
source tree via a problem report, mailing lists, or by being able to commit it!</p>

<pre class="screen"> 1:<samp class="prompt">#</samp> <kbd class="userinput">cd /usr/obj/usr/src/sys/<var class="replaceable">KERNCONF</var></kbd>
 2:<samp class="prompt">#</samp> <kbd class="userinput">kgdb kernel.debug /var/crash/vmcore.0</kbd>
 3:GNU gdb 5.2.1 (FreeBSD)
 4:Copyright 2002 Free Software Foundation, Inc.
 5:GDB is free software, covered by the GNU General Public License, and you are
 6:welcome to change it and/or distribute copies of it under certain conditions.
 7:Type "show copying" to see the conditions.
 8:There is absolutely no warranty for GDB.  Type "show warranty" for details.
 9:This GDB was configured as "i386-undermydesk-freebsd"...
10:panic: page fault
11:panic messages:
12:---
13:Fatal trap 12: page fault while in kernel mode
14:cpuid = 0; apic id = 00
15:fault virtual address   = 0x300
16:fault code:             = supervisor read, page not present
17:instruction pointer     = 0x8:0xc0713860
18:stack pointer           = 0x10:0xdc1d0b70
19:frame pointer           = 0x10:0xdc1d0b7c
20:code segment            = base 0x0, limit 0xfffff, type 0x1b
21:                        = DPL 0, pres 1, def32 1, gran 1
22:processor eflags        = resume, IOPL = 0
23:current process         = 14394 (uname)
24:trap number             = 12
25:panic: page fault
26      cpuid = 0;
27:Stack backtrace:
28
29:syncing disks, buffers remaining... 2199 2199 panic: mi_switch: switch in a critical section
30:cpuid = 0;
31:Uptime: 2h43m19s
32:Dumping 255 MB
33: 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
34:---
35:Reading symbols from /boot/kernel/snd_maestro3.ko...done.
36:Loaded symbols for /boot/kernel/snd_maestro3.ko
37:Reading symbols from /boot/kernel/snd_pcm.ko...done.
38:Loaded symbols for /boot/kernel/snd_pcm.ko
39:#0  doadump () at /usr/src/sys/kern/kern_shutdown.c:240
40:240             dumping++;
41:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">list *0xc0713860</kbd>
42:0xc0713860 is in lapic_ipi_wait (/usr/src/sys/i386/i386/local_apic.c:663).
43:658                     incr = 0;
44:659                     delay = 1;
45:660             } else
46:661                     incr = 1;
47:662             for (x = 0; x &#60; delay; x += incr) {
48:663                     if ((lapic-&#62;icr_lo &#38; APIC_DELSTAT_MASK) == APIC_DELSTAT_IDLE)
49:664                             return (1);
50:665                     ia32_pause();
51:666             }
52:667             return (0);
53:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">backtrace</kbd>
54:#0  doadump () at /usr/src/sys/kern/kern_shutdown.c:240
55:#1  0xc055fd9b in boot (howto=260) at /usr/src/sys/kern/kern_shutdown.c:372
56:#2  0xc056019d in panic () at /usr/src/sys/kern/kern_shutdown.c:550
57:#3  0xc0567ef5 in mi_switch () at /usr/src/sys/kern/kern_synch.c:470
58:#4  0xc055fa87 in boot (howto=256) at /usr/src/sys/kern/kern_shutdown.c:312
59:#5  0xc056019d in panic () at /usr/src/sys/kern/kern_shutdown.c:550
60:#6  0xc0720c66 in trap_fatal (frame=0xdc1d0b30, eva=0)
61:    at /usr/src/sys/i386/i386/trap.c:821
62:#7  0xc07202b3 in trap (frame=
63:      {tf_fs = -1065484264, tf_es = -1065484272, tf_ds = -1065484272, tf_edi = 1, tf_esi = 0, tf_ebp = -602076292, tf_isp = -602076324, tf_ebx = 0, tf_edx = 0, tf_ecx = 1000000, tf_eax = 243, tf_trapno = 12, tf_err = 0, tf_eip = -1066321824, tf_cs = 8, tf_eflags = 65671, tf_esp = 243, tf_ss = 0})
64:    at /usr/src/sys/i386/i386/trap.c:250
65:#8  0xc070c9f8 in calltrap () at {standard input}:94
66:#9  0xc07139f3 in lapic_ipi_vectored (vector=0, dest=0)
67:    at /usr/src/sys/i386/i386/local_apic.c:733
68:#10 0xc0718b23 in ipi_selected (cpus=1, ipi=1)
69:    at /usr/src/sys/i386/i386/mp_machdep.c:1115
70:#11 0xc057473e in kseq_notify (ke=0xcc05e360, cpu=0)
71:    at /usr/src/sys/kern/sched_ule.c:520
72:#12 0xc0575cad in sched_add (td=0xcbcf5c80)
73:    at /usr/src/sys/kern/sched_ule.c:1366
74:#13 0xc05666c6 in setrunqueue (td=0xcc05e360)
75:    at /usr/src/sys/kern/kern_switch.c:422
76:#14 0xc05752f4 in sched_wakeup (td=0xcbcf5c80)
77:    at /usr/src/sys/kern/sched_ule.c:999
78:#15 0xc056816c in setrunnable (td=0xcbcf5c80)
79:    at /usr/src/sys/kern/kern_synch.c:570
80:#16 0xc0567d53 in wakeup (ident=0xcbcf5c80)
81:    at /usr/src/sys/kern/kern_synch.c:411
82:#17 0xc05490a8 in exit1 (td=0xcbcf5b40, rv=0)
83:    at /usr/src/sys/kern/kern_exit.c:509
84:#18 0xc0548011 in sys_exit () at /usr/src/sys/kern/kern_exit.c:102
85:#19 0xc0720fd0 in syscall (frame=
86:      {tf_fs = 47, tf_es = 47, tf_ds = 47, tf_edi = 0, tf_esi = -1, tf_ebp = -1077940712, tf_isp = -602075788, tf_ebx = 672411944, tf_edx = 10, tf_ecx = 672411600, tf_eax = 1, tf_trapno = 12, tf_err = 2, tf_eip = 671899563, tf_cs = 31, tf_eflags = 642, tf_esp = -1077940740, tf_ss = 47})
87:    at /usr/src/sys/i386/i386/trap.c:1010
88:#20 0xc070ca4d in Xint0x80_syscall () at {standard input}:136
89:---Can't read userspace from dump, or kernel process---
90:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">quit</kbd>
</pre>

<p>This next trace is an older dump from the FreeBSD 2 time frame, but is more involved
and demonstrates more of the features of <tt class="command">gdb</tt>. Long lines have
been folded to improve readability, and the lines are numbered for reference. Despite
this, it is a real-world error trace taken during the development of the pcvt console
driver.</p>

<pre class="screen"> 1:Script started on Fri Dec 30 23:15:22 1994
 2:<samp class="prompt">#</samp> <kbd class="userinput">cd /sys/compile/URIAH</kbd>
 3:<samp class="prompt">#</samp> <kbd class="userinput">gdb -k kernel /var/crash/vmcore.1</kbd>
 4:Reading symbol data from /usr/src/sys/compile/URIAH/kernel
...done.
 5:IdlePTD 1f3000
 6:panic: because you said to!
 7:current pcb at 1e3f70
 8:Reading in symbols for ../../i386/i386/machdep.c...done.
 9:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">backtrace</kbd>
10:#0  boot (arghowto=256) (../../i386/i386/machdep.c line 767)
11:#1  0xf0115159 in panic ()
12:#2  0xf01955bd in diediedie () (../../i386/i386/machdep.c line 698)
13:#3  0xf010185e in db_fncall ()
14:#4  0xf0101586 in db_command (-266509132, -266509516, -267381073)
15:#5  0xf0101711 in db_command_loop ()
16:#6  0xf01040a0 in db_trap ()
17:#7  0xf0192976 in kdb_trap (12, 0, -272630436, -266743723)
18:#8  0xf019d2eb in trap_fatal (...)
19:#9  0xf019ce60 in trap_pfault (...)
20:#10 0xf019cb2f in trap (...)
21:#11 0xf01932a1 in exception:calltrap ()
22:#12 0xf0191503 in cnopen (...)
23:#13 0xf0132c34 in spec_open ()
24:#14 0xf012d014 in vn_open ()
25:#15 0xf012a183 in open ()
26:#16 0xf019d4eb in syscall (...)
27:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">up 10</kbd>
28:Reading in symbols for ../../i386/i386/trap.c...done.
29:#10 0xf019cb2f in trap (frame={tf_es = -260440048, tf_ds = 16, tf_\
30:edi = 3072, tf_esi = -266445372, tf_ebp = -272630356, tf_isp = -27\
31:2630396, tf_ebx = -266427884, tf_edx = 12, tf_ecx = -266427884, tf\
32:_eax = 64772224, tf_trapno = 12, tf_err = -272695296, tf_eip = -26\
33:6672343, tf_cs = -266469368, tf_eflags = 66066, tf_esp = 3072, tf_\
34:ss = -266427884}) (../../i386/i386/trap.c line 283)
35:283                             (void) trap_pfault(&#38;frame, FALSE);
36:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">frame frame-&#62;tf_ebp frame-&#62;tf_eip</kbd>
37:Reading in symbols for ../../i386/isa/pcvt/pcvt_drv.c...done.
38:#0  0xf01ae729 in pcopen (dev=3072, flag=3, mode=8192, p=(struct p\
39:roc *) 0xf07c0c00) (../../i386/isa/pcvt/pcvt_drv.c line 403)
40:403             return ((*linesw[tp-&#62;t_line].l_open)(dev, tp));
41:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">list</kbd>
42:398
43:399             tp-&#62;t_state |= TS_CARR_ON;
44:400             tp-&#62;t_cflag |= CLOCAL;  /* cannot be a modem (:-) */
45:401
46:402     #if PCVT_NETBSD || (PCVT_FREEBSD &#62;= 200)
47:403             return ((*linesw[tp-&#62;t_line].l_open)(dev, tp));
48:404     #else
49:405             return ((*linesw[tp-&#62;t_line].l_open)(dev, tp, flag));
50:406     #endif /* PCVT_NETBSD || (PCVT_FREEBSD &#62;= 200) */
51:407     }
52:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">print tp</kbd>
53:Reading in symbols for ../../i386/i386/cons.c...done.
54:$1 = (struct tty *) 0x1bae
55:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">print tp-&#62;t_line</kbd>
56:$2 = 1767990816
57:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">up</kbd>
58:#1  0xf0191503 in cnopen (dev=0x00000000, flag=3, mode=8192, p=(st\
59:ruct proc *) 0xf07c0c00) (../../i386/i386/cons.c line 126)
60:       return ((*cdevsw[major(dev)].d_open)(dev, flag, mode, p));
61:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">up</kbd>
62:#2  0xf0132c34 in spec_open ()
63:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">up</kbd>
64:#3  0xf012d014 in vn_open ()
65:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">up</kbd>
66:#4  0xf012a183 in open ()
67:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">up</kbd>
68:#5  0xf019d4eb in syscall (frame={tf_es = 39, tf_ds = 39, tf_edi =\
69: 2158592, tf_esi = 0, tf_ebp = -272638436, tf_isp = -272629788, tf\
70:_ebx = 7086, tf_edx = 1, tf_ecx = 0, tf_eax = 5, tf_trapno = 582, \
71:tf_err = 582, tf_eip = 75749, tf_cs = 31, tf_eflags = 582, tf_esp \
72:= -272638456, tf_ss = 39}) (../../i386/i386/trap.c line 673)
73:673             error = (*callp-&#62;sy_call)(p, args, rval);
74:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">up</kbd>
75:Initial frame selected; you cannot go up.
76:<samp class="prompt">(kgdb)</samp> <kbd class="userinput">quit</kbd>
</pre>

<p>Comments to the above script:</p>


<dl>
<dt>line 6:</dt>

<dd>
<p>This is a dump taken from within DDB (see below), hence the panic comment ``because
you said to!'', and a rather long stack trace; the initial reason for going into DDB has
been a page fault trap though.</p>
</dd>

<dt>line 20:</dt>

<dd>
<p>This is the location of function <code class="function">trap()</code> in the stack
trace.</p>
</dd>

<dt>line 36:</dt>

<dd>
<p>Force usage of a new stack frame; this is no longer necessary. The stack frames are
supposed to point to the right locations now, even in case of a trap. From looking at the
code in source line 403, there is a high probability that either the pointer access for
``tp'' was messed up, or the array access was out of bounds.</p>
</dd>

<dt>line 52:</dt>

<dd>
<p>The pointer looks suspicious, but happens to be a valid address.</p>
</dd>

<dt>line 56:</dt>

<dd>
<p>However, it obviously points to garbage, so we have found our error! (For those
unfamiliar with that particular piece of code: <var class="literal">tp-&#62;t_line</var>
refers to the line discipline of the console device here, which must be a rather small
integer number.)</p>
</dd>
</dl>



<blockquote class="tip">
<p><b>Tip:</b> If your system is crashing regularly and you are running out of disk
space, deleting old <tt class="filename">vmcore</tt> files in <tt class="filename">/var/crash</tt> could save a considerable amount of disk space!</p>
</blockquote>




<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="11.3 Debugging a Crash Dump with DDD" id="KERNELDEBUG-DDD">
		<div class="sect2">
			<h2 class="title">11.3 Debugging a Crash
Dump with DDD</h2>

<p>Examining a kernel crash dump with a graphical debugger like <tt class="command">ddd</tt> is also possible (you will need to install the <a href="http://www.freebsd.org/cgi/url.cgi?ports/devel/ddd/pkg-descr"><tt class="filename">devel/ddd</tt></a> port in order to use the <tt class="command">ddd</tt>
debugger). Add the <var class="option">-k</var> option to the <tt class="command">ddd</tt> command line you would use normally. For example;</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">ddd -k /var/crash/kernel.0 /var/crash/vmcore.0</kbd>
</pre>

<p>You should then be able to go about looking at the crash dump using <tt class="command">ddd</tt>'s graphical interface.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="11.4 Post-Mortem Analysis of a Dump" id="KERNELDEBUG-POST-MORTEM">
		<div class="sect2">
			<h2 class="title">11.4
Post-Mortem Analysis of a Dump</h2>

<p>What do you do if a kernel dumped core but you did not expect it, and it is therefore
not compiled using <tt class="command">config -g</tt>? Not everything is lost here. Do
not panic!</p>

<p>Of course, you still need to enable crash dumps. See above for the options you have to
specify in order to do this.</p>

<p>Go to your kernel config directory (<tt class="filename">/usr/src/sys/<var class="replaceable">arch</var>/conf</tt>) and edit your configuration file. Uncomment (or
add, if it does not exist) the following line:</p>


		<pkg:outlineMarker OutlineName="code_46" id="code_46" visible="false" copy="true">
				<pre class="programlisting">makeoptions    DEBUG=-g                #Build kernel with gdb(1) debug symbols
</pre>
		</pkg:outlineMarker>


<p>Rebuild the kernel. Due to the time stamp change on the Makefile, some other object
files will be rebuilt, for example <tt class="filename">trap.o</tt>. With a bit of luck,
the added <var class="option">-g</var> option will not change anything for the generated
code, so you will finally get a new kernel with similar code to the faulting one but some
debugging symbols. You should at least verify the old and new sizes with the <a href="http://www.freebsd.org/cgi/man.cgi?query=size&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">size</span>(1)</span></a> command. If
there is a mismatch, you probably need to give up here.</p>

<p>Go and examine the dump as described above. The debugging symbols might be incomplete
for some places, as can be seen in the stack trace in the example above where some
functions are displayed without line numbers and argument lists. If you need more
debugging symbols, remove the appropriate object files, recompile the kernel again and
repeat the <tt class="command">gdb <var class="option">-k</var></tt> session until you
know enough.</p>

<p>All this is not guaranteed to work, but it will do it fine in most cases.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="11.5 On-Line Kernel Debugging Using DDB" id="KERNELDEBUG-ONLINE-DDB">
		<div class="sect2">
			<h2 class="title">11.5
On-Line Kernel Debugging Using DDB</h2>

<p>While <tt class="command">gdb <var class="option">-k</var></tt> as an off-line
debugger provides a very high level of user interface, there are some things it cannot
do. The most important ones being breakpointing and single-stepping kernel code.</p>

<p>If you need to do low-level debugging on your kernel, there is an on-line debugger
available called DDB. It allows setting of breakpoints, single-stepping kernel functions,
examining and changing kernel variables, etc. However, it cannot access kernel source
files, and only has access to the global and static symbols, not to the full debug
information like <tt class="command">gdb</tt> does.</p>

<p>To configure your kernel to include DDB, add the option line</p>


		<pkg:outlineMarker OutlineName="code_47" id="code_47" visible="false" copy="true">
				<pre class="programlisting">options DDB
</pre>
		</pkg:outlineMarker>


to your config file, and rebuild. (See <a href="pkg://FreeBSD Handbook/INDEX" target="_top">The
FreeBSD Handbook</a> for details on configuring the FreeBSD kernel).<br />
<br />

<blockquote class="note">
<p><b>Note:</b> If you have an older version of the boot blocks, your debugger symbols
might not be loaded at all. Update the boot blocks; the recent ones load the DDB symbols
automatically.</p>
</blockquote>


<p>Once your DDB kernel is running, there are several ways to enter DDB. The first, and
earliest way is to type the boot flag <var class="option">-d</var> right at the boot
prompt. The kernel will start up in debug mode and enter DDB prior to any device probing.
Hence you can even debug the device probe/attach functions.</p>

<p>The second scenario is to drop to the debugger once the system has booted. There are
two simple ways to accomplish this. If you would like to break to the debugger from the
command prompt, simply type the command:</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">sysctl debug.enter_debugger=ddb</kbd>
</pre>

<p>Alternatively, if you are at the system console, you may use a hot-key on the
keyboard. The default break-to-debugger sequence is <b class="keycap">Ctrl</b>+<b class="keycap">Alt</b>+<b class="keycap">ESC</b>. For syscons, this sequence can be
remapped and some of the distributed maps out there do this, so check to make sure you
know the right sequence to use. There is an option available for serial consoles that
allows the use of a serial line BREAK on the console line to enter DDB (<var class="literal">options BREAK_TO_DEBUGGER</var> in the kernel config file). It is not the
default since there are a lot of serial adapters around that gratuitously generate a
BREAK condition, for example when pulling the cable.</p>

<p>The third way is that any panic condition will branch to DDB if the kernel is
configured to use it. For this reason, it is not wise to configure a kernel with DDB for
a machine running unattended.</p>

<p>The DDB commands roughly resemble some <tt class="command">gdb</tt> commands. The
first thing you probably need to do is to set a breakpoint:</p>

<pre class="screen"><kbd class="userinput">b function-name</kbd>
<kbd class="userinput">b address</kbd>
</pre>

<p>Numbers are taken hexadecimal by default, but to make them distinct from symbol names;
hexadecimal numbers starting with the letters <var class="literal">a-f</var> need to be
preceded with <var class="literal">0x</var> (this is optional for other numbers). Simple
expressions are allowed, for example: <var class="literal">function-name +
0x103</var>.</p>

<p>To continue the operation of an interrupted kernel, simply type:</p>

<pre class="screen"><kbd class="userinput">c</kbd>
</pre>

<p>To get a stack trace, use:</p>

<pre class="screen"><kbd class="userinput">trace</kbd>
</pre>


<blockquote class="note">
<p><b>Note:</b> Note that when entering DDB via a hot-key, the kernel is currently
servicing an interrupt, so the stack trace might be not of much use to you.</p>
</blockquote>


<p>If you want to remove a breakpoint, use</p>

<pre class="screen"><kbd class="userinput">del</kbd>
<kbd class="userinput">del address-expression</kbd>
</pre>

<p>The first form will be accepted immediately after a breakpoint hit, and deletes the
current breakpoint. The second form can remove any breakpoint, but you need to specify
the exact address; this can be obtained from:</p>

<pre class="screen"><kbd class="userinput">show b</kbd>
</pre>

<p>To single-step the kernel, try:</p>

<pre class="screen"><kbd class="userinput">s</kbd>
</pre>

<p>This will step into functions, but you can make DDB trace them until the matching
return statement is reached by:</p>

<pre class="screen"><kbd class="userinput">n</kbd>
</pre>


<blockquote class="note">
<p><b>Note:</b> This is different from <tt class="command">gdb</tt>'s <tt class="command">next</tt> statement; it is like <tt class="command">gdb</tt>'s <tt class="command">finish</tt>.</p>
</blockquote>


<p>To examine data from memory, use (for example):</p>

<pre class="screen"><kbd class="userinput">x/wx 0xf0133fe0,40</kbd>
<kbd class="userinput">x/hd db_symtab_space</kbd>
<kbd class="userinput">x/bc termbuf,10</kbd>
<kbd class="userinput">x/s stringbuf</kbd>
</pre>

for word/halfword/byte access, and hexadecimal/decimal/character/ string display. The
number after the comma is the object count. To display the next 0x10 items, simply
use:<br />
<br />
<pre class="screen"><kbd class="userinput">x ,10</kbd>
</pre>

<p>Similarly, use</p>

<pre class="screen"><kbd class="userinput">x/ia foofunc,10</kbd>
</pre>

to disassemble the first 0x10 instructions of <code class="function">foofunc</code>, and
display them along with their offset from the beginning of <code class="function">foofunc</code>.<br />
<br />
<p>To modify memory, use the write command:</p>

<pre class="screen"><kbd class="userinput">w/b termbuf 0xa 0xb 0</kbd>
<kbd class="userinput">w/w 0xf0010030 0 0</kbd>
</pre>

<p>The command modifier (<var class="literal">b</var>/<var class="literal">h</var>/<var class="literal">w</var>) specifies the size of the data to be written, the first
following expression is the address to write to and the remainder is interpreted as data
to write to successive memory locations.</p>

<p>If you need to know the current registers, use:</p>

<pre class="screen"><kbd class="userinput">show reg</kbd>
</pre>

<p>Alternatively, you can display a single register value by e.g.</p>

<pre class="screen"><kbd class="userinput">p $eax</kbd>
</pre>

and modify it by:<br />
<br />
<pre class="screen"><kbd class="userinput">set $eax new-value</kbd>
</pre>

<p>Should you need to call some kernel functions from DDB, simply say:</p>

<pre class="screen"><kbd class="userinput">call func(arg1, arg2, ...)</kbd>
</pre>

<p>The return value will be printed.</p>

<p>For a <a href="http://www.freebsd.org/cgi/man.cgi?query=ps&#38;sektion=1"><span class="citerefentry"><span class="refentrytitle">ps</span>(1)</span></a> style summary of
all running processes, use:</p>

<pre class="screen"><kbd class="userinput">ps</kbd>
</pre>

<p>Now you have examined why your kernel failed, and you wish to reboot. Remember that,
depending on the severity of previous malfunctioning, not all parts of the kernel might
still be working as expected. Perform one of the following actions to shut down and
reboot your system:</p>

<pre class="screen"><kbd class="userinput">panic</kbd>
</pre>

<p>This will cause your kernel to dump core and reboot, so you can later analyze the core
on a higher level with <tt class="command">gdb</tt>. This command usually must be
followed by another <tt class="command">continue</tt> statement.</p>

<pre class="screen"><kbd class="userinput">call boot(0)</kbd>
</pre>

<p>Which might be a good way to cleanly shut down the running system, <code class="function">sync()</code> all disks, and finally reboot. As long as the disk and
filesystem interfaces of the kernel are not damaged, this might be a good way for an
almost clean shutdown.</p>

<pre class="screen"><kbd class="userinput">call cpu_reset()</kbd>
</pre>

<p>This is the final way out of disaster and almost the same as hitting the Big Red
Button.</p>

<p>If you need a short command summary, simply type:</p>

<pre class="screen"><kbd class="userinput">help</kbd>
</pre>

<p>However, it is highly recommended to have a printed copy of the <a href="http://www.freebsd.org/cgi/man.cgi?query=ddb&#38;sektion=4"><span class="citerefentry"><span class="refentrytitle">ddb</span>(4)</span></a> manual page
ready for a debugging session. Remember that it is hard to read the on-line manual while
single-stepping the kernel.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="11.6 On-Line Kernel Debugging Using Remote GDB" id="KERNELDEBUG-ONLINE-GDB">
		<div class="sect2">
			<h2 class="title">11.6
On-Line Kernel Debugging Using Remote GDB</h2>

<p>This feature has been supported since FreeBSD 2.2, and it is actually a very neat
one.</p>

<p>GDB has already supported <span class="emphasis"><i class="emphasis">remote
debugging</i></span> for a long time. This is done using a very simple protocol along a
serial line. Unlike the other methods described above, you will need two machines for
doing this. One is the host providing the debugging environment, including all the
sources, and a copy of the kernel binary with all the symbols in it, and the other one is
the target machine that simply runs a similar copy of the very same kernel (but stripped
of the debugging information).</p>

<p>You should configure the kernel in question with <tt class="command">config -g</tt>,
include <var class="option">DDB</var> into the configuration, and compile it as usual.
This gives a large binary, due to the debugging information. Copy this kernel to the
target machine, strip the debugging symbols off with <tt class="command">strip -x</tt>,
and boot it using the <var class="option">-d</var> boot option. Connect the serial line
of the target machine that has "flags 080" set on its sio device to any serial line of
the debugging host. Now, on the debugging machine, go to the compile directory of the
target kernel, and start <tt class="command">gdb</tt>:</p>

<pre class="screen"><samp class="prompt">%</samp> <kbd class="userinput">gdb -k kernel</kbd>
GDB is free software and you are welcome to distribute copies of it
 under certain conditions; type "show copying" to see the conditions.
There is absolutely no warranty for GDB; type "show warranty" for details.
GDB 4.16 (i386-unknown-freebsd),
Copyright 1996 Free Software Foundation, Inc...
<samp class="prompt">(kgdb)</samp>
</pre>

<p>Initialize the remote debugging session (assuming the first serial port is being used)
by:</p>

<pre class="screen"><samp class="prompt">(kgdb)</samp> <kbd class="userinput">target remote /dev/cuaa0</kbd>
</pre>

<p>Now, on the target host (the one that entered DDB right before even starting the
device probe), type:</p>

<pre class="screen">Debugger("Boot flags requested debugger")
Stopped at Debugger+0x35: movb  $0, edata+0x51bc
<samp class="prompt">db&#62;</samp> <kbd class="userinput">gdb</kbd>
</pre>

<p>DDB will respond with:</p>

<pre class="screen">Next trap will enter GDB remote protocol mode
</pre>

<p>Every time you type <tt class="command">gdb</tt>, the mode will be toggled between
remote GDB and local DDB. In order to force a next trap immediately, simply type <tt class="command">s</tt> (step). Your hosting GDB will now gain control over the target
kernel:</p>

<pre class="screen">Remote debugging using /dev/cuaa0
Debugger (msg=0xf01b0383 "Boot flags requested debugger")
    at ../../i386/i386/db_interface.c:257
<samp class="prompt">(kgdb)</samp>
</pre>

<p>You can use this session almost as any other GDB session, including full access to the
source, running it in gud-mode inside an Emacs window (which gives you an automatic
source code display in another Emacs window), etc.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="11.7 Debugging Loadable Modules Using GDB" id="KERNELDEBUG-KLD">
		<div class="sect2">
			<h2 class="title">11.7 Debugging Loadable
Modules Using GDB</h2>

<p>When debugging a panic that occurred within a module, or using remote GDB against a
machine that uses dynamic modules, you need to tell GDB how to obtain symbol information
for those modules.</p>

<p>First, you need to build the module(s) with debugging information:</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">cd /sys/modules/linux</kbd>
<samp class="prompt">#</samp> <kbd class="userinput">make clean; make COPTS=-g</kbd>
</pre>

<p>If you are using remote GDB, you can run <tt class="command">kldstat</tt> on the
target machine to find out where the module was loaded:</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">kldstat</kbd>
Id Refs Address    Size     Name
 1    4 0xc0100000 1c1678   kernel
 2    1 0xc0a9e000 6000     linprocfs.ko
 3    1 0xc0ad7000 2000     warp_saver.ko
 4    1 0xc0adc000 11000    linux.ko
</pre>

<p>If you are debugging a crash dump, you will need to walk the <var class="literal">linker_files</var> list, starting at <var class="literal">linker_files-&#62;tqh_first</var> and following the <var class="literal">link.tqe_next</var> pointers until you find the entry with the <var class="literal">filename</var> you are looking for. The <var class="literal">address</var> member of that entry is the load address of the module.</p>

<p>Next, you need to find out the offset of the text section within the module:</p>

<pre class="screen"><samp class="prompt">#</samp> <kbd class="userinput">objdump --section-headers /sys/modules/linux/linux.ko | grep text</kbd>
  3 .rel.text     000016e0  000038e0  000038e0  000038e0  2**2
 10 .text         00007f34  000062d0  000062d0  000062d0  2**2
</pre>

<p>The one you want is the <var class="literal">.text</var> section, section 10 in the
above example. The fourth hexadecimal field (sixth field overall) is the offset of the
text section within the file. Add this offset to the load address of the module to obtain
the relocation address for the module's code. In our example, we get 0xc0adc000 + 0x62d0
= 0xc0ae22d0. Use the <tt class="command">add-symbol-file</tt> command in GDB to tell the
debugger about the module:</p>

<pre class="screen"><samp class="prompt">(kgdb)</samp> <kbd class="userinput">add-symbol-file /sys/modules/linux/linux.ko 0xc0ae22d0</kbd>
add symbol table from file "/sys/modules/linux/linux.ko" at text_addr = 0xc0ae22d0?
(y or n) <kbd class="userinput">y</kbd>
Reading symbols from /sys/modules/linux/linux.ko...done.
<samp class="prompt">(kgdb)</samp>
</pre>

<p>You should now have access to all the symbols in the module.</p>



<hr />

		</div>
	</pkg:outlineMarker>

	<pkg:outlineMarker OutlineName="11.8 Debugging a Console Driver" id="KERNELDEBUG-CONSOLE">
		<div class="sect2">
			<h2 class="title">11.8 Debugging a
Console Driver</h2>

<p>Since you need a console driver to run DDB on, things are more complicated if the
console driver itself is failing. You might remember the use of a serial console (either
with modified boot blocks, or by specifying <var class="option">-h</var> at the <samp class="prompt">Boot:</samp> prompt), and hook up a standard terminal onto your first
serial port. DDB works on any configured console driver, including a serial console.</p>




<hr />

	</div>
</pkg:outlineMarker>


		</div>
	</pkg:outlineMarker>
<pkg:outlineMarker OutlineName="Chapter 12 * UFS" id="UFS">
	<div class="sect1">
		<h1 class="title">Chapter 12 * UFS</h1>

<p>UFS, FFS, Ext2FS, JFS, inodes, buffer cache, labeling, locking, metadata,
soft-updates, LFS, portalfs, procfs, vnodes, memory sharing, memory objects, TLBs,
caching</p>



<hr />

	</div>
</pkg:outlineMarker>

<pkg:outlineMarker OutlineName="Chapter 13 * AFS" id="AFS">
	<div class="sect1">
		<h1 class="title">Chapter 13 * AFS</h1>

<p>AFS, NFS, SANs, etc.</p>



<hr />

	</div>
</pkg:outlineMarker>

<pkg:outlineMarker OutlineName="Chapter 14 * Syscons" id="SYSCONS">
	<div class="sect1">
		<h1 class="title">Chapter 14 * Syscons</h1>

<p>Syscons, tty, PCVT, serial console, screen savers, etc.</p>



<hr />

	</div>
</pkg:outlineMarker>

<pkg:outlineMarker OutlineName="Chapter 15 * Compatibility Layers" id="COMPATIBILITY">
	<div class="sect1">
		<h1 class="title">Chapter 15 * Compatibility Layers</h1>



	<pkg:outlineMarker OutlineName="15.1 * Linux" id="LINUX">
		<div class="sect2">
			<h2 class="title">15.1 * Linux</h2>

<p>Linux, SVR4, etc.</p>





				<div align="right"><img align="right" src="bsd_sm.png"  /></div>
		</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">&#60;<a href="mailto:adam@redprince.net">adam@redprince.net</a>&#62;</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&#38;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&#38;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&#38;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>&#160;<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 &#62; (do not copy the &#62; 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
&#62;   cmp al, 0Ah
&#62;   jne .loop
&#62;   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  '&#60;?xml version="1.0" encoding="UTF-8"?&#62;', 0Ah
    db  '&#60;!DOCTYPE html PUBLIC "-//W3C/DTD XHTML Strict//EN" '
    db  '"DTD/xhtml1-strict.dtd"&#62;', 0Ah
    db  '&#60;html xmlns="http://www.w3.org/1999/xhtml" '
    db  'xml.lang="en" lang="en"&#62;', 0Ah
    db  '&#60;head&#62;', 0Ah
    db  '&#60;title&#62;Web Environment&#60;/title&#62;', 0Ah
    db  '&#60;meta name="author" content="G. Adam Stanislav" /&#62;', 0Ah
    db  '&#60;/head&#62;', 0Ah, 0Ah
    db  '&#60;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"&#62;', 0Ah
    db  '&#60;div class="webvars"&#62;', 0Ah
    db  '&#60;h1&#62;Web Environment&#60;/h1&#62;', 0Ah
    db  '&#60;p&#62;The following &#60;b&#62;environment variables&#60;/b&#62; are defined '
    db  'on this web server:&#60;/p&#62;', 0Ah, 0Ah
    db  '&#60;table align="center" width="80" border="0" cellpadding="10" '
    db  'cellspacing="0" class="webvars"&#62;', 0Ah
httplen equ $-http
left    db  '&#60;tr&#62;', 0Ah
    db  '&#60;td class="name"&#62;&#60;tt&#62;'
leftlen equ $-left
middle  db  '&#60;/tt&#62;&#60;/td&#62;', 0Ah
    db  '&#60;td class="value"&#62;&#60;tt&#62;&#60;b&#62;'
midlen  equ $-middle
undef   db  '&#60;i&#62;(undefined)&#60;/i&#62;'
undeflen    equ $-undef
right   db  '&#60;/b&#62;&#60;/tt&#62;&#60;/td&#62;', 0Ah
    db  '&#60;/tr&#62;', 0Ah
rightlen    equ $-right
wrap    db  '&#60;/table&#62;', 0Ah
    db  '&#60;/div&#62;', 0Ah
    db  '&#60;/body&#62;', 0Ah
    db  '&#60;/html&#62;', 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&#38;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&#38;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&#60;delim&#62;] [-c&#60;comma&#62;] [-p] [-o &#60;outfile&#62;] [-i &#60;infile&#62;]
</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&#60;delim&#62;] [-c&#60;comma&#62;] [-p] [-o &#60;outfile&#62;] [-i &#60;infile&#62;]', 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, (',' &#60;&#60; 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 &#60;&#60; 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 &#38; 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 &#60;value&#62;] [-o &#60;outfile&#62;] [-i &#60;infile&#62;]', 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 &#62; 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 &#62; 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>
<pkg:outlineMarker OutlineName="Chapter 17 * Alpha" id="ALPHA">
	<div class="sect1">
		<h1 class="title">Chapter 17 * Alpha</h1>

<p>Explanation of alignment errors, how to fix, how to ignore.</p>

<p>Example assembly language code for FreeBSD/alpha.</p>




				<div align="right"><img align="right" src="bsd_sm.png"  /></div>
		</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]&#160;<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]&#160;<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]&#160;<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]&#160;<span class="author">Aleph One</span>, <i>Phrack 49; "Smashing the Stack for
Fun and Profit"</i>.</p>


<a name="STACKGUARD"></a>
<p>[5]&#160;<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]&#160;<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 &#60;<a href="mailto:questions@FreeBSD.org">questions@FreeBSD.org</a>&#62;.<br />
For questions about this documentation, e-mail &#60;<a href="mailto:doc@FreeBSD.org">doc@FreeBSD.org</a>&#62;.</small></p>

				<div align="right"><img align="right" src="bsd_sm.png"  /></div>
		</div>
</pkg:outlineMarker>


	</div>
</pkg:outlineMarker>
</pkg:outlineMarker>
		
	</pkg:content>
</pkg:package>