diff --git a/documentation/content/de/articles/x86-assembly/_index.adoc b/documentation/content/de/articles/x86-assembly/_index.adoc index 0a3aa3831a..da56b90f38 100644 --- a/documentation/content/de/articles/x86-assembly/_index.adoc +++ b/documentation/content/de/articles/x86-assembly/_index.adoc @@ -1,3889 +1,3889 @@ --- title: x86-Assembler-Programmierung authors: - author: Adam Stanislav email: adam@redprince.net description: A tutorial on writing programs for FreeBSD in x86 assembly language -tags: ["x86", "assembly", "programming", "guide"] +tags: ["assembly", "guide", "ia32", "ld", "llvm-as", "nasm", "programming", "x86"] --- = x86-Assembler-Programmierung :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] _Dieses Kapitel wurde geschrieben von {stanislav}._ [[x86-intro]] == Synopsis Assembler-Programmierung unter UNIX(R) ist höchst undokumentiert. Es wird allgemein angenommen, dass niemand sie jemals benutzen will, da UNIX(R)-Systeme auf verschiedenen Mikroprozessoren laufen, und man deshalb aus Gründen der Portabilität alles in C schreiben sollte. In Wirklichkeit ist die Portabilität von C größtenteils ein Mythos. Auch C-Programme müssen angepasst werden, wenn man sie von einem UNIX(R) auf ein anderes portiert, egal auf welchem Prozessor jedes davon läuft. Typischerweise ist ein solches Programm voller Bedingungen, die unterscheiden für welches System es kompiliert wird. Sogar wenn wir glauben, dass jede UNIX(R)-Software in C, oder einer anderen High-Level-Sprache geschrieben werden sollte, brauchen wir dennoch Assembler-Programmierer: Wer sonst sollte den Abschnitt der C-Bibliothek schreiben, die auf den Kernel zugreift? In diesem Kapitel möchte ich versuchen zu zeigen, wie man Assembler-Sprache verwenden kann, um UNIX(R)-Programme, besonders unter FreeBSD, zu schreiben. Dieses Kapitel erklärt nicht die Grundlagen der Assembler-Sprache. Zu diesem Thema gibt es bereits genug Quellen (einen vollständigen Online-Kurs finden Sie in Randall Hydes http://webster.cs.ucr.edu/[Art of Assembly Language]; oder falls Sie ein gedrucktes Buch bevorzugen, können Sie einen Blick auf Jeff Duntemanns http://www.int80h.org/cgi-bin/isbn?isbn=0471375233[Assembly Language Step-by-Step] werfen). Jedenfalls sollte jeder Assembler-Programmierer nach diesem Kapitel schnell und effizient Programme für FreeBSD schreiben können. Copyright (R) 2000-2001 G. Adam Stanislav. All rights reserved. [[x86-the-tools]] == Die Werkzeuge [[x86-the-assembler]] === Der Assembler Das wichtigste Werkzeug der Assembler-Programmierung ist der Assembler, diese Software übersetzt Assembler-Sprache in Maschinencode. Für FreeBSD stehen zwei verschiedene Assembler zur Verfügung. Der erste ist man:as[1], der die traditionelle UNIX(R)-Assembler-Sprache verwendet. Dieser ist Teil des Systems. Der andere ist /usr/ports/devel/nasm. Dieser benutzt die Intel-Syntax und sein Vorteil ist, dass es Code fü viele Vetriebssysteme übersetzen kann. Er muss gesondert installiert werden, aber ist völlig frei. In diesem Kapitel wird die nasm-Syntax verwendet. Einerseits weil es die meisten Assembler-Programmierer, die von anderen Systemen zu FreeBSD kommen, leichter verstehen werden. Und offen gesagt, weil es das ist, was ich gewohnt bin. [[x86-the-linker]] === Der Linker Die Ausgabe des Assemblers muss, genau wie der Code jedes Compilers, gebunden werden, um eine ausführbare Datei zu bilden. Der Linker man:ld[1] ist der Standard und Teil von FreeBSD. Er funktioniert mit dem Code beider Assembler. [[x86-system-calls]] == Systemaufrufe [[x86-default-calling-convention]] === Standard-Aufrufkonvention Standardmäßig benutzt der FreeBSD-Kernel die C-Aufrufkonvention. Weiterhin wird, obwohl auf den Kernel durch `int 80h` zugegriffen wird, angenommen, dass das Programm eine Funktion aufruft, die `int 80h` verwendet, anstatt `int 80h` direkt aufzurufen. Diese Konvention ist sehr praktisch und der Microsoft(R)-Konvention von MS-DOS(R) überlegen. Warum? Weil es die UNIX(R)-Konvention jedem Programm, egal in welcher Sprache es geschrieben ist, erlaubt auf den Kernel zuzugreifen. Ein Assembler-Programm kann das ebenfalls. Beispielsweise könnten wir eine Datei öffnen: [.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 .... Das ist ein sehr sauberer und portabler Programmierstil. Wenn Sie das Programm auf ein anderes UNIX(R) portieren, das einen anderen Interrupt oder eie andere Art der Parameterübergabe verwendet, müssen sie nur die Prozedur kernel ändern. Aber Assembler-Programmierer lieben es Taktzyklen zu schinden. Das obige Beispiel benötigt eine `call/ret`-Kombination. Das können wir entfernen, indem wir einen weiteren Parameter mit `push` übergeben: [.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 .... Die Konstante [constant]#5#, die wir in `EAX` ablegen, identifiziert die Kernel-Funktion, die wir aufrufen. In diesem Fall ist das `open`. [[x86-alternate-calling-convention]] === Alternative Aufruf-Konvention FreeBSD ist ein extrem flexibles System. Es bietet noch andere Wege, um den Kernel aufzurufen. Damit diese funktionieren muss allerdings die Linux-Emulation installiert sein. Linux ist ein UNIX(R)-artiges System. Allerdings verwendet dessen Kernel die gleiche Systemaufruf-Konvention, bei der Parameter in Registern abgelegt werden, wie MS-DOS(R). Genau wie bei der UNIX(R)-Konvention wird die Nummer der Funktion in `EAX` abgelegt. Allerdings werden die Parameter nicht auf den Stack gelegt, sondern in die Register `EBX, ECX, EDX, ESI, EDI, EBP`: [.programlisting] .... open: mov eax, 5 mov ebx, path mov ecx, flags mov edx, mode int 80h .... Diese Konvention hat einen großen Nachteil gegenüber der von UNIX(R), was die Assembler-Programmierung angeht: Jedesmal, wenn Sie einen Kernel-Aufruf machen, müssen Sie die Register ``push``en und sie später ``pop``en. Das macht Ihren Code unförmiger und langsamer. Dennoch lässt FreeBSD ihnen die Wahl. Wenn Sie sich für die Linux-Konvention entscheiden, müssen Sie es das System wissen lassen. Nachdem ihr Programm übersetzt und gebunden wurde, müssen Sie die ausführbare Datei kennzeichnen: [source,shell] .... % brandelf -t Linux filename .... [[x86-use-geneva]] === Welche Konvention Sie verwenden sollten Wenn Sie speziell für FreeBSD programmieren, sollten Sie die UNIX(R)-Konvention verwenden: Diese ist schneller, Sie können globale Variablen in Registern ablegen, Sie müssen die ausführbare Datei nicht kennzeichnen und Sie erzwingen nicht die Installation der Linux-Emulation auf dem Zielsystem. Wenn Sie portablen Programmcode erzeugen wollen, der auch unter Linux funktioniert, wollen Sie den FreeBSD-Nutzern vielleicht dennoch den effizientesten Programmcode bieten, der möglich ist. Ich werde Ihnen zeigen, wie Sie das erreichen können, nachdem ich die Grundlagen erklärt habe. [[x86-call-numbers]] === Aufruf-Nummern Um dem Kernel mitzuteilen welchen Dienst Sie aufrufen, legen Sie dessen Nummer in `EAX` ab. Natürlich müssen Sie dazu wissen welche Nummer die Richtige ist. [[x86-the-syscalls-file]] ==== Die Datei [.filename]#syscalls# Die Nummer der Funktionen sind in der Datei [.filename]#syscalls# aufgeführt. Mittels `locate syscalls` finden Sie diese in verschiedenen Formaten, die alle auf die gleiche Weise aus [.filename]#syscalls.master# erzeugt werden. Die Master-Datei für die UNIX(R)-Standard-Aufrufkonvention finden sie unter [.filename]#/usr/src/sys/kern/syscalls.master#. Falls Sie die andere Konvention, die im Linux-Emulations-Modus implementiert ist, verwenden möchten, lesen Sie bitte [.filename]#/usr/src/sys/i386/linux/syscalls.master#. [NOTE] ==== FreeBSD und Linux unterscheiden sich nicht nur in den Aufrufkonventionen, sie haben teilweise auch verschiedene Nummern für die gleiche Funktion. ==== [.filename]#syscalls.master# beschreibt, wie der Aufruf gemacht werden muss: [.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... .... In der ersten Spalte steht die Nummer, die in `EAX` abgelegt werden muss. Die Spalte ganz rechts sagt uns welche Parameter wir ``push``en müssen. Die Reihenfolge ist dabei _von rechts nach links_. [example] ==== Um beispielsweise eine Datei mittels `open` zu öffnen, müssen wir zuerst den `mode` auf den Stack ``push``en, danach die `flags`, dann die Adresse an der der `path` gespeichert ist. ==== [[x86-return-values]] == Rückgabewerte Ein Systemaufruf wäre meistens nicht sehr nützlich, wenn er nicht irgendeinen Wert zurückgibt: Beispielsweise den Dateideskriptor einer geöffneten Datei, die Anzahl an Bytes die in einen Puffer gelesen wurde, die Systemzeit, etc. Außerdem muss Sie das System informieren, falls ein Fehler auftritt: Wenn eine Datei nicht existiert, die Systemressourcen erschöpft sind, wir ein ungültiges Argument übergeben haben, etc. [[x86-man-pages]] === Manualpages Der herkömmliche Ort, um nach Informationen über verschiedene Systemaufrufe unter UNIX(R)-Systemen zu suchen, sind die Manualpages. FreeBSD beschreibt seine Systemaufrufe in Abschnitt 2, manchmal auch Abschnitt 3. In man:open[2] steht beispielsweise: [.blockquote] Falls erfolgreich, gibt `open()` einen nicht negativen Integerwert, als Dateideskriptor bezeichnet, zurück. Es gibt `-1` im Fehlerfall zurück und setzt `errno` um den Fehler anzuzeigen. Ein Assembler-Programmierer, der neu bei UNIX(R) und FreeBSD ist, wird sich sofort fragen: Wo finde ich `errno` und wie erreiche ich es? [NOTE] ==== Die Information der Manualpage bezieht sich auf C-Programme. Der Assembler-Programmierer benötigt zusätzliche Informationen. ==== [[x86-where-return-values]] === Wo sind die Rückgabewerde? Leider gilt: Es kommt darauf an... Für die meisten Systemaufrufe liegt er in `EAX`, aber nicht für alle. Eine gute Daumenregel, wenn man zum ersten Mal mit einem Systemaufruf arbeitet, ist in `EAX` nach dem Rückgabewert zu suchen. Wenn er nicht dort ist, sind weitere Untersuchungen nötig. [NOTE] ==== Mir ist ein Systemaufruf bekannt, der den Rückgabewert in `EDX` ablegt: `SYS_fork` Alle anderen mit denen ich bisher gearbeitet habe verwenden `EAX`. Allerdings habe ich noch nicht mit allen gearbeitet. ==== [TIP] ==== Wenn Sie die Antwort weder hier, noch irgendwo anders finden, studieren Sie den Quelltext von libc und sehen sich an, wie es mit dem Kernel zusammenarbeitet. ==== [[x86-where-errno]] === Wo ist `errno`? Tatsächlich, nirgendwo... `errno` ist ein Teil der Sprache C, nicht des UNIX(R)-Kernels. Wenn man direkt auf Kernel-Dienste zugreift, wird der Fehlercode in `EAX` zurückgegeben, das selbe Register in dem der Rückgabewert, bei einem erfolgreichen Aufruf landet. Das macht auch Sinn. Wenn kein Fehler auftritt, gibt es keinen Fehlercode. Wenn ein Fehler auftritt, gibt es keinen Rückgabewert. Ein einziges Register kann also beides enthalten. [[x86-how-to-know-error]] === Feststellen, dass ein Fehler aufgetreten ist Wenn Sie die Standard FreeBSD-Aufrufkonvention verwenden wird das `carry flag` gelöscht wenn der Aufruf erfolgreich ist und gesetzt wenn ein Fehler auftritt. Wenn Sie den Linux-Emulationsmodus verwenden ist der vorzeichenbehaftete Wert in `EAX` nicht negativ, bei einem erfolgreichen Aufruf. Wenn ein Fehler auftritt ist der Wert negativ, also `-errno`. [[x86-portable-code]] == Portablen Code erzeugen Portabilität ist im Allgemeinen keine Stärke der Assembler-Programmierung. Dennoch ist es, besonders mit nasm, möglich Assembler-Programme für verschiedene Plattformen zu schreiben. Ich selbst habe bereits Assembler-Bibliotheken geschrieben die auf so unterschiedlichen Systemen wie Windows(R) und FreeBSD übersetzt werden können. Das ist um so besser möglich, wenn Ihr Code auf zwei Plattformen laufen soll , die, obwohl sie verschieden sind, auf ähnlichen Architekturen basieren. Beispielsweise ist FreeBSD ein UNIX(R), während Linux UNIX(R)-artig ist. Ich habe bisher nur drei Unterschiede zwischen beiden (aus Sicht eines Assembler-Programmierers) erwähnt: Die Aufruf-Konvention, die Funktionsnummern und die Art der Übergabe von Rückgabewerten. [[x86-deal-with-function-numbers]] === Mit Funktionsnummern umgehen In vielen Fällen sind die Funktionsnummern die selben. Allerdings kann man auch wenn sie es nicht sind leicht mit diesem Problem umgehen: Anstatt die Nummern in Ihrem Code zu verwenden, benutzen Sie Konstanten, die Sie abhängig von der Zielarchitektur unterschiedlich definieren: [.programlisting] .... %ifdef LINUX %define SYS_execve 11 %else %define SYS_execve 59 %endif .... [[x86-deal-with-geneva]] === Umgang mit Konventionen Sowohl die Aufrufkonvention, als auch die Rückgabewerte (das `errno` Problem) kann man mit Hilfe von Makros lösen: [.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 .... [[x86-deal-with-other-portability]] === Umgang mit anderen Portabilitätsangelegenheiten Die oben genannte Lösung funktioniert in den meisten Fällen, wenn man Code schreibt, der zwischen FreeBSD und Linux portierbar sein soll. Allerdings sind die Unterschiede bei einigen Kernel-Diensten tiefgreifender. In diesem Fällen müssen Sie zwei verschiedene Handler für diese Systemaufrufe schreiben und bedingte Assemblierung benutzen, um diese zu übersetzen. Glücklicherweise wird der größte Teil Ihres Codes nicht den Kernel aufrufen und Sie werden deshalb nur wenige solcher bedingten Abschnitte benötigen. [[x86-portable-library]] === Eine Bibliothek benutzen Sie können Portabilitätsprobleme im Hauptteil ihres Codes komplett vermeiden, indem Sie eine Bibliothek für Systemaufrufe schreiben. Erstellen Sie eine Bibliothek für FreeBSD, eine für Linux und weitere für andere Betriebssysteme. Schreiben Sie in ihrer Bibliothek eine gesonderte Funktion (oder Prozedur, falls Sie die traditionelle Assembler-Terminologie bevorzugen) für jeden Systemaufruf. Verwenden Sie dabei die C-Aufrufkonvention um Parameter zu übergeben, aber verwenden Sie weiterhin `EAX`, für die Aufrufnummer. In diesem Fall kann ihre FreeBSD-Bibliothek sehr einfach sein, da viele scheinbar unterschiedliche Funktionen als Label für denselben Code implementiert sein können: [.programlisting] .... sys.open: sys.close: [etc...] int 80h ret .... Ihre Linux-Bibliothek wird mehr verschiedene Funktionen benötigen, aber auch hier können Sie Systemaufrufe, welche die Anzahl an Parametern akzeptieren zusammenfassen: [.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 .... Der Bibliotheks-Ansatz mag auf den ersten Blick unbequem aussehen, weil Sie eine weitere Datei erzeugen müssen von der Ihr Code abhängt. Aber er hat viele Vorteile: Zum einen müssen Sie die Bibliothek nur einmal schreiben und können sie dann in allen Ihren Programmen verwenden. Sie können sie sogar von anderen Assembler-Programmierern verwenden lassen, oder eine die von jemand anderem geschrieben wurde verwenden. Aber der vielleicht größte Vorteil ist, dass Ihr Code sogar von anderen Programmierer auf andere Systeme portiert werden kann, einfach indem man eine neue Bibliothek schreibt, völlig ohne Änderungen an Ihrem Code. Falls Ihnen der Gedanke eine Bibliothek zu nutzen nicht gefällt, können Sie zumindest all ihre Systemaufrufe in einer gesonderten Assembler-Datei ablegen und diese mit Ihrem Hauptprogramm zusammen binden. Auch hier müssen alle, die ihr Programm portieren, nur eine neue Objekt-Datei erzeugen und an Ihr Hauptprogramm binden. [[x86-portable-include]] === Eine Include-Datei verwenden Wenn Sie ihre Software als (oder mit dem) Quelltext ausliefern, können Sie Makros definieren und in einer getrennten Datei ablegen, die Sie ihrem Code beilegen. Porter Ihrer Software schreiben dann einfach eine neue Include-Datei. Es ist keine Bibliothek oder eine externe Objekt-Datei nötig und Ihr Code ist portabel, ohne dass man ihn editieren muss. [NOTE] ==== Das ist der Ansatz den wir in diesem Kapitel verwenden werden. Wir werden unsere Include-Datei [.filename]#system.inc# nennen und jedesmal, wenn wir einen neuen Systemaufruf verwenden, den entsprechenden Code dort einfügen. ==== Wir können unsere [.filename]#system.inc# beginnen indem wir die Standard-Dateideskriptoren deklarieren: [.programlisting] .... %define stdin 0 %define stdout 1 %define stderr 2 .... Als Nächstes erzeugen wir einen symbolischen Namen für jeden Systemaufruf: [.programlisting] .... %define SYS_nosys 0 %define SYS_exit 1 %define SYS_fork 2 %define SYS_read 3 %define SYS_write 4 ; [etc...] .... Wir fügen eine kleine, nicht globale Prozedur mit langem Namen ein, damit wir den Namen nicht aus Versehen in unserem Code wiederverwenden: [.programlisting] .... section .text align 4 access.the.bsd.kernel: int 80h ret .... Wir erzeugen ein Makro, das ein Argument erwartet, die Systemaufruf-Nummer: [.programlisting] .... %macro system 1 mov eax, %1 call access.the.bsd.kernel %endmacro .... Letztlich erzeugen wir Makros für jeden Systemaufruf. Diese Argumente erwarten keine Argumente. [.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...] .... Fahren Sie fort, geben das in Ihren Editor ein und speichern es als [.filename]#system.inc#. Wenn wir Systemaufrufe besprechen, werden wir noch Ergänzungen in dieser Datei vornehmen. [[x86-first-program]] == Unser erstes Programm Jetzt sind wir bereit für unser erstes Programm, das übliche Hello, World! [.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 .... Hier folgt die Erklärung des Programms: Zeile 1 fügt die Definitionen ein, die Makros und den Code aus [.filename]#system.inc#. Die Zeilen 3 bis 5 enthalten die Daten: Zeile 3 beginnt den Datenabschnitt/das Datensegment. Zeile 4 enthält die Zeichenkette "Hello, World!", gefolgt von einem Zeilenumbruch ([constant]#0Ah#). Zeile 5 erstellt eine Konstante, die die Länge der Zeichenkette aus Zeile 4 in Bytes enthält. Die Zeilen 7 bis 16 enthalten den Code. Beachten Sie bitte, dass FreeBSD das Dateiformat _elf_ für diese ausführbare Datei verwendet, bei dem jedes Programm mit dem Label `_start` beginnt (oder, um genau zu sein, wird dies vom Linker erwartet). Diese Label muss global sein. Die Zeilen 10 bis 13 weisen das System an `hbytes` Bytes der Zeichenkette `hello` nach `stdout` zu schreiben. Die Zeilen 15 und 16 weisen das System an das Programm mit dem Rückgabewert [constant]#0# zu beenden. Der Systemaufruf `SYS_exit` kehrt niemals zurück, somit endet das Programm hier. [NOTE] ==== Wenn Sie von MS-DOS(R)-Assembler zu UNIX(R) gekommen sind, sind Sie es vielleicht gewohnt direktauf die Video-Hardware zu schreiben. Unter FreeBSD müssen Sie sich darum keine Gedanken machen, ebenso bei jeder anderen Art von UNIX(R). Soweit es Sie betrifft schreiben Sie in eine Datei namens [.filename]#stdout#. Das kann der Bildschirm, oder ein telnet-Terminal, eine wirkliche Datei, oder die Eingabe eines anderen Programms sein. Es liegt beim System herauszufinden, welches davon es tatsächlich ist. ==== [[x86-assemble-1]] === Den Code assemblieren Geben Sie den Code (außer den Zeilennummern) in einen Editor ein und speichern Sie ihn in einer Datei namens [.filename]#hello.asm#. Um es zu assemblieren benötigen Sie nasm. [[x86-get-nasm]] ==== nasm installieren Wenn Sie nasm noch nicht installiert haben geben Sie folgendes ein: [source,shell] .... % su Password:your root password # cd /usr/ports/devel/nasm # make install # exit % .... Sie können auch `make install clean` anstatt `make install` eingeben, wenn Sie den Quelltext von nasm nicht behalten möchten. Auf jeden Fall wird FreeBSD nasm automatisch aus dem Internet herunterladen, es kompilieren und auf Ihrem System installieren. [NOTE] ==== Wenn es sich bei Ihrem System nicht um FreeBSD handelt, müssen Sie nasm von dessen https://sourceforge.net/projects/nasm[Homepage] herunterladen. Sie können es aber dennoch verwenden um FreeBSD code zu assemblieren. ==== Nun können Sie den Code assemblieren, binden und ausführen: [source,shell] .... % nasm -f elf hello.asm % ld -s -o hello hello.o % ./hello Hello, World! % .... [[x86-unix-filters]] == UNIX(R)-Filter schreiben Ein häufiger Typ von UNIX(R)-Anwendungen ist ein Filter - ein Programm, das Eingaben von [.filename]#stdin# liest, sie verarbeitet und das Ergebnis nach [.filename]#stdout# schreibt. In diesem Kapitel möchten wir einen einfachen Filter entwickeln und lernen, wie wir von [.filename]#stdin# lesen und nach [.filename]#stdout# schreiben. Dieser Filter soll jedes Byte seiner Eingabe in eine hexadezimale Zahl gefolgt von einem Leerzeichen umwandeln. [.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 .... Im Datenabschnitt erzeugen wir ein Array mit Namen `hex`. Es enthält die 16 hexadezimalen Ziffern in aufsteigender Reihenfolge. Diesem Array folgt ein Puffer, den wir sowohl für die Ein- als auch für die Ausgabe verwenden. Die ersten beiden Bytes dieses Puffers werden am Anfang auf [constant]#0# gesetzt. Dorthin schreiben wir die beiden hexadezimalen Ziffern (das erste Byte ist auch die Stelle an die wir die Eingabe lesen). Das dritte Byte ist ein Leerzeichen. Der Code-Abschnitt besteht aus vier Teilen: Das Byte lesen, es in eine hexadezimale Zahl umwandeln, das Ergebnis schreiben und letztendlich das Programm verlassen. Um das Byte zu lesen, bitten wir das System ein Byte von [.filename]#stdin# zu lesen und speichern es im ersten Byte von `buffer`. Das System gibt die Anzahl an Bytes, die gelesen wurden, in `EAX` zurück. Diese wird [constant]#1# sein, wenn eine Eingabe empfangen wird und [constant]#0#, wenn keine Eingabedaten mehr verfügbar sind. Deshalb überprüfen wir den Wert von `EAX`. Wenn dieser [constant]#0# ist, springen wir zu `.done`, ansonsten fahren wir fort. [NOTE] ==== Zu Gunsten der Einfachheit ignorieren wir hier die Möglichkeit eines Fehlers. ==== Die Umwandlungsroutine in eine Hexadezimalzahl liest das Byte aus `buffer` in `EAX`, oder genaugenommen nur in `AL`, wobei die übrigen Bits von `EAX` auf null gesetzt werden. Außerdem kopieren wir das Byte nach `EDX`, da wir die oberen vier Bits (Nibble) getrennt von den unteren vier Bits umwandeln müssen. Das Ergebnis speichern wir in den ersten beiden Bytes des Puffers. Als Nächstes bitten wir das System die drei Bytes in den Puffer zu schreiben, also die zwei hexadezimalen Ziffern und das Leerzeichen nach [.filename]#stdout#. Danach springen wir wieder an den Anfang des Programms und verarbeiten das nächste Byte. Wenn die gesamte Eingabe verarbeitet ist, bitten wie das System unser Programm zu beenden und null zurückzuliefern, welches traditionell die Bedeutung hat, dass unser Programm erfolgreich war. Fahren Sie fort und speichern Sie den Code in eine Datei namens [.filename]#hex.asm#. Geben Sie danach folgendes ein (`^D` bedeutet, dass Sie die Steuerungstaste drücken und dann `D` eingeben, während Sie Steuerung gedrückt halten): [source,shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come! 48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D % .... [NOTE] ==== Wenn Sie von MS-DOS(R) zu UNIX(R) wechseln, wundern Sie sich vielleicht, warum jede Zeile mit [constant]#0A# an Stelle von [constant]#0D 0A# endet. Das liegt daran, dass UNIX(R) nicht die CR/LF-Konvention, sondern die "new line"-Konvention verwendet, welches hexadezimal als [constant]#0A# dargestellt wird. ==== Können wir das Programm verbessern? Nun, einerseits ist es etwas verwirrend, dass die Eingabe, nachdem wir eine Zeile verarbeitet haben, nicht wieder am Anfang der Zeile beginnt. Deshalb können wir unser Programm anpassen um einen Zeilenumbruch an Stelle eines Leerzeichens nach jedem [constant]#0A# auszugeben: [.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 .... Wir haben das Leerzeichen im Register `CL` abgelegt. Das können wir bedenkenlos tun, da UNIX(R)-Systemaufrufe im Gegensatz zu denen von Microsoft(R) Windows(R) keine Werte von Registern ändern in denen sie keine Werte zurückliefern. Das bedeutet, dass wir `CL` nur einmal setzen müssen. Dafür haben wir ein neues Label `.loop` eingefügt, zu dem wir an Stelle von `_start` springen, um das nächste Byte einzulesen. Außerdem haben wir das Label `.hex` eingefügt, somit können wir wahlweise ein Leerzeichen oder einen Zeilenumbruch im dritten Byte von `buffer` ablegen. Nachdem Sie [.filename]#hex.asm# entsprechend der Neuerungen geändert haben, geben Sie Folgendes ein: [source,shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come! 48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D % .... Das sieht doch schon besser aus. Aber der Code ist ziemlich ineffizient! Wir führen für jeden einzelne Byte zweimal einen Systemaufruf aus (einen zum Lesen und einen um es in die Ausgabe zu schreiben). [[x86-buffered-io]] == Gepufferte Eingabe und Ausgabe Wir können die Effizienz unseres Codes erhöhen, indem wir die Ein- und Ausgabe puffern. Wir erzeugen einen Eingabepuffer und lesen dann eine Folge von Bytes auf einmal. Danach holen wir sie Byte für Byte aus dem Puffer. Wir erzeugen ebenfalls einen Ausgabepuffer. Darin speichern wir unsere Ausgabe bis er voll ist. Dann bitten wir den Kernel den Inhalt des Puffers nach [.filename]#stdout# zu schreiben. Diese Programm endet, wenn es keine weitere Eingaben gibt. Aber wir müssen den Kernel immernoch bitten den Inhalt des Ausgabepuffers ein letztes Mal nach [.filename]#stdout# zu schreiben, denn sonst würde ein Teil der Ausgabe zwar im Ausgabepuffer landen, aber niemals ausgegeben werden. Bitte vergessen Sie das nicht, sonst fragen Sie sich später warum ein Teil Ihrer Ausgabe verschwunden ist. [.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 .... Als dritten Abschnitt im Quelltext haben wir `.bss`. Dieser Abschnitt wird nicht in unsere ausführbare Datei eingebunden und kann daher nicht initialisiert werden. Wir verwenden `resb` anstelle von `db`. Dieses reserviert einfach die angeforderte Menge an uninitialisiertem Speicher zu unserer Verwendung. Wir nutzen, die Tatsache, dass das System die Register nicht verändert: Wir benutzen Register, wo wir anderenfalls globale Variablen im Abschnitt `.data` verwenden müssten. Das ist auch der Grund, warum die UNIX(R)-Konvention, Parameter auf dem Stack zu übergeben, der von Microsoft, hierfür Register zu verwenden, überlegen ist: Wir können Register für unsere eigenen Zwecke verwenden. Wir verwenden `EDI` und `ESI` als Zeiger auf das nächste zu lesende oder schreibende Byte. Wir verwenden `EBX` und `ECX`, um die Anzahl der Bytes in den beiden Puffern zu zählen, damit wir wissen, wann wir die Ausgabe an das System übergeben, oder neue Eingabe vom System entgegen nehmen müssen. Lassen Sie uns sehen, wie es funktioniert: [source,shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! Here I come! 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 ^D % .... Nicht was Sie erwartet haben? Das Programm hat die Ausgabe nicht auf dem Bildschirm ausgegeben bis sie `^D` gedrückt haben. Das kann man leicht zu beheben indem man drei Zeilen Code einfügt, welche die Ausgabe jedesmal schreiben, wenn wir einen Zeilenumbruch in [constant]#0A# umgewandelt haben. Ich habe die betreffenden Zeilen mit > markiert (kopieren Sie die > bitte nicht mit in Ihre [.filename]#hex.asm#). [.programlisting] .... %include 'system.inc' %define BUFSIZE 2048 section .data hex db '0123456789ABCDEF' section .bss ibuffer resb BUFSIZE obuffer resb BUFSIZE section .text global _start _start: sub eax, eax sub ebx, ebx sub ecx, ecx mov edi, obuffer .loop: ; read a byte from stdin call getchar ; convert it to hex mov dl, al shr al, 4 mov al, [hex+eax] call putchar mov al, dl and al, 0Fh mov al, [hex+eax] call putchar mov al, ' ' cmp dl, 0Ah jne .put mov al, dl .put: call putchar > cmp al, 0Ah > jne .loop > call write jmp short .loop align 4 getchar: or ebx, ebx jne .fetch call read .fetch: lodsb dec ebx ret read: push dword BUFSIZE mov esi, ibuffer push esi push dword stdin sys.read add esp, byte 12 mov ebx, eax or eax, eax je .done sub eax, eax ret align 4 .done: call write ; flush output buffer push dword 0 sys.exit align 4 putchar: stosb inc ecx cmp ecx, BUFSIZE je write ret align 4 write: sub edi, ecx ; start of buffer push ecx push edi push dword stdout sys.write add esp, byte 12 sub eax, eax sub ecx, ecx ; buffer is empty now ret .... Lassen Sie uns jetzt einen Blick darauf werfen, wie es funktioniert. [source,shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come! 48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D % .... Nicht schlecht für eine 644 Byte große Binärdatei, oder? [NOTE] ==== Dieser Ansatz für gepufferte Ein- und Ausgabe enthält eine Gefahr, auf die ich im Abschnitt <> eingehen werde. ==== [[x86-ungetc]] === Ein Zeichen ungelesen machen [WARNING] ==== Das ist vielleicht ein etwas fortgeschrittenes Thema, das vor allem für Programmierer interessant ist, die mit der Theorie von Compilern vertraut sind. Wenn Sie wollen, können Sie <> und das hier vielleicht später lesen. ==== Unser Beispielprogramm benötigt es zwar nicht, aber etwas anspruchsvollere Filter müssen häufig vorausschauen. Mit anderen Worten, sie müssen wissen was das nächste Zeichen ist (oder sogar mehrere Zeichen). Wenn das nächste Zeichen einen bestimmten Wert hat, ist es Teil des aktuellen Tokens, ansonsten nicht. Zum Beispiel könnten Sie den Eingabestrom für eine Text-Zeichenfolge parsen (z.B. wenn Sie einen Compiler einer Sprache implementieren): Wenn einem Buchstaben ein anderer Buchstabe oder vielleicht eine Ziffer folgt, ist er ein Teil des Tokens, das Sie verarbeiten. Wenn ihm ein Leerzeichen folgt, oder ein anderer Wert, ist er nicht Teil des aktuellen Tokens. Das führt uns zu einem interessanten Problem: Wie kann man ein Zeichen zurück in den Eingabestrom geben, damit es später noch einmal gelesen werden kann? Eine mögliche Lösung ist, das Zeichen in einer Variable zu speichern und ein Flag zu setzen. Wir können `getchar` so anpassen, dass es das Flag überprüft und, wenn es gesetzt ist, das Byte aus der Variable anstatt dem Eingabepuffer liest und das Flag zurück setzt. Aber natürlich macht uns das langsamer. Die Sprache C hat eine Funktion `ungetc()` für genau diesen Zweck. Gibt es einen schnellen Weg, diese in unserem Code zu implementieren? Ich möchte Sie bitten nach oben zu scrollen und sich die Prozedur `getchar` anzusehen und zu versuchen eine schöne und schnelle Lösung zu finden, bevor Sie den nächsten Absatz lesen. Kommen Sie danach hierher zurück und schauen sich meine Lösung an. Der Schlüssel dazu ein Zeichen an den Eingabestrom zurückzugeben, liegt darin, wie wir das Zeichen bekommen: Als erstes überprüfen wir, ob der Puffer leer ist, indem wir den Wert von `EBX` testen. Wenn er null ist, rufen wir die Prozedur `read` auf. Wenn ein Zeichen bereit ist verwenden wir `lodsb`, dann verringern wir den Wert von `EBX`. Die Anweisung `lodsb` ist letztendlich identisch mit: [.programlisting] .... mov al, [esi] inc esi .... Das Byte, welches wir abgerufen haben, verbleibt im Puffer bis `read` zum nächsten Mal aufgerufen wird. Wir wissen nicht wann das passiert, aber wir wissen, dass es nicht vor dem nächsten Aufruf von `getchar` passiert. Daher ist alles was wir tun müssen um das Byte in den Strom "zurückzugeben" ist den Wert von `ESI` zu verringern und den von `EBX` zu erhöhen: [.programlisting] .... ungetc: dec esi inc ebx ret .... Aber seien Sie vorsichtig! Wir sind auf der sicheren Seite, solange wir immer nur ein Zeichen im Voraus lesen. Wenn wir mehrere kommende Zeichen betrachten und `ungetc` mehrmals hintereinander aufrufen, wird es meistens funktionieren, aber nicht immer (und es wird ein schwieriger Debug). Warum? Solange `getchar``read` nicht aufrufen muss, befinden sich alle im Voraus gelesenen Bytes noch im Puffer und `ungetc` arbeitet fehlerfrei. Aber sobald `getchar``read` aufruft verändert sich der Inhalt des Puffers. Wir können uns immer darauf verlassen, dass `ungetc` auf dem zuletzt mit `getchar` gelesenen Zeichen korrekt arbeitet, aber nicht auf irgendetwas, das davor gelesen wurde. Wenn Ihr Programm mehr als ein Byte im Voraus lesen soll, haben Sie mindestens zwei Möglichkeiten: Die einfachste Lösung ist, Ihr Programm so zu ändern, dass es immer nur ein Byte im Voraus liest, wenn das möglich ist. Wenn Sie diese Möglichkeit nicht haben, bestimmen Sie zuerst die maximale Anzahl an Zeichen, die Ihr Programm auf einmal an den Eingabestrom zurückgeben muss. Erhöhen Sie diesen Wert leicht, nur um sicherzugehen, vorzugsweise auf ein Vielfaches von 16-damit er sich schön ausrichtet. Dann passen Sie den `.bss` Abschnitt Ihres Codes an und erzeugen einen kleinen Reserver-Puffer, direkt vor ihrem Eingabepuffer, in etwa so: [.programlisting] .... section .bss resb 16 ; or whatever the value you came up with ibuffer resb BUFSIZE obuffer resb BUFSIZE .... Außerdem müssen Sie `ungetc` anpassen, sodass es den Wert des Bytes, das zurückgegeben werden soll, in `AL` übergibt: [.programlisting] .... ungetc: dec esi inc ebx mov [esi], al ret .... Mit dieser Änderung können Sie sicher `ungetc` bis zu 17 Mal hintereinander gqapaufrufen (der erste Aufruf erfolgt noch im Puffer, die anderen 16 entweder im Puffer oder in der Reserve). [[x86-command-line]] == Kommandozeilenparameter Unser hex-Programm wird nützlicher, wenn es die Dateinamen der Ein- und Ausgabedatei über die Kommandozeile einlesen kann, d.h., wenn es Kommandozeilenparameter verarbeiten kann. Aber... Wo sind die? Bevor ein UNIX(R)-System ein Programm ausführt, legt es einige Daten auf dem Stack ab (`push`) und springt dann an das `_start`-Label des Programms. Ja, ich sagte springen, nicht aufrufen. Das bedeutet, dass auf die Daten zugegriffen werden kann, indem `[esp+offset]` ausgelesen wird oder die Daten einfach vom Stack genommen werden (`pop`). Der Wert ganz oben auf dem Stack enthält die Zahl der Kommandozeilenparameter. Er wird traditionell `argc` wie "argument count" genannt. Die Kommandozeilenparameter folgen einander, alle `argc`. Von diesen wird üblicherweise als `argv` wie "argument value(s)" gesprochen. So erhalten wir `argv[0]`, `argv[1]`, `...` und `argv[argc-1]`. Dies sind nicht die eigentlichen Parameter, sondern Zeiger (Pointer) auf diese, d.h., Speicheradressen der tatsächlichen Parameter. Die Parameter selbst sind durch NULL beendete Zeichenketten. Der `argv`-Liste folgt ein NULL-Zeiger, was einfach eine [constant]#0# ist. Es gibt noch mehr, aber dies ist erst einmal genug für unsere Zwecke. [NOTE] ==== Falls Sie von der MS-DOS(R)-Programmierumgebung kommen, ist der größte Unterschied die Tatsache, dass jeder Parameter eine separate Zeichenkette ist. Der zweite Unterschied ist, dass es praktisch keine Grenze gibt, wie viele Parameter vorhanden sein können. ==== Ausgerüstet mit diesen Kenntnissen, sind wir beinahe bereit für eine weitere Version von [.filename]#hex.asm#. Zuerst müssen wir jedoch noch ein paar Zeilen zu [.filename]#system.inc# hinzufügen: Erstens benötigen wir zwei neue Einträge in unserer Liste mit den Systemaufrufnummern: [.programlisting] .... %define SYS_open 5 %define SYS_close 6 .... Zweitens fügen wir zwei neue Makros am Ende der Datei ein: [.programlisting] .... %macro sys.open 0 system SYS_open %endmacro %macro sys.close 0 system SYS_close %endmacro .... Und hier ist schließlich unser veränderter Quelltext: [.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 .... In unserem `.data`-Abschnitt befinden sich nun die zwei neuen Variablen `fd.in` und `fd.out`. Hier legen wir die Dateideskriptoren der Ein- und Ausgabedatei ab. Im `.text`-Abschnitt haben wir die Verweise auf `stdin` und `stdout` durch `[fd.in]` und `[fd.out]` ersetzt. Der `.text`-Abschnitt beginnt nun mit einer einfachen Fehlerbehandlung, welche nur das Programm mit einem Rückgabewert von [constant]#1# beendet. Die Fehlerbehandlung befindet sich vor `_start`, sodass wir in geringer Entfernung von der Stelle sind, an der der Fehler auftritt. Selbstverständlich beginnt die Programmausführung immer noch bei `_start`. Zuerst entfernen wir `argc` und `argv[0]` vom Stack: Sie sind für uns nicht von Interesse (sprich, in diesem Programm). Wir nehmen `argv[1]` vom Stack und legen es in `ECX` ab. Dieses Register ist besonders für Zeiger geeignet, da wir mit `jecxz` NULL-Zeiger verarbeiten können. Falls `argv[1]` nicht NULL ist, versuchen wir, die Datei zu öffnen, die der erste Parameter festlegt. Andernfalls fahren wir mit dem Programm fort wie vorher: Lesen von `stdin` und Schreiben nach `stdout`. Falls wir die Eingabedatei nicht öffnen können (z.B. sie ist nicht vorhanden), springen wir zur Fehlerbehandlung und beenden das Programm. Falls es keine Probleme gibt, sehen wir nun nach dem zweiten Parameter. Falls er vorhanden ist, öffnen wir die Ausgabedatei. Andernfalls schreiben wir die Ausgabe nach `stdout`. Falls wir die Ausgabedatei nicht öffnen können (z.B. sie ist zwar vorhanden, aber wir haben keine Schreibberechtigung), springen wir auch wieder in die Fehlerbehandlung. Der Rest des Codes ist derselbe wie vorher, außer dem Schließen der Ein- und Ausgabedatei vor dem Verlassen des Programms und, wie bereits erwähnt, die Benutzung von `[fd.in]` und `[fd.out]`. Unsere Binärdatei ist nun kolossale 768 Bytes groß. Können wir das Programm immer noch verbessern? Natürlich! Jedes Programm kann verbessert werden. Hier finden sich einige Ideen, was wir tun könnten: * Die Fehlerbehandlung eine Warnung auf `stderr` ausgeben lassen. * Den `Lese`- und ``Schreib``funkionen eine Fehlerbehandlung hinzufügen. * Schließen von `stdin`, sobald wir eine Eingabedatei öffnen, von `stdout`, sobald wir eine Ausgabedatei öffnen. * Hinzufügen von Kommandozeilenschaltern wie zum Beispiel [parameter]#-i# und [parameter]#-o#, sodass wir die Ein- und Ausgabedatei in irgendeiner Reihenfolge angeben oder vielleicht von `stdin` lesen und in eine Datei schreiben können. * Ausgeben einer Gebrauchsanweisung, falls die Kommandozeilenparameter fehlerhaft sind. Ich beabsichtige, diese Verbesserungen dem Leser als Übung zu hinterlassen: Sie wissen bereits alles, das Sie wissen müssen, um die Verbesserungen durchzuführen. [[x86-environment]] == Die UNIX(R)-Umgebung Ein entscheidendes Konzept hinter UNIX(R) ist die Umgebung, die durch _Umgebungsvariablen_ festgelegt wird. Manche werden vom System gesetzt, andere von Ihnen und wieder andere von der shell oder irgendeinem Programm, das ein anderes lädt. [[x86-find-environment]] === Umgebungsvariablen herausfinden Ich sagte vorher, dass wenn ein Programm mit der Ausführung beginnt, der Stack `argc` gefolgt vom durch NULL beendeten `argv`-Array und etwas Anderem enthält. Das "etwas Andere" ist die _Umgebung_ oder, um genauer zu sein, ein durch NULL beendetes Array von Zeigern auf _Umgebungsvariablen_. Davon wird oft als `env` gesprochen. Der Aufbau von `env` entspricht dem von `argv`, eine Liste von Speicheradressen gefolgt von NULL ([constant]#0#). In diesem Fall gibt es kein `"envc"`-wir finden das Ende heraus, indem wir nach dem letzten NULL suchen. Die Variablen liegen normalerweise in der Form `name=value` vor, aber manchmal kann der `=value`-Teil fehlen. Wir müssen diese Möglichkeit in Betracht ziehen. [[x86-webvar]] === webvars Ich könnte Ihnen einfach etwas Code zeigen, der die Umgebung in der Art vom UNIX(R)-Befehl env ausgibt. Aber ich dachte, dass es interessanter sei, ein einfaches CGI-Werkzeug in Assembler zu schreiben. [[x86-cgi]] ==== CGI: Ein kurzer Überblick Ich habe eine http://www.whizkidtech.redprince.net/cgi-bin/tutorial[detaillierte CGI-Anleitung] auf meiner Webseite, aber hier ist ein sehr kurzer Überblick über CGI: * Der Webserver kommuniziert mit dem CGI-Programm, indem er _Umgebungsvariablen_ setzt. * Das CGI-Programm schreibt seine Ausgabe auf [.filename]#stdout#. Der Webserver liest von da. * Die Ausgabe muss mit einem HTTP-Kopfteil gefolgt von zwei Leerzeilen beginnen. * Das Programm gibt dann den HTML-Code oder was für einen Datentyp es auch immer verarbeitet aus. * [NOTE] ==== Während bestimmte _Umgebungsvariablen_ Standardnamen benutzen, unterscheiden sich andere, abhängig vom Webserver. Dies macht webvars zu einem recht nützlichen Werkzeug. ==== [[x86-webvars-the-code]] ==== Der Code Unser webvars-Programm muss also den HTTP-Kopfteil gefolgt von etwas HTML-Auszeichnung versenden. Dann muss es die _Umgebungsvariablen_ eine nach der anderen auslesen und sie als Teil der HTML-Seite versenden. Nun der Code. Ich habe Kommentare und Erklärungen direkt in den Code eingefügt: [.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 '', 0Ah db '', 0Ah db '', 0Ah db '', 0Ah db 'Web Environment', 0Ah db '', 0Ah db '', 0Ah, 0Ah db '', 0Ah db '
', 0Ah db '

Web Environment

', 0Ah db '

The following environment variables are defined ' db 'on this web server:

', 0Ah, 0Ah db '', 0Ah httplen equ $-http left db '', 0Ah db '', 0Ah db '', 0Ah db '', 0Ah rightlen equ $-right wrap db '
' leftlen equ $-left middle db '' midlen equ $-middle undef db '(undefined)' undeflen equ $-undef right db '
', 0Ah db '
', 0Ah db '', 0Ah db '', 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 .... Dieser Code erzeugt eine 1.396-Byte große Binärdatei. Das meiste davon sind Daten, d.h., die HTML-Auszeichnung, die wir versenden müssen. Assemblieren Sie es wie immer: [source,shell] .... % nasm -f elf webvars.asm % ld -s -o webvars webvars.o .... Um es zu benutzen, müssen Sie [.filename]#webvars# auf Ihren Webserver hochladen. Abhängig von Ihrer Webserver-Konfiguration, müssen Sie es vielleicht in einem speziellen [.filename]#cgi-bin#-Verzeichnis ablegen oder es mit einer [.filename]#.cgi#-Dateierweiterung versehen. Schließlich benötigen Sie Ihren Webbrowser, um sich die Ausgabe anzusehen. Um die Ausgabe auf meinem Webserver zu sehen, gehen Sie bitte auf http://www.int80h.org/webvars/[http://www.int80h.org/webvars/]. Falls Sie neugierig sind, welche zusätzlichen Variablen in einem passwortgeschützten Webverzeichnis vorhanden sind, gehen Sie auf http://www.int80h.org/private/[http://www.int80h.org/private/] unter Benutzung des Benutzernamens `asm` und des Passworts `programmer`. [[x86-files]] == Arbeiten mit Dateien Wir haben bereits einfache Arbeiten mit Dateien gemacht: Wir wissen wie wir sie öffnen und schliessen, oder wie man sie mit Hilfe von Buffern liest und schreibt. Aber UNIX(R) bietet viel mehr Funktionalität wenn es um Dateien geht. Wir werden einige von ihnen in dieser Sektion untersuchen und dann mit einem netten Datei Konvertierungs Werkzeug abschliessen. In der Tat, Lasst uns am Ende beginnen, also mit dem Datei Konvertierungs Werkzeug. Es macht Programmieren immer einfacher, wenn wir bereits am Anfang wissen was das End Produkt bezwecken soll. Eines der ersten Programme die ich für UNIX(R) schrieb war link:ftp://ftp.int80h.org/unix/tuc/[ tuc], ein Text-Zu-UNIX(R) Datei Konvertierer. Es konvertiert eine Text Datei von einem anderen Betriebssystem zu einer UNIX(R) Text Datei. Mit anderen Worten, es ändert die verschiedenen Arten von Zeilen Begrenzungen zu der Zeilen Begrenzungs Konvention von UNIX(R). Es speichert die Ausgabe in einer anderen Datei. Optional konvertiert es eine UNIX(R) Text Datei zu einer DOS Text Datei. Ich habe tuc sehr oft benutzt, aber nur von irgendeinem anderen OS nach UNIX(R) zu konvertieren, niemals anders herum. Ich habe mir immer gewünscht das die Datei einfach überschrieben wird anstatt das ich die Ausgabe in eine andere Datei senden muss. Meistens, habe ich diesen Befehl verwendet: [source,shell] .... % tuc myfile tempfile % mv tempfile myfile .... Es wäre schö ein ftuc zu haben, also, _fast tuc_, und es so zu benutzen: [source,shell] .... % ftuc myfile .... In diesem Kapitel werden wir dann, ftuc in Assembler schreiben (das Original tuc ist in C), und verschiedene Datei-Orientierte Kernel Dienste in dem Prozess studieren. Auf erste Sicht, ist so eine Datei Konvertierung sehr simpel: Alles was du zu tun hast, ist die Wagenrückläufe zu entfernen, richtig? Wenn du mit ja geantwortet hast, denk nochmal darüber nach: Dieses Vorgehen wird die meiste Zeit funktionieren (zumindest mit MSDOS Text Dateien), aber gelegentlich fehlschlagen. Das Problem ist das nicht alle UNIX(R) Text Dateien ihre Zeilen mit einer Wagen Rücklauf / Zeilenvorschub Sequenz beenden. Manche benutzen Wagenrücklauf ohne Zeilenvorschub. Andere kombinieren mehrere leere Zeilen in einen einzigen Wagenrücklauf gefolgt von mehreren Zeilenvorschüben. Und so weiter. Ein Text Datei Konvertierer muss dann also in der Lage sein mit allen möglichen Zeilenenden umzugehen: * Wagenrücklauf / Zeilenvorschub * Wagenrücklauf * Zeilenvorschub / Wagenrücklauf * Zeilenvorschub Es sollte außerdem in der Lage sein mit Dateien umzugehen die irgendeine Art von Kombination der oben stehenden Möglichkeiten verwendet. (z.B., Wagenrücklauf gefolgt von mehreren Zeilenvorschüben). [[x86-finite-state-machine]] === Endlicher Zustandsautomat Das Problem wird einfach gelöst in dem man eine Technik benutzt die sich _Endlicher Zustandsautomat_ nennt, ursprünglich wurde sie von den Designern digitaler elektronischer Schaltkreise entwickelt. Eine _Endlicher Zustandsautomat_ ist ein digitaler Schaltkreis dessen Ausgabe nicht nur von der Eingabe abhängig ist sondern auch von der vorherigen Eingabe, d.h., von seinem Status. Der Mikroprozessor ist ein Beispiel für einen _Endlichen Zustandsautomaten_: Unser Assembler Sprach Code wird zu Maschinensprache übersetzt in der manche Assembler Sprach Codes ein einzelnes Byte produzieren, während andere mehrere Bytes produzieren. Da der Microprozessor die Bytes einzeln aus dem Speicher liest, ändern manche nur seinen Status anstatt eine Ausgabe zu produzieren. Wenn alle Bytes eines OP Codes gelesen wurden, produziert der Mikroprozessor eine Ausgabe, oder ändert den Wert eines Registers, etc. Aus diesem Grund, ist jede Software eigentlich nur eine Sequenz von Status Anweisungen für den Mikroprozessor. Dennoch, ist das Konzept eines _Endlichen Zustandsautomaten_ auch im Software Design sehr hilfreich. Unser Text Datei Konvertierer kann als _Endlicher Zustandsautomat_ mit 3 möglichen Stati desgined werden. Wir könnten diese von 0-2 benennen, aber es wird uns das Leben leichter machen wenn wir ihnen symbolische Namen geben: * ordinary * cr * lf Unser Programm wird in dem ordinary Status starten. Während dieses Status, hängt die Aktion des Programms von seiner Eingabe wie folgt ab: * Wenn die Eingabe etwas anderes als ein Wagenrücklauf oder einem Zeilenvorschub ist, wird die Eingabe einfach nur an die Ausgabe geschickt. Der Status bleibt unverändert. * Wenn die Eingabe ein Wagenrücklauf ist, wird der Status auf cr gesetzt. Die Eingabe wird dann verworfen, d.h., es entsteht keine Ausgabe. * Wenn die Eingabe ein Zeilenvorschub ist, wird der Status auf lf gesetzt. Die Eingabe wird dann verworfen. Wann immer wir in dem cr Status sind, ist das weil die letzte Eingabe ein Wagenrücklauf war, welcher nicht verarbeitet wurde. Was unsere Software in diesem Status macht hängt von der aktuellen Eingabe ab: * Wenn die Eingabe irgendetwas anderes als ein Wagenrücklauf oder ein Zeilenvorschub ist, dann gib einen Zeilenvorschub aus, dann gib die Eingabe aus und dann ändere den Status zu ordinary. * Wenn die Eingabe ein Wagenrücklauf ist, haben wir zwei (oder mehr) Wagenrückläufe in einer Reihe. Wir verwerfen die Eingabe, wir geben einen Zeilenvorschub aus und lassen den Status unverändert. * Wenn die Eingabe ein Zeilenvorschub ist, geben wir den Zeilenvorschub aus und ändern den Status zu ordinary. Achte darauf, dass das nicht das gleiche wie in dem Fall oben drüber ist - würden wir versuchen beide zu kombinieren, würden wir zwei Zeilenvorschübe anstatt einen ausgeben. Letztendlich, sind wir in dem lf Status nachdem wir einen Zeilenvorschub empfangen haben der nicht nach einem Wagenrücklauf kam. Das wird passieren wenn unsere Datei bereits im UNIX(R) Format ist, oder jedesmal wenn mehrere Zeilen in einer Reihe durch einen einzigen Wagenrücklauf gefolgt von mehreren Zeilenvorschüben ausgedrückt wird, oder wenn die Zeile mit einer Zeilenvorschub / Wagenrücklauf Sequenz endet. Wir sollten mit unserer Eingabe in diesem Status folgendermaßen umgehen: * Wenn die Eingabe irgendetwas anderes als ein Wagenrücklauf oder ein Zeilenvorschub ist, geben wir einen Zeilenvorschub aus, geben dann die Eingabe aus und ändern dann den Status zu ordinary. Das ist exakt die gleiche Aktion wie in dem cr Status nach dem Empfangen der selben Eingabe. * Wenn die Eingabe ein Wagenrücklauf ist, verwerfen wir die Eingabe, geben einen Zeilenvorschub aus und ändern dann den Status zu ordinary. * Wenn die Eingabe ein Zeilenvorschub ist, geben wir den Zeilenvorschub aus und lassen den Status unverändert. [[x86-final-state]] ==== Der Endgültige Status Der obige _Endliche Zustandsautomat_ funktioniert für die gesamte Datei, aber lässt die Möglichkeit das die letzte Zeile ignoriert wird. Das wird jedesmal passieren wenn die Datei mit einem einzigen Wagenrücklauf oder einem einzigen Zeilenvorschub endet. Daran habe ich nicht gedacht als ich tuc schrieb, nur um festzustellen, daß das letzte Zeilenende gelegentlich weggelassen wird. Das Problem wird einfach dadurch gelöst, indem man den Status überprüft nachdem die gesamte Datei verarbeitet wurde. Wenn der Status nicht ordinary ist, müssen wir nur den letzten Zeilenvorschub ausgeben. [NOTE] ==== Nachdem wir unseren Algorithmus nun als einen _Endlichen Zustandsautomaten_ formuliert haben, könnten wir einfach einen festgeschalteten digitalen elektronischen Schaltkreis (einen "Chip") designen, der die Umwandlung für uns übernimmt. Natürlich wäre das sehr viel teurer, als ein Assembler Programm zu schreiben. ==== [[x86-tuc-counter]] ==== Der Ausgabe Zähler Weil unser Datei Konvertierungs Programm möglicherweise zwei Zeichen zu einem kombiniert, müssen wir einen Ausgabe Zähler verwenden. Wir initialisieren den Zähler zu [constant]#0# und erhöhen ihn jedes mal wenn wir ein Zeichen an die Ausgabe schicken. Am Ende des Programms, wird der Zähler uns sagen auf welche Grösse wir die Datei setzen müssen. [[x86-software-fsm]] === Implementieren von EZ als Software Der schwerste Teil beim arbeiten mit einer _Endlichen Zustandsmaschine_ ist das analysieren des Problems und dem ausdrücken als eine _Endliche Zustandsmaschine_. That geschafft, schreibt sich die Software fast wie von selbst. In eine höheren Sprache, wie etwa C, gibt es mehrere Hauptansätze. Einer wäre ein `switch` Angabe zu verwenden die auswählt welche Funktion genutzt werden soll. Zum Beispiel, [.programlisting] .... switch (state) { default: case REGULAR: regular(inputchar); break; case CR: cr(inputchar); break; case LF: lf(inputchar); break; } .... Ein anderer Ansatz ist es ein Array von Funktions Zeigern zu benutzen, etwa wie folgt: [.programlisting] .... (output[state])(inputchar); .... Noch ein anderer ist es aus `state` einen Funktions Zeiger zu machen und ihn zu der entsprechenden Funktion zeigen zu lassen: [.programlisting] .... (*state)(inputchar); .... Das ist der Ansatz den wir in unserem Programm verwenden werden, weil es in Assembler sehr einfach und schnell geht. Wir werden einfach die Adresse der Prozedur in `EBX` speichern und dann einfach das ausgeben: [.programlisting] .... call ebx .... Das ist wahrscheinlich schneller als die Adresse im Code zu hardcoden weil der Mikroprozessor die Adresse nicht aus dem Speicher lesen muss-es ist bereits in einer der Register gespeichert. Ich sagte _wahrscheinlich_ weil durch das Cachen neuerer Mikroprozessoren beide Varianten in etwa gleich schnell sind. [[memory-mapped-files]] === Speicher abgebildete Dateien Weil unser Programm nur mit einzelnen Dateien funktioniert, können wir nicht den Ansatz verwedenden der zuvor funktioniert hat, d.h., von einer Eingabe Datei zu lesen und in eine Ausgabe Datei zu schreiben. UNIX(R) erlaubt es uns eine Datei, oder einen Bereich einer Datei, in den Speicher abzubilden. Um das zu tun, müssen wir zuerst eine Datei mit den entsprechenden Lese/Schreib Flags öffnen. Dann benutzen wir den `mmap` system call um sie in den Speicher abzubilden. Ein Vorteil von `mmap` ist, das es automatisch mit virtuellem Speicher arbeitet: Wir können mehr von der Datei im Speicher abbilden als wir überhaupt physikalischen Speicher zur Verfügung haben, noch immer haben wir aber durch normale OP Codes wie `mov`, `lods`, und `stos` Zugriff darauf. Egal welche Änderungen wir an dem Speicherabbild der Datei vornehmen, sie werden vom System in die Datei geschrieben. Wir müssen die Datei nicht offen lassen: So lange sie abgebildet bleibt, können wir von ihr lesen und in sie schreiben. Ein 32-bit Intel Mikroprozessor kann auf bis zu vier Gigabyte Speicher zugreifen - physisch oder virtuell. Das FreeBSD System erlaubt es uns bis zu der Hälfte für die Datei Abbildung zu verwenden. Zur Vereinfachung, werden wir in diesem Tutorial nur Dateien konvertieren die in ihrere Gesamtheit im Speicher abgebildet werden können. Es gibt wahrscheinlich nicht all zu viele Text Dateien die eine Grösse von zwei Gigabyte überschreiben. Falls unser Programm doch auf eine trifft, wird es einfach eine Meldung anzeigen mit dem Vorschlag das originale tuc statt dessen zu verwenden. Wenn du deine Kopie von [.filename]#syscalls.master# überprüfst, wirst du zwei verschiedene Systemaufrufe finden die sich `mmap` nennen. Das kommt von der Entwicklung von UNIX(R): Es gab das traditionelle BSD``mmap``, Systemaufruf 71. Dieses wurde durch das POSIX(R) `mmap` ersetzt, Systemaufruf 197. Das FreeBSD System unterstützt beide, weil ältere Programme mit der originalen BSD Version geschrieben wurden. Da neue Software die POSIX(R) Version nutzt, werden wir diese auch verwenden. Die [.filename]#syscalls.master# Datei zeigt die POSIX(R) Version wie folgt: [.programlisting] .... 197 STD BSD { caddr_t mmap(caddr_t addr, size_t len, int prot, \ int flags, int fd, long pad, off_t pos); } .... Das weicht etwas von dem ab was man:mmap[2] sagt. Das ist weil man:mmap[2] die C Version beschreibt. Der Unterschiede liegt in dem `long pad` Argument, welches in der C Version nicht vorhanden ist. Wie auch immer, der FreeBSD Systemaufruf fügt einen 32-bit Block ein nachdem es ein 64-Bit Argument auf den Stack ge``push``t hat. In diesem Fall, ist `off_t` ein 64-Bit Wert. Wenn wir fertig sind mit dem Arbeiten einer im Speicher abgebildeten Datei, entfernen wir das Speicherabbild mit dem `munmap` Systemaufruf: [TIP] ==== Für eine detailliert Behandlung von `mmap`, sieh in W. Richard Stevens' http://www.int80h.org/cgi-bin/isbn?isbn=0130810819[ Unix Network Programming, Volume 2, Chapter 12] nach. ==== [[x86-file-size]] === Feststellen der Datei Grösse Weil wir `mmap` sagen müssen wie viele Bytes von Datei wir im Speicher abbilden wollen und wir außerdem die gesamte Datei abbilden wollen, müssen wir die Grösse der Datei feststellen. Wir können den `fstat` Systemaufruf verwenden um alle Informationen über eine geöffnete Datei zu erhalten die uns das System geben kann. Das beinhaltet die Datei Grösse. Und wieder, zeigt uns [.filename]#syscalls.master# zwei Versionen von `fstat`, eine traditionelle (Systemaufruf 62), und eine POSIX(R) (Systemaufruf 189) Variante. Natürlich, verwenden wir die POSIX(R) Version: [.programlisting] .... 189 STD POSIX { int fstat(int fd, struct stat *sb); } .... Das ist ein sehr unkomplizierter Aufruf: Wir übergeben ihm die Adresse einer `stat` Structure und den Deskriptor einer geöffneten Datei. Es wird den Inhalt der `stat` Struktur ausfüllen. Ich muss allerdings sagen, das ich versucht habe die `stat` Struktur in dem `.bss` Bereich zu deklarieren, und `fstat` mochte es nicht: Es setzte das Carry Flag welches einen Fehler anzeigt. Nachdem ich den Code veränderte so dass er die Struktur auf dem Stack anlegt, hat alles gut funktioniert. [[x86-ftruncate]] === Ändern der Dateigrösse Dadurch das unser Programm Wagenrücklauf/Zeilenvorschub-Sequenzen in einfache Zeilenvorschübe zusammenfassen könnte, könnte unsere Ausgabe kleiner sein als unsere Eingabe. Und da wir die Ausgabe in dieselbe Datei um, aus der wir unsere Eingabe erhalten, müssen wir eventuell die Dateigrösse anpassen. Der Systemaufruf `ftruncate` erlaubt uns, dies zu tun. Abgesehen von dem etwas unglücklich gewählten Namen `ftruncate` können wir mit dieser Funktion eine Datei vergrössern, oder verkleinern. Und ja, wir werden zwei Versionen von `ftruncate` in [.filename]#syscalls.master# finden, eine ältere (130) und eine neuere (201). Wir werden die neuere Version verwenden: [.programlisting] .... 201 STD BSD { int ftruncate(int fd, int pad, off_t length); } .... Beachten Sie bitte, dass hier wieder `int pad` verwendet wird. [[x86-ftuc]] === ftuc Wir wissen jetzt alles nötige, um ftuc zu schreiben. Wir beginnen, indem wir ein paar neue Zeilen der Datei [.filename]#system.inc# hinzufügen. Als erstes definieren wir irgendwo am Anfang der Datei einige Konstanten und Strukturen: [.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 .... Wir definieren die neuen Systemaufrufe: [.programlisting] .... %define SYS_mmap 197 %define SYS_munmap 73 %define SYS_fstat 189 %define SYS_ftruncate 201 .... Wir fügen die Makros hinzu: [.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 .... Und hier ist unser Code: [.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 .... [WARNING] ==== Verwenden Sie dieses Programm nicht mit Dateien, die sich auf Datenträgern befinden, welche mit MS-DOS(R) oder Windows(R) formatiert wurden. Anscheinend gibt es im Code von FreeBSD einen subtilen Bug, wenn `mmap` auf solchen Datenträgern verwendet wird: Wenn die Datei eine bestimmte Grösse überschreitet, füllt `mmap` den Speicher mit lauter Nullen, und überschreibt damit anschliessend den Dateiinhalt. ==== [[x86-one-pointed-mind]] == One-Pointed Mind Als ein Zen-Schüler liebe ich die Idee eines fokussierten Bewußtseins: Tu nur ein Ding zur gleichen Zeit, aber mache es richtig. Das ist ziemlich genau die gleiche Idee, welche UNIX(R) richtig funktionieren lässt. Während eine typische Windows(R)-Applikation versucht alles Vorstellbare zu tun (und daher mit Fehler durchsetzt ist), versucht eine UNIX(R)-Applikation nur eine Funktion zu erfüllen und das gut. Der typische UNIX(R)-Nutzer stellt sich sein eigenes System durch Shell-Skripte zusammen, die er selbst schreibt, und welche die Vorteile bestehender Applikationen dadurch kombinieren, indem sie die Ausgabe eines Programmes als Eingabe in ein anderes Programm durch eine Pipe übergeben. Wenn Sie ihre eigene UNIX(R)-Software schreiben, ist es generell eine gute Idee zu betrachten, welcher Teil der Problemlösung durch bestehende Programme bewerkstelligt werden kann. Man schreibt nur die Programme selbst, für die keine vorhandene Lösung existiert. [[x86-csv]] === CSV Ich will dieses Prinzip an einem besonderen Beispiel aus der realen Welt demonstrieren, mit dem ich kürzlich konfrontiert wurde: Ich mußte jeweils das elfte Feld von jedem Datensatz aus einer Datenbank extrahieren, die ich von einer Webseite heruntergeladen hatte. Die Datenbank war eine CSV-Datei, d.h. eine Liste von _Komma-getrennten Werten_. Dies ist ein ziemlich gewöhnliches Format für den Code-Austausch zwischen Menschen, die eine unterschiedliche Datenbank-Software nutzen. Die erste Zeile der Datei enthält eine Liste der Felder durch Kommata getrennt. Der Rest der Datei enthält die einzelnen Datensätze mit durch Kommata getrennten Werten in jeder Zeile. Ich versuchte awk unter Nutzung des Kommas als Trenner. Da aber einige Zeilen durch in Bindestriche gesetzte Kommata getrennt waren, extrahierte awk das falsche Feld aus diesen Zeilen. Daher mußte ich meine eigene Software schreiben, um das elfte Feld aus der CSV-Datei auszulesen. Aber durch Anwendung der UNIX(R)-Philosophie mußte ich nur einen einfachen Filter schreiben, das Folgende tat: * Entferne die erste Zeile aus der Datei. * Ändere alle Kommata ohne Anführungszeichen in einen anderen Buchstaben. * Entferne alle Anführungszeichen. Streng genommen könnte ich sed benutzen, um die erste Zeile der Datei zu entfernen, aber das zu Bewerkstelligen war in meinem Programm sehr einfach, also entschloss ich mich dazu und reduzierte dadurch die Größe der Pipeline. Unter Berücksichtigung aller Faktoren kostete mich das Schreiben dieses Programmes ca. 20 Minuten. Das Schreiben eines Programmes, welches jeweils das elfte Feld aus einer CSV-Datei extrahiert hätte wesentlich länger gedauert und ich hätte es nicht wiederverwenden können, um ein anderes Feld aus irgendeiner anderen Datenbank zu extrahieren. Diesmal entschied ich mich dazu, etwas mehr Arbeit zu investieren, als man normalerweise für ein typisches Tutorial verwenden würde: * Es parst die Kommandozeilen nach Optionen. * Es zeigt die richtige Nutzung an, falls es ein falsches Argument findet. * Es gibt vernünftige Fehlermeldungen aus. Hier ist ein Beispiel für seine Nutzung: [source,shell] .... Usage: csv [-t] [-c] [-p] [-o ] [-i ] .... Alle Parameter sind optional und können in beliebiger Reihenfolge auftauchen. Der [parameter]#-t#-Parameter legt fest, was zu die Kommata zu ersetzen sind. Der [constant]#tab# ist die Vorgabe hierfür. Zum Beispiel wird [parameter]#-t;# alle unquotierten Kommata mit Semikolon ersetzen. Ich brauche die [parameter]#-c#-Option nicht, aber sie könnte zukünftig nützlich sein. Sie ermöglicht mir festzulegen, daß ich einen anderen Buchstaben als das Kommata mit etwas anderem ersetzen möchte. Zum Beispiel wird der Parameter [parameter]#-c@# alle @-Zeichen ersetzen (nützlich, falls man eine Liste von Email-Adressen in Nutzername und Domain aufsplitten will). Die [parameter]#-p#-Option erhält die erste Zeile, d.h. die erste Zeile der Datei wird nicht gelöscht. Als Vorgabe löschen wir die erste Zeile, weil die CSV-Datei in der ersten Zeile keine Daten, sondern Feldbeschreibungen enthält. Die Parameter [parameter]#-i#- und [parameter]#-o#-Optionen erlauben es mir, die Ausgabe- und Eingabedateien festzulegen. Vorgabe sind [.filename]#stdin# und [.filename]#stdout#, also ist es ein regulärer UNIX(R)-Filter. Ich habe sichergestellt, daß sowohl [parameter]#-i filename# und [parameter]#-ifilename# akzeptiert werden. Genauso habe ich dafür Sorge getragen, daß sowohl Eingabe- als auch Ausgabedateien festgelegt werden können. Um das elfte Feld jeden Datensatzes zu erhalten kann ich nun folgendes eingeben: [source,shell] .... % csv '-t;' data.csv | awk '-F;' '{print $11}' .... Der Code speichert die Optionen (bis auf die Dateideskriptoren) in `EDX`: Das Kommata in `DH`, den neuen Feldtrenner in `DL` und das Flag für die [parameter]#-p#-Option in dem höchsten Bit von `EDX`. Ein kurzer Abgleich des Zeichens wird uns also eine schnelle Entscheidung darüber erlauben, was zu tun ist. Hier ist der Code: [.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] [-c] [-p] [-o ] [-i ]', 0Ah usglen equ $-usg iemsg db "csv: Can't open input file", 0Ah iemlen equ $-iemsg oemsg db "csv: Can't create output file", 0Ah oemlen equ $-oemsg section .bss ibuffer resb BUFSIZE obuffer resb BUFSIZE section .text align 4 ierr: push dword iemlen push dword iemsg push dword stderr sys.write push dword 1 ; return failure sys.exit align 4 oerr: push dword oemlen push dword oemsg push dword stderr sys.write push dword 2 sys.exit align 4 usage: push dword usglen push dword usg push dword stderr sys.write push dword 3 sys.exit align 4 global _start _start: add esp, byte 8 ; discard argc and argv[0] mov edx, (',' << 8) | 9 .arg: pop ecx or ecx, ecx je near .init ; no more arguments ; ECX contains the pointer to an argument cmp byte [ecx], '-' jne usage inc ecx mov ax, [ecx] .o: cmp al, 'o' jne .i ; Make sure we are not asked for the output file twice cmp dword [fd.out], stdout jne usage ; Find the path to output file - it is either at [ECX+1], ; i.e., -ofile -- ; or in the next argument, ; i.e., -o file inc ecx or ah, ah jne .openoutput pop ecx jecxz usage .openoutput: push dword 420 ; file mode (644 octal) push dword 0200h | 0400h | 01h ; O_CREAT | O_TRUNC | O_WRONLY push ecx sys.open jc near oerr add esp, byte 12 mov [fd.out], eax jmp short .arg .i: cmp al, 'i' jne .p ; Make sure we are not asked twice cmp dword [fd.in], stdin jne near usage ; Find the path to the input file inc ecx or ah, ah jne .openinput pop ecx or ecx, ecx je near usage .openinput: push dword 0 ; O_RDONLY push ecx sys.open jc near ierr ; open failed add esp, byte 8 mov [fd.in], eax jmp .arg .p: cmp al, 'p' jne .t or ah, ah jne near usage or edx, 1 << 31 jmp .arg .t: cmp al, 't' ; redefine output delimiter jne .c or ah, ah je near usage mov dl, ah jmp .arg .c: cmp al, 'c' jne near usage or ah, ah je near usage mov dh, ah jmp .arg align 4 .init: sub eax, eax sub ebx, ebx sub ecx, ecx mov edi, obuffer ; See if we are to preserve the first line or edx, edx js .loop .firstline: ; get rid of the first line call getchar cmp al, 0Ah jne .firstline .loop: ; read a byte from stdin call getchar ; is it a comma (or whatever the user asked for)? cmp al, dh jne .quote ; Replace the comma with a tab (or whatever the user wants) mov al, dl .put: call putchar jmp short .loop .quote: cmp al, '"' jne .put ; Print everything until you get another quote or EOL. If it ; is a quote, skip it. If it is EOL, print it. .qloop: call getchar cmp al, '"' je .loop cmp al, 0Ah je .put call putchar jmp short .qloop align 4 getchar: or ebx, ebx jne .fetch call read .fetch: lodsb dec ebx ret read: jecxz .read call write .read: push dword BUFSIZE mov esi, ibuffer push esi push dword [fd.in] sys.read add esp, byte 12 mov ebx, eax or eax, eax je .done sub eax, eax ret align 4 .done: call write ; flush output buffer ; close files push dword [fd.in] sys.close push dword [fd.out] sys.close ; return success push dword 0 sys.exit align 4 putchar: stosb inc ecx cmp ecx, BUFSIZE je write ret align 4 write: jecxz .ret ; nothing to write sub edi, ecx ; start of buffer push ecx push edi push dword [fd.out] sys.write add esp, byte 12 sub eax, eax sub ecx, ecx ; buffer is empty now .ret: ret .... Vieles daraus ist aus [.filename]#hex.asm# entnommen worden. Aber es gibt einen wichtigen Unterschied: Ich rufe nicht länger `write` auf, wann immer ich eine Zeilenvorschub ausgebe. Nun kann der Code sogar interaktiv genutzt werden. Ich habe eine bessere Lösung gefunden für das Interaktivitätsproblem seit ich mit dem Schreiben dieses Kapitels begonnen habe. Ich wollte sichergehen, daß jede Zeile einzeln ausgegeben werden kann, falls erforderlich. Aber schlussendlich gibt es keinen Bedarf jede Zeile einzeln auszugeben, falls nicht-interaktiv genutzt. Die neue Lösung besteht darin, die Funktion `write` jedesmal aufzurufen, wenn ich den Eingabepuffer leer vorfinde. Auf diesem Wege liest das Programm im interaktiven Modus eine Zeile aus der Tastatur des Nutzers, verarbeitet sie und stellt fest, ob deren Eingabepuffer leer ist, dann leert es seine Ausgabe und liest die nächste Zeile. [[x86-buffered-dark-side]] ==== Die dunkle Seite des Buffering Diese Änderung verhindert einen mysteriösen Aufhänger in einem speziellen Fall. Ich bezeichne dies als die _dunkle Seite des Buffering_, hauptsächlich, weil es eine nicht offensichtliche Gefahr darstellt. Es ist unwahrscheinlich, daß dies mit dem csv-Programm oben geschieht aber lassen Sie uns einen weiteren Filter betrachten: Nehmen wir an ihre Eingabe sind rohe Daten, die Farbwerte darstellen, wie z.B. die Intensität eines Pixel mit den Farben _rot_, _grün_ und _blau_. Unsere Ausgabe wird der negative Wert unserer Eingabe sein. Solch ein Filter würde sehr einfach zu schreiben sein. Der größte Teil davon würde so aussehen wie all die anderen Filter, die wir bisher geschrieben haben, daher beziehe ich mich nur auf den Kern der Prozedur: [.programlisting] .... .loop: call getchar not al ; Create a negative call putchar jmp short .loop .... Da dieser Filter mit rohen Daten arbeitet ist es unwahrscheinlich, daß er interaktiv genutzt werden wird. Aber das Programm könnte als Bildbearbeitungssoftware tituliert werden. Wenn es nicht `write` vor jedem Aufruf von `read` durchführt, ist die Möglichkeit gegeben, das es sich aufhängt. Dies könnte passieren: [.procedure] ==== . Der Bildeditor wird unseren Filter laden mittels der C-Funktion `popen()`. . Er wird die erste Zeile von Pixeln laden aus einer Bitmap oder Pixmap. . Er wird die erste Zeile von Pixeln geschrieben in die _Pipe_, welche zur Variable `fd.in` unseres Filters führt. . Unser Filter wird jeden Pixel von der Eingabe auslesen, diesen in seinen negativen Wert umkehren und ihn in den Ausgabepuffer schreiben. . Unser Filter wird die Funktion `getchar` aufrufen, um das nächste Pixel abzurufen. . Die Funktion `getchar` wird einen leeren Eingabepuffer vorfinden und daher die Funktion `read` aufrufen. . `read` wird den Systemaufruf `SYS_read` starten. . Der _Kernel_ wird unseren Filter unterbrechen, bis der Bildeditor mehr Daten zur Pipe sendet. . Der Bildedior wird aus der anderen Pipe lesen, welche verbunden ist mit `fd.out` unseres Filters, damit er die erste Zeile des auszugebenden Bildes setzen kann _bevor_ er uns die zweite Zeile der Eingabe einliest. . Der _Kernel_ unterbricht den Bildeditor, bis er eine Ausgabe unseres Filters erhält, um ihn an den Bildeditor weiterzureichen. ==== An diesem Punkt wartet unser Filter auf den Bildeditor, daß er ihm mehr Daten zur Verarbeitung schicken möge. Gleichzeitig wartet der Bildeditor darauf, daß unser Filter das Resultat der Berechnung ersten Zeile sendet. Aber das Ergebnis sitzt in unserem Ausgabepuffer. Der Filter und der Bildeditor werden fortfahren bis in die Ewigkeit aufeinander zu warten (oder zumindest bis sie per kill entsorgt werden). Unsere Software hat den eine <> erreicht. Das Problem tritt nicht auf, wenn unser Filter seinen Ausgabepuffer leert _bevor_ er vom _Kernel_ mehr Eingabedaten anfordert. [[x86-fpu]] == Die FPU verwenden Seltsamerweise erwähnt die meiste Literatur zu Assemblersprachen nicht einmal die Existenz der FPU, oder _floating point unit_ (Fließkomma-Recheneinheit), geschweige denn, daß auf die Programmierung mit dieser eingegangen wird. Dabei kann die Assemblerprogrammierung gerade bei hoch optimiertem FPU-Code, der _nur_ mit einer Assemblersprache realisiert werden kann, ihre große Stärke ausspielen. [[x86-fpu-organization]] === Organisation der FPU Die FPU besteht aus 8 80-bit Fließkomma-Registern. Diese sind in Form eines Stacks organisiert-Sie können einen Wert durch den Befehl `push` auf dem TOS (_top of stack_) ablegen, oder durch `pop` von diesem holen. Da also die Befehle `push` und `pop` schon verwendet werden, kann es keine op-Codes in Assemblersprache mit diesen Namen geben. Sie können mit einen Wert auf dem TOS ablegen, indem Sie `fld`, `fild`, und `fbld` verwenden. Mit weiteren op-Codes lassen sich _Konstanten_-wie z.B. _Pi_-auf dem TOS ablegen. Analog dazu können Sie einen Wert holen, indem Sie `fst`, `fstp`, `fist`, `fistp`, und `fbstp` verwenden. Eigentlich holen (`pop`) nur die op-Codes, die auf _p_ enden, einen Wert, während die anderen den Wert irgendwo speichern (`store`) ohne ihn vom TOS zu entfernen. Daten können zwischen dem TOS und dem Hauptspeicher als 32-bit, 64-bit oder 80-bit _real_, oder als 16-bit, 32-bit oder 64-bit _Integer_, oder als 80-bit _packed decimal_ übertragen werden. Das 80-bit _packed decimal_-Format ist ein Spezialfall des _binary coded decimal_-Formates, welches üblicherweise bei der Konvertierung zwischen der ASCII- und FPU-Darstellung von Daten verwendet wird. Dieses erlaubt die Verwendung von 18 signifikanten Stellen. Unabhängig davon, wie Daten im Speicher dargestellt werden, speichert die FPU ihre Daten immer im 80-bit _real_-Format in den Registern. Ihre interne Genauigkeit beträgt mindestens 19 Dezimalstellen. Selbst wenn wir also Ergebnisse im ASCII-Format mit voller 18-stelliger Genauigkeit darstellen lassen, werden immer noch korrekte Werte angezeigt. Des weiteren können mathematische Operationen auf dem TOS ausgeführt werden: Wir können dessen _Sinus_ berechnen, wir können ihn _skalieren_ (z.B. können wir ihn mit dem Faktor 2 Multiplizieren oder Dividieren), wir können dessen _Logarithmus_ zur Basis 2 nehmen, und viele weitere Dinge. Wir können auch FPU-Register _multiplizieren_, _dividieren_, _addieren_ und _subtrahieren_, sogar einzelne Register mit sich selbst. Der offizielle Intel op-Code für den TOS ist `st` und für die _Register_ `st(0)`- `st(7)`. `st` und `st(0)` beziehen sich dabei auf das gleiche Register. Aus welchen Gründen auch immer hat sich der Originalautor von nasm dafür entschieden, andere op-Codes zu verwenden, nämlich `st0`- `st7`. Mit anderen Worten, es gibt keine Klammern, und der TOS ist immer `st0`, niemals einfach nur `st`. [[x86-fpu-packed-decimal]] ==== Das Packed Decimal-Format Das _packed decimal_-Format verwendet 10 Bytes (80 Bits) zur Darstellung von 18 Ziffern. Die so dargestellte Zahl ist immer ein _Integer_. [TIP] ==== Sie können durch Multiplikation des TOS mit Potenzen von 10 die einzelnen Dezimalstellen verschieben. ==== Das höchste Bit des höchsten Bytes (Byte 9) ist das _Vorzeichenbit_: Wenn es gesetzt ist, ist die Zahl _negativ_, ansonsten _positiv_. Die restlichen Bits dieses Bytes werden nicht verwendet bzw. ignoriert. Die restlichen 9 Bytes enthalten die 18 Ziffern der gespeicherten Zahl: 2 Ziffern pro Byte. Die _signifikantere Ziffer_ wird in der _oberen Hälfte_ (4 Bits) eines Bytes gespeichert, die andere in der _unteren Hälfte_. Vielleicht würden Sie jetzt annehmen, das [constant]#-1234567# auf die folgende Art im Speicher abgelegt wird (in hexadezimaler Notation): [.programlisting] .... 80 00 00 00 00 00 01 23 45 67 .... Dem ist aber nicht so! Bei Intel werden alle Daten im _little-endian_-Format gespeichert, auch das _packed decimal_-Format. Dies bedeutet, daß [constant]#-1234567# wie folgt gespeichert wird: [.programlisting] .... 67 45 23 01 00 00 00 00 00 80 .... Erinnern Sie sich an diesen Umstand, bevor Sie sich aus lauter Verzweiflung die Haare ausreißen. [NOTE] ==== Das lesenswerte Buch-falls Sie es finden können-ist Richard Startz' http://www.int80h.org/cgi-bin/isbn?isbn=013246604X[ 8087/80287/80387 for the IBM PC & Compatibles]. Obwohl es anscheinend die Speicherung der _packed decimal_ im little-endian-Format für gegeben annimmt. Ich mache keine Witze über meine Verzweiflung, als ich den Fehler im unten stehenden Filter gesucht habe, _bevor_ mir einfiel, daß ich einfach mal versuchen sollte, das little-endian-Format, selbst für diesen Typ von Daten, anzuwenden. ==== [[x86-pinhole-photography]] === Ausflug in die Lochblendenphotographie Um sinnvolle Programme zu schreiben, müssen wir nicht nur unsere Programmierwerkzeuge beherrschen, sondern auch das Umfeld, für das die Programme gedacht sind. Unser nächster Filter wird uns dabei helfen, wann immer wir wollen, eine _Lochkamera_ zu bauen. Wir brauchen also etwas Hintergrundwissen über die _Lochblendenphotographie_, bevor wir weiter machen können. [[x86-camera]] ==== Die Kamera Die einfachste Form, eine Kamera zu beschreiben, ist die eines abgeschlossenen, lichtundurchlässigen Raumes, in dessen Abdeckung sich ein kleines Loch befindet. Die Abdeckung ist normalerweise fest (z.B. eine Schachtel), manchmal jedoch auch flexibel (z.B. ein Balgen). Innerhalb der Kamera ist es sehr dunkel. Nur durch ein kleines Loch kann Licht von einem einzigen Punkt aus in den Raum eindringen (in manchen Fällen sind es mehrere Löcher). Diese Lichtstrahlen kommen von einem Bild, einer Darstellung von dem was sich außerhalb der Kamera, vor dem kleinen Loch, befindet. Wenn ein lichtempfindliches Material (wie z.B. ein Film) in der Kamera angebracht wird, so kann dieses das Bild einfangen. Das Loch enthält häufig eine _Linse_, oder etwas linsenartiges, häufig auch einfach _Objektiv_ genannt. [[x86-the-pinhole]] ==== Die Lochblende Streng genommen ist die Linse nicht notwendig: Die ursprünglichen Kameras verwendeten keine Linse, sondern eine _Lochblende_. Selbst heutzutage werden noch _Lochblenden_ verwendet, zum einen, um die Funktionsweise einer Kamera zu erlernen, und zum anderen, um eine spezielle Art von Bildern zu erzeugen. Das Bild, das von einer _Lochblende_ erzeugt wird, ist überall scharf. Oder unscharf. Es gibt eine ideale Größe für eine Lochblende: Wenn sie größer oder kleiner ist, verliert das Bild seine Schärfe. [[x86-focal-length]] ==== Brennweite Dieser ideale Lochblendendurchmesser ist eine Funktion der Quadratwurzel der _Brennweite_, welche dem Abstand der Lochblende von dem Film entspricht. [.programlisting] .... D = PC * sqrt(FL) .... Hier ist `D` der ideale Durchmesser der Lochblende, `FL` die Brennweite und [constant]#PC# eine Konstante der Brennweite. Nach Jay Bender hat die Konstante den Wert [constant]#0.04#, nach Kenneth Connors [constant]#0.037#. Andere Leute haben andere Werte vorgeschlagen. Des weiteren gelten diese Werte nur für Tageslicht: Andere Arten von Licht benötigen andere konstante Werte, welche nur durch Experimente bestimmt werden können. [[x86-f-number]] ==== Der f-Wert Der f-Wert ist eine sehr nützliche Größe, die angibt, wieviel Licht den Film erreicht. Ein Belichtungsmesser kann dies messen, um z.B. für einen Film mit einer Empfindlichkeit von f5.6 eine Belichtungsdauer von 1/1000 Sekunden auszurechnen. Es spielt keine Rolle, ob es eine 35-mm- oder eine 6x9cm-Kamera ist, usw. Solange wir den f-Wert kennen, können wir die benötigte Belichtungszeit berechnen. Der f-Wert läßt sich einfach wie folgt berechnen: [.programlisting] .... F = FL / D .... Mit anderen Worten, der f-Wert ergibt sich aus der Brennweite (FL), dividiert durch den Durchmesser (D) der Lochblende. Ein großer f-Wert impliziert also entweder eine kleine Lochblende, oder eine große Brennweite, oder beides. Je größer also der f-Wert ist, um so länger muß die Belichtungszeit sein. Des weiteren sind der Lochblendendurchmesser und die Brennweite eindimensionale Meßgrößen, während der Film und die Lochblende an sich zweidimensionale Objekte darstellen. Das bedeutet, wenn man für einen f-Wert `A` eine Belichtungsdauer `t` bestimmt hat, dann ergibt sich daraus für einen f-Wert `B` eine Belichtungszeit von: [.programlisting] .... t * (B / A)² .... [[x86-normalized-f-number]] ==== Normalisierte f-Werte Während heutige moderne Kameras den Durchmesser der Lochblende, und damit deren f-Wert, weich und schrittweise verändern können, war dies früher nicht der Fall. Um unterschiedliche f-Werte einstellen zu können, besaßen Kameras typischerweise eine Metallplatte mit Löchern unterschiedlichen Durchmessers als Lochblende. Die Durchmesser wurden entsprechend obiger Formel gewählt, daß der resultierende f-Wert ein fester Standardwert war, der für alle Kameras verwendet wurde. Z.B. hat eine sehr alte Kodak Duaflex IV Kamera in meinem Besitz drei solche Löcher für die f-Werte 8, 11 und 16. Eine neuere Kamera könnte f-Werte wie 2.8, 4, 5.6, 8, 11, 16, 22, und 32 (und weitere) besitzen. Diese Werte wurden nicht zufällig ausgewählt: Sie sind alle vielfache der Quadratwurzel aus 2, wobei manche Werte gerundet wurden. [[x86-f-stop]] ==== Der f-Stopp Eine typische Kamera ist so konzipiert, daß die Nummernscheibe bei den normalisierten f-Werten einrastet. Die Nummernscheibe _stoppt_ an diesen Positionen. Daher werden diese Positionen auch f-Stopps genannt. Da die f-Werte bei jedem Stopp vielfache der Quadratwurzel aus 2 sind, verdoppelt die Drehung der Nummernscheibe um einen Stopp die für die gleiche Belichtung benötigte Lichtmenge. Eine Drehung um 2 Stopps vervierfacht die benötigte Belichtungszeit. Eine Drehung um 3 Stopps verachtfacht sie, etc. [[x86-pinhole-software]] === Entwurf der Lochblenden-Software Wir können jetzt festlegen, was genau unsere Lochblenden-Software tun soll. [[xpinhole-processing-input]] ==== Verarbeitung der Programmeingaben Da der Hauptzweck des Programms darin besteht, uns beim Entwurf einer funktionierenden Lochkamera zu helfen, wird die _Brennweite_ die Programmeingabe sein. Dies ist etwas, das wir ohne zusätzliche Programme feststellen können: Die geeignete Brennweite ergibt sich aus der Größe des Films und der Art des Fotos, ob dieses ein "normales" Bild, ein Weitwinkelbild oder ein Telebild sein soll. Die meisten bisher geschriebenen Programme arbeiteten mit einzelnen Zeichen, oder Bytes, als Eingabe: Das hex-Programm konvertierte einzelne Bytes in hexadezimale Werte, das csv-Programm ließ entweder einzelne Zeichen unverändert, löschte oder veränderte sie, etc. Das Programm ftuc verwendete einen Zustandsautomaten, um höchstens zwei gleichzeitig eingegebene Bytes zu verarbeiten. Das pinhole-Programm dagegen kann nicht nur mit einzelnen Zeichen arbeiten, sondern muß mit größeren syntaktischen Einheiten zurrecht kommen. Wenn wir z.B. möchten, daß unser Programm den Lochblendendurchmesser (und weitere Werte, die wir später noch diskutieren werden) für die Brennweiten [constant]#100 mm#, [constant]#150 mm# und [constant]#210 mm# berechnet, wollen wir etwa folgendes eingeben: [source,shell] .... 100, 150, 210 .... Unser Programm muß mit der gleichzeitigen Eingabe von mehr als nur einem einzelnen Byte zurecht kommen. Wenn es eine [constant]#1# erkennt, muß es wissen, daß dies die erste Stelle einer dezimalen Zahl ist. Wenn es eine [constant]#0#, gefolgt von einer weiteren [constant]#0# sieht, muß es wissen, daß dies zwei unterschiedliche Stellen mit der gleichen Zahl sind. Wenn es auf das erste Komma trifft, muß es wissen, daß die folgenden Stellen nicht mehr zur ersten Zahl gehören. Es muß die Stellen der ersten Zahl in den Wert [constant]#100# konvertieren können. Und die Stellen der zweiten Zahl müssen in den Wert [constant]#150# konvertiert werden. Und die Stellen der dritten Zahl müssen in den Wert [constant]#210# konvertiert werden. Wir müssen festlegen, welche Trennsymbole zulässig sind: Sollen die Eingabewerte durch Kommas voneinander getrennt werden? Wenn ja, wie sollen zwei Zahlen behandelt werden, die durch ein anderes Zeichen getrennt sind? Ich persönlich mag es einfach. Entweder etwas ist eine Zahl, dann wird es verarbeitet, oder es ist keine Zahl, dann wird es verworfen. Ich mag es nicht, wenn sich der Computer bei der _offensichtlichen_ Eingabe eines zusätzlichen Zeichens beschwert. Duh! Zusätzlich erlaubt es mir, die Monotonie des Tippens zu durchbrechen, und eine Anfrage anstelle einer simplen Zahl zu stellen: [source,shell] .... Was ist der beste Lochblendendurchmesser bei einer Brennweite von 150? .... Es gibt keinen Grund dafür, die Ausgabe mehrerer Fehlermeldungen aufzuteilen: [source,shell] .... Syntax error: Was Syntax error: ist Syntax error: der Syntax error: beste .... Et cetera, et cetera, et cetera. Zweitens mag ich das [constant]###-Zeichen, um Kommentare zu markieren, die ab dem Zeichen bis zum Ende der jeweiligen Zeile gehen. Dies verlangt nicht viel Programmieraufwand, und ermöglicht es mir, Eingabedateien für meine Programme als ausführbare Skripte zu handhaben. In unserem Fall müssen wir auch entscheiden, in welchen Einheiten die Dateneingabe erfolgen soll: Wir wählen _Millimeter_, da die meisten Photographen die Brennweite in dieser Einheit messen. Letztendlich müssen wir noch entscheiden, ob wir die Verwendung des dezimalen Punktes erlauben (in diesem Fall müssen wir berücksichtigen, daß in vielen Ländern der Welt das dezimale _Komma_ verwendet wird). In unserem Fall würde das Zulassen eines dezimalen Punktes/Kommas zu einer fälschlicherweise angenommenen, höheren Genauigkeit führen: Der Unterschied zwischen den Brennweiten [constant]#50# und [constant]#51# ist fast nicht wahrnehmbar. Die Zulassung von Eingaben wie [constant]#50.5# ist also keine gute Idee. Beachten Sie bitte, das dies meine Meinung ist. In diesem Fall bin ich der Autor des Programmes. Bei Ihren eigenen Programmen müssen Sie selbst solche Entscheidungen treffen. [[x86-pinhole-options]] ==== Optionen anbieten Das wichtigste, was wir zum Bau einer Lochkamera wissen müssen, ist der Durchmesser der Lochblende. Da wir scharfe Bilder schießen wollen, werden wir obige Formel für die Berechnung des korrekten Durchmessers zu gegebener Brennweite verwenden. Da Experten mehrere Werte für die [constant]#PC#-Konstante anbieten, müssen wir uns hier für einen Wert entscheiden. In der Programmierung unter UNIX(R) ist es üblich, zwei Hauptvarianten anzubieten, um Parameter an Programme zu übergeben, und des weiteren eine Standardeinstellung für den Fall zu haben, das der Benutzer gar keine Parameter angibt. Warum zwei Varianten, Parameter anzugeben? Ein Grund ist, eine (relativ) _feste_ Einstellung anzubieten, die automatisch bei jedem Programmaufruf verwendet wird, ohne das wir diese Einstellung immer und immer wieder mit angeben müssen. Die feste Einstellung kann in einer Konfigurationsdatei gespeichert sein, typischerweise im Heimatverzeichnis des Benutzers. Die Datei hat üblicherweise denselben Namen wie das zugehörige Programm, beginnt jedoch mit einem Punkt. Häufig wird _"rc"_ dem Dateinamen hinzugefügt. Unsere Konfigurationsdatei könnte also [.filename]#~/.pinhole# oder [.filename]#~/.pinholerc# heißen. (Die Zeichenfolge [.filename]#~/# steht für das Heimatverzeichnis des aktuellen Benutzers.) Konfigurationsdateien werden häufig von Programmen verwendet, die viele konfigurierbare Parameter besitzen. Programme, die nur eine (oder wenige) Parameter anbieten, verwenden häufig eine andere Methode: Sie erwarten die Parameter in einer _Umgebungsvariablen_. In unserem Fall könnten wir eine Umgebungsvariable mit dem Namen `PINHOLE` benutzen. Normalerweise verwendet ein Programm entweder die eine, oder die andere der beiden obigen Methoden. Ansonsten könnte ein Programm verwirrt werden, wenn eine Konfigurationsdatei das eine sagt, die Umgebungsvariable jedoch etwas anderes. Da wir nur _einen_ Parameter unterstützen müssen, verwenden wir die zweite Methode, und benutzen eine Umgebungsvariable mit dem Namen `PINHOLE`. Der andere Weg erlaubt uns, _ad hoc_ Entscheidungen zu treffen: _"Obwohl ich normalerweise einen Wert von 0.039 verwende, will ich dieses eine Mal einen Wert von 0.03872 anwenden."_ Mit anderen Worten, dies erlaubt uns, die Standardeinstellung außer Kraft zu setzen. Diese Art der Auswahl wird häufig über Kommandozeilenparameter gemacht. Schließlich braucht ein Programm _immer_ eine _Standardeinstellung_. Der Benutzer könnte keine Parameter angeben. Vielleicht weiß er auch gar nicht, was er einstellen sollte. Vielleicht will er es "einfach nur ausprobieren". Vorzugsweise wird die Standardeinstellung eine sein, die die meisten Benutzer sowieso wählen würden. Somit müssen diese keine zusätzlichen Parameter angeben, bzw. können die Standardeinstellung ohne zusätzlichen Aufwand benutzen. Bei diesem System könnte das Programm widersprüchliche Optionen vorfinden, und auf die folgende Weise reagieren: [.procedure] ==== . Wenn es eine _ad hoc_-Einstellung vorfindet (z.B. ein Kommandozeilenparameter), dann sollte es diese Einstellung annehmen. Es muß alle vorher festgelegten sowie die standardmäßige Einstellung ignorieren. . _Andererseits_, wenn es eine festgelegte Option (z.B. eine Umgebungsvariable) vorfindet, dann sollte es diese akzeptieren und die Standardeinstellung ignorieren. . _Ansonsten_ sollte es die Standardeinstellung verwenden. ==== Wir müssen auch entscheiden, welches _Format_ unsere [constant]#PC#-Option haben soll. Auf den ersten Blick scheint es einleuchtend, das Format `PINHOLE=0.04` für die Umgebungsvariable, und [parameter]#-p0.04# für die Kommandozeile zu verwenden. Dies zuzulassen wäre eigentlich eine Sicherheitslücke. Die [constant]#PC#-Konstante ist eine sehr kleine Zahl. Daher würden wir unsere Anwendung mit verschiedenen, kleinen Werten für [constant]#PC# testen. Aber was würde passieren, wenn jemand das Programm mit einem sehr großen Wert aufrufen würde? Es könnte abstürzen, weil wir das Programm nicht für den Umgang mit großen Werten entworfen haben. Oder wir investieren noch weiter Zeit in das Programm, so daß dieses dann auch mit großen Zahlen umgehen kann. Wir könnten dies machen, wenn wir kommerzielle Software für computertechnisch unerfahrene Benutzer schreiben würden. Oder wir könnten auch sagen _"Pech gehabt! Der Benutzer sollte es besser wissen."_ Oder wir könnten es für den Benutzer unmöglich machen, große Zahlen einzugeben. Dies ist die Variante, die wir verwenden werden: Wir nehmen einen _impliziten 0._-Präfix an. Mit anderen Worten, wenn der Benutzer den Wert [constant]#0.04# angeben will, so muß er entweder [parameter]#-p04# als Parameter angeben, oder `PINHOLE=04` als Variable in seiner Umgebung definieren. Falls der Benutzer [parameter]#-p9999999# angibt, so wird dies als [constant]#0.9999999# interpretiert-zwar immer noch sinnlos, aber zumindest sicher. Zweitens werden viele Benutzer einfach die Konstanten von Bender oder Connors benutzen wollen. Um es diesen Benutzern einfacher zu machen, werden wir [parameter]#-b# als [parameter]#-p04#, und [parameter]#-c# als [parameter]#-p037# interpretieren. [[x86-pinhole-output]] ==== Die Ausgabe Wir müssen festlegen, was und in welchem Format unsere Anwendung Daten ausgeben soll. Da wir als Eingabe beliebig viele Brennweiten erlauben, macht es Sinn, die Ergebnisse in Form einer traditionellen Datenbank-Ausgabe darzustellen, bei der zeilenweise zu jeder Brennweite der zugehörige berechnete Wert, getrennt durch ein [constant]#tab#-Zeichen, ausgegeben wird. Optional sollten wir dem Benutzer die Möglichkeit geben, die Ausgabe in dem schon beschriebenen CSV-Format festzulegen. In diesem Fall werden wir zu Beginn der Ausgabe eine Zeile einfügen, in der die Beschreibungen der einzelnen Felder, durch Kommas getrennt, aufgelistet werden, gefolgt von der Ausgabe der Daten wie schon beschrieben, wobei das [constant]#tab#-Zeichen durch ein [constant]#Komma# ersetzt wird. Wir brauchen eine Kommandozeilenoption für das CSV-Format. Wir können nicht [parameter]#-c# verwenden, da diese Option bereits für _verwende Connors Konstante_ steht. Aus irgendeinem seltsamen Grund bezeichnen viele Webseiten CSV-Dateien als _"Excel Kalkulationstabelle"_ (obwohl das CSV-Format älter ist als Excel). Wir werden daher [parameter]#-e# als Schalter für die Ausgabe im CSV-Format verwenden. Jede Zeile der Ausgabe wird mit einer Brennweite beginnen. Dies mag auf den ersten Blick überflüssig erscheinen, besonders im interaktiven Modus: Der Benutzer gibt einen Wert für die Brennweite ein, und das Programm wiederholt diesen. Der Benutzer kann jedoch auch mehrere Brennweiten in einer Zeile angeben. Die Eingabe kann auch aus einer Datei, oder aus der Ausgabe eines anderen Programmes, kommen. In diesen Fällen sieht der Benutzer die Eingabewerte überhaupt nicht. Ebenso kann die Ausgabe in eine Datei umgelenkt werden, was wir später noch untersuchen werden, oder sie könnte an einen Drucker geschickt werden, oder auch als Eingabe für ein weiteres Programm dienen. Es macht also wohl Sinn, jede Zeile mit einer durch den Benutzer eingegebenen Brennweite beginnen zu lassen. Halt! Nicht, wie der Benutzer die Daten eingegeben hat. Was passiert, wenn der Benutzer etwas wie folgt eingibt: [source,shell] .... 00000000150 .... Offensichtlich müssen wir die führenden Nullen vorher abschneiden. Wir müssen also die Eingabe des Benutzers sorgfältig prüfen, diese dann in der FPU in die binäre Form konvertieren, und dann von dort aus ausgeben. Aber... Was ist, wenn der Benutzer etwas wie folgt eingibt: [source,shell] .... 17459765723452353453534535353530530534563507309676764423 .... Ha! Das packed decimal-Format der FPU erlaubt uns die Eingabe einer 18-stelligen Zahl. Aber der Benutzer hat mehr als 18 Stellen eingegeben. Wie gehen wir damit um? Wir _könnten_ unser Programm so modifizieren, daß es die ersten 18 Stellen liest, der FPU übergibt, dann weitere 18 Stellen liest, den Inhalt des TOS mit einem Vielfachen von 10, entsprechend der Anzahl der zusätzlichen Stellen multipliziert, und dann beide Werte mittels `add` zusammen addiert. Ja, wir könnten das machen. Aber in _diesem_ Programm wäre es unnötig (in einem anderen wäre es vielleicht der richtige Weg): Selbst der Erdumfang in Millimetern ergibt nur eine Zahl mit 11 Stellen. Offensichtlich können wir keine Kamera dieser Größe bauen (jedenfalls jetzt noch nicht). Wenn der Benutzer also eine so große Zahl eingibt, ist er entweder gelangweilt, oder er testet uns, oder er versucht, in das System einzudringen, oder er spielt- indem er irgendetwas anderes macht als eine Lochkamera zu entwerfen. Was werden wir tun? Wir werden ihn ohrfeigen, gewissermaßen: [source,shell] .... 17459765723452353453534535353530530534563507309676764423 ??? ??? ??? ??? ??? .... Um dies zu erreichen, werden wir einfach alle führenden Nullen ignorieren. Sobald wir eine Ziffer gefunden haben, die nicht Null ist, initialisieren wir einen Zähler mit [constant]#0# und beginnen mit drei Schritten: [.procedure] ==== . Sende die Ziffer an die Ausgabe. . Füge die Ziffer einem Puffer hinzu, welchen wir später benutzen werden, um den packed decimal-Wert zu erzeugen, den wir an die FPU schicken können. . Erhöhe den Zähler um eins. ==== Während wir diese drei Schritte wiederholen, müssen wir auf zwei Bedingungen achten: * Wenn der Zähler den Wert 18 übersteigt, hören wir auf, Ziffern dem Puffer hinzuzufügen. Wir lesen weiterhin Ziffern und senden sie an die Ausgabe. * Wenn, bzw. _falls_, das nächste Eingabezeichen keine Zahl ist, sind wir mit der Bearbeitung der Eingabe erst einmal fertig. + Übrigends können wir einfach Zeichen, die keine Ziffern sind, verwerfen, solange sie kein [constant]###-Zeichen sind, welches wir an den Eingabestrom zurückgeben müssen. Dieses Zeichen markiert den Beginn eines Kommentars. An dieser Stelle muß die Erzeugung der Ausgabe fertig sein, und wir müssen mit der Suche nach weiteren Eingabedaten fortfahren. Es bleibt immer noch eine Möglichkeit unberücksichtigt: Wenn der Benutzer eine Null (oder mehrere) eingibt, werden wir niemals eine von Null verschiedene Zahl vorfinden. Wir können solch einen Fall immer anhand des Zählerstandes feststellen, welcher dann immer bei [constant]#0# bleibt. In diesem Fall müssen wir einfach eine [constant]#0# an die Ausgabe senden, und anschließend dem Benutzer erneut eine "Ohrfeige" verpassen: [source,shell] .... 0 ??? ??? ??? ??? ??? .... Sobald wir die Brennweite ausgegeben, und die Gültigkeit dieser Eingabe verifiziert haben, (größer als [constant]#0# und kleiner als 18 Zahlen) können wir den Durchmesser der Lochblende berechnen. Es ist kein Zufall, daß _Lochblende_ das Wort _Loch_ enthält. In der Tat ist eine Lochblende buchstäblich eine _Loch Blende_, also eine Blende, in die mit einer Nadel vorsichtig ein kleines Loch gestochen wird. Daher ist eine typische Lochblende sehr klein. Unsere Formel liefert uns das Ergebnis in Millimetern. Wir werden dieses mit [constant]#1000# multiplizieren, so daß die Ausgabe in [constant]#Mikrometern# erfolgt. An dieser Stelle müssen wir auf eine weitere Falle achten: _Zu hohe Genauigkeit._ Ja, die FPU wurde für mathematische Berechnungen mit hoher Genauigkeit entworfen. Unsere Berechnungen hier erfordern jedoch keine solche mathematische Genauigkeit. Wir haben es hier mit Physik zu tun (Optik, um genau zu sein). Angenommen, wir wollten aus eine Lastkraftwagen eine Lochkamera bauen (wir wären dabei nicht die ersten, die das versuchen würden!). Angenommen, die Länge des Laderaumes beträgt [constant]#12# Meter lang, so daß wir eine Brennweite von [constant]#12000# hätten. Verwenden wir Benders Konstante, so erhalten wir durch Multiplizieren von [constant]#0.04# mit der Quadratwurzel aus [constant]#12000# einen Wert von [constant]#4.381780460# Millimetern, oder [constant]#4381.780460# Micrometern. So oder so ist das Rechenergebnis absurd präzise. Unser Lastkraftwagen ist nicht _genau_[constant]#12000# Millimeter lang. Wir haben diese Länge nicht mit einer so hohen Genauigkeit gemessen, weswegen es falsch wäre zu behaupten, unser Lochblendendurchmesser müsse exakt [constant]#4.381780460# Millimeter sein. Es reicht vollkommen aus, wenn der Durchmesser [constant]#4.4# Millimeter beträgt. [NOTE] ==== Ich habe in obigem Beispiel das Rechenergebnis "nur" auf 10 Stellen genau angegeben. Stellen Sie sich vor, wie absurd es wäre, die vollen uns zur Verfügung stehenden, 18 Stellen anzugeben! ==== Wir müssen also die Anzahl der signifikanten Stellen beschränken. Eine Möglichkeit wäre, die Mikrometer durch eine ganze Zahl darzustellen. Unser Lastkraftwaren würde dann eine Lochblende mit einem Durchmesser von [constant]#4382# Mikrometern benötigen. Betrachten wir diesen Wert, dann stellen wir fest, das [constant]#4400# Mikrometer, oder [constant]#4.4# Millimeter, immer noch genau genug ist. Zusätzlich können wir noch, unabhängig von der Größe eines Rechenergebnisses, festlegen, daß wir nur vier signifikante Stellen anzeigen wollen (oder weniger). Leider bietet uns die FPU nicht die Möglichkeit, das Ergebnis automatisch bis auf eine bestimmte Stelle zu runden (sie sieht die Daten ja nicht als Zahlen, sondern als binäre Daten an). Wir müssen also selber einen Algorithmus entwerfen, um die Anzahl der signifikanten Stellen zu reduzieren. Hier ist meiner (ich denke er ist peinlich-wenn Ihnen ein besserer Algorithmus einfällt, verraten sie ihn mir _bitte_): [.procedure] ==== . Initialisiere einen Zähler mit [constant]#0#. . Solange die Zahl größer oder gleich [constant]#10000# ist, dividiere die Zahl durch [constant]#10#, und erhöhe den Zähler um eins. . Gebe das Ergebnis aus. . Solange der Zähler größer als [constant]#0# ist, gebe eine [constant]#0# aus, und reduziere den Zähler um eins. ==== [NOTE] ==== Der Wert [constant]#10000# ist nur für den Fall, daß Sie _vier_ signifikante Stellen haben wollen. Für eine andere Anzahl signifikanter Stellen müssen Sie den Wert [constant]#10000# mit [constant]#10#, hoch der Anzahl der gewünschten signifikanten Stellen, ersetzen. ==== Wir können so den Lochblendendurchmesser, auf vier signifikante Stellen gerundet, ausgeben. An dieser Stellen kennen wir nun die _Brennweite_ und den _Lochblendendurchmesser_. Wir haben also jetzt genug Informationen, um den _f-Wert_ zu bestimmen. Wir werden den f-Wert, auf vier signifikante Stellen gerundet, ausgeben. Es könnte passieren, daß diese vier Stellen recht wenig aussagen. Um die Aussagekraft des f-Wertes zu erhöhen, könnten wir den nächstliegenden, _normalisierten f-Wert_ bestimmen, also z.B. das nächstliegende Vielfache der Quadratwurzel aus 2. Wir erreichen dies, indem wir den aktuellen f-Wert mit sich selbst multiplizieren, so daß wir dessen Quadrat (`square`) erhalten. Anschließend berechnen wir den Logarithmus zur Basis 2 von dieser Zahl. Dies ist sehr viel einfacher, als direkt den Logarithmus zur Basis der Quadratwurzel aus 2 zu berechnen! Wir runden dann das Ergebnis auf die nächstliegende ganze Zahl. Genau genommen können wir mit Hilfe der FPU diese Berechnung beschleunigen: Wir können den op-Code `fscale` verwenden, um eine Zahl um 1 zu "skalieren", was dasselbe ist, wie eine Zahl mittels `shift` um eine Stelle nach links zu verschieben. Am Ende berechnen wir noch die Quadratwurzel aus allem, und erhalten dann den nächstliegenden, normalisierten f-Wert. Wenn das alles jetzt viel zu kompliziert wirkt-oder viel zu aufwendig-wird es vielleicht klarer, wenn man den Code selber betrachtet. Wir benötigen insgesamt 9 op-Codes: [.programlisting] .... fmul st0, st0 fld1 fld st1 fyl2x frndint fld1 fscale fsqrt fstp st1 .... Die erste Zeile, `fmul st0, st0`, quadriert den Inhalt des TOS (Top Of Stack, was dasselbe ist wie `st`, von nasm auch `st0` genannt). Die Funktion `fld1` fügt eine [constant]#1# dem TOS hinzu. Die nächste Zeile, `fld st1`, legt das Quadrat auf dem TOS ab. An diesem Punkt befindet sich das Quadrat sowohl in `st` als auch in `st(2)` (es wird sich gleich zeigen, warum wir eine zweite Kopie auf dem Stack lassen.) `st(1)` enthält die [constant]#1#. Im nächsten Schritt, `fyl2x`, wird der Logarithmus von `st` zur Basis 2 berechnet, und anschließend mit `st(1)` multipliziert. Deshalb haben wir vorher die [constant]#1# in `st(1)` abgelegt. An dieser Stelle enthält `st` den gerade berechneten Logarithmus, und `st(1)` das Quadrat des aktuellen f-Wertes, den wir für später gespeichert haben. `frndint` rundet den TOS zur nächstliegenden ganzen Zahl. `fld1` legt eine [constant]#1# auf dem Stack ab. `fscale` shiftet die [constant]#1# auf dem TOS um `st(1)` Stellen, wodurch im Endeffekt eine 2 in `st(1)` steht. Schließlich berechnet `fsqrt` die Quadratwurzel des Rechenergebnisses, also des nächstliegenden, normalisierten f-Wertes. Wir haben nun den nächstliegenden, normalisierten f-Wert auf dem TOS liegen, den auf den Logarithmus zur Basis 2 gerundeten, nächstliegenden ganzzahligen Wert in `st(1)`, und das Quadrat des aktuellen f-Wertes in `st(2)`. Wir speichern den Wert für eine spätere Verwendung in `st(2)`. Aber wir brauchen den Inhalt von `st(1)` gar nicht mehr. Die letzte Zeile, `fstp st1`, platziert den Inhalt von `st` in `st(1)`, und erniedrigt den Stackpointer um eins. Dadurch ist der Inhalt von `st(1)` jetzt `st`, der Inhalt von `st(2)` jetzt `st(1)` usw. Der neue `st` speichert jetzt den normalisierten f-Wert. Der neue `st(1)` speichert das Quadrat des aktuellen f-Wertes für die Nachwelt. Jetzt können wir den normalisierten f-Wert ausgeben. Da er normalisiert ist, werden wir ihn nicht auf vier signifikante Stellen runden, sondern stattdessen mit voller Genauigkeit ausgeben. Der normalisierte f-Wert ist nützlich, solange er so klein ist, daß wir ihn auf einem Photometer wiederfinden können. Ansonsten brauchen wir eine andere Methode, um die benötigten Belichtungsdaten zu bestimmen. Wir haben weiter oben eine Formel aufgestellt, über die wir einen f-Wert mit Hilfe eines anderen f-Wertes und den zugehörigen Belichtungsdaten bestimmen können. Jedes Photometer, das ich jemals gesehen habe, konnte die benötigte Belichtungszeit für f5.6 berechnen. Wir werden daher einen _"f5.6 Multiplizierer"_ berechnen, der uns den Faktor angibt, mit dem wir die bei f5.6 gemessene Belichtungszeit für unsere Lochkamera multiplizieren müssen. Durch die Formel wissen wir, daß dieser Faktor durch Dividieren unseres f-Wertes (der aktuelle Wert, nicht der normalisierte) durch [constant]#5.6# und anschließendes Quadrieren, berechnen können. Mathematisch äquivalent dazu wäre, wenn wir das Quadrat unseres f-Wertes durch das Quadrat von [constant]#5.6# dividieren würden. Numerisch betrachtet wollen wir nicht zwei Zahlen quadrieren, wenn es möglich ist, nur eine Zahl zu quadrieren. Daher wirkt die erste Variante auf den ersten Blick besser. Aber... [constant]#5.6# ist eine _Konstante_. Wir müssen nicht wertvolle Rechenzeit der FPU verschwenden. Es reicht aus, daß wir die Quadrate der einzelnen f-Werte durch den konstanten Wert [constant]#5.6²# dividieren. Oder wir können den jeweiligen f-Wert durch [constant]#5.6# dividieren, und dann das Ergebnis quadrieren. Zwei Möglichkeiten, die gleich erscheinen. Aber das sind sie nicht! Erinnern wir uns an die Grundlagen der Photographie weiter oben, dann wissen wir, daß sich die Konstante [constant]#5.6# aus dem 5-fachen der Quadratwurzel aus 2 ergibt. Eine _irrationale_ Zahl. Das Quadrat dieser Zahl ist _exakt_[constant]#32#. [constant]#32# ist nicht nur eine ganze Zahl, sondern auch ein Vielfaches von 2. Wir brauchen also gar nicht das Quadrat eines f-Wertes durch [constant]#32# zu teilen. Wir müssen lediglich mittels `fscale` den f-Wert um fünf Stellen nach rechts shiften. Aus Sicht der FPU müssen wir also `fscale` mit `st(1)`, welcher gleich [constant]#-5# ist, auf den f-Wert anwenden. Dies ist _sehr viel schneller_ als die Division. Jetzt wird es auch klar, warum wir das Quadrat des f-Wertes ganz oben auf dem Stack der FPU gespeichert haben. Die Berechnung des f5.6 Multiplizierers ist die einfachste Berechnung des gesamten Programmes! Wir werden das Ergebnis auf vier signifikante Stellen gerundet ausgeben. Es gibt noch eine weitere nützliche Zahl, die wir berechnen können: Die Anzahl der Stopps, die unser f-Wert von f5.6 entfernt ist. Dies könnte hilfreich sein, wenn unser f-Wert außerhalb des Meßbereiches unseres Photometers liegt, wir aber eine Blende haben, bei der wir unterschiedliche Geschwindigkeiten einstellen können, und diese Blende Stopps benutzt. Angenommen, unser f-Wert ist 5 Stopps von f5.6 entfernt, und unser Photometer sagt uns, daß wir eine Belichtungszeit von 1/1000 Sek. einstellen sollen. Dann können wir unsere Blende auf die Geschwindigkeit 1/1000 einstellen, und unsere Skala um 5 Stopps verschieben. Diese Rechnung ist ebenfalls sehr einfach. Alles, was wir tun müssen, ist, den Logarithmus des f5.6 Multiplizierers, den wir schon berechnet haben (wobei wir dessen Wert vor der Rundung nehmen müssen) zur Basis 2 zu nehmen. Wir runden dann das Ergebnis zur nächsten ganzen Zahl hin, und geben dies aus. Wir müssen uns nicht darum kümmern, ob wir mehr als vier signifikante Stellen haben: Das Ergebnis besteht höchstwahrscheinlich nur aus einer oder zwei Stellen. [[x86-fpu-optimizations]] === FPU Optimierungen In Assemblersprache können wir den Code für die FPU besser optimieren, als in einer der Hochsprachen, inklusive C. Sobald eine C-Funktion die Berechnung einer Fließkommazahl durchführen will, lädt sie erst einmal alle benötigten Variablen und Konstanten in die Register der FPU. Dann werden die Berechnungen durchgeführt, um das korrekte Ergebnis zu erhalten. Gute C-Compiler können diesen Teil des Codes sehr gut optimieren. Das Ergebnis wird "zurückgegeben", indem dieses auf dem TOS abgelegt wird. Vorher wird aufgeräumt. Sämtliche Variablen und Konstanten, die während der Berechnung verwendet wurden, werden dabei aus der FPU entfernt. Was wir im vorherigen Abschnitt selber getan haben, kann so nicht durchgeführt werden: Wir haben das Quadrat des f-Wertes berechnet, und das Ergebnis für eine weitere Berechnung mit einer anderen Funktion auf dem Stack behalten. Wir _wußten_, daß wir diesen Wert später noch einmal brauchen würden. Wir wußten auch, daß auf dem Stack genügend Platz war (welcher nur Platz für 8 Zahlen bietet), um den Wert dort zu speichern. Ein C-Compiler kann nicht wissen, ob ein Wert auf dem Stack in naher Zukunft noch einmal gebraucht wird. Natürlich könnte der C-Programmierer dies wissen. Aber die einzige Möglichkeit, die er hat, ist, den Wert im verfügbaren Speicher zu halten. Das bedeutet zum einen, daß der Wert mit der FPU-internen, 80-stelligen Genauigkeit in einer normalen C-Variable vom Typ _double_ (64 Bit) oder vom Typ _single_ (32 Bit) gespeichert wird. Dies bedeutet außerdem, daß der Wert aus dem TOS in den Speicher verschoben werden muß, und später wieder zurück. Von allen Operationen mit der FPU ist der Zugriff auf den Speicher die langsamste. Wann immer also mit der FPU in einer Assemblersprache programmiert wird, sollte nach Möglichkeiten gesucht werden, Zwischenergebnisse auf dem Stack der FPU zu lassen. Wir können mit dieser Idee noch einen Schritt weiter gehen! In unserem Programm verwenden wir eine _Konstante_ (die wir [constant]#PC# genannt haben). Es ist unwichtig, wieviele Lochblendendurchmesser wir berechnen: 1, 10, 20, 1000, wir verwenden immer dieselbe Konstante. Daher können wir unser Programm so optimieren, daß diese Konstante immer auf dem Stack belassen wird. Am Anfang unseres Programmes berechnen wir die oben erwähnte Konstante. Wir müssen die Eingabe für jede Dezimalstelle der Konstanten durch [constant]#10# dividieren. Multiplizieren geht sehr viel schneller als Dividieren. Wir teilen also zu Beginn unseres Programmes [constant]#1# durch [constant]#10#, um [constant]#0.1# zu erhalten, was wir auf dem Stack speichern: Anstatt daß wir nun für jede einzelne Dezimalstelle die Eingabe wieder durch [constant]#10# teilen, multiplizieren wir sie stattdessen mit [constant]#0.1#. Auf diese Weise geben wir [constant]#0.1# nicht direkt ein, obwohl wir dies könnten. Dies hat einen Grund: Während [constant]#0.1# durch nur eine einzige Dezimalstelle dargestellt werden kann, wissen wir nicht, wieviele _binäre_ Stellen benötigt werden. Wir überlassen die Berechnung des binären Wertes daher der FPU, mit dessen eigener, hoher Genauigkeit. Wir verwenden noch weitere Konstanten: Wir multiplizieren den Lochblendendurchmesser mit [constant]#1000#, um den Wert von Millimeter in Micrometer zu konvertieren. Wir vergleichen Werte mit [constant]#10000#, wenn wir diese auf vier signifikante Stellen runden wollen. Wir behalten also beide Konstanten, [constant]#1000# und [constant]#10000#, auf dem Stack. Und selbstverständlich verwenden wir erneut die gespeicherte [constant]#0.1#, um Werte auf vier signifikante Stellen zu runden. Zu guter letzt behalten wir [constant]#-5# noch auf dem Stack. Wir brauchen diesen Wert, um das Quadrat des f-Wertes zu skalieren, anstatt diesen durch [constant]#32# zu teilen. Es ist kein Zufall, daß wir diese Konstante als letztes laden. Dadurch wird diese Zahl die oberste Konstante auf dem Stack. Wenn später das Quadrat des f-Wertes skaliert werden muß, befindet sich die [constant]#-5# in `st(1)`, also genau da, wo die Funktion `fscale` diesen Wert erwartet. Es ist üblich, einige Konstanten per Hand zu erzeugen, anstatt sie aus dem Speicher zu laden. Genau das machen wir mit der [constant]#-5#: [.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 .... Wir können all diese Optimierungen in einer Regel zusammenfassen: _Behalte wiederverwendbare Werte auf dem Stack!_ [TIP] ==== _PostScript(R)_ ist eine Stack-orientierte Programmiersprache. Es gibt weit mehr Bücher über PostScript(R), als über die Assemblersprache der FPU: Werden Sie in PostScript(R) besser, dann werden Sie auch automatisch in der Programmierung der FPU besser. ==== [[x86-pinhole-the-code]] === pinhole-Der Code [.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 ] [-o ] [-i ]', 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 .... Der Code folgt demselben Aufbau wie alle anderen Filter, die wir bisher gesehen haben, bis auf eine Kleinigkeit: Wir nehmen nun nicht mehr an, daß das Ende der Eingabe auch das Ende der nötigen Arbeit bedeutet, etwas, das wir für _zeichenbasierte_ Filter automatisch angenommen haben. Dieser Filter verarbeitet keine Zeichen. Er verarbeitet eine _Sprache_ (obgleich eine sehr einfache, die nur aus Zahlen besteht). Wenn keine weiteren Eingaben vorliegen, kann das zwei Ursachen haben: * Wir sind fertig und können aufhören. Dies ist dasselbe wie vorher. * Das Zeichen, das wir eingelesen haben, war eine Zahl. Wir haben diese am Ende unseres ASCII -zu-float Kovertierungspuffers gespeichert. Wir müssen nun den gesamten Pufferinhalt in eine Zahl konvertieren, und die letzte Zeile unserer Ausgabe ausgeben. Aus diesem Grund haben wir unsere `getchar`- und ``read``-Routinen so angepaßt, daß sie das `carry flag` _clear_ immer dann zurückgeben, wenn wir ein weiteres Zeichen aus der Eingabe lesen, und das `carry flag` _set_ immer dann zurückgeben, wenn es keine weiteren Eingabedaten gibt. Selbstverständlich verwenden wir auch hier die Magie der Assemblersprache! Schauen Sie sich `getchar` näher an. Dieses gibt _immer_ das `carry flag` _clear_ zurück. Dennoch basiert der Hauptteil unseres Programmes auf dem `carry flag`, um diesem eine Beendigung mitzuteilen-und es funktioniert. Die Magie passiert in `read`. Wann immer weitere Eingaben durch das System zur Verfügung stehen, ruft diese Funktion `getchar` auf, welche ein weiteres Zeichen aus dem Eingabepuffer einliest, und anschließend das `carry flag` __clear__t. Wenn aber `read` keine weiteren Eingaben von dem System bekommt, ruft dieses _nicht_ `getchar` auf. Stattdessen addiert der op-Code `add esp, byte 4` 4 zu `ESP` hinzu, _setzt_ das `carry flag`, und springt zurück. Wo springt diese Funktion hin? Wann immer ein Programm den op-Code `call` verwendet, ``push``t der Mikroprozessor die Rücksprungandresse, d.h. er speichert diese ganz oben auf dem Stack (nicht auf dem Stack der FPU, sondern auf dem Systemstack, der sich im Hauptspeicher befindet). Wenn ein Programm den op-Code `ret` verwendet, ``pop``t der Mikroprozessor den Rückgabewert von dem Stack, und springt zu der Adresse, die dort gespeichert wurde. Da wir aber 4 zu `ESP` hinzuaddiert haben (welches das Register der Stackzeiger ist), haben wir effektiv dem Mikroprzessor eine kleine _Amnesie_ verpaßt: Dieser erinnert sich nun nicht mehr daran, daß `getchar` durch `read` aufgerufen wurde. Und da `getchar` nichts vor dem Aufruf von `read` auf dem Stack abgelegt hat, enthält der Anfang des Stacks nun die Rücksprungadresse von der Funktion, die `getchar` aufgerufen hat. Soweit es den Aufrufer betrifft, hat dieser `getchar` ge``call``t, welche mit einem gesetzten ``carry flag ret``urned. Des weiteren wird die Routine `bcdload` bei einem klitzekleinen Problem zwischen der Big-Endian- und Little-Endian-Codierung aufgerufen. Diese konvertiert die Textrepräsentation einer Zahl in eine andere Textrepräsentation: Der Text wird in der Big-Endian-Codierung gespeichert, die _packed decimal_-Darstellung jedoch in der Little-Endian-Codierung. Um dieses Problem zu lösen haben wir vorher den op-Code `std` verwendet. Wir machen diesen Aufruf später mittels `cld` wieder rückgängig: Es ist sehr wichtig, daß wir keine Funktion mittels `call` aufrufen, die von einer Standardeinstellung des _Richtungsflags_ abhängig ist, während `std` ausgeführt wird. Alles weitere in dem Programm sollte leicht zu verstehen sein, vorausgesetzt, daß Sie das gesamte vorherige Kapitel gelesen haben. Es ist ein klassisches Beispiel für das Sprichwort, daß das Programmieren eine Menge Denkarbeit, und nur ein wenig Programmcode benötigt. Sobald wir uns über jedes Detail im klaren sind, steht der Code fast schon da. [[x86-pinhole-using]] === Das Programm pinhole verwenden Da wir uns bei dem Programm dafür entschieden haben, alle Eingaben, die keine Zahlen sind, zu ignorieren (selbst die in Kommentaren), können wir jegliche _textbasierten Eingaben_ verarbeiten. Wir _müssen_ dies nicht tun, wir _könnten_ aber. Meiner bescheidenen Meinung nach wird ein Programm durch die Möglichkeit, anstatt einer strikten Eingabesyntax textbasierte Anfragen stellen zu können, sehr viel benutzerfreundlicher. Angenommen, wir wollten eine Lochkamera für einen 4x5 Zoll Film bauen. Die standardmäßige Brennweite für diesen Film ist ungefähr 150mm. Wir wollen diesen Wert _optimieren_, so daß der Lochblendendurchmesser eine möglichst runde Zahl ergibt. Lassen Sie uns weiter annehmen, daß wir zwar sehr gut mit Kameras umgehen können, dafür aber nicht so gut mit Computern. Anstatt das wir nun eine Reihe von Zahlen eingeben, wollen wir lieber ein paar _Fragen_ stellen. Unsere Sitzung könnte wie folgt aussehen: [source,shell] .... % pinhole Computer, Wie groß müßte meine Lochblende bei einer Brennweite von 150 sein? 150 490 306 362 2930 12 Hmmm... Und bei 160? 160 506 316 362 3125 12 Laß uns bitte 155 nehmen. 155 498 311 362 3027 12 Ah, laß uns 157 probieren... 157 501 313 362 3066 12 156? 156 500 312 362 3047 12 Das ist es! Perfekt! Vielen Dank! ^D .... Wir haben herausgefunden, daß der Lochblendendurchmesser bei einer Brennweite von 150 mm 490 Mikrometer, oder 0.49 mm ergeben würde. Bei einer fast identischen Brennweite von 156 mm würden wir einen Durchmesser von genau einem halben Millimeter bekommen. [[x86-pinhole-scripting]] === Skripte schreiben Da wir uns dafür entschieden haben, das Zeichen [constant]### als den Anfang eines Kommentares zu interpretieren, können wir unser pinhole-Programm auch als _Skriptsprache_ verwenden. Sie haben vielleicht schon einmal shell _-Skripte_ gesehen, die mit folgenden Zeichen begonnen haben: [.programlisting] .... #! /bin/sh .... oder [.programlisting] .... #!/bin/sh .... ... da das Leerzeichen hinter dem `#!` optional ist. Wann immer UNIX(R) eine Datei ausführen soll, die mit einem `#!` beginnt, wird angenommen, das die Datei ein Skript ist. Es fügt den Befehl an das Ende der ersten Zeile an, und versucht dann, dieses auszuführen. Angenommen, wir haben unser Programm pinhole unter /usr/local/bin/ installiert, dann können wir nun Skripte schreiben, um unterschiedliche Lochblendendurchmesser für mehrere Brennweiten zu berechnen, die normalerweise mit 120er Filmen verwendet werden. Das Skript könnte wie folgt aussehen: [.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 .... Da ein 120er Film ein Film mittlerer Größe ist, könnten wir die Datei medium nennen. Wir können die Datei ausführbar machen und dann aufrufen, als wäre es ein Programm: [source,shell] .... % chmod 755 medium % ./medium .... UNIX(R) wird den letzten Befehl wie folgt interpretieren: [source,shell] .... % /usr/local/bin/pinhole -b -i ./medium .... Es wird den Befehl ausführen und folgendes ausgeben: [source,shell] .... 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 .... Lassen Sie uns nun das folgende eingeben: [source,shell] .... % ./medium -c .... UNIX(R) wird dieses wie folgt behandeln: [source,shell] .... % /usr/local/bin/pinhole -b -i ./medium -c .... Dadurch erhält das Programm zwei widersprüchliche Optionen: [parameter]#-b# und [parameter]#-c# (Verwende Benders Konstante und verwende Connors Konstante). Wir haben unser Programm so geschrieben, daß später eingelesene Optionen die vorheringen überschreiben-unser Programm wird also Connors Konstante für die Berechnungen verwenden: [source,shell] .... 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 .... Wir entscheiden uns am Ende doch für Benders Konstante. Wir wollen die Ergebnisse im CSV-Format in einer Datei speichern: [source,shell] .... % ./medium -b -e > bender % cat bender 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 % .... [[x86-caveats]] == Vorsichtsmassnahmen Assembler-Programmierer, die aufwuchsen mit MS-DOS(R) und windows Windows(R) neigen oft dazu Shotcuts zu verwenden. Das Lesen der Tastatur-Scancodes und das direkte Schreiben in den Grafikspeicher sind zwei klassische Beispiele von Gewohnheiten, die unter MS-DOS(R) nicht verpönt sind, aber nicht als richtig angesehen werden. Warum dies? Sowohl das PC-BIOS als auch MS-DOS(R) sind notorisch langsam bei der Ausführung dieser Operationen. Sie mögen versucht sein ähnliche Angewohnheiten in der UNIX(R)-Umgebung fortzuführen. Zum Beispiel habe ich eine Webseite gesehen, welche erklärt, wie man auf einem beliebten UNIX(R)-Ableger die Tastatur-Scancodes verwendet. Das ist generell eine _sehr schlechte Idee_ in einer UNIX(R)-Umgebung! Lassen Sie mich erklären warum. [[x86-protected]] === UNIX(R) ist geschützt Zum Einen mag es schlicht nicht möglich sein. UNIX(R) läuft im Protected Mode. Nur der Kernel und Gerätetreiber dürfen direkt auf die Hardware zugreifen. Unter Umständen erlaubt es Ihnen ein bestimmter UNIX(R)-Ableger Tastatur-Scancodes auszulesen, aber ein wirkliches UNIX(R)-Betriebssystem wird dies zu verhindern wissen. Und falls eine Version es Ihnen erlaubt wird es eine andere nicht tun, daher kann eine sorgfältig erstellte Software über Nacht zu einem überkommenen Dinosaurier werden. [[x86-abstraction]] === UNIX(R) ist eine Abstraktion Aber es gibt einen viel wichtigeren Grund, weshalb Sie nicht versuchen sollten, die Hardware direkt anzusprechen (natürlich nicht, wenn Sie einen Gerätetreiber schreiben), selbst auf den UNIX(R)-ähnlichen Systemen, die es Ihnen erlauben: _UNIX(R) ist eine Abstraktion!_ Es gibt einen wichtigen Unterschied in der Design-Philosophie zwischen MS-DOS(R) und UNIX(R). MS-DOS(R) wurde entworfen als Einzelnutzer-System. Es läuft auf einem Rechner mit einer direkt angeschlossenen Tastatur und einem direkt angeschlossenem Bildschirm. Die Eingaben des Nutzers kommen nahezu immer von dieser Tastatur. Die Ausgabe Ihres Programmes erscheint fast immer auf diesem Bildschirm. Dies ist NIEMALS garantiert unter UNIX(R). Es ist sehr verbreitet für ein UNIX(R), daß der Nutzer seine Aus- und Eingaben kanalisiert und umleitet: [source,shell] .... % program1 | program2 | program3 > file1 .... Falls Sie eine Anwendung program2 geschrieben haben, kommt ihre Eingabe nicht von der Tastatur, sondern von der Ausgabe von program1. Gleichermassen geht Ihre Ausgabe nicht auf den Bildschirm, sondern wird zur Eingabe für program3, dessen Ausgabe wiederum in [.filename]#file1# endet. Aber es gibt noch mehr! Selbst wenn Sie sichergestellt haben, daß Ihre Eingabe und Ausgabe zum Terminal kommt bzw. gelangt, dann ist immer noch nicht garantiert, daß ihr Terminal ein PC ist: Es mag seinen Grafikspeicher nicht dort haben, wo Sie ihn erwarten, oder die Tastatur könnte keine PC-ähnlichen Scancodes erzeugen können. Es mag ein Macintosh(R) oder irgendein anderer Rechner sein. Sie mögen nun den Kopf schütteln: Mein Programm ist in PC-Assembler geschrieben, wie kann es auf einem Macintosh(R) laufen? Aber ich habe nicht gesagt, daß Ihr Programm auf Macintosh(R) läuft, nur sein Terminal mag ein Macintosh(R) sein. Unter UNIX(R) muß der Terminal nicht direkt am Rechner angeschlossen sein, auf dem die Software läuft, er kann sogar auf einem anderen Kontinent sein oder sogar auf einem anderen Planeten. Es ist nicht ungewöhnlich, daß ein Macintosh(R)-Nutzer in Australien sich auf ein UNIX(R)-System in Nordamerika (oder sonstwo) mittels telnet verbindet. Die Software läuft auf einem Rechner während das Terminal sich auf einem anderen Rechner befindet: Falls Sie versuchen sollten die Scancodes auszulesen werden Sie die falschen Eingaben erhalten! Das Gleiche gilt für jede andere Hardware: Eine Datei, welche Sie einlesen, mag auf einem Laufwerk sein, auf das Sie keinen direkten Zugriff haben. Eine Kamera, deren Bilder Sie auslesen, befindet sich möglicherweise in einem Space Shuttle, durch Satelliten mit Ihnen verbunden. Das sind die Gründe, weshalb Sie niemals unter UNIX(R) Annahmen treffen dürfen, woher Ihre Daten kommen oder gehen. Lassen Sie immer das System den physischen Zugriff auf die Hardware regeln. [NOTE] ==== Das sind Vorsichtsmassnahmen, keine absoluten Regeln. Ausnahmen sind möglich. Wenn zum Beispiel ein Texteditor bestimmt hat, daß er auf einer lokalen Maschine läuft, dann mag er die Tastatur-Scancodes direkt auslesen, um eine bessere Kontrolle zu gewährleisten. Ich erwähne diese Vorsichtsmassnahmen nicht, um Ihnen zu sagen, was sie tun oder lassen sollen, ich will Ihnen nur bewusst machen, daß es bestimmte Fallstricke gibt, die Sie erwarten, wenn Sie soeben ihn UNIX(R) von MS-DOS(R) angelangt sind. Kreative Menschen brechen oft Regeln und das ist in Ordnung, solange sie wissen welche Regeln und warum. ==== [[x86-acknowledgements]] == Danksagungen Dieses Handbuch wäre niemals möglich gewesen ohne die Hilfe vieler erfahrener FreeBSD-Programmierer aus {freebsd-hackers}. Viele dieser Personen haben geduldig meine Fragen beantwortet und mich in die richtige Richtung gewiesen bei meinem Versuch, die tieferen liegenden Mechanismen der UNIX(R)-Systemprogrammierung zu erforschen im Allgemeinen und bei FreeBSD im Besonderen. Thomas M. Sommers öffnete die Türen für mich. Seine http://www.codebreakers-journal.com/content/view/262/27/[Wie schreibe ich "Hallo Welt" in FreeBSD-Assembler?] Webseite war mein erster Kontakt mit Assembler-Programmierung unter FreeBSD. Jake Burkholder hat die Tür offen gehalten durch das bereitwillige Beantworten all meiner Fragen und das Zurverfügungstellen von Assembler-Codebeispielen. Copyright (R) 2000-2001 G. Adam Stanislav. Alle Rechte vorbehalten. diff --git a/documentation/content/en/articles/x86-assembly/_index.adoc b/documentation/content/en/articles/x86-assembly/_index.adoc index 73e34b3817..b14d045530 100644 --- a/documentation/content/en/articles/x86-assembly/_index.adoc +++ b/documentation/content/en/articles/x86-assembly/_index.adoc @@ -1,4303 +1,4285 @@ --- title: x86 Assembly Language Programming authors: - author: Adam Stanislav email: adam@redprince.net description: A tutorial on writing programs for FreeBSD in x86 assembly language -tags: ["x86", "assembly", "programming", "guide"] +trademarks: ["apple", "freebsd", "general", "intel", "linux", "microsoft", "posix", "unix"] +tags: ["assembly", "guide", "ia32", "ld", "llvm-as", "nasm", "programming", "x86"] --- = x86 Assembly Language Programming :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] -_This chapter was written by {stanislav}._ +_This article was written by {stanislav} (2001), and adjusted by {mhorne} (2026)._ + +[NOTE] +==== +The content in this article is historical. +==== [[x86-intro]] == Synopsis Assembly language programming under UNIX(R) is highly undocumented. -It is generally assumed that no one would ever want to use it because various UNIX(R) systems run on different microprocessors, so everything should be written in C for portability. +It is generally assumed that no one would ever want to use it because various UNIX systems run on different microprocessors, so everything should be written in C for portability. In reality, C portability is quite a myth. -Even C programs need to be modified when ported from one UNIX(R) to another, regardless of what processor each runs on. +Even C programs need to be modified when ported from one UNIX 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. -Even if we believe that all of UNIX(R) 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? +Even if we believe that all of UNIX 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? -In this chapter I will attempt to show you how you can use assembly language writing UNIX(R) programs, specifically under FreeBSD. +In this article I will attempt to show you how you can use assembly language writing UNIX programs, specifically under FreeBSD. -This chapter does not explain the basics of assembly language. +This article 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 http://webster.cs.ucr.edu/[Art of Assembly Language]; or if you prefer a printed book, take a look at Jeff Duntemann's Assembly Language Step-by-Step (ISBN: 0471375233). -However, once the chapter is finished, any assembly language programmer will be able to write programs for FreeBSD quickly and efficiently. +However, once the article is finished, any assembly language programmer will be able to write programs for FreeBSD quickly and efficiently. Copyright (R) 2000-2001 G. Adam Stanislav. All rights reserved. [[x86-the-tools]] == The Tools [[x86-the-assembler]] === The Assembler The most important tool for assembly language programming is the assembler, the software that converts assembly language code into machine language. +Two very different types of assemblers are available for FreeBSD. -Three very different assemblers are available for FreeBSD. -Both man:llvm-as[1] (included in package:devel/llvm[]) and man:as[1] (included in package:devel/binutils[]) use the traditional UNIX(R) assembly language syntax. +The first is the GNU man:as[1] (package:devel/binutils[]), which uses the traditional UNIX assembly language syntax. +Alternatively, one can use man:clang[1], which is a compatible replacement for the GNU assembler and comes with the system. -On the other hand, man:nasm[1] (installed through package:devel/nasm[]) uses the Intel syntax. -Its main advantage is that it can assemble code for many operating systems. +The other is man:nasm[1] (package:devel/nasm[]). +This assembler uses the Intel syntax, and its main advantage is that it can assemble code for many operating systems. -This chapter uses nasm syntax because most assembly language programmers coming to FreeBSD from other operating systems will find it easier to understand. +This article uses nasm 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. [[x86-the-linker]] === The Linker The output of the assembler, like that of any compiler, needs to be linked to form an executable file. The standard man:ld[1] linker comes with FreeBSD. It works with the code assembled with either assembler. [[x86-system-calls]] == System Calls [[x86-default-calling-convention]] === Default Calling Convention By default, the FreeBSD kernel uses the C calling convention. Further, although the kernel is accessed using `int 80h`, it is assumed the program will call a function that issues `int 80h`, rather than issuing `int 80h` directly. This convention is very convenient, and quite superior to the Microsoft(R) convention used by MS-DOS(R). -Why? Because the UNIX(R) convention allows any program written in any language to access the kernel. +Why? Because the UNIX convention allows any program written in any language to access the kernel. An assembly language program can do that as well. For example, we could open a file: [.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 .... This is a very clean and portable way of coding. -If you need to port the code to a UNIX(R) system which uses a different interrupt, or a different way of passing parameters, all you need to change is the kernel procedure. +If you need to port the code to a UNIX system which uses a different interrupt, or a different way of passing parameters, all you need to change is the kernel procedure. But assembly language programmers like to shave off cycles. The above example requires a `call/ret` combination. We can eliminate it by ``push``ing an extra dword: [.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 .... The `5` that we have placed in `EAX` identifies the kernel function, in this case `open`. [[x86-alternate-calling-convention]] === Alternate Calling Convention 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. +For it to work, however, the system must have Linux(R) emulation installed. -Linux is a UNIX(R) like system. -However, its kernel uses the same system-call convention of passing parameters in registers MS-DOS(R) does. -As with the UNIX(R) convention, the function number is placed in `EAX`. +Linux is a UNIX-like system. +However, its kernel uses the same system-call convention of passing parameters in registers MS-DOS does. +As with the UNIX convention, the function number is placed in `EAX`. The parameters, however, are not passed on the stack but in `EBX, ECX, EDX, ESI, EDI, EBP`: [.programlisting] .... open: mov eax, 5 mov ebx, path mov ecx, flags mov edx, mode int 80h .... This convention has a great disadvantage over the UNIX(R) way, at least as far as assembly language programming is concerned: Every time you make a kernel call you must `push` the registers, then `pop` them later. This makes your code bulkier and slower. Nevertheless, FreeBSD gives you a choice. 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: [source,shell] .... % brandelf -t Linux filename .... [[x86-use-geneva]] === Which Convention Should You Use? -If you are coding specifically for FreeBSD, you should always use the UNIX(R) convention: +If you are coding specifically for FreeBSD, you should always use the UNIX 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. 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. [[x86-call-numbers]] === Call Numbers To tell the kernel which system service you are calling, place its number in `EAX`. Of course, you need to know what the number is. [[x86-the-syscalls-file]] ==== The [.filename]#syscalls# File The numbers are listed in [.filename]#syscalls#. `locate syscalls` finds this file in several different formats, all produced automatically from [.filename]#syscalls.master#. -You can find the master file for the default UNIX(R) calling convention in [.filename]#/usr/src/sys/kern/syscalls.master#. +You can find the master file for the default UNIX calling convention in [.filename]#/usr/src/sys/kern/syscalls.master#. If you need to use the other convention implemented in the Linux emulation mode, read [.filename]#/usr/src/sys/i386/linux/syscalls.master#. [NOTE] ==== Not only do FreeBSD and Linux use different calling conventions, they sometimes use different numbers for the same functions. ==== [.filename]#syscalls.master# describes how the call is to be made: [.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... .... It is the leftmost column that tells us the number to place in `EAX`. The rightmost column tells us what parameters to `push`. They are ``push``ed _from right to left_. For example, to `open` a file, we need to `push` the `mode` first, then `flags`, then the address at which the `path` is stored. [[x86-return-values]] == Return Values 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. 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. [[x86-man-pages]] === Man Pages -The traditional place to look for information about various system calls under UNIX(R) systems are the manual pages. +The traditional place to look for information about various system calls under UNIX systems are the manual pages. FreeBSD describes its system calls in section 2, sometimes in section 3. For example, man:open[2] says: [.blockquote] If successful, `open()` returns a non-negative integer, termed a file descriptor. It returns `-1` on failure, and sets `errno` to indicate the error. -The assembly language programmer new to UNIX(R) and FreeBSD will immediately ask the puzzling question: Where is `errno` and how do I get to it? +The assembly language programmer new to UNIX and FreeBSD will immediately ask the puzzling question: Where is `errno` and how do I get to it? [NOTE] ==== The information presented in the manual pages applies to C programs. The assembly language programmer needs additional information. ==== [[x86-where-return-values]] === Where Are the Return Values? Unfortunately, it depends... For most system calls it is in `EAX`, 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 `EAX`. If it is not there, you need further research. [NOTE] ==== I am aware of one system call that returns the value in `EDX`: `SYS_fork`. All others I have worked with use `EAX`. But I have not worked with them all yet. ==== [TIP] ==== If you cannot find the answer here or anywhere else, study libc source code and see how it interfaces with the kernel. ==== [[x86-where-errno]] === Where Is `errno`? Actually, nowhere... -`errno` is part of the C language, not the UNIX(R) kernel. +`errno` is part of the C language, not the UNIX kernel. When accessing kernel services directly, the error code is returned in `EAX`, the same register the proper return value generally ends up in. 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. [[x86-how-to-know-error]] === Determining an Error Occurred When using the standard FreeBSD calling convention, the `carry flag` is cleared upon success, set upon failure. When using the Linux emulation mode, the signed value in `EAX` is non-negative upon success, and contains the return value. In case of an error, the value is negative, i.e., `-errno`. [[x86-portable-code]] == Creating Portable Code Portability is generally not one of the strengths of assembly language. Yet, writing assembly language programs for different platforms is possible, especially with nasm. I have written assembly language libraries that can be assembled for such different operating systems as Windows(R) and FreeBSD. It is all the more possible when you want your code to run on two platforms which, while different, are based on similar architectures. -For example, FreeBSD is UNIX(R), Linux is UNIX(R) like. +For example, FreeBSD is UNIX, Linux is UNIX-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. [[x86-deal-with-function-numbers]] === Dealing with Function Numbers 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: [.programlisting] .... %ifdef LINUX %define SYS_execve 11 %else %define SYS_execve 59 %endif .... [[x86-deal-with-geneva]] === Dealing with Conventions Both, the calling convention, and the return value (the `errno` problem) can be resolved with macros: [.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 .... [[x86-deal-with-other-portability]] === Dealing with Other Portability Issues The above solutions can handle most cases of writing code portable between FreeBSD and Linux. Nevertheless, with some kernel services the differences are deeper. 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. [[x86-portable-library]] === Using a Library 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. 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 `EAX` 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: [.programlisting] .... sys.open: sys.close: [etc...] int 80h ret .... Your Linux library will require more different functions. But even here you can group system calls using the same number of parameters: [.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 .... 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. 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. [[x86-portable-include]] === Using an Include File 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. 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. [NOTE] ==== -This is the approach we will use throughout this chapter. +This is the approach we will use throughout this article. We will name our include file [.filename]#system.inc#, and add to it whenever we deal with a new system call. ==== We can start our [.filename]#system.inc# by declaring the standard file descriptors: [.programlisting] .... %define stdin 0 %define stdout 1 %define stderr 2 .... Next, we create a symbolic name for each system call: [.programlisting] .... %define SYS_nosys 0 %define SYS_exit 1 %define SYS_fork 2 %define SYS_read 3 %define SYS_write 4 ; [etc...] .... We add a short, non-global procedure with a long name, so we do not accidentally reuse the name in our code: [.programlisting] .... section .text align 4 access.the.bsd.kernel: int 80h ret .... We create a macro which takes one argument, the syscall number: [.programlisting] .... %macro system 1 mov eax, %1 call access.the.bsd.kernel %endmacro .... Finally, we create macros for each syscall. These macros take no arguments. [.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...] .... Go ahead, enter it into your editor and save it as [.filename]#system.inc#. We will add more to it as we discuss more syscalls. [[x86-first-program]] == Our First Program We are now ready for our first program, the mandatory Hello, World! [.programlisting] .... %include 'system.inc' section .data hello db 'Hello, World!', 0Ah hbytes equ $-hello section .text global _start _start: push dword hbytes push dword hello push dword stdout sys.write push dword 0 sys.exit .... Here is what it does: Line 1 includes the defines, the macros, and the code from [.filename]#system.inc#. 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 (`0Ah`). Line 5 creates a constant that contains the length of the string from line 4 in bytes. Lines 7-16 contain the code. Note that FreeBSD uses the _elf_ file format for its executables, which requires every program to start at the point labeled `_start` (or, more precisely, the linker expects that). This label has to be global. Lines 10-13 ask the system to write `hbytes` bytes of the `hello` string to `stdout`. Lines 15-16 ask the system to end the program with the return value of `0`. The `SYS_exit` syscall never returns, so the code ends there. [NOTE] ==== -If you have come to UNIX(R) from MS-DOS(R) 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 UNIX(R). +If you have come to UNIX from MS-DOS 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 UNIX. As far as you are concerned, you are writing to a file known as [.filename]#stdout#. This can be the video screen, or a telnet terminal, or an actual file, or even the input of another program. Which one it is, is for the system to figure out. ==== [[x86-assemble-1]] === Assembling the Code Type the code in an editor, and save it in a file named [.filename]#hello.asm#. -You need nasm to assemble it. - -[[x86-get-nasm]] -==== Installing nasm - -If you do not have nasm, type: - -[source,shell] -.... -% su -Password:your root password -# cd /usr/ports/devel/nasm -# make install -# exit -% -.... - -You may type `make install clean` instead of just `make install` if you do not want to keep nasm source code. - -Either way, FreeBSD will automatically download nasm from the Internet, compile it, and install it on your system. - -[NOTE] -==== -If your system is not FreeBSD, you need to get nasm from its https://sourceforge.net/projects/nasm[home page]. -You can still use it to assemble FreeBSD code. -==== +You need package:devel/nasm[] to assemble it. Now you can assemble, link, and run the code: [source,shell] .... % nasm -f elf hello.asm % ld -s -o hello hello.o % ./hello Hello, World! % .... [[x86-unix-filters]] -== Writing UNIX(R) Filters +== Writing UNIX Filters -A common type of UNIX(R) application is a filter-a program that reads data from the [.filename]#stdin#, processes it somehow, then writes the result to [.filename]#stdout#. +A common type of UNIX application is a filter-a program that reads data from the [.filename]#stdin#, processes it somehow, then writes the result to [.filename]#stdout#. In this chapter, we shall develop a simple filter, and learn how to read from [.filename]#stdin# and write to [.filename]#stdout#. This filter will convert each byte of its input into a hexadecimal number followed by a blank space. [.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 .... In the data section we create an array called `hex`. 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 `0`. 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. The code section consists of four parts: Reading the byte, converting it to a hexadecimal number, writing the result, and eventually exiting the program. To read the byte, we ask the system to read one byte from [.filename]#stdin#, and store it in the first byte of the `buffer`. The system returns the number of bytes read in `EAX`. This will be `1` while data is coming, or `0`, when no more input data is available. Therefore, we check the value of `EAX`. If it is `0`, we jump to `.done`, otherwise we continue. [NOTE] ==== For simplicity sake, we are ignoring the possibility of an error condition at this time. ==== The hexadecimal conversion reads the byte from the `buffer` into `EAX`, or actually just `AL`, while clearing the remaining bits of `EAX` to zeros. We also copy the byte to `EDX` 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. Next, we ask the system to write the three bytes of the buffer, i.e., the two hexadecimal digits and the blank space, to [.filename]#stdout#. We then jump back to the beginning of the program and process the next byte. 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. Go ahead, and save the code in a file named [.filename]#hex.asm#, then type the following (the `^D` means press the control key and type `D` while holding the control key down): [source,shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come! 48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D % .... [NOTE] ==== -If you are migrating to UNIX(R) from MS-DOS(R), you may be wondering why each line ends with `0A` instead of `0D 0A`. -This is because UNIX(R) does not use the cr/lf convention, but a "new line" convention, which is `0A` in hexadecimal. +If you are migrating to UNIX from MS-DOS, you may be wondering why each line ends with `0A` instead of `0D 0A`. +This is because UNIX does not use the cr/lf convention, but a "new line" convention, which is `0A` in hexadecimal. ==== 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 `0A`: [.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 .... We have stored the space in the `CL` register. -We can do this safely because, unlike Microsoft(R) Windows(R), UNIX(R) system calls do not modify the value of any register they do not use to return a value in. +We can do this safely because, unlike Microsoft Windows, UNIX system calls do not modify the value of any register they do not use to return a value in. That means we only need to set `CL` once. We have, therefore, added a new label `.loop` and jump to it for the next byte instead of jumping at `_start`. We have also added the `.hex` label so we can either have a blank space or a new line as the third byte of the `buffer`. Once you have changed [.filename]#hex.asm# to reflect these changes, type: [source,shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come! 48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D % .... 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). [[x86-buffered-io]] == Buffered Input and Output 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. 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 [.filename]#stdout#. 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 [.filename]#stdout# 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. [.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 .... We now have a third section in the source code, named `.bss`. This section is not included in our executable file, and, therefore, cannot be initialized. We use `resb` instead of `db`. It simply reserves the requested size of uninitialized memory for our use. 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 `.data` section. -This is also why the UNIX(R) 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. +This is also why the UNIX 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. We use `EDI` and `ESI` as pointers to the next byte to be read from or written to. We use `EBX` and `ECX` 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. Let us see how it works now: [source,shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! Here I come! 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 ^D % .... Not what you expected? The program did not print the output until we pressed `^D`. That is easy to fix by inserting three lines of code to write the output every time we have converted a new line to `0A`. I have marked the three lines with > (do not copy the > in your [.filename]#hex.asm#). [.programlisting] .... %include 'system.inc' %define BUFSIZE 2048 section .data hex db '0123456789ABCDEF' section .bss ibuffer resb BUFSIZE obuffer resb BUFSIZE section .text global _start _start: sub eax, eax sub ebx, ebx sub ecx, ecx mov edi, obuffer .loop: ; read a byte from stdin call getchar ; convert it to hex mov dl, al shr al, 4 mov al, [hex+eax] call putchar mov al, dl and al, 0Fh mov al, [hex+eax] call putchar mov al, ' ' cmp dl, 0Ah jne .put mov al, dl .put: call putchar > cmp al, 0Ah > jne .loop > call write jmp short .loop align 4 getchar: or ebx, ebx jne .fetch call read .fetch: lodsb dec ebx ret read: push dword BUFSIZE mov esi, ibuffer push esi push dword stdin sys.read add esp, byte 12 mov ebx, eax or eax, eax je .done sub eax, eax ret align 4 .done: call write ; flush output buffer push dword 0 sys.exit align 4 putchar: stosb inc ecx cmp ecx, BUFSIZE je write ret align 4 write: sub edi, ecx ; start of buffer push ecx push edi push dword stdout sys.write add esp, byte 12 sub eax, eax sub ecx, ecx ; buffer is empty now ret .... Now, let us see how it works: [source,shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come! 48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D % .... Not bad for a 644-byte executable, is it! [NOTE] ==== This approach to buffered input/output still contains a hidden danger. I will discuss-and fix-it later, when I talk about the crossref:x86[x86-buffered-dark-side,dark side of buffering]. ==== [[x86-ungetc]] === How to Unread a Character [WARNING] ==== This may be a somewhat advanced topic, mostly of interest to programmers familiar with the theory of compilers. If you wish, you may crossref:x86[x86-command-line,skip to the next section], and perhaps read this later. ==== 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. 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. This presents an interesting problem: How to return the next character back to the input stream, so it can be read again later? One possible solution is to store it in a character variable, then set a flag. We can modify `getchar` 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. The C language has an `ungetc()` 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 `getchar` 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. The key to returning a character back to the stream is in how we are getting the characters to start with: First we check if the buffer is empty by testing the value of `EBX`. If it is zero, we call the `read` procedure. If we do have a character available, we use `lodsb`, then decrease the value of `EBX`. The `lodsb` instruction is effectively identical to: [.programlisting] .... mov al, [esi] inc esi .... The byte we have fetched remains in the buffer until the next time `read` is called. We do not know when that happens, but we do know it will not happen until the next call to `getchar`. Hence, to "return" the last-read byte back to the stream, all we have to do is decrease the value of `ESI` and increase the value of `EBX`: [.programlisting] .... ungetc: dec esi inc ebx ret .... 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 `ungetc` several times in a row, it will work most of the time, but not all the time (and will be tough to debug). Why? Because as long as `getchar` does not have to call `read`, all of the pre-read bytes are still in the buffer, and our `ungetc` works without a glitch. But the moment `getchar` calls `read`, the contents of the buffer change. We can always rely on `ungetc` working properly on the last character we have read with `getchar`, but not on anything we have read before that. If your program reads more than one byte ahead, you have at least two choices: If possible, modify the program so it only reads one byte ahead. This is the simplest solution. 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 `.bss` section of your code, and create a small "spare" buffer right before your input buffer, something like this: [.programlisting] .... section .bss resb 16 ; or whatever the value you came up with ibuffer resb BUFSIZE obuffer resb BUFSIZE .... You also need to modify your `ungetc` to pass the value of the byte to unget in `AL`: [.programlisting] .... ungetc: dec esi inc ebx mov [esi], al ret .... With this modification, you can call `ungetc` 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"). [[x86-command-line]] == Command Line Arguments Our hex 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? -Before a UNIX(R) system starts a program, it ``push``es some data on the stack, then jumps at the `_start` label of the program. +Before a UNIX system starts a program, it ``push``es some data on the stack, then jumps at the `_start` label of the program. Yes, I said jumps, not calls. That means the data can be accessed by reading `[esp+offset]`, or by simply ``pop``ping it. The value at the top of the stack contains the number of command line arguments. It is traditionally called `argc`, for "argument count." Command line arguments follow next, all `argc` of them. These are typically referred to as `argv`, for "argument value(s)." That is, we get `argv[0]`, `argv[1]`, `...`, `argv[argc-1]`. 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. The `argv` list is followed by a NULL pointer, which is simply a `0`. There is more, but this is enough for our purposes right now. [NOTE] ==== -If you have come from the MS-DOS(R) programming environment, the main difference is that each argument is in a separate string. +If you have come from the MS-DOS 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. ==== Armed with this knowledge, we are almost ready for the next version of [.filename]#hex.asm#. First, however, we need to add a few lines to [.filename]#system.inc#: First, we need to add two new entries to our list of system call numbers: [.programlisting] .... %define SYS_open 5 %define SYS_close 6 .... Then we add two new macros at the end of the file: [.programlisting] .... %macro sys.open 0 system SYS_open %endmacro %macro sys.close 0 system SYS_close %endmacro .... Here, then, is our modified source code: [.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 .... In our `.data` section we now have two new variables, `fd.in` and `fd.out`. We store the input and output file descriptors here. In the `.text` section we have replaced the references to `stdin` and `stdout` with `[fd.in]` and `[fd.out]`. The `.text` section now starts with a simple error handler, which does nothing but exit the program with a return value of `1`. The error handler is before `_start` so we are within a short distance from where the errors occur. Naturally, the program execution still begins at `_start`. First, we remove `argc` and `argv[0]` from the stack: They are of no interest to us (in this program, that is). We pop `argv[1]` to `ECX`. This register is particularly suited for pointers, as we can handle NULL pointers with `jecxz`. If `argv[1]` is not NULL, we try to open the file named in the first argument. Otherwise, we continue the program as before: Reading from `stdin`, writing to `stdout`. If we fail to open the input file (e.g., it does not exist), we jump to the error handler and quit. 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 `stdout`. 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. 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 `[fd.in]` and `[fd.out]`. Our executable is now a whopping 768 bytes long. Can we still improve it? Of course! Every program can be improved. Here are a few ideas of what we could do: * Have our error handler print a message to `stderr`. * Add error handlers to the `read` and `write` functions. * Close `stdin` when we open an input file, `stdout` when we open an output file. * Add command line switches, such as `-i` and `-o`, so we can list the input and output files in any order, or perhaps read from `stdin` and write to a file. * Print a usage message if command line arguments are incorrect. I shall leave these enhancements as an exercise to the reader: You already know everything you need to know to implement them. [[x86-environment]] -== UNIX(R) Environment +== UNIX Environment -An important UNIX(R) concept is the environment, which is defined by _environment variables_. +An important UNIX concept is the environment, which is defined by _environment variables_. Some are set by the system, others by you, yet others by the shell, or any program that loads another program. [[x86-find-environment]] === How to Find Environment Variables I said earlier that when a program starts executing, the stack contains `argc` followed by the NULL-terminated `argv` array, followed by something else. The "something else" is the _environment_, or, to be more precise, a NULL-terminated array of pointers to _environment variables_. This is often referred to as `env`. The structure of `env` is the same as that of `argv`, a list of memory addresses followed by a NULL (`0`). In this case, there is no `"envc"`-we figure out where the array ends by searching for the final NULL. The variables usually come in the `name=value` format, but sometimes the `=value` part may be missing. We need to account for that possibility. [[x86-webvar]] === webvars -I could just show you some code that prints the environment the same way the UNIX(R) env command does. +I could just show you some code that prints the environment the same way the UNIX env command does. But I thought it would be more interesting to write a simple assembly language CGI utility. [[x86-cgi]] ==== CGI: a Quick Overview I have a http://www.whizkidtech.redprince.net/cgi-bin/tutorial[detailed CGI tutorial] on my web site, but here is a very quick overview of CGI: * The web server communicates with the CGI program by setting _environment variables_. * The CGI program sends its output to [.filename]#stdout#. The web server reads it from there. * It must start with an HTTP header followed by two blank lines. * It then prints the HTML code, or whatever other type of data it is producing. [NOTE] ==== While certain _environment variables_ use standard names, others vary, depending on the web server. That makes webvars quite a useful diagnostic tool. ==== [[x86-webvars-the-code]] ==== The Code Our webvars program, then, must send out the HTTP header followed by some HTML mark-up. It then must read the _environment variables_ one by one and send them out as part of the HTML page. The code follows. I placed comments and explanations right inside the code: [.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 '', 0Ah db '', 0Ah db '', 0Ah db '', 0Ah db 'Web Environment', 0Ah db '', 0Ah db '', 0Ah, 0Ah db '', 0Ah db '
', 0Ah db '

Web Environment

', 0Ah db '

The following environment variables are defined ' db 'on this web server:

', 0Ah, 0Ah db '', 0Ah httplen equ $-http left db '', 0Ah db '', 0Ah db '', 0Ah db '', 0Ah rightlen equ $-right wrap db '
' leftlen equ $-left middle db '' midlen equ $-middle undef db '(undefined)' undeflen equ $-undef right db '
', 0Ah db '
', 0Ah db '', 0Ah db '', 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 .... This code produces a 1,396-byte executable. Most of it is data, i.e., the HTML mark-up we need to send out. Assemble and link it as usual: [source,shell] .... % nasm -f elf webvars.asm % ld -s -o webvars webvars.o .... To use it, you need to upload [.filename]#webvars# to your web server. Depending on how your web server is set up, you may have to store it in a special [.filename]#cgi-bin# directory, or perhaps rename it with a [.filename]#.cgi# extension. Then you need to use your browser to view its output. To see its output on my web server, please go to http://www.int80h.org/webvars/[http://www.int80h.org/webvars/]. If curious about the additional environment variables present in a password protected web directory, go to http://www.int80h.org/private/[http://www.int80h.org/private/], using the name `asm` and password `programmer`. [[x86-files]] == Working with Files 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 UNIX(R) offers much more functionality when it comes to files. +But UNIX 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. 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. -One of the first programs I wrote for UNIX(R) was link:ftp://ftp.int80h.org/unix/tuc/[tuc], a text-to-UNIX(R) file converter. -It converts a text file from other operating systems to a UNIX(R) text file. -In other words, it changes from different kind of line endings to the newline convention of UNIX(R). +One of the first programs I wrote for UNIX was package:converters/tuc[tuc(1)], a text-to-UNIX file converter. +It converts a text file from other operating systems to a UNIX text file. +In other words, it changes from different kind of line endings to the newline convention of UNIX. It saves the output in a different file. -Optionally, it converts a UNIX(R) text file to a DOS text file. +Optionally, it converts a UNIX text file to a DOS text file. -I have used tuc extensively, but always only to convert from some other OS to UNIX(R), never the other way. +I have used tuc extensively, but always only to convert from some other OS to UNIX, 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: [source,shell] .... % tuc myfile tempfile % mv tempfile myfile .... It would be nice to have a ftuc, i.e., _fast tuc_, and use it like this: [source,shell] .... % ftuc myfile .... -In this chapter, then, we will write ftuc in assembly language (the original tuc is in C), and study various file-oriented kernel services in the process. +In this article, then, we will write ftuc in assembly language (the original tuc is in C), and study various file-oriented kernel services in the process. At first sight, such a file conversion is very simple: All you have to do is strip the carriage returns, right? If you answered yes, think again: That approach will work most of the time (at least with MS DOS text files), but will fail occasionally. -The problem is that not all non UNIX(R) text files end their line with the carriage return / line feed sequence. +The problem is that not all non-UNIX 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. A text file converter, then, must be able to handle any possible line endings: * carriage return / line feed * carriage return * line feed / carriage return * line feed It should also handle files that use some kind of a combination of the above (e.g., carriage return followed by several line feeds). [[x86-finite-state-machine]] === Finite State Machine The problem is easily solved by the use of a technique called _finite state machine_, originally developed by the designers of digital electronic circuits. A _finite state machine_ 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 _finite state machine_: 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. Because of that, all software is essentially a sequence of state instructions for the microprocessor. Nevertheless, the concept of _finite state machine_ is useful in software design as well. Our text file converter can be designer as a _finite state machine_ with three possible states. We could call them states 0-2, but it will make our life easier if we give them symbolic names: * ordinary * cr * lf Our program will start in the ordinary state. During this state, the program action depends on its input as follows: * 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. * If the input is a carriage return, the state is changed to cr. The input is then discarded, i.e., no output is made. * If the input is a line feed, the state is changed to lf. The input is then discarded. Whenever we are in the cr 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: * 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 ordinary. * 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. * If the input is a line feed, we output the line feed and change the state to ordinary. 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. Finally, we are in the lf 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 UNIX(R) 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. +This will happen when our file already is in UNIX 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: * 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 ordinary. This is exactly the same action as in the cr state upon receiving the same kind of input. * If the input is a carriage return, we discard the input, we output a line feed, then change the state to ordinary. * If the input is a line feed, we output the line feed, and leave the state unchanged. [[x86-final-state]] ==== The Final State The above _finite state machine_ 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 tuc, just to discover that occasionally it strips the last line ending. This problem is easily fixed by checking the state after the entire file was processed. If the state is not ordinary, we simply need to output one last line feed. [NOTE] ==== Now that we have expressed our algorithm as a _finite state machine_, 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. ==== [[x86-tuc-counter]] ==== The Output Counter Because our file conversion program may be combining two characters into one, we need to use an output counter. We initialize it to `0`, 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. [[x86-software-fsm]] === Implementing FSM in Software The hardest part of working with a _finite state machine_ is analyzing the problem and expressing it as a _finite state machine_. That accomplished, the software almost writes itself. In a high-level language, such as C, there are several main approaches. One is to use a `switch` statement which chooses what function should be run. For example, [.programlisting] .... switch (state) { default: case REGULAR: regular(inputchar); break; case CR: cr(inputchar); break; case LF: lf(inputchar); break; } .... Another approach is by using an array of function pointers, something like this: [.programlisting] .... (output[state])(inputchar); .... Yet another is to have `state` be a function pointer, set to point at the appropriate function: [.programlisting] .... (*state)(inputchar); .... 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 `EBX`, and then just issue: [.programlisting] .... call ebx .... 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 _possibly_ because with the caching modern microprocessors do, either way may be equally fast. [[memory-mapped-files]] === Memory Mapped Files 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. -UNIX(R) allows us to map a file, or a section of a file, into memory. +UNIX 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 `mmap` system call to map it into the memory. One nice thing about `mmap` 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 `mov`, `lods`, and `stos`. 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. 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. 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 tuc instead. If you examine your copy of [.filename]#syscalls.master#, you will find two separate syscalls named `mmap`. -This is because of evolution of UNIX(R): There was the traditional BSD `mmap`, syscall 71. +This is because of evolution of UNIX: There was the traditional BSD `mmap`, syscall 71. That one was superseded by the POSIX(R) `mmap`, syscall 197. The FreeBSD system supports both because older programs were written by using the original BSD version. -But new software uses the POSIX(R) version, which is what we will use. +But new software uses the POSIX version, which is what we will use. -The [.filename]#syscalls.master# lists the POSIX(R) version like this: +The [.filename]#syscalls.master# lists the POSIX version like this: [.programlisting] .... 197 STD BSD { caddr_t mmap(caddr_t addr, size_t len, int prot, \ int flags, int fd, long pad, off_t pos); } .... This differs slightly from what man:mmap[2] says. That is because man:mmap[2] describes the C version. The difference is in the `long pad` argument, which is not present in the C version. However, the FreeBSD syscalls add a 32-bit pad after ``push``ing a 64-bit argument. In this case, `off_t` is a 64-bit value. When we are finished working with a memory-mapped file, we unmap it with the `munmap` syscall: [TIP] ==== For an in-depth treatment of `mmap`, see W. Richard Stevens' http://www.int80h.org/cgi-bin/isbn?isbn=0130810819[Unix Network Programming, Volume 2, Chapter 12]. ==== [[x86-file-size]] === Determining File Size Because we need to tell `mmap` 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. We can use the `fstat` syscall to get all the information about an open file that the system can give us. That includes the file size. -Again, [.filename]#syscalls.master# lists two versions of `fstat`, a traditional one (syscall 62), and a POSIX(R) one (syscall 189). -Naturally, we will use the POSIX(R) version: +Again, [.filename]#syscalls.master# lists two versions of `fstat`, a traditional one (syscall 62), and a POSIX one (syscall 189). +Naturally, we will use the POSIX version: [.programlisting] .... 189 STD POSIX { int fstat(int fd, struct stat *sb); } .... This is a very straightforward call: We pass to it the address of a `stat` structure and the descriptor of an open file. It will fill out the contents of the `stat` structure. I do, however, have to say that I tried to declare the `stat` structure in the `.bss` section, and `fstat` 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. [[x86-ftruncate]] === Changing the File Size 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. The `ftruncate` system call allows us to do just that. Despite its somewhat misleading name, the `ftruncate` system call can be used to both truncate the file (make it smaller) and to grow it. And yes, we will find two versions of `ftruncate` in [.filename]#syscalls.master#, an older one (130), and a newer one (201). We will use the newer one: [.programlisting] .... 201 STD BSD { int ftruncate(int fd, int pad, off_t length); } .... Please note that this one contains a `int pad` again. [[x86-ftuc]] === ftuc We now know everything we need to write ftuc. We start by adding some new lines in [.filename]#system.inc#. First, we define some constants and structures, somewhere at or near the beginning of the file: [.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 .... We define the new syscalls: [.programlisting] .... %define SYS_mmap 197 %define SYS_munmap 73 %define SYS_fstat 189 %define SYS_ftruncate 201 .... We add the macros for their use: [.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 .... And here is our code: [.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 .... [WARNING] ==== -Do not use this program on files stored on a disk formatted by MS-DOS(R) or Windows(R). +Do not use this program on files stored on a disk formatted by MS-DOS or Windows. There seems to be a subtle bug in the FreeBSD code when using `mmap` on these drives mounted under FreeBSD: If the file is over a certain size, `mmap` will just fill the memory with zeros, and then copy them to the file overwriting its contents. ==== [[x86-one-pointed-mind]] == One-Pointed Mind As a student of Zen, I like the idea of a one-pointed mind: Do one thing at a time, and do it well. -This, indeed, is very much how UNIX(R) works as well. -While a typical Windows(R) application is attempting to do everything imaginable (and is, therefore, riddled with bugs), a typical UNIX(R) program does only one thing, and it does it well. +This, indeed, is very much how UNIX works as well. +While a typical Windows application is attempting to do everything imaginable (and is, therefore, riddled with bugs), a typical UNIX program does only one thing, and it does it well. -The typical UNIX(R) 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. +The typical UNIX 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. -When writing your own UNIX(R) 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. +When writing your own UNIX 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. [[x86-csv]] === CSV I will illustrate this principle with a specific real-life example I was faced with recently: I needed to extract the 11th field of each record from a database I downloaded from a web site. The database was a CSV file, i.e., a list of _comma-separated values_. That is quite a standard format for sharing data among people who may be using different database software. 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. I tried awk, using the comma as a separator. But because several lines contained a quoted comma, awk was extracting the wrong field from those lines. Therefore, I needed to write my own software to extract the 11th field from the CSV file. -However, going with the UNIX(R) spirit, I only needed to write a simple filter that would do the following: +However, going with the UNIX spirit, I only needed to write a simple filter that would do the following: * Remove the first line from the file; * Change all unquoted commas to a different character; * Remove all quotation marks. Strictly speaking, I could use sed 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. At any rate, writing a program like this took me about 20 minutes. Writing a program that extracts the 11th field from the CSV file would take a lot longer, and I could not reuse it to extract some other field from some other database. This time I decided to let it do a little more work than a typical tutorial program would: * It parses its command line for options; * It displays proper usage if it finds wrong arguments; * It produces meaningful error messages. Here is its usage message: [source,shell] .... Usage: csv [-t] [-c] [-p] [-o ] [-i ] .... All parameters are optional, and can appear in any order. The `-t` parameter declares what to replace the commas with. The `tab` is the default here. For example, `-t;` will replace all unquoted commas with semicolons. I did not need the `-c` 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, `-c@` will replace all at signs (useful if you want to split a list of email addresses to their user names and domains). The `-p` option preserves the first line, i.e., it does not delete it. By default, we delete the first line because in a CSV file it contains the field names rather than data. The `-i` and `-o` options let me specify the input and the output files. -Defaults are [.filename]#stdin# and [.filename]#stdout#, so this is a regular UNIX(R) filter. +Defaults are [.filename]#stdin# and [.filename]#stdout#, so this is a regular UNIX filter. I made sure that both `-i filename` and `-ifilename` are accepted. I also made sure that only one input and one output files may be specified. To get the 11th field of each record, I can now do: [source,shell] .... % csv '-t;' data.csv | awk '-F;' '{print $11}' .... The code stores the options (except for the file descriptors) in `EDX`: The comma in `DH`, the new separator in `DL`, and the flag for the `-p` option in the highest bit of `EDX`, so a check for its sign will give us a quick decision what to do. Here is the code: [.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] [-c] [-p] [-o ] [-i ]', 0Ah usglen equ $-usg iemsg db "csv: Can't open input file", 0Ah iemlen equ $-iemsg oemsg db "csv: Can't create output file", 0Ah oemlen equ $-oemsg section .bss ibuffer resb BUFSIZE obuffer resb BUFSIZE section .text align 4 ierr: push dword iemlen push dword iemsg push dword stderr sys.write push dword 1 ; return failure sys.exit align 4 oerr: push dword oemlen push dword oemsg push dword stderr sys.write push dword 2 sys.exit align 4 usage: push dword usglen push dword usg push dword stderr sys.write push dword 3 sys.exit align 4 global _start _start: add esp, byte 8 ; discard argc and argv[0] mov edx, (',' << 8) | 9 .arg: pop ecx or ecx, ecx je near .init ; no more arguments ; ECX contains the pointer to an argument cmp byte [ecx], '-' jne usage inc ecx mov ax, [ecx] .o: cmp al, 'o' jne .i ; Make sure we are not asked for the output file twice cmp dword [fd.out], stdout jne usage ; Find the path to output file - it is either at [ECX+1], ; i.e., -ofile -- ; or in the next argument, ; i.e., -o file inc ecx or ah, ah jne .openoutput pop ecx jecxz usage .openoutput: push dword 420 ; file mode (644 octal) push dword 0200h | 0400h | 01h ; O_CREAT | O_TRUNC | O_WRONLY push ecx sys.open jc near oerr add esp, byte 12 mov [fd.out], eax jmp short .arg .i: cmp al, 'i' jne .p ; Make sure we are not asked twice cmp dword [fd.in], stdin jne near usage ; Find the path to the input file inc ecx or ah, ah jne .openinput pop ecx or ecx, ecx je near usage .openinput: push dword 0 ; O_RDONLY push ecx sys.open jc near ierr ; open failed add esp, byte 8 mov [fd.in], eax jmp .arg .p: cmp al, 'p' jne .t or ah, ah jne near usage or edx, 1 << 31 jmp .arg .t: cmp al, 't' ; redefine output delimiter jne .c or ah, ah je near usage mov dl, ah jmp .arg .c: cmp al, 'c' jne near usage or ah, ah je near usage mov dh, ah jmp .arg align 4 .init: sub eax, eax sub ebx, ebx sub ecx, ecx mov edi, obuffer ; See if we are to preserve the first line or edx, edx js .loop .firstline: ; get rid of the first line call getchar cmp al, 0Ah jne .firstline .loop: ; read a byte from stdin call getchar ; is it a comma (or whatever the user asked for)? cmp al, dh jne .quote ; Replace the comma with a tab (or whatever the user wants) mov al, dl .put: call putchar jmp short .loop .quote: cmp al, '"' jne .put ; Print everything until you get another quote or EOL. If it ; is a quote, skip it. If it is EOL, print it. .qloop: call getchar cmp al, '"' je .loop cmp al, 0Ah je .put call putchar jmp short .qloop align 4 getchar: or ebx, ebx jne .fetch call read .fetch: lodsb dec ebx ret read: jecxz .read call write .read: push dword BUFSIZE mov esi, ibuffer push esi push dword [fd.in] sys.read add esp, byte 12 mov ebx, eax or eax, eax je .done sub eax, eax ret align 4 .done: call write ; flush output buffer ; close files push dword [fd.in] sys.close push dword [fd.out] sys.close ; return success push dword 0 sys.exit align 4 putchar: stosb inc ecx cmp ecx, BUFSIZE je write ret align 4 write: jecxz .ret ; nothing to write sub edi, ecx ; start of buffer push ecx push edi push dword [fd.out] sys.write add esp, byte 12 sub eax, eax sub ecx, ecx ; buffer is empty now .ret: ret .... Much of it is taken from [.filename]#hex.asm# above. But there is one important difference: I no longer call `write` whenever I am outputting a line feed. Yet, the code can be used interactively. -I have found a better solution for the interactive problem since I first started writing this chapter. +I have found a better solution for the interactive problem since I first started writing this article. 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. The new solution I use now is to call `write` 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. [[x86-buffered-dark-side]] ==== The Dark Side of Buffering This change prevents a mysterious lockup in a very specific case. I refer to it as the _dark side of buffering_, mostly because it presents a danger that is not quite obvious. It is unlikely to happen with a program like the csv 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 _red_, _green_, and _blue_ intensities of a pixel. Our output will be the negative of our input. 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: [.programlisting] .... .loop: call getchar not al ; Create a negative call putchar jmp short .loop .... Because this filter works with raw data, it is unlikely to be used interactively. But it could be called by image manipulation software. And, unless it calls `write` before each call to `read`, chances are it will lock up. Here is what might happen: [.procedure] . The image editor will load our filter using the C function `popen()`. . It will read the first row of pixels from a bitmap or pixmap. . It will write the first row of pixels to the _pipe_ leading to the `fd.in` of our filter. . Our filter will read each pixel from its input, turn it to a negative, and write it to its output buffer. . Our filter will call `getchar` to fetch the next pixel. . `getchar` will find an empty input buffer, so it will call `read`. . `read` will call the `SYS_read` system call. . The _kernel_ will suspend our filter until the image editor sends more data to the pipe. . The image editor will read from the other pipe, connected to the `fd.out` of our filter so it can set the first row of the output image _before_ it sends us the second row of the input. . The _kernel_ suspends the image editor until it receives some output from our filter, so it can pass it on to the image editor. 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. 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 crossref:secure[secure-race-conditions,race condition]. This problem does not exist if our filter flushes its output buffer _before_ asking the _kernel_ for more input data. [[x86-fpu]] == Using the FPU Strangely enough, most of assembly language literature does not even mention the existence of the FPU, or _floating point unit_, let alone discuss programming it. Yet, never does assembly language shine more than when we create highly optimized FPU code by doing things that can be done _only_ in assembly language. [[x86-fpu-organization]] === Organization of the FPU The FPU consists of 8 80-bit floating-point registers. These are organized in a stack fashion-you can `push` a value on TOS (_top of stack_) and you can `pop` it. That said, the assembly language op codes are not `push` and `pop` because those are already taken. You can `push` a value on TOS by using `fld`, `fild`, and `fbld`. Several other op codes let you `push` many common _constants_-such as _pi_-on the TOS. Similarly, you can `pop` a value by using `fst`, `fstp`, `fist`, `fistp`, and `fbstp`. Actually, only the op codes that end with a _p_ will literally `pop` the value, the rest will `store` it somewhere else without removing it from the TOS. We can transfer the data between the TOS and the computer memory either as a 32-bit, 64-bit, or 80-bit _real_, a 16-bit, 32-bit, or 64-bit _integer_, or an 80-bit _packed decimal_. The 80-bit _packed decimal_ is a special case of _binary coded decimal_ which is very convenient when converting between the ASCII representation of data and the internal data of the FPU. It allows us to use 18 significant digits. No matter how we represent data in the memory, the FPU always stores it in the 80-bit _real_ format in its registers. Its internal precision is at least 19 decimal digits, so even if we choose to display results as ASCII in the full 18-digit precision, we are still showing correct results. We can perform mathematical operations on the TOS: We can calculate its _sine_, we can _scale_ it (i.e., we can multiply or divide it by a power of 2), we can calculate its base-2 _logarithm_, and many other things. We can also _multiply_ or _divide_ it by, _add_ it to, or _subtract_ it from, any of the FPU registers (including itself). The official Intel op code for the TOS is `st`, and for the _registers_ `st(0)`-`st(7)`. `st` and `st(0)`, then, refer to the same register. For whatever reasons, the original author of nasm has decided to use different op codes, namely `st0`-`st7`. In other words, there are no parentheses, and the TOS is always `st0`, never just `st`. [[x86-fpu-packed-decimal]] ==== The Packed Decimal Format The _packed decimal_ format uses 10 bytes (80 bits) of memory to represent 18 digits. The number represented there is always an _integer_. [TIP] ==== You can use it to get decimal places by multiplying the TOS by a power of 10 first. ==== The highest bit of the highest byte (byte 9) is the _sign bit_: If it is set, the number is _negative_, otherwise, it is _positive_. The rest of the bits of this byte are unused/ignored. The remaining 9 bytes store the 18 digits of the number: 2 digits per byte. The _more significant digit_ is stored in the high _nibble_ (4 bits), the _less significant digit_ in the low _nibble_. That said, you might think that `-1234567` would be stored in the memory like this (using hexadecimal notation): [.programlisting] .... 80 00 00 00 00 00 01 23 45 67 .... Alas it is not! As with everything else of Intel make, even the _packed decimal_ is _little-endian_. That means our `-1234567` is stored like this: [.programlisting] .... 67 45 23 01 00 00 00 00 00 80 .... Remember that, or you will be pulling your hair out in desperation! [NOTE] ==== The book to read-if you can find it-is Richard Startz' http://www.amazon.com/exec/obidos/ASIN/013246604X/whizkidtechnomag[8087/80287/80387 for the IBM PC & Compatibles]. Though it does seem to take the fact about the little-endian storage of the _packed decimal_ for granted. I kid you not about the desperation of trying to figure out what was wrong with the filter I show below _before_ it occurred to me I should try the little-endian order even for this type of data. ==== [[x86-pinhole-photography]] === Excursion to Pinhole Photography To write meaningful software, we must not only understand our programming tools, but also the field we are creating software for. Our next filter will help us whenever we want to build a _pinhole camera_, so, we need some background in _pinhole photography_ before we can continue. [[x86-camera]] ==== The Camera 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. 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. If some light sensitive material (such as film) is placed inside the camera, it can capture the image. The hole often contains a _lens_, or a lens assembly, often called the _objective_. [[x86-the-pinhole]] ==== The Pinhole But, strictly speaking, the lens is not necessary: The original cameras did not use a lens but a _pinhole_. Even today, _pinholes_ are used, both as a tool to study how cameras work, and to achieve a special kind of image. The image produced by the _pinhole_ is all equally sharp. Or _blurred_. There is an ideal size for a pinhole: If it is either larger or smaller, the image loses its sharpness. [[x86-focal-length]] ==== Focal Length This ideal pinhole diameter is a function of the square root of _focal length_, which is the distance of the pinhole from the film. [.programlisting] .... D = PC * sqrt(FL) .... In here, `D` is the ideal diameter of the pinhole, `FL` is the focal length, and `PC` is a pinhole constant. According to Jay Bender, its value is `0.04`, while Kenneth Connors has determined it to be `0.037`. 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. [[x86-f-number]] ==== The F-Number 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 f/5.6 may require the exposure to last 1/1000 sec. 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. The f-number is easy to calculate: [.programlisting] .... F = FL / D .... 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. 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 `A` as `t`, then the exposure at f-number `B` is: [.programlisting] .... t * (B / A)² .... [[x86-normalized-f-number]] ==== Normalized F-Number 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. To allow for different f-numbers, cameras typically contained a metal plate with several holes of different sizes drilled to them. 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. 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 somewha. [[x86-f-stop]] ==== The F-Stop 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 _stop_ in that position. Because of that, these positions of the dial are called f-stops. 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. [[x86-pinhole-software]] === Designing the Pinhole Software We are now ready to decide what exactly we want our pinhole software to do. [[xpinhole-processing-input]] ==== Processing Program Input Since its main purpose is to help us design a working pinhole camera, we will use the _focal length_ 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. Most of the programs we have written so far worked with individual characters, or bytes, as their input: The hex program converted individual bytes into a hexadecimal number, the csv program either let a character through, or deleted it, or changed it to a different character, etc. One program, ftuc used the state machine to consider at most two input bytes at a time. But our pinhole program cannot just work with individual characters, it has to deal with larger syntactic units. For example, if we want the program to calculate the pinhole diameter (and other values we will discuss later) at the focal lengths of `100 mm`, `150 mm`, and `210 mm`, we may want to enter something like this: [source,shell] .... 100, 150, 210 .... Our program needs to consider more than a single byte of input at a time. When it sees the first `1`, it must understand it is seeing the first digit of a decimal number. When it sees the `0` and the other `0`, it must know it is seeing more digits of the same number. 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 `100`. And the digits of the second number into the value of `150`. And, of course, the digits of the third number into the numeric value of `210`. 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? 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 _obvious_ that it is an extra character. Duh! Plus, it allows me to break up the monotony of computing and type in a query instead of just a number: [source,shell] .... What is the best pinhole diameter for the focal length of 150? .... There is no reason for the computer to spit out a number of complaints: [source,shell] .... Syntax error: What Syntax error: is Syntax error: the Syntax error: best .... Et cetera, et cetera, et cetera. Secondly, I like the `+#+` 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. In our case, we also need to decide what units the input should come in: We choose _millimeters_ because that is how most photographers measure the focus length. 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 _comma_). 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 `50` and `51`, so allowing the user to input something like `50.5` 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. [[x86-pinhole-options]] ==== Offering Options 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 `PC` constant, we will need to have the choice. -It is traditional in UNIX(R) 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. +It is traditional in UNIX 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. Why have two ways of choosing? One is to allow a (relatively) _permanent_ 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. 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 _"rc"_ is added to the file name. So, ours could be [.filename]#~/.pinhole# or [.filename]#~/.pinholerc#. (The [.filename]#~/# means current user's home directory.) 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 _environment variable_. In our case, we might look at an environment variable named `PINHOLE`. 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). Because we only need to choose _one_ such parameter, we will go with the second method and search the environment for a variable named `PINHOLE`. The other way allows us to make _ad hoc_ decisions: _"Though I usually want you to use 0.039, this time I want 0.03872."_ In other words, it allows us to _override_ the permanent choice. This type of choice is usually done with command line parameters. Finally, a program _always_ needs a _default_. 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. Given this system, the program may find conflicting options, and handle them this way: [.procedure] . If it finds an _ad hoc_ choice (e.g., command line parameter), it should accept that choice. It must ignore any permanent choice and any default. . _Otherwise_, if it finds a permanent option (e.g., an environment variable), it should accept it, and ignore the default. . _Otherwise_, it should use the default. We also need to decide what _format_ our `PC` option should have. At first site, it seems obvious to use the `PINHOLE=0.04` format for the environment variable, and `-p0.04` for the command line. Allowing that is actually a security risk. The `PC` constant is a very small number. Naturally, we will test our software using various small values of `PC`. But what will happen if someone runs the program choosing a huge value? It may crash the program because we have not designed it to handle huge numbers. 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. Or, we might say, _"Tough! The user should know better.""_ 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 _implied 0._ prefix. In other words, if the user wants `0.04`, we will expect him to type `-p04`, or set `PINHOLE=04` in his environment. So, if he says `-p9999999`, we will interpret it as ``0.9999999``-still ridiculous but at least safer. 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 `-b` as identical to `-p04`, and `-c` as identical to `-p037`. [[x86-pinhole-output]] ==== The Output We need to decide what we want our software to send to the output, and in what format. 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 `tab` character. Optionally, we should also allow the user to specify the use of the CSV 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 `comma` for the `tab`. We need a command line option for the CSV format. We cannot use `-c` because that already means _use Connors' constant_. For some strange reason, many web sites refer to CSV files as _"Excel spreadsheet"_ (though the CSV format predates Excel). We will, therefore, use the `-e` switch to inform our software we want the output in the CSV format. 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. 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. 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. So, it makes perfect sense to start each line with the focal length as entered by the user. No, wait! Not as entered by the user. What if the user types in something like this: [source,shell] .... 00000000150 .... Clearly, we need to strip those leading zeros. So, we might consider reading the user input as is, converting it to binary inside the FPU, and printing it out from there. But... What if the user types something like this: [source,shell] .... 17459765723452353453534535353530530534563507309676764423 .... Ha! The packed decimal FPU format lets us input 18-digit numbers. But the user has entered more than 18 digits. How do we handle that? Well, we _could_ modify our code to read the first 18 digits, enter it to the FPU, then read more, multiply what we already have on the TOS by 10 raised to the number of additional digits, then `add` to it. Yes, we could do that. But in _this_ 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). 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. What will we do? We will slap him in the face, in a manner of speaking: [source,shell] .... 17459765723452353453534535353530530534563507309676764423 ??? ??? ??? ??? ??? .... To achieve that, we will simply ignore any leading zeros. Once we find a non-zero digit, we will initialize a counter to `0` and start taking three steps: [.procedure] . Send the digit to the output. . Append the digit to a buffer we will use later to produce the packed decimal we can send to the FPU. . Increase the counter. Now, while we are taking these three steps, we also need to watch out for one of two conditions: * If the counter grows above 18, we stop appending to the buffer. We continue reading the digits and sending them to the output. * If, or rather _when_, the next input character is not a digit, we are done inputting for now. + Incidentally, we can simply discard the non-digit, unless it is a `+#+`, 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. 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. We can determine this has happened whenever our counter stays at `0`. In that case we need to send `0` to the output, and perform another "slap in the face": [source,shell] .... 0 ??? ??? ??? ??? ??? .... Once we have displayed the focal length and determined it is valid (greater than `0` but not exceeding 18 digits), we can calculate the pinhole diameter. It is not by coincidence that _pinhole_ contains the word _pin_. Indeed, many a pinhole literally is a _pin hole_, a hole carefully punched with the tip of a pin. That is because a typical pinhole is very small. Our formula gets the result in millimeters. We will multiply it by `1000`, so we can output the result in _microns_. At this point we have yet another trap to face: _Too much precision._ Yes, the FPU was designed for high precision mathematics. But we are not dealing with high precision mathematics. We are dealing with physics (optics, specifically). 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 `12` meters long, so we have the focal length of `12000`. Well, using Bender's constant, it gives us square root of `12000` multiplied by `0.04`, which is `4.381780460` millimeters, or `4381.780460` microns. Put either way, the result is absurdly precise. Our truck is not _exactly_ `12000` millimeters long. We did not measure its length with such a precision, so stating we need a pinhole with the diameter of `4.381780460` millimeters is, well, deceiving. `4.4` millimeters would do just fine. [NOTE] ==== I "only" used ten digits in the above example. Imagine the absurdity of going for all 18! ==== 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 `4382` microns. Looking at that number, we still decide that `4400` microns, or `4.4` millimeters is close enough. 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 FPU does not offer rounding to a specific number of digits (after all, it does not view the numbers as decimal but as binary). We, therefore, must devise an algorithm to reduce the number of significant digits. Here is mine (I think it is awkward-if you know a better one, _please_, let me know): [.procedure] . Initialize a counter to `0`. . While the number is greater than or equal to `10000`, divide it by `10` and increase the counter. . Output the result. . While the counter is greater than `0`, output `0` and decrease the counter. [NOTE] ==== The `10000` is only good if you want _four_ significant digits. For any other number of significant digits, replace `10000` with `10` raised to the number of significant digits. ==== We will, then, output the pinhole diameter in microns, rounded off to four significant digits. At this point, we know the _focal length_ and the _pinhole diameter_. That means we have enough information to also calculate the _f-number_. 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 _normalized f-number_, i.e., the nearest power of the square root of 2. We do that by multiplying the actual f-number by itself, which, of course, will give us its `square`. 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 FPU gives us a good shortcut to do that: We can use the `fscale` op code to "scale" 1, which is analogous to ``shift``ing an integer left. Finally, we calculate the square root of it all, and we have the nearest normalized f-number. 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: [.programlisting] .... fmul st0, st0 fld1 fld st1 fyl2x frndint fld1 fscale fsqrt fstp st1 .... The first line, `fmul st0, st0`, squares the contents of the TOS (top of the stack, same as `st`, called `st0` by nasm). The `fld1` pushes `1` on the TOS. The next line, `fld st1`, pushes the square back to the TOS. At this point the square is both in `st` and `st(2)` (it will become clear why we leave a second copy on the stack in a moment). `st(1)` contains `1`. Next, `fyl2x` calculates base-2 logarithm of `st` multiplied by `st(1)`. That is why we placed `1` on `st(1)` before. At this point, `st` contains the logarithm we have just calculated, `st(1)` contains the square of the actual f-number we saved for later. `frndint` rounds the TOS to the nearest integer. `fld1` pushes a `1`. `fscale` shifts the `1` we have on the TOS by the value in `st(1)`, effectively raising 2 to `st(1)`. Finally, `fsqrt` calculates the square root of the result, i.e., the nearest normalized f-number. We now have the nearest normalized f-number on the TOS, the base-2 logarithm rounded to the nearest integer in `st(1)`, and the square of the actual f-number in `st(2)`. We are saving the value in `st(2)` for later. But we do not need the contents of `st(1)` anymore. The last line, `fstp st1`, places the contents of `st` to `st(1)`, and pops. As a result, what was `st(1)` is now `st`, what was `st(2)` is now `st(1)`, etc. The new `st` contains the normalized f-number. The new `st(1)` contains the square of the actual f-number we have stored there for posterity. 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. 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. Earlier we have figured out the formula of calculating proper exposure at an arbitrary f-number from that measured at a different f-number. Every light meter I have ever seen can determine proper exposure at f5.6. We will, therefore, calculate an _"f5.6 multiplier,"_ i.e., by how much we need to multiply the exposure measured at f5.6 to determine the proper exposure for our pinhole camera. From the above formula we know this factor can be calculated by dividing our f-number (the actual one, not the normalized one) by `5.6`, and squaring the result. Mathematically, dividing the square of our f-number by the square of `5.6` will give us the same result. Computationally, we do not want to square two numbers when we can only square one. So, the first solution seems better at first. But... `5.6` is a _constant_. We do not have to have our FPU waste precious cycles. We can just tell it to divide the square of the f-number by whatever `5.6²` equals to. Or we can divide the f-number by `5.6`, and then square the result. The two ways now seem equal. But, they are not! Having studied the principles of photography above, we remember that the `5.6` is actually square root of 2 raised to the fifth power. An _irrational_ number. The square of this number is _exactly_ `32`. Not only is `32` an integer, it is a power of 2. We do not need to divide the square of the f-number by `32`. We only need to use `fscale` to shift it right by five positions. In the FPU lingo it means we will `fscale` it with `st(1)` equal to `-5`. That is _much faster_ than a division. So, now it has become clear why we have saved the square of the f-number on the top of the FPU 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. 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. 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. 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. [[x86-fpu-optimizations]] === FPU Optimizations In assembly language we can optimize the FPU code in ways impossible in high languages, including C. Whenever a C function needs to calculate a floating-point value, it loads all necessary variables and constants into FPU 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. It "returns" the value by leaving the result on the TOS. However, before it returns, it cleans up. Any variables and constants it used in its calculation are now gone from the FPU. 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. We _knew_ 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. 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. Of course, the C programmer may know it. But the only recourse he has is to store the value in a memory variable. That means, for one, the value will be changed from the 80-bit precision used internally by the FPU to a C _double_ (64 bits) or even _single_ (32 bits). That also means that the value must be moved from the TOS into the memory, and then back again. Alas, of all FPU operations, the ones that access the computer memory are the slowest. So, whenever programming the FPU in assembly language, look for the ways of keeping intermediate results on the FPU stack. We can take that idea even further! In our program we are using a _constant_ (the one we named `PC`). 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. Early on in our program, we are calculating the value of the above constant. We need to divide our input by `10` for every digit in the constant. It is much faster to multiply than to divide. So, at the start of our program, we divide `10` into `1` to obtain `0.1`, which we then keep on the stack: Instead of dividing the input by `10` for every digit, we multiply it by `0.1`. By the way, we do not input `0.1` directly, even though we could. We have a reason for that: While `0.1` can be expressed with just one decimal place, we do not know how many _binary_ places it takes. We, therefore, let the FPU calculate its binary value to its own high precision. We are using other constants: We multiply the pinhole diameter by `1000` to convert it from millimeters to microns. We compare numbers to `10000` when we are rounding them off to four significant digits. So, we keep both, `1000` and `10000`, on the stack. And, of course, we reuse the `0.1` when rounding off numbers to four digits. Last but not least, we keep `-5` on the stack. We need it to scale the square of the f-number, instead of dividing it by `32`. 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 `-5` is at `st(1)`, precisely where `fscale` expects it to be. It is common to create certain constants from scratch instead of loading them from the memory. That is what we are doing with `-5`: [.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 .... We can generalize all these optimizations into one rule: _Keep repeat values on the stack!_ [TIP] ==== _PostScript(R)_ is a stack-oriented programming language. There are many more books available about PostScript(R) than about the FPU assembly language: Mastering PostScript(R) will help you master the FPU. ==== [[x86-pinhole-the-code]] === pinhole-The Code [.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 ] [-o ] [-i ]', 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 .... The code follows the same format as all the other filters we have seen before, with one subtle exception: ____ We are no longer assuming that the end of input implies the end of things to do, something we took for granted in the _character-oriented_ filters. This filter does not process characters. It processes a _language_ (albeit a very simple one, consisting only of numbers). When we have no more input, it can mean one of two things: * We are done and can quit. This is the same as before. * The last character we have read was a digit. We have stored it at the end of our ASCII-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. For that reason, we have modified our `getchar` and our `read` routines to return with the `carry flag` _clear_ whenever we are fetching another character from the input, or the `carry flag` _set_ whenever there is no more input. Of course, we are still using assembly language magic to do that! Take a good look at `getchar`. It _always_ returns with the `carry flag` _clear_. Yet, our main code relies on the `carry flag` to tell it when to quit-and it works. The magic is in `read`. Whenever it receives more input from the system, it just returns to `getchar`, which fetches a character from the input buffer, _clears_ the `carry flag` and returns. But when `read` receives no more input from the system, it does _not_ return to `getchar` at all. Instead, the `add esp, byte 4` op code adds `4` to `ESP`, _sets_ the `carry flag`, and returns. So, where does it return to? Whenever a program uses the `call` op code, the microprocessor ``push``es the return address, i.e., it stores it on the top of the stack (not the FPU stack, the system stack, which is in the memory). When a program uses the `ret` op code, the microprocessor ``pop``s the return value from the stack, and jumps to the address that was stored there. But since we added `4` to `ESP` (which is the stack pointer register), we have effectively given the microprocessor a minor case of _amnesia_: It no longer remembers it was `getchar` that ``call``ed `read`. And since `getchar` never ``push``ed anything before ``call``ing `read`, the top of the stack now contains the return address to whatever or whoever ``call``ed `getchar`. As far as that caller is concerned, he ``call``ed `getchar`, which ``ret``urned with the `carry flag` set! ____ Other than that, the `bcdload` routine is caught up in the middle of a Lilliputian conflict between the Big-Endians and the Little-Endians. It is converting the text representation of a number into that number: The text is stored in the big-endian order, but the _packed decimal_ is little-endian. To solve the conflict, we use the `std` op code early on. We cancel it with `cld` later on: It is quite important we do not `call` anything that may depend on the default setting of the _direction flag_ while `std` is active. -Everything else in this code should be quit eclear, providing you have read the entire chapter that precedes it. +Everything else in this code should be quit eclear, providing you have read the entire article that precedes it. 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. [[x86-pinhole-using]] === Using pinhole Because we have decided to make the program _ignore_ any input except for numbers (and even those inside a comment), we can actually perform _textual queries_. We do not _have to_, but we _can_. In my humble opinion, forming a textual query, instead of having to follow a very strict syntax, makes software much more user friendly. 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 _fine-tune_ 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 _ask_ a couple of questions. Our session might look like this: [source,shell] .... % pinhole Computer, What size pinhole do I need for the focal length of 150? 150 490 306 362 2930 12 Hmmm... How about 160? 160 506 316 362 3125 12 Let's make it 155, please. 155 498 311 362 3027 12 Ah, let's try 157... 157 501 313 362 3066 12 156? 156 500 312 362 3047 12 That's it! Perfect! Thank you very much! ^D .... 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. [[x86-pinhole-scripting]] === Scripting Because we have chosen the `+#+` character to denote the start of a comment, we can treat our pinhole software as a _scripting language_. You have probably seen shell _scripts_ that start with: [.programlisting] .... #! /bin/sh .... ...or... [.programlisting] .... #!/bin/sh .... ...because the blank space after the `#!` is optional. -Whenever UNIX(R) is asked to run an executable file which starts with the `#!`, it assumes the file is a script. +Whenever UNIX is asked to run an executable file which starts with the `#!`, 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. Suppose now that we have installed pinhole in /usr/local/bin/, we can now write a script to calculate various pinhole diameters suitable for various focal lengths commonly used with the 120 film. The script might look something like this: [.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 .... Because 120 is a medium size film, we may name this file medium. We can set its permissions to execute, and run it as if it were a program: [source,shell] .... % chmod 755 medium % ./medium .... -UNIX(R) will interpret that last command as: +UNIX will interpret that last command as: [source,shell] .... % /usr/local/bin/pinhole -b -i ./medium .... It will run that command and display: [source,shell] .... 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 .... Now, let us enter: [source,shell] .... % ./medium -c .... -UNIX(R) will treat that as: +UNIX will treat that as: [source,shell] .... % /usr/local/bin/pinhole -b -i ./medium -c .... That gives it two conflicting options: `-b` and `-c` (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: [source,shell] .... 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 .... We decide we want to go with Bender's constant after all. We want to save its values as a comma-separated file: [source,shell] .... % ./medium -b -e > bender % cat bender 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 % .... [[x86-caveats]] == Caveats -Assembly language programmers who "grew up" under MS-DOS(R) and Windows(R) often tend to take shortcuts. -Reading the keyboard scan codes and writing directly to video memory are two classical examples of practices which, under MS-DOS(R) are not frowned upon but considered the right thing to do. +Assembly language programmers who "grew up" under MS-DOS and Windows often tend to take shortcuts. +Reading the keyboard scan codes and writing directly to video memory are two classical examples of practices which, under MS-DOS are not frowned upon but considered the right thing to do. -The reason? Both the PC BIOS and MS-DOS(R) are notoriously slow when performing these operations. +The reason? Both the PC BIOS and MS-DOS are notoriously slow when performing these operations. -You may be tempted to continue similar practices in the UNIX(R) environment. -For example, I have seen a web site which explains how to access the keyboard scan codes on a popular UNIX(R) clone. +You may be tempted to continue similar practices in the UNIX environment. +For example, I have seen a web site which explains how to access the keyboard scan codes on a popular UNIX clone. -That is generally a _very bad idea_ in UNIX(R) environment! Let me explain why. +That is generally a _very bad idea_ in UNIX environment! Let me explain why. [[x86-protected]] -=== UNIX(R) Is Protected +=== UNIX Is Protected For one thing, it may simply not be possible. -UNIX(R) runs in protected mode. +UNIX runs in protected mode. Only the kernel and device drivers are allowed to access hardware directly. -Perhaps a particular UNIX(R) clone will let you read the keyboard scan codes, but chances are a real UNIX(R) operating system will not. +Perhaps a particular UNIX clone will let you read the keyboard scan codes, but chances are a real UNIX 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. [[x86-abstraction]] -=== UNIX(R) Is an Abstraction +=== UNIX Is an Abstraction -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 UNIX(R) like systems that let you do it: +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 UNIX like systems that let you do it: -_UNIX(R) is an abstraction!_ +_UNIX is an abstraction!_ -There is a major difference in the philosophy of design between MS-DOS(R) and UNIX(R). -MS-DOS(R) was designed as a single-user system. +There is a major difference in the philosophy of design between MS-DOS and UNIX. +MS-DOS 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. -This is NEVER guaranteed under UNIX(R). -It is quite common for a UNIX(R) user to pipe and redirect program input and output: +This is NEVER guaranteed under UNIX. +It is quite common for a UNIX user to pipe and redirect program input and output: [source,shell] .... % program1 | program2 | program3 > file1 .... If you have written program2, your input does not come from the keyboard but from the output of program1. Similarly, your output does not go to the screen but becomes the input for program3 whose output, in turn, goes to [.filename]#file1#. 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 PC-style scan codes. -It may be a Macintosh(R), or any other computer. +It may be a Macintosh, or any other computer. -Now you may be shaking your head: My software is in PC assembly language, how can it run on a Macintosh(R)? But I did not say your software would be running on a Macintosh(R), only that its terminal may be a Macintosh(R). +Now you may be shaking your head: My software is in PC assembly language, how can it run on a Macintosh? But I did not say your software would be running on a Macintosh, only that its terminal may be a Macintosh. -Under UNIX(R), 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 Macintosh(R) user in Australia connects to a UNIX(R) system in North America (or anywhere else) via telnet. +Under UNIX, 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 Macintosh user in Australia connects to a UNIX system in North America (or anywhere else) via telnet. 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! 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. -That is why under UNIX(R) you must never make any assumptions about where your data is coming from and going to. +That is why under UNIX 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. [NOTE] ==== 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 UNIX(R) form MS-DOS(R). +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 UNIX form MS-DOS. Of course, creative people often break rules, and it is OK as long as they know they are breaking them and why. ==== [[x86-acknowledgements]] == Acknowledgements -This tutorial would never have been possible without the help of many experienced FreeBSD programmers from the {freebsd-hackers}, many of whom have patiently answered my questions, and pointed me in the right direction in my attempts to explore the inner workings of UNIX(R) system programming in general and FreeBSD in particular. +This tutorial would never have been possible without the help of many experienced FreeBSD programmers from the {freebsd-hackers}, many of whom have patiently answered my questions, and pointed me in the right direction in my attempts to explore the inner workings of UNIX system programming in general and FreeBSD in particular. Thomas M. Sommers opened the door for me. His https://web.archive.org/web/20090914064615/http://www.codebreakers-journal.com/content/view/262/27[How do I write "Hello, world" in FreeBSD assembler?] web page was my first encounter with an example of assembly language programming under FreeBSD. Jake Burkholder has kept the door open by willingly answering all of my questions and supplying me with example assembly language source code. Copyright (R) 2000-2001 G. Adam Stanislav. All rights reserved. diff --git a/documentation/content/ru/articles/x86-assembly/_index.adoc b/documentation/content/ru/articles/x86-assembly/_index.adoc index a7222e861b..94c8727391 100644 --- a/documentation/content/ru/articles/x86-assembly/_index.adoc +++ b/documentation/content/ru/articles/x86-assembly/_index.adoc @@ -1,3855 +1,3855 @@ --- title: 'Программирование на языке ассемблера для x86' authors: ~ description: 'Программирование на ассемблере x86' -tags: ["x86", "assembly", "programming", "guide"] +tags: ["assembly", "guide", "ia32", "ld", "llvm-as", "nasm", "programming", "x86"] --- [[x86]] = Программирование на ассемблере x86 :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] _Эта глава была написана {stanislav}._ [[x86-intro]] == Обзор Программирование на ассемблере в UNIX(R) крайне плохо документировано. Обычно предполагается, что никто не захочет его использовать, поскольку различные системы UNIX(R) работают на разных микропроцессорах, и поэтому всё должно быть написано на C для обеспечения переносимости. В действительности переносимость программ на C — это скорее миф. Даже программы на C требуют изменений при переносе с одной UNIX(R)-системы на другую, независимо от процессора, на котором они работают. Обычно такая программа содержит множество условных операторов, зависящих от системы, для которой она компилируется. Даже если мы считаем, что всё программное обеспечение UNIX(R) должно быть написано на C или другом языке высокого уровня, нам всё равно нужны программисты на ассемблере: кто же ещё напишет часть библиотеки C, которая обращается к ядру? В этой главе я попытаюсь показать вам, как можно использовать язык ассемблера для написания программ под UNIX(R), в частности под FreeBSD. В этой главе не объясняются основы языка ассемблера. Существует достаточно ресурсов на эту тему (например, полный онлайн-курс по языку ассемблера можно найти в http://webster.cs.ucr.edu/[Искусстве языка ассемблера] Рэндалла Хайда; если вы предпочитаете печатные книги, обратите внимание на «Язык ассемблера шаг за шагом» Джеффа Дантемана (ISBN: 0471375233)). Однако после прочтения этой главы любой программист на языке ассемблера сможет писать программы для FreeBSD быстро и эффективно. Copyright (R) 2000-2001 G. Adam Stanislav. All rights reserved. [[x86-the-tools]] == Инструменты [[x86-the-assembler]] === Ассемблер Важнейшим инструментом для программирования на языке ассемблера является ассемблер — программа, преобразующая код на языке ассемблера в машинный код. Три очень разных ассемблера доступны для FreeBSD. И man:llvm-as[1] (включён в package:devel/llvm[]), и man:as[1] (включён в package:devel/binutils[]) используют традиционный синтаксис ассемблера UNIX(R). С другой стороны, man:nasm[1] (устанавливаемый через package:devel/nasm[]) использует синтаксис Intel. Его основное преимущество в том, что он может ассемблировать код для многих операционных систем. В этой главе используется синтаксис nasm, потому что большинство программистов на ассемблере, приходящих в FreeBSD из других операционных систем, найдут его более понятным. Кроме того, если честно, это то, к чему я привык. [[x86-the-linker]] === Компоновщик Результат работы ассемблера, как и любого компилятора, необходимо связать, чтобы получить исполняемый файл. Стандартный компоновщик man:ld[1] поставляется с FreeBSD. Он работает с кодом, собранным любым из ассемблеров. [[x86-system-calls]] == Системные вызовы [[x86-default-calling-convention]] === Стандартное соглашение о вызовах По умолчанию ядро FreeBSD использует соглашение о вызовах C. Кроме того, хотя доступ к ядру осуществляется с помощью `int 80h`, предполагается, что программа вызовет функцию, которая выполняет `int 80h`, а не будет выполнять `int 80h` напрямую. Эта традиция очень удобна и значительно превосходит соглашение Microsoft(R), используемое в MS-DOS(R). Почему? Потому что соглашение UNIX(R) позволяет любой программе, написанной на любом языке, обращаться к ядру. Программа на ассемблере также может это сделать. Например, мы могли бы открыть файл: [.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 .... Это очень понятный и переносимый способ написания кода. Если вам нужно перенести код на UNIX(R)-систему, которая использует другое прерывание или другой способ передачи параметров, все, что вам нужно изменить, это процедуру kernel. Но программисты на ассемблере любят экономить такты. Приведённый выше пример требует комбинации `call/ret`. Мы можем исключить её, сделав ``push`` дополнительного двойного слова: [.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 .... Помещённое в `EAX` значение `5` идентифицирует функцию ядра, в данном случае `open`. [[x86-alternate-calling-convention]] === Альтернативное соглашение о вызовах FreeBSD — это чрезвычайно гибкая система. Она предлагает другие способы вызова ядра. Однако для работы необходимо, чтобы в системе была установлена эмуляция Linux. Linux — это система, подобная UNIX(R). Однако её ядро использует то же соглашение о системных вызовов для передачи параметров в регистрах, что и MS-DOS(R). Как и в соглашении UNIX(R), номер функции помещается в `EAX`. Однако параметры передаются не в стеке, а в регистрах `EBX, ECX, EDX, ESI, EDI, EBP`: [.programlisting] .... open: mov eax, 5 mov ebx, path mov ecx, flags mov edx, mode int 80h .... Этот подход имеет значительный недостаток по сравнению с UNIX(R), по крайней мере, в контексте программирования на ассемблере: каждый раз при вызове ядра необходимо сохранять регистры с помощью `push`, а затем восстанавливать их с помощью `pop`. Это делает ваш код более громоздким и медленным. Тем не менее, FreeBSD предоставляет вам выбор. Если вы решите использовать соглашение Linux, вы должны сообщить об этом системе. После того как ваша программа будет ассемблирована и слинкована, вам нужно пометить исполняемый файл: [source, shell] .... % brandelf -t Linux filename .... [[x86-use-geneva]] === Какое соглашение следует использовать? Если вы разрабатываете код специально для FreeBSD, всегда следует использовать соглашение UNIX(R): это быстрее, вы можете хранить глобальные переменные в регистрах, вам не нужно маркировать исполняемый файл, и вы не требуете установки пакета эмуляции Linux на целевой системе. Хотя вы можете хотеть создать переносимый код, который также работает на Linux, вам, вероятно, по-прежнему будет нужен максимально эффективный код для пользователей FreeBSD. Я покажу вам, как этого добиться, после того как объясню основы. [[x86-call-numbers]] === Номера вызовов Чтобы сообщить ядру, какую системную службу вы вызываете, поместите её номер в `EAX`. Разумеется, вам необходимо знать, что это за номер. [[x86-the-syscalls-file]] ==== Файл [.filename]#syscalls# Номера перечислены в [.filename]#syscalls#. Команда `locate syscalls` находит этот файл в нескольких различных форматах, все они создаются автоматически из [.filename]#syscalls.master#. Основной файл для стандартного соглашения о вызовах UNIX(R) можно найти в [.filename]#/usr/src/sys/kern/syscalls.master#. Если вам необходимо использовать другое соглашение, реализованное в режиме эмуляции Linux, обратитесь к [.filename]#/usr/src/sys/i386/linux/syscalls.master#. [NOTE] ==== Не только FreeBSD и Linux используют разные соглашения о вызовах, но иногда они используют разные номера для одних и тех же функций. ==== [.filename]#syscalls.master# описывает, как должен быть выполнен вызов: [.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... .... Это крайний левый столбец, который указывает число, которое нужно поместить в `EAX`. Самый правый столбец указывает, какие параметры нужно `втолкнуть` в стек командой push. Они `вталкиваются` _справа налево_. Например, чтобы `открыть` файл, нам сначала нужно сделать `push` для `mode`, затем `flags`, а затем адрес, по которому хранится `path`. [[x86-return-values]] == Возвращаемые значения От системных вызовов не было бы никакой пользы, если бы они не возвращали какое-либо значение: дескриптор открытого файла, количество байтов, прочитанных в буфер, системное время и т.д. Кроме того, система должна уведомлять нас, если возникает ошибка: файл не существует, системные ресурсы исчерпаны, передан недопустимый параметр и т. д. [[x86-man-pages]] === Страницы Справочника Традиционным источником информации о различных системных вызовах в UNIX(R)-системах являются страницы Справочника. В FreeBSD системные вызовы описаны в разделе 2, иногда в разделе 3. Например, man:open[2] говорит: [.blockquote] В случае успеха `open()` возвращает неотрицательное целое число, называемое файловым дескриптором. В случае ошибки возвращается `-1`, а переменной `errno` присваивается код ошибки. Программист на ассемблере, впервые столкнувшийся с UNIX(R) и FreeBSD, сразу же задастся вопросом: где находится `errno` и как к ней обратиться? [NOTE] ==== Информация, представленная в руководствах, применима к программам на языке C. Программистам на языке ассемблера требуется дополнительная информация. ==== [[x86-where-return-values]] === Где возвращаемые значения? К сожалению, это зависит от ситуации... Для большинства системных вызовов возвращаемое значение находится в `EAX`, но не для всех. Хорошее правило при первой работе с системным вызовом — искать возвращаемое значение в `EAX`. Если его там нет, потребуется дополнительное исследование. [NOTE] ==== Я знаю о одном системном вызове, который возвращает значение в `EDX`: `SYS_fork`. Все остальные, с которыми я работал, используют `EAX`. Но я ещё не работал со всеми из них. ==== [TIP] ==== Если вы не можете найти ответ здесь или где-либо ещё, изучите исходный код libc и посмотрите, как он взаимодействует с ядром. ==== [[x86-where-errno]] === Где находится `errno`? Фактически, нигде... `errno` является частью языка C, а не ядра UNIX(R). При прямом доступе к сервисам ядра код ошибки возвращается в регистре `EAX` — том же регистре, в котором обычно оказывается корректное возвращаемое значение. Это совершенно логично. Если нет ошибки, то нет и кода ошибки. Если есть ошибка, то нет возвращаемого значения. Один регистр может содержать либо то, либо другое. [[x86-how-to-know-error]] === Определение возникновения ошибки При использовании стандартного соглашения о вызовах FreeBSD флаг `carry flag` сбрасывается при успехе и устанавливается при неудаче. При использовании режима эмуляции Linux знаковое значение в `EAX` неотрицательно в случае успеха и содержит возвращаемое значение. В случае ошибки значение отрицательное, т.е. `-errno`. [[x86-portable-code]] == Создание переносимого кода Портативность обычно не является сильной стороной языка ассемблера. Тем не менее, написание программ на ассемблере для разных платформ возможно, особенно с использованием nasm. Я создавал библиотеки на ассемблере, которые можно было собрать для таких разных операционных систем, как Windows(R) и FreeBSD. Это становится ещё более возможным, когда вы хотите, чтобы ваш код работал на двух платформах, которые, хотя и различны, основаны на схожих архитектурах. Например, FreeBSD — это UNIX(R), а Linux — UNIX(R)-подобная система. Я упомянул лишь три различия между ними (с точки зрения программиста на ассемблере): соглашение о вызовах, номера функций и способ возврата значений. [[x86-deal-with-function-numbers]] === Работа с номерами функций Во многих случаях номера функций совпадают. Однако, даже если это не так, проблему легко решить: вместо использования чисел в коде применяйте константы, объявленные по-разному в зависимости от целевой архитектуры: [.programlisting] .... %ifdef LINUX %define SYS_execve 11 %else %define SYS_execve 59 %endif .... [[x86-deal-with-geneva]] === Работа с соглашениями Оба, соглашение о вызовах и возвращаемое значение (проблема `errno`) могут быть решены с помощью макросов: [.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 .... [[x86-deal-with-other-portability]] === Устранение прочих проблем с переносимостью Приведённые выше решения могут помочь в большинстве случаев написания кода, переносимого между FreeBSD и Linux. Тем не менее, с некоторыми сервисами ядра различия более глубокие. В таком случае необходимо написать два разных обработчика для этих конкретных системных вызовов и использовать условную компиляцию. К счастью, большая часть вашего кода выполняет действия, отличные от вызовов ядра, поэтому обычно потребуется лишь несколько таких условных секций в коде. [[x86-portable-library]] === Использование библиотеки Вы можете полностью избежать проблем с переносимостью в основном коде, написав библиотеку системных вызовов. Создайте отдельную библиотеку для FreeBSD, другую для Linux и ещё другие библиотеки для дополнительных операционных систем. В вашей библиотеке напишите отдельную функцию (или процедуру, если вы предпочитаете традиционную терминологию ассемблера) для каждого системного вызова. Используйте соглашение о вызовах C для передачи параметров. Однако по-прежнему передавайте номер вызова через `EAX`. В таком случае ваша библиотека FreeBSD может быть очень простой, так как множество внешне различных функций могут быть просто метками одного и того же кода: [.programlisting] .... sys.open: sys.close: [etc...] int 80h ret .... Ваша библиотека Linux потребует больше различных функций. Но даже здесь вы можете группировать системные вызовы, используя одинаковое количество параметров: [.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 .... Подход с использованием библиотек может показаться неудобным на первый взгляд, так как требует создания отдельного файла, от которого зависит ваш код. Однако у него есть множество преимуществ: во-первых, вам нужно написать его лишь один раз, и затем вы можете использовать его во всех своих программах. Вы даже можете позволить другим программистам на ассемблере использовать его или, возможно, воспользоваться библиотекой, написанной кем-то другим. Но, пожалуй, самое большое преимущество библиотеки заключается в том, что ваш код может быть перенесён на другие системы, даже другими программистами, просто путём написания новой библиотеки без каких-либо изменений в вашем коде. Если вам не нравится идея использования библиотеки, вы можете хотя бы разместить все системные вызовы в отдельном файле на ассемблере и скомпоновать его с основной программой. Здесь, опять же, все, что нужно сделать переносчикам, — это создать новый объектный файл для компоновки с основной программой. [[x86-portable-include]] === Использование включаемого файла Если вы выпускаете своё программное обеспечение в виде исходного кода (или вместе с ним), вы можете использовать макросы и размещать их в отдельном файле, который включается в ваш код. Портеры вашего программного обеспечения просто напишут новый include-файл. Никакая библиотека или внешний объектный файл не требуются, и ваш код остаётся переносимым без необходимости редактирования. [NOTE] ==== Это подход, который мы будем использовать на протяжении всей главы. Мы назовем наш включаемый файл [.filename]#system.inc# и будем добавлять в него новые системные вызовы по мере их рассмотрения. ==== Мы можем начать наш [.filename]#system.inc# с объявления стандартных файловых дескрипторов: [.programlisting] .... %define stdin 0 %define stdout 1 %define stderr 2 .... Далее мы создаем символическое имя для каждого системного вызова: [.programlisting] .... %define SYS_nosys 0 %define SYS_exit 1 %define SYS_fork 2 %define SYS_read 3 %define SYS_write 4 ; [etc...] .... Добавляем короткую, неглобальную процедуру с длинным именем, чтобы случайно не использовать это имя в нашем коде: [.programlisting] .... section .text align 4 access.the.bsd.kernel: int 80h ret .... Мы создаем макрос, который принимает один аргумент — номер системного вызова: [.programlisting] .... %macro system 1 mov eax, %1 call access.the.bsd.kernel %endmacro .... Наконец, мы создаем макросы для каждого системного вызова. Эти макросы не принимают аргументов. [.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...] .... Продолжайте, введите это в ваш редактор и сохраните как [.filename]#system.inc#. Мы добавим больше по мере обсуждения дополнительных системных вызовов. [[x86-first-program]] == Наша первая программа Мы готовы к нашей первой обязательной программе — Hello, World! [.programlisting] .... %include 'system.inc' section .data hello db 'Hello, World!', 0Ah hbytes equ $-hello section .text global _start _start: push dword hbytes push dword hello push dword stdout sys.write push dword 0 sys.exit .... Вот что он делает: Строка 1 включает определения, макросы и код из файла [.filename]#system.inc#. Строки 3-5 содержат данные: строка 3 начинает раздел/сегмент данных. Строка 4 содержит строку "Hello, World!", за которой следует новая строка (`0Ah`). Строка 5 создаёт константу, содержащую длину строки из строки 4 в байтах. Строки 7-16 содержат код. Обратите внимание, что FreeBSD использует формат файлов _elf_ для исполняемых файлов, который требует, чтобы каждая программа запускается с адреса, помеченного как `_start` (или, точнее, компоновщик ожидает этого). Эта метка должна быть глобальной. Строки 10-13 указывают системе записать `hbytes` байтов строки `hello` в `stdout`. Строки 15-16 указывают системе завершить программу с возвращаемым значением `0`. Системный вызов `SYS_exit` никогда не возвращает управление, поэтому код завершается в этой точке. [NOTE] ==== Если вы перешли на UNIX(R) с опытом программирования на ассемблере для MS-DOS(R), вы, возможно, привыкли писать напрямую в видеопамять. В FreeBSD или любой другой разновидности UNIX(R) вам не придётся об этом беспокоиться. С вашей точки зрения, вы записываете данные в файл под названием [.filename]#stdout#. Это может быть экран, терминал telnet, обычный файл или даже входные данные другой программы. Определять, что именно это будет, — задача системы. ==== [[x86-assemble-1]] === Ассемблирование кода Наберите код в редакторе и сохраните его в файле с именем [.filename]#hello.asm#. Для сборки вам понадобится nasm. [[x86-get-nasm]] ==== Установка nasm Если у вас нет nasm, введите: [source, shell] .... % su Password:your root password # cd /usr/ports/devel/nasm # make install # exit % .... Вы можете ввести `make install clean` вместо просто `make install`, если не хотите сохранять исходный код nasm. В любом случае FreeBSD автоматически загрузит nasm из интернета, скомпилирует его и установит в вашу систему. [NOTE] ==== Если ваша система не FreeBSD, вам нужно получить nasm с его https://sourceforge.net/projects/nasm[домашней страницы]. Вы по-прежнему можете использовать его для ассемблирования кода FreeBSD. ==== Теперь вы можете собрать, скомпоновать и запустить код: [source, shell] .... % nasm -f elf hello.asm % ld -s -o hello hello.o % ./hello Hello, World! % .... [[x86-unix-filters]] == Написание фильтров UNIX(R) Распространённым типом приложений в UNIX(R) являются фильтры — программы, которые читают данные из [.filename]#stdin#, обрабатывают их определённым образом, а затем записывают результат в [.filename]#stdout#. В этой главе мы разработаем простой фильтр и научимся читать из [.filename]#stdin# и писать в [.filename]#stdout#. Этот фильтр будет преобразовывать каждый байт входных данных в шестнадцатеричное число, за которым следует пробел. [.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 .... В разделе данных мы создаем массив с именем `hex`. Он содержит 16 шестнадцатеричных цифр в порядке возрастания. За массивом следует буфер, который мы будем использовать как для ввода, так и для вывода. Первые два байта буфера изначально установлены в `0`. Именно сюда мы будем записывать две шестнадцатеричные цифры (первый байт также является местом, откуда мы будем считывать ввод). Третий байт — это пробел. Фрагмент кода состоит из четырёх частей: чтение байта, преобразование его в шестнадцатеричное число, запись результата и завершение программы. Для чтения байта мы просим систему прочитать один байт из [.filename]#stdin# и сохранить его в первом байте `buffer`. Система возвращает количество прочитанных байтов в `EAX`. Это значение будет `1`, пока поступают данные, или `0`, если больше нет доступных входных данных. Поэтому мы проверяем значение `EAX`. Если оно равно `0`, мы переходим к метке `.done`, в противном случае продолжаем выполнение. [NOTE] ==== Для простоты мы пока игнорируем возможность возникновения ошибки. ==== Шестнадцатеричное преобразование считывает байт из `buffer` в `EAX`, а точнее только в `AL`, обнуляя остальные биты `EAX`. Мы также копируем байт в `EDX`, потому что нам нужно преобразовать верхние четыре бита (ниббл) отдельно от нижних четырёх битов. Результат сохраняется в первых двух байтах буфера. Далее мы просим систему записать три байта буфера, то есть две шестнадцатеричные цифры и пробел, в [.filename]#stdout#. Затем мы возвращаемся к началу программы и обрабатываем следующий байт. Когда ввод больше не остаётся, мы просим систему завершить нашу программу, возвращая ноль, что традиционно означает успешное выполнение программы. Продолжайте и сохраните код в файле с именем [.filename]#hex.asm#, затем введите следующее (символ `^D` означает, что нужно нажать клавишу управления и, удерживая её, ввести `D`): [source, shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come! 48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D % .... [NOTE] ==== Если вы переходите на UNIX(R) с MS-DOS(R), вам может быть интересно, почему каждая строка заканчивается на `0A` вместо `0D 0A`. Это связано с тем, что UNIX(R) не использует соглашение cr/lf, а использует соглашение "новая строка", которое в шестнадцатеричном виде представлено как `0A`. ==== Можем ли мы это улучшить? Что ж, во-первых, это немного запутанно, потому что после преобразования строки текста наш ввод больше не начинается с начала строки. Мы можем изменить это, чтобы после каждого `0A` выводилась новая строка вместо пробела: [.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 .... Мы сохранили пробел в регистре `CL`. Это безопасно, потому что, в отличие от Microsoft(R) Windows(R), вызовы системы UNIX(R) не изменяют значение регистров, которые не используются для возврата значения. Это означает, что нам нужно установить `CL` только один раз. Поэтому мы добавили новую метку `.loop` и переходим к ней для следующего байта вместо перехода к `_start`. Мы также добавили метку `.hex`, чтобы третий байт `buffer` мог быть либо пробелом, либо новой строкой. После внесения изменений в файл [.filename]#hex.asm# введите: [source, shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come! 48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D % .... Выглядит лучше. Но этот код довольно неэффективен! Мы выполняем системный вызов для каждого отдельного байта дважды (один раз для чтения и ещё один для записи вывода). [[x86-buffered-io]] == Буферизованный ввод и вывод Мы можем повысить эффективность нашего кода, буферизуя ввод и вывод. Мы создаём входной буфер и читаем сразу целую последовательность байтов. Затем мы извлекаем их по одному из буфера. Мы также создаем выходной буфер. Мы сохраняем наш вывод в нём, пока он не заполнится. В этот момент мы просим ядро записать содержимое буфера в [.filename]#stdout#. Программа завершается, когда больше нет входных данных. Но нам всё ещё нужно попросить ядро записать содержимое нашего выходного буфера в [.filename]#stdout# в последний раз, иначе часть нашего вывода попадёт в буфер, но так и не будет отправлена. Не забудьте об этом, иначе будете недоумевать, куда пропала часть вывода. [.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 .... Теперь у нас есть третий раздел в исходном коде с именем `.bss`. Этот раздел не включается в исполняемый файл и, следовательно, не может быть инициализирован. Мы используем `resb` вместо `db`. Это просто резервирует запрошенный размер неинициализированной памяти для нашего использования. Мы используем тот факт, что система не изменяет регистры: мы используем регистры для того, что в противном случае пришлось бы хранить в глобальных переменных в секции `.data`. Именно поэтому соглашение UNIX(R) о передаче параметров системных вызовов через стек превосходит соглашение Microsoft о передаче их в регистрах: мы можем оставить регистры для собственного использования. Мы используем `EDI` и `ESI` как указатели на следующий байт для чтения или записи. Мы используем `EBX` и `ECX` для отслеживания количества байтов в двух буферах, чтобы знать, когда нужно вывести данные в систему или считать новые данные из системы. Давайте посмотрим, как это работает сейчас: [source, shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! Here I come! 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 ^D % .... Не то, что вы ожидали? Программа не выводила результат, пока мы не нажали `^D`. Это легко исправить, добавив три строки кода для вывода результата каждый раз, когда мы преобразуем новую строку в `0A`. Я пометил эти три строки символом > (не копируйте > в ваш [.filename]#hex.asm#). [.programlisting] .... %include 'system.inc' %define BUFSIZE 2048 section .data hex db '0123456789ABCDEF' section .bss ibuffer resb BUFSIZE obuffer resb BUFSIZE section .text global _start _start: sub eax, eax sub ebx, ebx sub ecx, ecx mov edi, obuffer .loop: ; read a byte from stdin call getchar ; convert it to hex mov dl, al shr al, 4 mov al, [hex+eax] call putchar mov al, dl and al, 0Fh mov al, [hex+eax] call putchar mov al, ' ' cmp dl, 0Ah jne .put mov al, dl .put: call putchar > cmp al, 0Ah > jne .loop > call write jmp short .loop align 4 getchar: or ebx, ebx jne .fetch call read .fetch: lodsb dec ebx ret read: push dword BUFSIZE mov esi, ibuffer push esi push dword stdin sys.read add esp, byte 12 mov ebx, eax or eax, eax je .done sub eax, eax ret align 4 .done: call write ; flush output buffer push dword 0 sys.exit align 4 putchar: stosb inc ecx cmp ecx, BUFSIZE je write ret align 4 write: sub edi, ecx ; start of buffer push ecx push edi push dword stdout sys.write add esp, byte 12 sub eax, eax sub ecx, ecx ; buffer is empty now ret .... Теперь давайте посмотрим, как это работает: [source, shell] .... % nasm -f elf hex.asm % ld -s -o hex hex.o % ./hex Hello, World! 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come! 48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D % .... Неплохо для исполняемого файла размером 644 байта, не так ли! [NOTE] ==== Такой подход к буферизированному вводу/выводу всё ещё содержит скрытую опасность. Я расскажу об этом и исправлю её позже, когда речь пойдёт о crossref:x86[x86-buffered-dark-side,тёмной стороне буферизации]. ==== [[x86-ungetc]] === Как отменить чтение символа [WARNING] ==== Это может быть несколько сложной темой, в основном представляющей интерес для программистов, знакомых с теорией компиляторов. Если хотите, вы можете crossref:x86[x86-command-line, перейти к следующему разделу], и, возможно, прочитаете это позже. ==== Хотя наш пример программы не требует этого, более сложные фильтры часто нуждаются в предварительном просмотре. Другими словами, им может потребоваться узнать, какой следующий символ (или даже несколько символов). Если следующий символ имеет определённое значение, он является частью текущего обрабатываемого токена. В противном случае — нет. Например, вы можете анализировать входной поток на наличие текстовой строки (например, при реализации компилятора языка): если символ следует за другим символом или, возможно, цифрой, он является частью обрабатываемой лексемы. Если за ним следует пробел или другое значение, то он не является частью текущей лексемы. Это представляет интересную проблему: как вернуть следующий символ обратно во входной поток, чтобы его можно было прочитать позже? Одно из возможных решений — сохранить его в символьной переменной, а затем установить флаг. Мы можем изменить `getchar`, чтобы он проверял флаг, и если он установлен, извлекал байт из этой переменной вместо буфера ввода, а затем сбрасывал флаг. Но, конечно, это замедляет работу. В языке C есть функция `ungetc()`, как раз для этой цели. Есть ли быстрый способ реализовать её в нашем коде? Я хочу, чтобы вы пролистали назад и взглянули на процедуру `getchar`, и попробовали найти красивое и быстрое решение, прежде чем читать следующий абзац. Затем вернитесь сюда и посмотрите моё собственное решение. Ключом к возвращению символа обратно в поток является то, как мы получаем символы изначально: Сначала проверяем, пуст ли буфер, проверяя значение `EBX`. Если оно равно нулю, вызываем процедуру `read`. Если у нас есть доступный символ, мы используем `lodsb`, затем уменьшаем значение `EBX`. Инструкция `lodsb` фактически идентична: [.programlisting] .... mov al, [esi] inc esi .... Байт, который мы извлекли, остаётся в буфере до следующего вызова `read`. Мы не знаем, когда это произойдет, но знаем, что этого не случится до следующего вызова `getchar`. Следовательно, чтобы "вернуть" последний прочитанный байт обратно в поток, нам достаточно уменьшить значение `ESI` и увеличить значение `EBX`: [.programlisting] .... ungetc: dec esi inc ebx ret .... Но будьте осторожны! Мы в полной безопасности, если заглядываем вперёд только на один символ за раз. Если же мы проверяем несколько следующих символов и вызываем `ungetc` несколько раз подряд, это будет работать в большинстве случаев, но не всегда (и ошибки будет сложно отладить). Почему? Потому что пока `getchar` не вызывает `read`, все предварительно прочитанные байты остаются в буфере, и наш `ungetc` работает без сбоев. Но как только `getchar` вызывает `read`, содержимое буфера изменяется. Мы всегда можем рассчитывать на корректную работу `ungetc` с последним символом, прочитанным через `getchar`, но не с любым символом, прочитанным до этого. Если ваша программа читает более одного байта вперёд, у вас есть как минимум два варианта: Если возможно, измените программу так, чтобы она читала только один байт вперёд. Это самое простое решение. Если эта опция недоступна, сначала определите максимальное количество символов, которое вашей программе может потребоваться вернуть во входной поток за один раз. Увеличьте это число немного, чтобы быть уверенным, предпочтительно до кратного 16 — так оно будет лучше выровнено. Затем измените секцию `.bss` в вашем коде и создайте небольшой "запасной" буфер прямо перед вашим входным буфером, примерно так: [.programlisting] .... section .bss resb 16 ; or whatever the value you came up with ibuffer resb BUFSIZE obuffer resb BUFSIZE .... Вам также необходимо изменить ваш `ungetc`, чтобы передать значение байта для возврата в `AL`: [.programlisting] .... ungetc: dec esi inc ebx mov [esi], al ret .... С этим изменением вы можете безопасно вызывать `ungetc` до 17 раз подряд (первый вызов всё ещё будет в пределах буфера, остальные 16 могут быть либо в пределах буфера, либо в пределах "запасного" пространства). [[x86-command-line]] == Аргументы командной строки Наша программа hex будет полезнее, если она сможет читать имена входного и выходного файлов из командной строки, т.е. если она сможет обрабатывать аргументы командной строки. Но... Где они? Прежде чем UNIX(R) система запустит программу, она делает ``push`` для некоторых данных, помещая их в стек, затем переходит к метке `_start` программы. Да, я сказал "переходит", а не "вызывает". Это означает, что данные можно прочитать с помощью `[esp+offset]` или просто сделать ``pop`` для них. Значение на вершине стека содержит количество аргументов командной строки. Оно традиционно называется `argc`, что означает "argument count". Далее следуют аргументы командной строки, все `argc` штук. Обычно их называют `argv`, что означает "значение(я) аргумента". То есть мы получаем `argv[0]`, `argv[1]`, `...`, `argv[argc-1]`. Это не сами аргументы, а указатели на аргументы, то есть адреса памяти, где находятся реальные аргументы. Сами аргументы представляют собой строки символов, завершающиеся нулевым символом ('\0'). Список `argv` завершается указателем NULL, который представляет собой просто `0`. Есть и другие детали, но пока этого достаточно для наших целей. [NOTE] ==== Если вы перешли из среды программирования MS-DOS(R), основное различие заключается в том, что каждый аргумент находится в отдельной строке. Второе различие состоит в том, что нет практического ограничения на количество аргументов. ==== Вооружившись этими знаниями, мы почти готовы к следующей версии [.filename]#hex.asm#. Однако сначала нам нужно добавить несколько строк в [.filename]#system.inc#: Сначала нам нужно добавить две новые записи в наш список номеров системных вызовов: [.programlisting] .... %define SYS_open 5 %define SYS_close 6 .... Затем мы добавляем два новых макроса в конце файла: [.programlisting] .... %macro sys.open 0 system SYS_open %endmacro %macro sys.close 0 system SYS_close %endmacro .... Вот наш измененный исходный код: [.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 .... В нашем разделе `.data` теперь есть две новые переменные, `fd.in` и `fd.out`. Здесь мы сохраняем дескрипторы файлов для ввода и вывода. В разделе `.text` мы заменили ссылки с `stdin` и `stdout` на `[fd.in]` и `[fd.out]`. Раздел `.text` теперь начинается с простого обработчика ошибок, который просто завершает программу с кодом возврата `1`. Обработчик ошибок расположен перед `_start`, чтобы находиться вблизи от места возникновения ошибок. Естественно, выполнение программы по-прежнему начинается с `_start`. Сначала мы удаляем `argc` и `argv[0]` из стека: они не представляют для нас интереса (по крайней мере, в этой программе). Мы помещаем `argv[1]` в `ECX`. Этот регистр особенно подходит для указателей, так как мы можем обрабатывать NULL-указатели с помощью `jecxz`. Если `argv[1]` не равен NULL, мы пытаемся открыть файл с именем, указанным в первом аргументе. В противном случае продолжаем программу как раньше: чтение из `stdin`, запись в `stdout`. Если нам не удаётся открыть входной файл (например, он не существует), мы переходим к обработчику ошибок и завершаем работу. Если всё прошло успешно, мы проверяем второй аргумент. Если он присутствует, мы открываем выходной файл. В противном случае, мы отправляем вывод в `stdout`. Если нам не удаётся открыть выходной файл (например, он существует и у нас нет прав на запись), мы снова переходим к обработчику ошибок. Остальная часть кода остаётся прежней, за исключением того, что мы закрываем входной и выходной файлы перед завершением, и, как упоминалось, используем `[fd.in]` и `[fd.out]`. Наш исполняемый файл теперь имеет внушительный размер в 768 байт. Можем ли мы улучшить его ещё? Конечно! Каждую программу можно улучшить. Вот несколько идей, что мы могли бы сделать: * Сделать наш обработчик ошибок, выводящий сообщение в `stderr`. * Добавить обработчики ошибок в функции `read` и `write`. * Закрывать `stdin` при открытии входного файла, `stdout` при открытии выходного файла. * Добавить параметры командной строки, такие как `-i` и `-o`, чтобы можно было перечислять входные и выходные файлы в любом порядке или, возможно, читать из `stdin` и записывать в файл. * Выводить сообщение с подсказкой об использовании программы, если аргументы командной строки указаны неверно. Я оставлю эти улучшения в качестве упражнения для читателя: вы уже знаете всё необходимое для их реализации. [[x86-environment]] == Окружение UNIX(R) Важным концептом UNIX(R) является окружение, которое определяется _переменными окружения_. Некоторые из них устанавливаются системой, другие — пользователем, третьи — оболочкой или любой программой, которая загружает другую программу. [[x86-find-environment]] === Как найти переменные окружения Я говорил ранее, что когда программа начинает выполняться, в стеке находятся `argc`, за которым следует массив `argv`, завершающийся NULL, а затем что-то ещё. Это "что-то ещё" — это _окружение_, или, если быть точнее, массив указателей на _переменные окружения_, завершающийся NULL. Это часто называют `env`. Структура `env` такая же, как у `argv` — список адресов памяти, заканчивающийся NULL (`0`). В данном случае нет `"envc"` — конец массива определяется поиском последнего NULL. Переменные обычно имеют формат `name=value`, но иногда часть `=value` может отсутствовать. Необходимо учитывать эту вероятность. [[x86-webvar]] === webvars Я мог бы просто показать вам код, который выводит окружение так же, как команда UNIX(R) env. Но я подумал, что будет интереснее написать простую CGI-утилиту на ассемблере. [[x86-cgi]] ==== CGI: краткий обзор У меня есть http://www.whizkidtech.redprince.net/cgi-bin/tutorial[подробное руководство по CGI] на моем веб-сайте, но вот очень краткий обзор CGI: * Веб-сервер взаимодействует с CGI-программой, устанавливая _переменные окружения_. * Программа CGI отправляет свой вывод в [.filename]#stdout#. Веб-сервер считывает его оттуда. * Он должен начинаться с HTTP-заголовка, за которым следуют две пустые строки. * Затем он выводит HTML-код или любые другие данные, которые он генерирует. [NOTE] ==== В то время как некоторые _переменные окружения_ используют стандартные имена, другие различаются в зависимости от веб-сервера. Это делает программу webvars весьма полезным инструментом для диагностики. ==== [[x86-webvars-the-code]] ==== Код Наша программа webvars, таким образом, должна отправить HTTP-заголовок, за которым следует HTML-разметка. Затем она должна прочитать _переменные окружения_ одну за другой и отправить их как часть HTML-страницы. Код приведен ниже. Я разместил комментарии и пояснения прямо в коде: [.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 '', 0Ah db '', 0Ah db '', 0Ah db '', 0Ah db 'Web Environment', 0Ah db '', 0Ah db '', 0Ah, 0Ah db '', 0Ah db '
', 0Ah db '

Web Environment

', 0Ah db '

The following environment variables are defined ' db 'on this web server:

', 0Ah, 0Ah db '', 0Ah httplen equ $-http left db '', 0Ah db '', 0Ah db '', 0Ah db '', 0Ah rightlen equ $-right wrap db '
' leftlen equ $-left middle db '' midlen equ $-middle undef db '(undefined)' undeflen equ $-undef right db '
', 0Ah db '
', 0Ah db '', 0Ah db '', 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 .... Этот код создаёт исполняемый файл размером 1 396 байт. Большая его часть — это данные, а именно HTML-разметка, которую нам нужно отправить. Запустите ассемблер и слинкуйте как обычно: [source, shell] .... % nasm -f elf webvars.asm % ld -s -o webvars webvars.o .... Для использования необходимо загрузить [.filename]#webvars# на ваш веб-сервер. В зависимости от настроек веб-сервера, возможно, потребуется разместить его в специальном каталоге [.filename]#cgi-bin# или переименовать с расширением [.filename]#.cgi#. Затем вам нужно использовать браузер для просмотра вывода. Чтобы увидеть вывод на моем веб-сервере, перейдите по ссылке http://www.int80h.org/webvars/[http://www.int80h.org/webvars/]. Если вам интересно узнать о дополнительных переменных окружения в защищенном паролем веб-каталоге, перейдите по адресу http://www.int80h.org/private/[http://www.int80h.org/private/], используя имя `asm` и пароль `programmer`. [[x86-files]] == Работа с файлами Мы уже выполнили некоторые базовые операции с файлами: мы знаем, как их открывать и закрывать, как читать и записывать их с использованием буферов. Однако UNIX(R) предлагает гораздо больше возможностей при работе с файлами. В этом разделе мы рассмотрим некоторые из них и в итоге создадим удобную утилиту для преобразования файлов. В самом деле, начнем с конца, то есть с утилиты преобразования файлов. Всегда легче программировать, когда с самого начала известно, каким должен быть конечный продукт. Одной из первых программ, которые я написал для UNIX(R), была link:ftp://ftp.int80h.org/unix/tuc/[tuc] — конвертер текста в файл UNIX(R). Она преобразует текстовый файл из других операционных систем в текстовый файл UNIX(R). Другими словами, она изменяет различные виды окончаний строк на стандартные для UNIX(R). Результат сохраняется в другом файле. По желанию, она может преобразовать текстовый файл UNIX(R) в текстовый файл DOS. Я широко использовал `tuc`, но всегда только для преобразования из какой-либо другой ОС в UNIX(R), никогда наоборот. Мне всегда хотелось, чтобы он просто перезаписывал файл, вместо того чтобы мне приходилось отправлять вывод в другой файл. В большинстве случаев я в итоге использую его так: [source, shell] .... % tuc myfile tempfile % mv tempfile myfile .... Было бы здорово иметь ftuc, т.е., _быстрый tuc_, и использовать его вот так: [source, shell] .... % ftuc myfile .... В этой главе мы напишем ftuc на языке ассемблера (оригинальный tuc написан на C) и в процессе изучим различные файловые сервисы ядра. На первый взгляд, такое преобразование файла кажется очень простым: нужно всего лишь удалить символы возврата каретки, верно? Если вы ответили «да», подумайте ещё раз: такой подход будет работать в большинстве случаев (по крайней мере, с текстовыми файлами MS DOS), но иногда он будет давать сбой. Проблема в том, что не все текстовые файлы, не относящиеся к UNIX(R), завершают строки последовательностью возврата каретки / перевода строки. Некоторые используют возврат каретки без перевода строки. Другие объединяют несколько пустых строк в один возврат каретки, за которым следует несколько переводов строки. И так далее. Конвертер текстовых файлов, следовательно, должен уметь обрабатывать любые возможные окончания строк: * возврат каретки (carriage return) / перевод строки (line feed) * возврат каретки * перевод строки / возврат каретки * перевод строки Это также должно обрабатывать файлы, использующие комбинации вышеуказанного (например, возврат каретки с последующими несколькими переводами строки). [[x86-finite-state-machine]] === Конечный автомат Проблема легко решается с использованием техники, называемой _конечный автомат_, изначально разработанной создателями цифровых электронных схем. _Конечный автомат_ — это цифровая схема, выход которой зависит не только от входа, но и от предыдущего входа, то есть от её состояния. Микропроцессор является примером _конечного автомата_: наш код на языке ассемблера транслируется в машинный язык, где одни инструкции ассемблера превращаются в один байт машинного кода, а другие — в несколько байтов. Когда микропроцессор извлекает байты из памяти один за другим, некоторые из них просто изменяют его состояние, а не производят какой-либо выходной сигнал. После извлечения всех байтов кода операции микропроцессор выдаёт выходной сигнал, изменяет значение регистра и т. д. Из-за этого всё программное обеспечение по сути представляет собой последовательность инструкций состояния для микропроцессора. Тем не менее, концепция _конечного автомата_ также полезна при проектировании программного обеспечения. Наш конвертер текстовых файлов можно представить в виде _конечного автомата_ с тремя возможными состояниями. Мы могли бы назвать их состояниями 0-2, но будет проще, если дадим им символические имена: * ordinary * cr * lf Наша программа начнёт работу в обычном состоянии. В этом состоянии действие программы зависит от её входных данных следующим образом: * Если ввод представляет собой что-либо, кроме возврата каретки или перевода строки, ввод просто передаётся на вывод. Состояние остаётся неизменным. * Если входной символ — возврат каретки, состояние изменяется на cr. Затем входной символ отбрасывается, т.е. вывод не производится. * Если входной символ является переводом строки, состояние изменяется на lf. Затем входной символ отбрасывается. Всякий раз, когда мы находимся в состоянии `cr`, это означает, что последним вводом был символ возврата каретки, который не был обработан. Действия нашего программного обеспечения в этом состоянии снова зависят от текущего ввода: * Если ввод отличается от возврата каретки или перевода строки, вывести перевод строки, затем вывести ввод, а затем изменить состояние на обычное. * Если входной символ — возврат каретки, значит, мы получили два (или более) возврата каретки подряд. Мы отбрасываем ввод, выводим перевод строки и оставляем состояние неизменным. * Если входной символ — это перевод строки, мы выводим перевод строки и меняем состояние на обычное. Обратите внимание, что это не то же самое, что в первом случае выше — если бы мы попытались объединить их, мы бы выводили два перевода строки вместо одного. Наконец, мы находимся в состоянии `lf` после получения перевода строки, которому не предшествовал возврат каретки. Это произойдет, если наш файл уже в формате UNIX(R), или когда несколько строк подряд выражены одним возвратом каретки, за которым следуют несколько переводов строк, или когда строка заканчивается последовательностью перевода строки / возврата каретки. Вот как нам нужно обрабатывать ввод в этом состоянии: * Если ввод отличается от возврата каретки или перевода строки, мы выводим перевод строки, затем выводим ввод и изменяем состояние на обычное. Это действие полностью совпадает с действием в состоянии `cr` при получении аналогичного ввода. * Если ввод представляет собой символ возврата каретки, мы отбрасываем ввод, выводим символ перевода строки, затем изменяем состояние на обычное. * Если входной символ — перевод строки, мы выводим перевод строки и оставляем состояние неизменным. [[x86-final-state]] ==== Конечное состояние Приведённый выше _конечный автомат_ работает для всего файла, но оставляет возможность, что последний конец строки будет проигнорирован. Это произойдёт, если файл заканчивается одиночным возвратом каретки или одиночным переводом строки. Я не подумал об этом, когда писал tuc, и лишь позже обнаружил, что иногда он удаляет последний конец строки. Эта проблема легко решается проверкой состояния после обработки всего файла. Если состояние не является обычным, нам просто нужно вывести последний перевод строки. [NOTE] ==== Теперь, когда мы выразили наш алгоритм в виде _конечного автомата_, мы могли бы легко разработать специализированную цифровую электронную схему («чип») для выполнения преобразования. Конечно, это было бы значительно дороже, чем написание программы на языке ассемблера. ==== [[x86-tuc-counter]] ==== Счетчик вывода Поскольку наша программа преобразования файлов может объединять два символа в один, нам необходимо использовать счётчик вывода. Мы инициализируем его значением `0` и увеличиваем каждый раз, когда отправляем символ на выход. В конце программы счётчик укажет, какой размер необходимо установить для файла. [[x86-software-fsm]] === Реализация конечного автомата в программном обеспечении Самая сложная часть работы с _конечным автоматом_ — это анализ задачи и её представление в виде _конечного автомата_. После этого программное обеспечение практически пишется само. На языке высокого уровня, таком как C, существует несколько основных подходов. Один из них — использование оператора `switch`, который выбирает, какую функцию следует выполнить. Например, [.programlisting] .... switch (state) { default: case REGULAR: regular(inputchar); break; case CR: cr(inputchar); break; case LF: lf(inputchar); break; } .... Еще один подход заключается в использовании массива указателей на функции, например: [.programlisting] .... (output[state])(inputchar); .... Еще один вариант — сделать `state` указателем на функцию, установив его на соответствующую функцию: [.programlisting] .... (*state)(inputchar); .... Это подход, который мы будем использовать в нашей программе, потому что его очень легко реализовать на языке ассемблера, и он также очень быстрый. Мы просто будем хранить адрес нужной процедуры в `EBX`, а затем выполним: [.programlisting] .... call ebx .... Это возможно быстрее, чем жёстко задавать адрес в коде, потому что микропроцессору не нужно извлекать адрес из памяти — он уже хранится в одном из его регистров. Я сказал _возможно_, потому что с учётом кэширования, которое выполняют современные микропроцессоры, оба варианта могут быть одинаково быстрыми. [[memory-mapped-files]] === Отображенные в память файлы Поскольку наша программа работает с одним файлом, мы не можем использовать подход, который работал ранее, то есть чтение из входного файла и запись в выходной файл. UNIX(R) позволяет нам отображать файл или его часть в память. Для этого сначала необходимо открыть файл с соответствующими флагами чтения/записи. Затем мы используем системный вызов `mmap`, чтобы отобразить его в память. Одно из преимуществ `mmap` заключается в том, что он автоматически работает с виртуальной памятью: мы можем отобразить в память больше файла, чем имеется физической памяти, и при этом обращаться к нему с помощью обычных команд работы с памятью, таких как `mov`, `lods` и `stos`. Все изменения, внесённые в память, отображённую из файла, будут записаны в файл системой. Нам даже не нужно держать файл открытым: пока он остаётся отображённым, мы можем читать из него и записывать в него. 32-разрядные микропроцессоры Intel могут адресовать до четырёх гигабайт памяти — физической или виртуальной. Система FreeBSD позволяет использовать до половины этого объёма для отображения файлов. Для упрощения в этом руководстве мы будем преобразовывать только файлы, которые могут быть полностью отображены в памяти. Вероятно, не так много текстовых файлов превышают размер в два гигабайта. Если наша программа встретит такой файл, она просто выведет сообщение с предложением использовать оригинальный tuc. Если вы изучите свою копию файла [.filename]#syscalls.master#, вы найдёте два отдельных системных вызова с именем `mmap`. Это связано с эволюцией UNIX(R): существовал традиционный BSD `mmap`, системный вызов 71. Он был заменён на POSIX(R) `mmap`, системный вызов 197. Система FreeBSD поддерживает оба, поскольку старые программы были написаны с использованием оригинальной BSD-версии. Но новое программное обеспечение использует версию POSIX(R), которую мы и будем применять. В [.filename]#syscalls.master# POSIX(R) версия указана следующим образом: [.programlisting] .... 197 STD BSD { caddr_t mmap(caddr_t addr, size_t len, int prot, \ int flags, int fd, long pad, off_t pos); } .... Это немного отличается от того, что указано в man:mmap[2]. Это связано с тем, что man:mmap[2] описывает версию на языке C. Разница заключается в аргументе `long pad`, который отсутствует в версии на C. Однако системные вызовы FreeBSD добавляют 32-битный заполнитель после ``push`` 64-битного аргумента. В данном случае `off_t` является 64-битным значением. Когда мы завершаем работу с файлом, отображённым в память, мы освобождаем его с помощью системного вызова `munmap`: [TIP] ==== Для подробного изучения `mmap` см. http://www.int80h.org/cgi-bin/isbn?isbn=0130810819[Unix Network Programming, Volume 2, Chapter 12] У. Ричарда Стивенса. ==== [[x86-file-size]] === Определение размера файла Поскольку нам нужно указать `mmap`, сколько байт файла отобразить в памяти, и поскольку мы хотим отобразить весь файл, нам необходимо определить его размер. Мы можем использовать системный вызов `fstat` для получения всей информации об открытом файле, которую система может нам предоставить. Это включает в себя размер файла. Вновь, в [.filename]#syscalls.master# указаны две версии `fstat`: традиционная (системный вызов 62) и POSIX(R) (системный вызов 189). Естественно, мы будем использовать версию POSIX(R): [.programlisting] .... 189 STD POSIX { int fstat(int fd, struct stat *sb); } .... Это очень простой вызов: мы передаем ему адрес структуры `stat` и дескриптор открытого файла. Он заполнит содержимое структуры `stat`. Однако должен сказать, что я пытался объявить структуру `stat` в секции `.bss`, и `fstat` это не понравилось: был установлен флаг переноса, указывающий на ошибку. После того как я изменил код, чтобы разместить структуру в стеке, всё заработало как надо. [[x86-ftruncate]] === Изменение размера файла Поскольку наша программа может объединять последовательности возврата каретки / перевода строки в простые переводы строк, наш вывод может быть меньше, чем ввод. Однако, так как мы помещаем вывод в тот же файл, из которого читаем ввод, нам может потребоваться изменить размер файла. Системный вызов `ftruncate` позволяет нам сделать именно это. Несмотря на название , несколько вводящее в заблуждение, системный вызов `ftruncate` может использоваться как для усечения файла (уменьшения его размера), так и для его увеличения. И да, мы найдем две версии `ftruncate` в [.filename]#syscalls.master#, старую (130) и новую (201). Мы будем использовать новую: [.programlisting] .... 201 STD BSD { int ftruncate(int fd, int pad, off_t length); } .... Обратите внимание, что здесь снова присутствует `int pad`. [[x86-ftuc]] === ftuc Теперь мы знаем всё, что нужно для написания ftuc. Начнём с добавления нескольких новых строк в [.filename]#system.inc#. Сначала определим некоторые константы и структуры, где-нибудь в начале или около начала файла: [.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 .... Мы определяем новые системные вызовы: [.programlisting] .... %define SYS_mmap 197 %define SYS_munmap 73 %define SYS_fstat 189 %define SYS_ftruncate 201 .... Добавляем макросы для их использования: [.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 .... И вот наш код: [.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 .... [WARNING] ==== Не используйте эту программу для файлов, хранящихся на диске, отформатированном в MS-DOS(R) или Windows(R). В коде FreeBSD присутствует неочевидная ошибка при использовании `mmap` на таких дисках, смонтированных в FreeBSD: если размер файла превышает определённое значение, `mmap` заполнит память нулями, а затем запишет их в файл, перезаписав его содержимое. ==== [[x86-one-pointed-mind]] == Спокойствие ума Как ученик дзэн, мне нравится идея спокойствия ума (экаггата): делай одно дело за раз и делай его хорошо. Вот именно так, в большинстве случаев, работает и UNIX(R). В то время как типичное приложение Windows(R) пытается сделать всё, что только можно (и поэтому кишит ошибками), типичная программа UNIX(R) делает только одну вещь, но делает её хорошо. Типичный пользователь UNIX(R) по сути собирает свои собственные приложения, написав shell-скрипт, который объединяет различные существующие программы, передавая вывод одной программы на вход другой. При написании собственного программного обеспечения для UNIX(R) обычно рекомендуется определить, какие части решаемой задачи могут быть обработаны существующими программами, и создавать собственные программы только для той части задачи, для которой нет готового решения. [[x86-csv]] === CSV Я проиллюстрирую этот принцип конкретным примером из реальной жизни, с которым недавно столкнулся: Мне нужно было извлечь 11-е поле каждой записи из базы данных, которую я загрузил с веб-сайта. База данных представляла собой CSV-файл, то есть список _значений, разделённых запятыми_. Это довольно стандартный формат для обмена данными между людьми, которые могут использовать разное программное обеспечение для работы с базами данных. Первая строка файла содержит список различных полей, разделенных запятыми. Остальная часть файла содержит данные, перечисленные построчно, со значениями, разделенными запятыми. Я попробовал awk, используя запятую в качестве разделителя. Но поскольку несколько строк содержали запятую в кавычках, awk извлекал неправильное поле из этих строк. Следовательно, мне нужно было написать собственное программное обеспечение для извлечения 11-го поля из CSV-файла. Однако, следуя духу UNIX(R), мне нужно было лишь создать простой фильтр, выполняющий следующие действия: * Удалить первую строку из файла; * Заменить все не заключённые в кавычки запятые на другой символ; * Удалить все кавычки. Строго говоря, я мог бы использовать sed для удаления первой строки из файла, но сделать это в моей собственной программе было очень просто, поэтому я решил так поступить и уменьшить размер конвейера. В любом случае, написание подобной программы заняло у меня около 20 минут. Написание программы, которая извлекает 11-е поле из CSV-файла, заняло бы гораздо больше времени, и я не смог бы повторно использовать её для извлечения другого поля из другой базы данных. На этот раз я решил позволить ей выполнить немного больше работы, чем обычная учебная программа: * Она анализирует свою командную строку на наличие опций; * Она отображает подсказку, если обнаруживает неверные аргументы; * Она выдаёт понятные сообщения об ошибках. Вот какое сообщение она выводит о том, как её использовать: [source, shell] .... Usage: csv [-t] [-c] [-p] [-o ] [-i ] .... Все параметры необязательны и могут располагаться в любом порядке. Параметр `-t` указывает, на что заменить запятые. По умолчанию используется `tab`. Например, `-t;` заменит все незакавыченные запятые на точку с запятой. Мне не понадобилась опция `-c`, но в будущем она может пригодиться. Она позволяет указать, что я хочу заменить символ, отличный от запятой, на что-то другое. Например, `-c@` заменит все знаки @ (полезно, если нужно разделить список email-адресов на имена пользователей и домены). Опция `-p` сохраняет первую строку, т.е. не удаляет её. По умолчанию мы удаляем первую строку, потому что в CSV-файле она содержит названия полей, а не данные. Опции `-i` и `-o` позволяют указать входной и выходной файлы. По умолчанию используются [.filename]#stdin# и [.filename]#stdout#, как обычно работает стандартный фильтр UNIX(R). Я убедился, что принимаются как `-i filename`, так и `-ifilename`. Также я убедился, что может быть указан только один входной и один выходной файл. Чтобы получить 11-е поле каждой записи, теперь я могу сделать: [source, shell] .... % csv '-t;' data.csv | awk '-F;' '{print $11}' .... Код сохраняет параметры (за исключением файловых дескрипторов) в `EDX`: запятая в `DH`, новый разделитель в `DL`, а флаг параметра `-p` в старшем бите `EDX`, поэтому проверка его знака даст нам быстрое решение о дальнейших действиях. Вот код: [.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] [-c] [-p] [-o ] [-i ]', 0Ah usglen equ $-usg iemsg db "csv: Can't open input file", 0Ah iemlen equ $-iemsg oemsg db "csv: Can't create output file", 0Ah oemlen equ $-oemsg section .bss ibuffer resb BUFSIZE obuffer resb BUFSIZE section .text align 4 ierr: push dword iemlen push dword iemsg push dword stderr sys.write push dword 1 ; return failure sys.exit align 4 oerr: push dword oemlen push dword oemsg push dword stderr sys.write push dword 2 sys.exit align 4 usage: push dword usglen push dword usg push dword stderr sys.write push dword 3 sys.exit align 4 global _start _start: add esp, byte 8 ; discard argc and argv[0] mov edx, (',' << 8) | 9 .arg: pop ecx or ecx, ecx je near .init ; no more arguments ; ECX contains the pointer to an argument cmp byte [ecx], '-' jne usage inc ecx mov ax, [ecx] .o: cmp al, 'o' jne .i ; Make sure we are not asked for the output file twice cmp dword [fd.out], stdout jne usage ; Find the path to output file - it is either at [ECX+1], ; i.e., -ofile -- ; or in the next argument, ; i.e., -o file inc ecx or ah, ah jne .openoutput pop ecx jecxz usage .openoutput: push dword 420 ; file mode (644 octal) push dword 0200h | 0400h | 01h ; O_CREAT | O_TRUNC | O_WRONLY push ecx sys.open jc near oerr add esp, byte 12 mov [fd.out], eax jmp short .arg .i: cmp al, 'i' jne .p ; Make sure we are not asked twice cmp dword [fd.in], stdin jne near usage ; Find the path to the input file inc ecx or ah, ah jne .openinput pop ecx or ecx, ecx je near usage .openinput: push dword 0 ; O_RDONLY push ecx sys.open jc near ierr ; open failed add esp, byte 8 mov [fd.in], eax jmp .arg .p: cmp al, 'p' jne .t or ah, ah jne near usage or edx, 1 << 31 jmp .arg .t: cmp al, 't' ; redefine output delimiter jne .c or ah, ah je near usage mov dl, ah jmp .arg .c: cmp al, 'c' jne near usage or ah, ah je near usage mov dh, ah jmp .arg align 4 .init: sub eax, eax sub ebx, ebx sub ecx, ecx mov edi, obuffer ; See if we are to preserve the first line or edx, edx js .loop .firstline: ; get rid of the first line call getchar cmp al, 0Ah jne .firstline .loop: ; read a byte from stdin call getchar ; is it a comma (or whatever the user asked for)? cmp al, dh jne .quote ; Replace the comma with a tab (or whatever the user wants) mov al, dl .put: call putchar jmp short .loop .quote: cmp al, '"' jne .put ; Print everything until you get another quote or EOL. If it ; is a quote, skip it. If it is EOL, print it. .qloop: call getchar cmp al, '"' je .loop cmp al, 0Ah je .put call putchar jmp short .qloop align 4 getchar: or ebx, ebx jne .fetch call read .fetch: lodsb dec ebx ret read: jecxz .read call write .read: push dword BUFSIZE mov esi, ibuffer push esi push dword [fd.in] sys.read add esp, byte 12 mov ebx, eax or eax, eax je .done sub eax, eax ret align 4 .done: call write ; flush output buffer ; close files push dword [fd.in] sys.close push dword [fd.out] sys.close ; return success push dword 0 sys.exit align 4 putchar: stosb inc ecx cmp ecx, BUFSIZE je write ret align 4 write: jecxz .ret ; nothing to write sub edi, ecx ; start of buffer push ecx push edi push dword [fd.out] sys.write add esp, byte 12 sub eax, eax sub ecx, ecx ; buffer is empty now .ret: ret .... Большая часть взята из [.filename]#hex.asm# выше. Однако есть одно важное отличие: я больше не вызываю `write` каждый раз при выводе перевода строки. Тем не менее, код можно использовать интерактивно. Я нашел лучшее решение для интерактивной проблемы с тех пор, как начал писать эту главу. Я хотел убедиться, что каждая строка выводится отдельно только при необходимости. В конце концов, нет необходимости выводить каждую строку при неинтерактивном использовании. Новое решение, которое я использую сейчас, заключается в вызове `write` каждый раз, когда обнаруживаю, что входной буфер пуст. Таким образом, при работе в интерактивном режиме программа считывает одну строку с клавиатуры пользователя, обрабатывает её и видит, что входной буфер пуст. Она сбрасывает свой вывод и читает следующую строку. [[x86-buffered-dark-side]] ==== Темная сторона буферизации Это изменение предотвращает загадочную блокировку в очень специфическом случае. Я называю это _тёмной стороной буферизации_, в основном потому, что это представляет опасность, которая не совсем очевидна. Маловероятно, что это произойдет с такой программой, как csv выше, поэтому рассмотрим ещё один фильтр: в этом случае мы ожидаем, что наши входные данные будут представлять собой необработанные данные, описывающие значения цветов, такие как интенсивности _красного_, _зеленого_ и _синего_ для пикселя. На выходе мы получим негатив входных данных. Такой фильтр было бы очень просто написать. Большая его часть выглядела бы так же, как и все другие фильтры, которые мы уже писали, поэтому я покажу только его внутренний цикл: [.programlisting] .... .loop: call getchar not al ; Create a negative call putchar jmp short .loop .... Поскольку этот фильтр работает с необработанными данными, он вряд ли будет использоваться интерактивно. Но он может вызываться программным обеспечением для обработки изображений. И, если он не вызывает `write` перед каждым вызовом `read`, высока вероятность, что он зависнет. Вот что может произойти: [.procedure] . Редактор изображений загрузит наш фильтр, используя функцию `popen()` на языке C. . Он прочитает первый ряд пикселей из битовой карты или пиксельной карты. . Он запишет первую строку пикселей в _канал_, ведущий к `fd.in` нашего фильтра. . Наш фильтр будет читать каждый пиксель из входных данных, преобразовывать его в негатив и записывать в выходной буфер. . Наш фильтр будет вызывать `getchar` для получения следующего пикселя. . `getchar` обнаружит пустой входной буфер, поэтому вызовет `read`. . `read` вызовет системный вызов `SYS_read`. . _Ядро_ приостановит работу нашего фильтра до тех пор, пока редактор изображений не отправит больше данных в канал. . Редактор изображений будет читать из другого канала, подключенного к `fd.out` нашего фильтра, чтобы он мог установить первую строку выходного изображения _до_ того, как отправит нам вторую строку входного. . _Ядро_ приостанавливает работу графического редактора до тех пор, пока не получит какие-либо данные от нашего фильтра, чтобы передать их редактору. На этом этапе наш фильтр ожидает, что редактор изображений отправит ему больше данных для обработки, в то время как редактор изображений ожидает, что наш фильтр отправит ему результат обработки первой строки. Однако результат находится в нашем выходном буфере. Фильтр и редактор изображений будут продолжать ждать друг друга вечно (или, по крайней мере, пока их не завершат командой kill). Наше программное обеспечение только что вошло в crossref:secure[secure-race-conditions,состояние гонки]. Эта проблема не возникает, если наш фильтр очищает свой выходной буфер _перед_ запросом к _ядру_ для получения дополнительных входных данных. [[x86-fpu]] == Использование FPU Как ни странно, большая часть литературы по ассемблеру даже не упоминает о существовании FPU, или _блока обработки чисел с плавающей запятой_, не говоря уже о программировании для него. Тем не менее, язык ассемблера проявляет себя наилучшим образом, когда мы создаем высокооптимизированный код для FPU, выполняя вещи, которые можно сделать _только_ на языке ассемблера. [[x86-fpu-organization]] === Организация FPU FPU состоит из 8 80-битных регистров с плавающей запятой. Они организованы в виде стека — вы можете `push` (поместить) значение на TOS (_вершина стека_) и `pop` (извлечь) его. Как бы то ни было, мнемоники ассемблера — не `push` и `pop`, потому что они уже заняты. Вы можете `push` (положить) значение на вершину стека (TOS), используя `fld`, `fild` и `fbld`. Несколько других кодов операций позволяют вам `push` (положить) многие распространённые _константы_ — например, _pi_ — на вершину стека (TOS). Аналогично, вы можете `извлечь` значение с помощью `fst`, `fstp`, `fist`, `fistp` и `fbstp`. На самом деле только коды операций, оканчивающиеся на _p_, буквально `извлекают` значение, остальные же `сохраняют` его в другом месте, не удаляя с вершины стека (TOS). Мы можем передавать данные между TOS и памятью компьютера либо как 32-битное, 64-битное или 80-битное _вещественное_ число, 16-битное, 32-битное или 64-битное _целое_ число, либо как 80-битное _упакованное десятичное_ число. 80-битный _упакованный десятичный_ формат является особым случаем _двоично-десятичного кодирования_, который очень удобен при преобразовании между ASCII-представлением данных и внутренними данными FPU. Он позволяет использовать до 18 значащих цифр. Независимо от того, как мы представляем данные в памяти, FPU всегда хранит их в 80-битном формате _real_ в своих регистрах. Его внутренняя точность составляет не менее 19 десятичных цифр, поэтому даже если мы решим отображать результаты в формате ASCII с полной 18-значной точностью, мы всё равно будем показывать корректные результаты. Мы можем выполнять математические операции над TOS: вычислять его _синус_, _масштабировать_ (то есть умножать или делить на степень двойки), вычислять его _логарифм_ по основанию 2 и многое другое. Мы также можем _умножить_ или _разделить_ его, _прибавить_ к нему или _вычесть_ его из любого из регистров FPU (включая его самого). Официальный код операции Intel для TOS — `st`, а для _регистров_ — `st(0)`-`st(7)`. Таким образом, `st` и `st(0)` ссылаются на один и тот же регистр. По каким-то причинам оригинальный автор nasm решил использовать другие коды операций, а именно `st0`-`st7`. Другими словами, скобки отсутствуют, а вершина стека всегда `st0`, но никогда просто `st`. [[x86-fpu-packed-decimal]] ==== Формат упакованного десятичного числа Формат _упакованного десятичного числа_ использует 10 байт (80 бит) памяти для представления 18 цифр. Представленное число всегда является _целым_. [TIP] ==== Вы можете использовать это для получения десятичных знаков, предварительно умножив TOS на степень 10. ==== Старший бит старшего байта (байт 9) является _знаковым битом_: если он установлен, число _отрицательное_, в противном случае — _положительное_. Остальные биты этого байта не используются/игнорируются. Оставшиеся 9 байт хранят 18 цифр числа: 2 цифры на байт. _Старший разряд_ хранится в старшем _полубайте_ (4 бита), _младший разряд_ — в младшем _полубайте_. Как бы то ни было, вы можете подумать, что `-1234567` будет храниться в памяти следующим образом (в шестнадцатеричной записи): [.programlisting] .... 80 00 00 00 00 00 01 23 45 67 .... Увы, это не так! Как и все остальное, созданное Intel, даже _упакованное десятичное число_ имеет порядок _от младшего к старшему_. Это означает, что наш `-1234567` хранится следующим образом: [.programlisting] .... 67 45 23 01 00 00 00 00 00 80 .... Помните об этом, иначе вы будете рвать на себе волосы в отчаянии! [NOTE] ==== Книга, которую стоит прочитать — если сможете её найти — это книга Ричарда Старца http://www.amazon.com/exec/obidos/ASIN/013246604X/whizkidtechnomag[8087/80287/80387 для IBM PC и совместимых]. Хотя в ней, кажется, факт о little-endian хранении _упакованного десятичного числа_ принимается как данность. Я не шучу насчёт отчаяния, которое испытывал, пытаясь понять, что не так с фильтром, который я привожу ниже, _прежде_ чем мне пришло в голову попробовать little-endian порядок даже для этого типа данных. ==== [[x86-pinhole-photography]] === Экскурсия в фотографию с помощью камеры-обскуры Чтобы создавать полезное программное обеспечение, мы должны понимать не только наши инструменты программирования, но и область, для которой разрабатываем ПО. Наш следующий фильтр поможет нам, когда мы захотим создать _камеру-обскуру_, поэтому нам понадобятся некоторые знания о _фотографии с помощью обскуры_, прежде чем мы сможем продолжить. [[x86-camera]] ==== Камера Самый простой способ описать любую когда-либо созданную камеру — это некоторое пустое пространство, заключённое в светонепроницаемый материал, с небольшим отверстием в корпусе. Корпус обычно прочный (например, коробка), хотя иногда он гибкий (гофрированная часть). Внутри камеры довольно темно. Однако отверстие пропускает световые лучи через одну точку (хотя в некоторых случаях их может быть несколько). Эти световые лучи формируют изображение — представление того, что находится снаружи камеры, перед отверстием. Если внутрь камеры поместить светочувствительный материал (например, плёнку), он может зафиксировать изображение. Отверстие часто содержит _линзу_ или сборку линз, которую часто называют _объективом_. [[x86-the-pinhole]] ==== Игольное ушко Но, строго говоря, линза не обязательна: первые камеры использовали не линзу, а _маленькое отверстие_ размером с игольное ушко. Даже сегодня _маленькие отверстия_ применяются как инструмент для изучения принципов работы камер и для создания особого вида изображений. Изображение, создаваемое _маленьким отверстием_, одинаково резкое. Или _размытое_. Существует идеальный размер для маленького отверстия: если оно больше или меньше, изображение теряет резкость. [[x86-focal-length]] ==== Фокусное расстояние Идеальный диаметр отверстия является функцией квадратного корня из _фокусного расстояния_, которое представляет собой расстояние от отверстия до плёнки. [.programlisting] .... D = PC * sqrt(FL) .... Здесь `D` — идеальный диаметр отверстия, `FL` — фокусное расстояние, а `PC` — константа отверстия. По данным Джейя Бендера, её значение равно `0,04`, тогда как Кеннет Коннорс определил его как `0,037`. Другие исследователи предложили иные значения. Кроме того, это значение справедливо только для дневного света: другие типы освещения потребуют иной константы, значение которой можно определить только экспериментальным путём. [[x86-f-number]] ==== Число f (диафрагменное число) Число f — это очень полезный показатель того, сколько света попадает на плёнку. Экспонометр может определить, что, например, для экспонирования плёнки определённой чувствительности при f/5.6 может потребоваться выдержка 1/1000 сек. Не имеет значения, 35-мм это камера или камера 6x9 см и т.д. Достаточно знать диафрагменное число, чтобы определить правильную экспозицию. Число f легко вычислить: [.programlisting] .... F = FL / D .... Другими словами, число f равно фокусному расстоянию, деленному на диаметр отверстия. Это также означает, что большее f-число подразумевает либо меньшее отверстие, либо большее фокусное расстояние, либо и то, и другое. В свою очередь, это означает, что чем больше число f, тем дольше должна быть выдержка. Кроме того, хотя диаметр отверстия и фокусное расстояние являются одномерными величинами, и плёнка, и отверстие — двумерны. Это означает, что если вы измерили экспозицию при диафрагменном числе `A` как `t`, то экспозиция при диафрагменном числе `B` будет: [.programlisting] .... t * (B / A)² .... [[x86-normalized-f-number]] ==== Нормализованное число f Хотя многие современные камеры могут изменять диаметр своего отверстия, а следовательно и свое число f, довольно плавно и постепенно, так было не всегда. Для обеспечения различных значений диафрагмы в камерах обычно использовалась металлическая пластина с несколькими отверстиями разного размера. Их размеры были выбраны в соответствии с приведённой выше формулой таким образом, чтобы результирующее f-число было одним из стандартных f-чисел, используемых на всех фотоаппаратах. Например, у моего очень старого фотоаппарата Kodak Duaflex IV есть три таких отверстия для чисел f — 8, 11 и 16. Более современные камеры могут предлагать значения диафрагменного числа 2.8, 4, 5.6, 8, 11, 16, 22 и 32 (а также другие). Эти числа выбраны не произвольно: все они являются степенями квадратного корня из 2, хотя могут быть немного округлены. [[x86-f-stop]] ==== Ступени числа f Типичная камера устроена так, что установка любого из нормализованных чисел f изменяет ощущение от регулятора. Он естественным образом _останавливается_ в этом положении. Из-за этого такие положения регулятора называются f-ступенями. Поскольку значения диафрагмы на каждой ступени являются степенями квадратного корня из 2, поворот диска на 1 ступень удваивает количество света, необходимое для правильной экспозиции. Поворот на 2 ступени увеличивает требуемую экспозицию вчетверо. Поворот диска на 3 ступени требует увеличения экспозиции в 8 раз и так далее. [[x86-pinhole-software]] === Проектирование программного обеспечения камеры-обскуры Мы готовы решить, что именно должно делать наше программное обеспечение для камер-обскур. [[xpinhole-processing-input]] ==== Обработка ввода программы Поскольку основная цель — помочь нам разработать работающую камеру-обскуру, мы будем использовать _фокусное расстояние_ в качестве входных данных для программы. Это можно определить без программного обеспечения: правильное фокусное расстояние зависит от размера плёнки и необходимости съёмки «обычных» изображений, широкоугольных или телефото. Большинство написанных нами до сих пор программ работали с отдельными символами или байтами в качестве входных данных: программа hex преобразовывала отдельные байты в шестнадцатеричное число, программа csv либо пропускала символ, либо удаляла его, либо заменяла на другой символ и т.д. Одна программа, `ftuc`, использовала конечный автомат для обработки не более двух входных байтов за раз. Но наша программа для камеры-обскуры не может работать только с отдельными символами, ей приходится иметь дело с более крупными синтаксическими единицами. Например, если мы хотим, чтобы программа рассчитала диаметр отверстия (и другие значения, которые мы обсудим позже) для фокусных расстояний `100 мм`, `150 мм` и `210 мм`, мы можем ввести что-то вроде этого: [source, shell] .... 100, 150, 210 .... Наша программа должна учитывать более одного байта входных данных за раз. Когда она видит первую `1`, она должна понимать, что это первая цифра десятичного числа. Когда она видит `0` и другой `0`, она должна знать, что это следующие цифры того же числа. Когда он встречает первую запятую, он должен понять, что больше не получает цифры первого числа. Он должен уметь преобразовать цифры первого числа в значение `100`. И цифры второго числа в значение `150`. И, конечно же, цифры третьего числа в числовое значение `210`. Нам нужно определиться с допустимыми разделителями: должны ли входные числа разделяться запятой? Если да, то как обрабатывать два числа, разделённые чем-то другим? Лично я предпочитаю простоту. Либо что-то является числом — и тогда я его обрабатываю. Либо не является числом — и тогда я это отбрасываю. Мне не нравится, когда компьютер жалуется на лишний символ, если _очевидно_, что он лишний. Да ладно! Плюс, это позволяет мне разбавить монотонность вычислений и ввести запрос вместо просто числа: [source, shell] .... What is the best pinhole diameter for the focal length of 150? .... Нет причины, чтобы компьютер выводил множество жалоб: [source, shell] .... Syntax error: What Syntax error: is Syntax error: the Syntax error: best .... И так далее, и так далее, и так далее. Во-вторых, мне нравится символ `+#+` для обозначения начала комментария, который продолжается до конца строки. Это не требует больших усилий для реализации и позволяет мне рассматривать входные файлы для моего программного обеспечения как исполняемые скрипты. В нашем случае также необходимо определиться с единицами измерения входных данных: мы выбираем _миллиметры_, так как большинство фотографов измеряют фокусное расстояние именно в них. Наконец, нам нужно решить, разрешать ли использование десятичной точки (в этом случае мы также должны учитывать тот факт, что во многих странах используется десятичная _запятая_). В нашем случае разрешение десятичной точки/запятой создало бы ложное ощущение точности: разница между фокусными расстояниями `50` и `51` практически незаметна, поэтому разрешать пользователю вводить что-то вроде `50.5` — не лучшая идея. Это моё мнение, конечно, но программу пишу я. В своей программе вы можете сделать другие выбор, разумеется. [[x86-pinhole-options]] ==== Передача параметров программе Самое важное, что нам нужно знать при создании камеры-обскуры — это диаметр отверстия. Поскольку мы хотим получать чёткие изображения, мы будем использовать приведённую выше формулу для расчёта диаметра отверстия от фокусного расстояния. Поскольку эксперты предлагают несколько различных значений для константы `PC`, нам нужно будет иметь выбор. В традициях программирования в UNIX(R) предусмотрены два основных способа выбора параметров программы, а также значение по умолчанию на случай, если пользователь не сделает выбор. Почему есть два способа выбора? Один из способов — это позволить (относительно) _постоянный_ выбор, который применяется автоматически каждый раз при запуске программы, без необходимости каждый раз указывать, что мы хотим, чтобы она сделала. Постоянные настройки могут быть сохранены в конфигурационном файле, обычно расположенном в домашнем каталоге пользователя. Файл обычно имеет то же имя, что и приложение, но начинается с точки. Часто к имени файла добавляется _"rc"_. Таким образом, наш файл может называться [.filename]#~/.pinhole# или [.filename]#~/.pinholerc#. (Обозначение [.filename]#~/# означает домашний каталог текущего пользователя.) Файл конфигурации в основном используется программами, у которых много настраиваемых параметров. Те, у которых он один (или несколько), часто используют другой метод: они ожидают найти параметр в _переменной окружения_. В нашем случае, мы можем посмотреть на переменную окружения с именем `PINHOLE`. Обычно программа использует один из вышеуказанных методов. В противном случае, если в конфигурационном файле указано одно, а в переменной окружения — другое, программа может запутаться (или стать слишком сложной). Поскольку нам нужно выбрать только _один_ такой параметр, мы воспользуемся вторым методом и поищем в окружении переменную с именем `PINHOLE`. Другой способ позволяет нам принимать _ad hoc_ решения: _"Хотя обычно я хочу, чтобы ты использовал 0.039, на этот раз мне нужно 0.03872."_ Другими словами, он позволяет нам _переопределить_ постоянный выбор. Такой выбор обычно осуществляется с помощью параметров командной строки. Наконец, программе _всегда_ необходим _значение по умолчанию_. Пользователь может не делать никакого выбора. Возможно, он не знает, что выбрать. Возможно, он «просто просматривает». Предпочтительно, чтобы значением по умолчанию было то, что выбрало бы большинство пользователей. Таким образом, им не нужно выбирать. Или, точнее, они могут выбрать значение по умолчанию без дополнительных усилий. Учитывая эту систему, программа может обнаружить конфликтующие параметры и обработать их следующим образом: [.procedure] . Если она находит _специальный_ выбор (например, параметр командной строки), она должна принять этот выбор. Она должна игнорировать любой постоянный выбор и значения по умолчанию. . _В противном случае_, если будет найден постоянный параметр (например, переменная окружения), он должен быть принят, а значение по умолчанию — проигнорировано. . _В противном случае_, следует использовать значение по умолчанию. Нам также необходимо решить, в каком _формате_ должна быть наша опция `PC`. На первый взгляд кажется очевидным использовать формат `PINHOLE=0.04` для переменной окружения и `-p0.04` для командной строки. Разрешение этого на самом деле представляет угрозу безопасности. Константа `PC` — это очень маленькое число. Естественно, мы протестируем наше программное обеспечение, используя различные небольшие значения `PC`. Но что произойдёт, если кто-то запустит программу, выбрав огромное значение? Это может привести к сбою программы, так как мы не разрабатывали её для обработки огромных чисел. Или мы можем потратить больше времени на программу, чтобы она могла обрабатывать огромные числа. Мы могли бы сделать это, если бы писали коммерческое программное обеспечение для аудитории, не знакомой с компьютерами. Или можно сказать: _"Пусть терпит! Пользователь сам должен был разобраться."_ Или мы можем просто сделать невозможным ввод пользователем слишком большого числа. Это подход, который мы выберем: мы будем использовать _подразумеваемый префикс 0._. Другими словами, если пользователь хочет `0.04`, мы ожидаем, что он введёт `-p04` или установит `PINHOLE=04` в своём окружении. Таким образом, если он укажет `-p9999999`, мы интерпретируем это как ``0.9999999`` — всё ещё нелепо, но по крайней мере безопаснее. Во-вторых, многие пользователи просто захотят использовать либо константу Бендера, либо константу Коннорса. Чтобы облегчить им задачу, мы будем интерпретировать `-b` как идентичное `-p04`, а `-c` как идентичное `-p037`. [[x86-pinhole-output]] ==== Вывод результата Нам нужно решить, что наше программное обеспечение должно отправлять на вывод и в каком формате. Поскольку наши входные данные допускают неограниченное количество значений фокусного расстояния, имеет смысл использовать традиционный вывод в стиле базы данных, показывая результат вычислений для каждого фокусного расстояния на отдельной строке, разделяя все значения в строке символом табуляции. Опционально, мы также должны разрешить пользователю указать использование формата CSV, который мы изучили ранее. В этом случае мы выведем строку с разделёнными запятыми названиями, описывающими каждое поле каждой строки, а затем отобразим результаты как прежде, но заменив `табуляцию` на `запятую`. Нам нужна опция командной строки для формата CSV. Мы не можем использовать `-c`, потому что это уже означает _использовать константу Коннорса_. По какой-то странной причине многие веб-сайты называют CSV-файлы _"электронными таблицами Excel"_ (хотя формат CSV появился раньше Excel). Поэтому мы будем использовать переключатель `-e`, чтобы указать нашему программному обеспечению, что мы хотим получить вывод в формате CSV. Мы начнем каждую строку вывода с фокусного расстояния. Это может показаться избыточным сначала, особенно в интерактивном режиме: пользователь вводит фокусное расстояние, а мы его повторяем. Но пользователь может ввести несколько фокусных расстояний в одной строке. Ввод также может поступать из файла или вывода другой программы. В этом случае пользователь вообще не видит вводимые данные. Таким же образом, вывод может быть направлен в файл, который мы захотим изучить позже, или на принтер, или стать входными данными для другой программы. Итак, имеет полный смысл начинать каждую строку с фокусного расстояния, введённого пользователем. Нет, подождите! Не так, как ввел пользователь. Что, если пользователь введет что-то вроде этого: [source, shell] .... 00000000150 .... Очевидно, нам нужно удалить ведущие нули. Итак, можно рассмотреть вариант чтения пользовательского ввода как есть, преобразования его в бинарный вид внутри FPU и последующего вывода оттуда. Но... Что делать, если пользователь введёт что-то вроде этого: [source, shell] .... 17459765723452353453534535353530530534563507309676764423 .... Ха! Упакованный десятичный формат FPU позволяет нам вводить 18-значные числа. Но пользователь ввёл больше 18 цифр. Как нам обработать это? Хорошо, мы _могли бы_ изменить наш код, чтобы он читал первые 18 цифр, передавал их в FPU, затем читал ещё, умножал уже имеющееся на вершине стека (TOS) на 10 в степени количества дополнительных цифр, а затем выполнял `сложение` с этим значением. Да, мы могли бы так поступить. Но в _этой_ программе это было бы нелепо (в другой это могло бы быть как раз тем, что нужно): даже длина окружности Земли, выраженная в миллиметрах, занимает всего 11 цифр. Очевидно, мы не можем построить камеру такого размера (по крайней мере, пока). Итак, если пользователь вводит такое огромное число, он либо скучает, либо проверяет нас, либо пытается взломать систему, либо играет — делает что угодно, кроме проектирования камеры-обскуры. Что мы будем делать? Мы ударим его по лицу, образно говоря: [source, shell] .... 17459765723452353453534535353530530534563507309676764423 ??? ??? ??? ??? ??? .... Для этого мы просто проигнорируем все ведущие нули. Как только мы найдем ненулевую цифру, мы инициализируем счетчик значением `0` и начнем выполнять три шага: [.procedure] . Отправить цифру на выход. . Добавить цифру в буфер, который мы позже используем для создания упакованного десятичного числа, которое можно отправить в FPU. . Увеличить счетчик. Теперь, пока мы выполняем эти три шага, нам также необходимо следить за одним из двух условий: * Если счётчик превышает 18, мы прекращаем добавление в буфер. Мы продолжаем читать цифры и отправлять их на вывод. * Если, или скорее _когда_, следующий вводимый символ не является цифрой, мы завершаем ввод на данный момент. + Между прочим, мы можем просто отбросить нецифровой символ, если это не `+#+`, который необходимо вернуть во входной поток. Он начинает комментарий, поэтому мы должны увидеть его после завершения вывода и начала поиска следующего ввода. Остается одна непокрытая возможность: если пользователь вводит только ноль (или несколько нулей), мы никогда не найдем ненулевое значение для отображения. Мы можем определить, что это произошло, когда наш счетчик остаётся на `0`. В этом случае нам нужно отправить `0` на выход и выполнить ещё один "удар по лицу": [source, shell] .... 0 ??? ??? ??? ??? ??? .... Как только мы определили фокусное расстояние и убедились, что оно корректно (больше `0`, но не превышает 18 цифр), можно рассчитать диаметр отверстия. Не случайно слово _булавочное ушко_ содержит слово _булавка_. Действительно, многие малые отверстия буквально являются _дырками от булавки_ — отверстиями, аккуратно проделанными остриём булавки. Вот потому что типичное отверстие очень маленькое. Наша формула даёт результат в миллиметрах. Мы умножим его на `1000`, чтобы вывести результат в _микронах_. На этом этапе нас ожидает ещё одна ловушка: _Излишняя точность._ Да, FPU был разработан для вычислений с высокой точностью. Но мы имеем дело не с вычислениями высокой точности. Мы имеем дело с физикой (конкретно, с оптикой). Предположим, мы хотим превратить грузовик в камеру-обскуру (мы будем не первыми, кто это сделал!). Допустим, его кузов имеет длину `12` метров, значит, фокусное расстояние равно `12000`. Используя константу Бендера, получаем квадратный корень из `12000`, умноженный на `0.04`, что составляет `4.381780460` миллиметра или `4381.780460` микрона. Как ни посмотри, результат абсурдно точен. Наш грузовик не имеет _точно_ `12000` миллиметров в длину. Мы не измеряли его длину с такой точностью, поэтому утверждение, что нам нужна отверстие диаметром `4,381780460` миллиметра, мягко говоря, вводит в заблуждение. `4,4` миллиметра будет вполне достаточно. [NOTE] ==== Я "всего лишь" использовал десять цифр в приведённом выше примере. Представьте абсурдность попытки использовать все 18! ==== Нам нужно ограничить количество значащих цифр в нашем результате. Один из способов сделать это — использовать целое число, представляющее микроны. Таким образом, нашему грузовику потребуется отверстие диаметром `4382` микрона. Глядя на это число, мы всё же решаем, что `4400` микрон, или `4.4` миллиметра, достаточно близко. Кроме того, мы можем решить, что независимо от размера результата, мы хотим отображать только четыре значащих цифры (или любое другое их количество, конечно). Увы, FPU не поддерживает округление до определённого количества цифр (в конце концов, он воспринимает числа не как десятичные, а как двоичные). Следовательно, мы должны разработать алгоритм для уменьшения количества значащих цифр. Вот мой (я думаю, он неуклюжий — если у вас есть вариант лучше, _пожалуйста_, дайте мне знать): [.procedure] . Инициализировать счетчик значением `0`. . Пока число больше или равно `10000`, делим его на `10` и увеличиваем счётчик. . Вывести результат. . Пока счетчик больше `0`, выводить `0` и уменьшать счетчик. [NOTE] ==== `10000` подходит только если вам нужно _четыре_ значащих цифры. Для любого другого количества значащих цифр замените `10000` на `10` в степени, равной количеству значащих цифр. ==== Мы затем выведем диаметр отверстия в микронах, округлённый до четырёх значащих цифр. На этом этапе нам известны _фокусное расстояние_ и _диаметр отверстия_. Это означает, что у нас достаточно информации для расчёта _диафрагменного числа_. Мы отобразим число f, округлённое до четырёх значащих цифр. Скорее всего, само число f мало что нам скажет. Чтобы придать ему больше смысла, мы можем найти ближайшее _нормализованное число f_, то есть ближайшую степень квадратного корня из 2. Мы делаем это, умножая фактическое значение диафрагмы на само себя, что, конечно же, даст нам его `квадрат`. Затем мы вычислим его логарифм по основанию 2, что намного проще, чем вычисление логарифма по основанию квадратного корня из 2! Мы округлим результат до ближайшего целого числа. Далее мы возведём 2 в полученную степень. На самом деле, FPU предоставляет нам удобный способ сделать это: мы можем использовать код операции `fscale` для "масштабирования" 1, что аналогично ``сдвигу`` целого числа влево. Наконец, мы вычисляем квадратный корень из всего этого и получаем ближайшее нормализованное значение диафрагмы. Если всё это звучит ошеломляюще — или, возможно, слишком сложно — всё может стать гораздо понятнее, если увидеть код. Вместе это занимает всего 9 инструкций процессора: [.programlisting] .... fmul st0, st0 fld1 fld st1 fyl2x frndint fld1 fscale fsqrt fstp st1 .... Первая строка, `fmul st0, st0`, возводит в квадрат содержимое TOS (вершина стека, то же что `st`, называется `st0` в nasm). Команда `fld1` помещает `1` на вершину стека. Следующая строка, `fld st1`, помещает квадрат обратно в TOS. На этом этапе квадрат находится и в `st`, и в `st(2)` (скоро станет ясно, зачем мы оставляем вторую копию в стеке). В `st(1)` содержится `1`. Далее, `fyl2x` вычисляет логарифм по основанию 2 от `st`, умноженный на `st(1)`. Именно поэтому мы ранее поместили `1` в `st(1)`. На этом этапе `st` содержит логарифм, который мы только что вычислили, а `st(1)` содержит квадрат фактического значения диафрагменного числа, который мы сохранили для последующего использования. `frndint` округляет TOS до ближайшего целого числа. `fld1` помещает `1` в стек. `fscale` сдвигает `1`, находящееся на TOS, на значение в `st(1)`, фактически возводя 2 в степень `st(1)`. Наконец, `fsqrt` вычисляет квадратный корень из результата, т.е. ближайшее нормализованное число f. У нас теперь есть ближайшее нормализованное число f на вершине стека (TOS), округлённый до ближайшего целого двоичный логарифм в `st(1)` и квадрат фактического число f в `st(2)`. Мы сохраняем значение в `st(2)` для последующего использования. Но нам больше не нужно содержимое `st(1)`. Последняя строка, `fstp st1`, помещает содержимое `st` в `st(1)` и выполняет извлечение. В результате, то, что было `st(1)`, теперь становится `st`, то, что было `st(2)`, теперь становится `st(1)`, и так далее. Новый `st` содержит нормализованное число f. Новый `st(1)` содержит квадрат фактического число f, который мы сохранили для потомков. На этом этапе мы готовы вывести нормализованное число f. Поскольку оно нормализовано, мы не будем округлять его до четырёх значащих цифр, а отправим его с полной точностью. Нормализованное диафрагменное число полезно, пока оно достаточно мало и может быть найдено на нашем экспонометре. В противном случае нам нужен другой метод определения правильной экспозиции. Ранее мы вывели формулу для расчёта правильной экспозиции при произвольной диафрагме на основе измерений, сделанных при другой диафрагме. Каждый экспонометр, который я когда-либо видел, может определить правильную экспозицию при f5.6. Поэтому мы рассчитаем _"множитель f5.6"_, то есть насколько нужно умножить экспозицию, измеренную при f5.6, чтобы определить правильную экспозицию для нашей камеры-обскуры. Из приведённой формулы мы знаем, что этот коэффициент можно вычислить, разделив наше число f (фактическое, а не нормализованное) на `5.6` и возведя результат в квадрат. Математически, деление квадрата нашего числа f на квадрат `5.6` даст нам тот же результат. С вычислительной точки зрения, нам не нужно возводить в квадрат два числа, когда можно возвести только одно. Таким образом, первое решение на первый взгляд кажется лучше. Но... `5.6` — это _константа_. Нам не нужно заставлять наш FPU тратить драгоценные циклы. Мы можем просто указать ему разделить квадрат f-числа на то, чему равно `5.6²`. Или мы можем разделить f-число на `5.6`, а затем возвести результат в квадрат. Теперь оба способа кажутся равнозначными. Но они не такие! Изучив принципы фотографии выше, мы помним, что `5.6` — это квадратный корень из 2, возведённый в пятую степень. Это _иррациональное_ число. Квадрат этого числа _ровно_ `32`. `32` — это не просто целое число, это степень двойки. Нам не нужно делить квадрат числа f на `32`. Достаточно использовать `fscale` для сдвига вправо на пять позиций. В терминологии FPU это означает, что мы применим `fscale` со значением `st(1)` равным `-5`. Это _гораздо быстрее_, чем деление. Итак, теперь стало ясно, зачем мы сохранили квадрат числа f на вершине стека FPU. Расчёт множителя для f5.6 — это самое простое вычисление во всей программе! Мы выведем его, округлив до четырёх значащих цифр. Есть ещё одно полезное число, которое мы можем вычислить: количество ступеней, на которые наше значение диафрагмы отличается от f5.6. Это может помочь, если наше значение диафрагмы находится чуть за пределами диапазона нашего экспонометра, но у нас есть затвор, который позволяет устанавливать различные выдержки, и этот затвор использует ступени. Предположим, наше число диафрагмы на 5 ступеней отличается от f5.6, а экспонометр показывает, что нужно использовать выдержку 1/1000 сек. Тогда мы можем сначала установить выдержку на 1/1000, а затем повернуть диск на 5 ступеней. Этот расчет также довольно прост. Все, что нам нужно сделать, это вычислить логарифм по основанию 2 от множителя f5.6, который мы только что рассчитали (хотя нам нужно его значение до округления). Затем мы выводим результат, округленный до ближайшего целого числа. Нам не нужно беспокоиться о наличии более четырёх значащих цифр в этом случае: скорее всего, результат будет содержать только одну или две цифры. [[x86-fpu-optimizations]] === Оптимизации FPU В ассемблерном коде мы можем оптимизировать инструкции FPU способами, невозможными в языках высокого уровня, включая C. Всякий раз, когда функции на языке C требуется вычислить значение с плавающей запятой, она загружает все необходимые переменные и константы в регистры FPU. Затем выполняются все необходимые вычисления для получения правильного результата. Хорошие компиляторы C могут очень эффективно оптимизировать эту часть кода. Он "возвращает" значение, оставляя результат на вершине стека (TOS). Однако перед возвратом он выполняет очистку. Все переменные и константы, использованные в вычислениях, теперь удалены из FPU. Он не может сделать то, что мы только что сделали выше: мы вычислили квадрат числа f и оставили его в стеке для последующего использования другой функцией. Мы _знали_, что это значение понадобится позже. Мы также знали, что у нас достаточно места в стеке (в котором помещается только 8 чисел), чтобы сохранить его там. Компилятор C не может знать, что значение, находящееся в стеке, потребуется снова в ближайшем будущем. Конечно, программист на C может это знать. Но единственное средство, которое у него есть, — это сохранить значение в переменной памяти. Это означает, что значение будет изменено с 80-битной точности, используемой внутри FPU, на тип _double_ (64 бита) или даже _single_ (32 бита) в C. Это также означает, что значение должно быть перемещено из TOS в память, а затем обратно. Увы, среди всех операций с FPU, доступ к памяти компьютера является самым медленным. Итак, при программировании FPU на языке ассемблера ищите способы хранения промежуточных результатов в стеке FPU. Мы можем развить эту идею ещё дальше! В нашей программе мы используем _константу_ (ту, которую назвали `PC`). Не имеет значения, сколько диаметров отверстий мы рассчитываем: 1, 10, 20, 1000, мы всегда используем одну и ту же константу. Следовательно, мы можем оптимизировать нашу программу, сохраняя константу в стеке всё время. В начале нашей программы мы вычисляем значение указанной константы. Нам нужно разделить наш вход на `10` для каждой цифры в константе. Гораздо быстрее умножать, чем делить. Поэтому в начале нашей программы мы делим `1` на `10`, чтобы получить `0.1`, который затем сохраняем в стеке: вместо того чтобы делить ввод на `10` для каждой цифры, мы умножаем его на `0.1`. Кстати, мы не вводим `0.1` напрямую, хотя могли бы. У нас есть причина для этого: хотя `0.1` можно выразить всего одним десятичным знаком, мы не знаем, сколько _двоичных_ разрядов для этого потребуется. Поэтому мы позволяем FPU вычислить его двоичное значение с собственной высокой точностью. Мы используем другие константы: умножаем диаметр отверстия на `1000`, чтобы перевести его из миллиметров в микроны. Мы сравниваем числа с `10000`, когда округляем их до четырёх значащих цифр. Таким образом, мы оставляем и `1000`, и `10000` в стеке. И, конечно же, мы повторно используем `0.1` при округлении чисел до четырёх цифр. И последнее, но не менее важное: мы оставляем `-5` в стеке. Он нам нужен для масштабирования квадрата числа f вместо деления его на `32`. Не случайно мы загружаем эту константу последней. Это делает её вершиной стека, когда в нём находятся только константы. Таким образом, при масштабировании квадрата число f `-5` находится в `st(1)`, именно там, где `fscale` ожидает его увидеть. Это обычная ситуация, когда некоторые константы создаются с нуля, вместо загрузки их из памяти. Именно это мы делаем с `-5`: [.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 .... Мы можем обобщить все эти оптимизации в одном правиле: _Держите повторяющиеся значения в стеке!_ [TIP] ==== _PostScript(R)_ — это стековая язык программирования. Существует гораздо больше книг о PostScript(R), чем о языке ассемблера FPU: освоение PostScript(R) поможет вам овладеть FPU. ==== [[x86-pinhole-the-code]] === Код pinhole [.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 ] [-o ] [-i ]', 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 .... Код следует тому же формату, что и все остальные фильтры, которые мы видели ранее, с одним небольшим исключением: ____ Мы больше не предполагаем, что конец ввода означает конец задач, как мы привыкли в фильтрах, _ориентированных на символы_. Этот фильтр не обрабатывает символы. Он обрабатывает _язык_ (хотя и очень простой, состоящий только из чисел). Когда у нас больше нет входных данных, это может означать одно из двух: * Мы закончили и можем выйти. Это то же самое, что и раньше. * Последний прочитанный символ был цифрой. Мы сохранили его в конце буфера преобразования ASCII в число с плавающей точкой. Теперь нам нужно преобразовать содержимое этого буфера в число и записать последнюю строку нашего вывода. По этой причине мы изменили наши подпрограммы `getchar` и `read`, чтобы они возвращались с _сброшенным_ флагом `carry`, когда получают очередной символ из ввода, или с _установленным_ флагом `carry`, когда ввода больше нет. Конечно, мы по-прежнему используем магию ассемблера для этого! Внимательно посмотрите на `getchar`. Он _всегда_ возвращает _очищенный_ `флаг переноса`. Тем не менее, наш основной код использует `флаг переноса` для определения момента завершения — и это работает. Волшебство кроется в `read`. Каждый раз, когда он получает больше входных данных от системы, он просто возвращается к `getchar`, который извлекает символ из входного буфера, _сбрасывает_ флаг переноса (`carry flag`) и возвращает управление. Но когда `read` больше не получает входных данных от системы, он _не_ возвращается к `getchar` вообще. Вместо этого, инструкция `add esp, byte 4` добавляет `4` к `ESP`, _устанавливает_ флаг переноса (`carry flag`) и возвращает управление. Итак, куда же она возвращается? Каждый раз, когда программа использует операцию `call`, микропроцессор делает ``push`` для адрес возврата, то есть сохраняет его на вершине стека (не стека FPU, а системного стека, который находится в памяти). Когда программа использует операцию `ret`, микропроцессор делает ``pop`` для значения возврата из стека и переходит по адресу, который там был сохранён. Но поскольку мы добавили `4` к `ESP` (который является регистром указателя стека), мы фактически вызвали у микропроцессора лёгкий случай _амнезии_: он больше не помнит, что именно `getchar` ``вызвал`` `read`. И поскольку `getchar` не делал ``push`` ни для чего перед вызовом `read`, верхушка стека теперь содержит адрес возврата к тому, что или кто вызывал `getchar`. С точки зрения этого вызывающего, он вызывал `getchar`, который вызвал ``ret`` с установленным `флагом переноса`! ____ Помимо этого, процедура `bcdload` оказывается втянута в лилипутский конфликт между Биг-Эндианцами и Литл-Эндианцами. Он преобразует текстовое представление числа в само число: текст хранится в порядке big-endian, но _упакованный десятичный_ формат имеет порядок little-endian. Для разрешения конфликта мы используем инструкцию процессора `std` в самом начале. Позже мы отменяем его с помощью `cld`: очень важно не вызывать ничего, что может зависеть от стандартного значения _флага направления_, пока активен `std`. Всё остальное в этом коде должно быть достаточно понятным, при условии, что вы прочитали всю предшествующую главу. Это классический пример поговорки о том, что программирование требует много размышлений и лишь немного кодирования. Как только мы продумаем каждую мельчайшую деталь, код практически напишется сам. [[x86-pinhole-using]] === Использование программы pinhole Поскольку мы решили сделать так, чтобы программа _игнорировала_ любой ввод, кроме чисел (и даже их внутри комментария), мы можем выполнять _текстовые запросы_. Мы не _обязаны_ этого делать, но _можем_. По моему скромному мнению, формирование текстового запроса вместо необходимости следовать очень строгому синтаксису делает программное обеспечение гораздо более дружелюбным к пользователю. Предположим, мы хотим построить камеру-обскуру для использования плёнки размером 4x5 дюймов. Стандартное фокусное расстояние для такой плёнки составляет около 150 мм. Мы хотим _точно настроить_ фокусное расстояние, чтобы диаметр отверстия был как можно более круглым числом. Допустим также, что мы хорошо разбираемся в фотоаппаратах, но немного боимся компьютеров. Вместо того чтобы просто вводить кучу цифр, мы хотим _задать_ пару вопросов. Наша сессия может выглядеть так: [source, shell] .... % pinhole Computer, What size pinhole do I need for the focal length of 150? 150 490 306 362 2930 12 Hmmm... How about 160? 160 506 316 362 3125 12 Let's make it 155, please. 155 498 311 362 3027 12 Ah, let's try 157... 157 501 313 362 3066 12 156? 156 500 312 362 3047 12 That's it! Perfect! Thank you very much! ^D .... Мы выяснили, что при фокусном расстоянии 150 мм диаметр отверстия должен составлять 490 микрон, или 0,49 мм, но если взять почти идентичное фокусное расстояние 156 мм, можно использовать отверстие диаметром ровно половину миллиметра. [[x86-pinhole-scripting]] === Скриптинг Поскольку мы выбрали символ `+#+` для обозначения начала комментария, мы можем рассматривать наше программное обеспечение pinhole как _скриптовый язык_. Вы, вероятно, видели _сценарии_ оболочки, которые начинаются с: [.programlisting] .... #! /bin/sh .... ...или... [.programlisting] .... #!/bin/sh .... ...потому что пробел после `#!` необязателен. Когда UNIX(R) получает запрос на выполнение исполняемого файла, который начинается с `#!`, он предполагает, что это скрипт. Он добавляет команду к остальной части первой строки скрипта и пытается выполнить её. Предположим, что мы установили pinhole в /usr/local/bin/, теперь мы можем написать скрипт для расчёта различных диаметров отверстий, подходящих для различных фокусных расстояний, обычно используемых с плёнкой 120. Скрипт может выглядеть примерно так: [.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 .... Поскольку 120 — это плёнка среднего размера, мы можем назвать этот файл `medium`. Мы можем установить права на выполнение и запустить его, как если бы это была программа: [source, shell] .... % chmod 755 medium % ./medium .... UNIX(R) интерпретирует последнюю команду следующим образом: [source, shell] .... % /usr/local/bin/pinhole -b -i ./medium .... Он выполнит эту команду и отобразит: [source, shell] .... 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 .... Теперь введем: [source, shell] .... % ./medium -c .... UNIX(R) интерпретирует это следующим образом: [source, shell] .... % /usr/local/bin/pinhole -b -i ./medium -c .... Это даёт ему два конфликтующих параметра: `-b` и `-c` (Использовать константу Бендера и использовать константу Коннорса). Мы запрограммировали его так, что более поздние параметры переопределяют ранние — наша программа будет вычислять все, используя константу Коннорса: [source, shell] .... 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 .... Мы решаем, что всё же выбираем константу Бендера. Мы хотим сохранить её значения в виде файла с разделителями-запятыми: [source, shell] .... % ./medium -b -e > bender % cat bender 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 % .... [[x86-caveats]] == Предостережения Программисты на ассемблере, которые "выросли" на MS-DOS(R) и Windows(R), часто склонны искать короткие пути. Чтение скан-кодов клавиатуры и запись напрямую в видеопамять — это два классических примера подходов, которые в MS-DOS(R) не только не порицаются, но и считаются правильными. Причина? И BIOS ПК, и MS-DOS(R) печально известны своей медленной работой при выполнении этих операций. Вас может возникнуть соблазн продолжить подобные практики в среде UNIX(R). Например, я видел веб-сайт, который объясняет, как получить доступ к скан-кодам клавиатуры на популярном клоне UNIX(R). Это, как правило, *очень плохая идея* в среде UNIX(R)! Позвольте объяснить почему. [[x86-protected]] === UNIX(R) защищен Прежде всего, это может быть просто невозможно. UNIX(R) работает в защищённом режиме. Только ядро и драйверы устройств имеют прямой доступ к аппаратному обеспечению. Возможно, какой-то конкретный клон UNIX(R) позволит вам читать скан-коды клавиатуры, но скорее всего настоящая операционная система UNIX(R) этого не допустит. И даже если одна версия разрешает это, следующая может запретить, так что ваше тщательно разработанное программное обеспечение может в одночасье устареть. [[x86-abstraction]] === UNIX(R) — это работа с абстракциями Но существует гораздо более важная причина не пытаться обращаться к оборудованию напрямую (если, конечно, вы не пишете драйвер устройства), даже в UNIX(R)-подобных системах, которые позволяют это делать: _UNIX(R) — это работа с абстракциями!_ Существует фундаментальное различие в философии проектирования между MS-DOS(R) и UNIX(R). MS-DOS(R) разрабатывалась как однопользовательская система. Она работает на компьютере, к которому напрямую подключены клавиатура и монитор. Ввод пользователя практически гарантированно поступает с этой клавиатуры. Вывод вашей программы почти всегда отображается на этом экране. Это НИКОГДА не гарантируется в UNIX(R). Довольно часто пользователь UNIX(R) перенаправляет ввод и вывод программы с помощью конвейеров и перенаправлений: [source, shell] .... % program1 | program2 | program3 > file1 .... Если вы написали program2, ваш ввод поступает не с клавиатуры, а из вывода program1. Аналогично, ваш вывод не выводится на экран, а становится вводом для program3, чей вывод, в свою очередь, отправляется в [.filename]#file1#. Но это ещё не все! Даже если вы убедились, что ваш ввод поступает с терминала, а вывод отправляется на терминал, нет гарантии, что терминал является ПК: его видеопамять может находиться не там, где вы ожидаете, а клавиатура может генерировать не PC-совместимые скан-коды. Это может быть Macintosh(R) или любой другой компьютер. Вот вы, возможно, покачаете головой: мое программное обеспечение написано на языке ассемблера для ПК, как оно может работать на Macintosh(R)? Но я не говорил, что ваше программное обеспечение будет работать на Macintosh(R), а лишь что его терминалом может быть Macintosh(R). В UNIX(R) терминал не обязательно должен быть напрямую подключён к компьютеру, на котором работает ваше программное обеспечение — он может находиться даже на другом континенте или, например, на другой планете. Вполне возможно, что пользователь Macintosh(R) в Австралии подключается к системе UNIX(R) в Северной Америке (или где-либо ещё) через telnet. Программное обеспечение работает на одном компьютере, а терминал находится на другом: если попытаться считать скан-коды, будут получены неверные данные! То же самое относится и к любому другому оборудованию: файл, который вы читаете, может находиться на диске, к которому у вас нет прямого доступа. Камера, с которой вы считываете изображения, может находиться на космическом корабле, соединённом с вами через спутники. Вот почему в UNIX(R) никогда нельзя делать никаких предположений о том, откуда поступают ваши данные и куда они направляются. Всегда позволяйте системе управлять физическим доступом к оборудованию. [NOTE] ==== Это предостережения, а не абсолютные правила. Возможны исключения. Например, если текстовый редактор определил, что работает на локальной машине, он может захотеть читать скан-коды напрямую для улучшенного управления. Я упоминаю эти предостережения не для того, чтобы сказать вам, что делать или чего не делать, а просто чтобы вы осознавали определённые подводные камни, которые ждут вас, если вы только что перешли с MS-DOS(R) на UNIX(R). Конечно, творческие люди часто нарушают правила, и это нормально, пока они осознают, что нарушают их, и понимают почему. ==== [[x86-acknowledgements]] == Благодарности Это руководство никогда бы не было создано без помощи многих опытных программистов FreeBSD из {freebsd-hackers}, которые терпеливо отвечали на мои вопросы и направляли меня в моих попытках изучить внутренние механизмы программирования в системе UNIX(R) в целом и в FreeBSD в частности. Томас М. Соммерс открыл дверь для меня. Его https://web.archive.org/web/20090914064615/http://www.codebreakers-journal.com/content/view/262/27[Как написать "Hello, world" на ассемблере в FreeBSD?] веб-страница стала моей первой встречей с примером программирования на ассемблере под FreeBSD. Джейк Буркхолдер держал дверь открытой, охотно отвечая на все мои вопросы и предоставляя примеры исходного кода на языке ассемблера. Copyright (R) 2000-2001 G. Adam Stanislav. All rights reserved.