17_Lisa_Development_System_Internals_ation_Feb84 17 Lisa Development System Internals Ation Feb84

17_Lisa_Development_System_Internals_ation_Feb84 17_Lisa_Development_System_Internals_ation_Feb84

User Manual: 17_Lisa_Development_System_Internals_ation_Feb84

Open the PDF directly: View PDF PDF.
Page Count: 87

Download17_Lisa_Development_System_Internals_ation_Feb84 17 Lisa Development System Internals Ation Feb84
Open PDF In BrowserView PDF
DeveJopn18I1t SystBl11

DOCUMENTA TION

.,

DeveJq:ment TOOls Grotp

FIRST CRAFT--FetuuBty 1984

Preface
The purpose of this document is to explain the internal structures and
algorithms used by the Lisa's run-time environment and development tools, and
the internal library units (such as OBJIOLIB) that are related only to Lisa
systems software. It is actually a collection of documents and memos, any of
which can be used separately, all relating to different aspects of the system.
This is a reference document for programmers working on the following:
* Maintaining or enhancing existing lisa development software.
* Writing compilers or utilities for the Lisa Workshop, either on contract
with Apple or as third-party independants.
* .riting assembly-language programs that will interfaced with our compiled
code.
How will they benefit from this document?
* It will save the people maintaining tools the trouble of looking through
the code themselves to find information.
* It will save outside programmers, who don't have access to the code, from

calling us to ask questions about things that ,ehave to look up in the

code.
* Perts of it will be included es e reference section in technical
contracts that we assign to outside programmers.
* It will provide assembly-language programmers with such specifics as
register conventions, parameter-passing techniques, and memory layouts
used by the conmpiler for different types of arrays and structures.
* It cen be used to trein new systems softwere programmers on the existing
internals of the system.

Contents
Lisa Development Software Documentation: A Road Map
Pascal Compi ler Directives
Pascal Code-Cruncher's Handbook
The Last Whole Earth Text File Format
Pascal's Packing Algorithm
PASLIB Procedure Interface
PPaslibC Unit: Privileged PASLIB Calls
Execution Environment of the Pascal Compiler
Intrinsic Units Mechanism (overview)
IUManager (old and "spring release" versions)
Object Fi Ie Formats
Inbterface to OBJIOLIB
Format of .SYMBOLS File
Shell-Writer's Guide

17/~. L

Lisa Development Software
Documentation:

A Road Map
Irtroduction
Thh roed map was designed to help you to rind your w~ around the verious

documents describing program development for the Lisa. It will help you decide
which software you need to learn more about, which software you can ignore for the
moment, and how you should proceed in stuctying the rest of the technical
documentation.
General CWerview cI the Erwirormertl Available
lhere are 8., many way~ of writing programs as t.here are creative programmers.
However, Apple supports only three general $tyles of programs that you can Yflite for
the Lhe.: those written for 1) the Workshop environment, 2) the QuickPort
environment, and 3) the ToolKit erwironment. Programs written tor eny of these
environments can use most of the. same units and libraries, but there ere lome
important differences of which you should be ewere.
The Workshop (Figure 1) provides e simple non-window, character and graphic
environment within which 8 program may run. Programs written to run in thi$
environment me)' use Pascal's built-in 110 for both fUes end textual display to the console', terminal emulatta", or they may directly utilize the Lisa OS's file SY$tem
primitives. They may elso use the QulckDraw unit for drawing bitmap graphics end
displaying text in e. variety of fonts wit.h variou$ attribute" and may utilize e. veriet~,
of other useful librery routines. These programs are not able to use the Lhe Desktop
libraries dealing with windows, menus, and dialog boxes, nor do they have easy Elccess
to Lha Office Systern document,.
In addition to providing these run-time facilities, the Workshop eho includes 8
command shell which make, available to users an extensive set or facilities for: 1)
Interactive program development in Pascal, Assembly, BASIC, and COEl1L; 2) File and
device manipulation; end 3) Interactive and batch program execution and control.
QuickPort (Figure 2) provides the simplest Desktop erwironment, at least from the
programmer', viewpoint. In most respects, writing a program for the QuickPort
environment it identical to writing one for t.he Work,hop environment. Uting Pascal' ~
bu11t-in 110 facUities, programs written for QulckPort may do t.extuel display t.o 8

variety of window-based t.erminal emulators, end may also dbplay graphics using
QulckOraw. These programs do not directly ute the Lisa Desktop libraries, and ere, in
fact, unaware of such things a, the window eN/ironment, the mouse, and menul. They

14-'ebrutr1)l-84

Road Nap-I

Internals

II Confident i 81

may, however ex change information with Lisa Office System documents via the
I

Cut/Paste mechanism.

The ToolKit (Figure 3) provides the most complete acceu to the Desktop tacilitiei.
Frorr. the programmer's viewpoint, it. also requires the most knowledge of these
f'acilitie$. Programs \lJJ'itten using the --1oo1Kit use the Generic Application and may
use 8ny of the toolKit building blocks, which provide easy, controlled accen to t~le
Lisa Desktop libraries, the mouse, and menus. They may also exchange information
with Lisa Office System document' vie. the Cut/Paste mechanism.
(Nerview cI the Pieces
QuicItPa1 is a set or units that are USEd and linked with a program which it to be

run in the Desktop environment. QuickPort then provides the prograrn with 8.
·'terminal window", to which the program's console 110 may be directed through the
use of Pascal's built-in Text 110 facilities. The progTarn simply rrlakes ReadLn and
WriteLn cells to display text or receive keyboard input. QuickPort code hides from
the program such issues as cuttinQ end pastino information rrorn other Desktop
applications, communicating with the Desktop shell, growing and shrinking the windo'-N,
covering and uncovering the window, end activating or deactivating the prograrn. For
e program using QuickPort, such iuues ere of no concern.
The ToolKit Is a set of libraries that provides ttanderd Lise application behavior,
including windows that can be moved, resized, and scro11ed, pull-down menus with
standard functions such as s8Ving and printing,. and the Cut/Paste mechanism. The
loon·tit define, the perts of an application common to all Lisa applications. The
object-oriented structure of the ToolKit e.llows you to Implement your applicat10n as
extensions to the "Generic Application".
The u. ~l1ting ~ provides the program with an environment in which
multiple processes cen coexht, with the ability to communicate and shere data.. It
provide, e. device-independent rile tyatem for 110 and information storage, end he.ndles
exceptions (software interrupts) and me~or)' management for both ~ode and data
$egments.
PASUB is the Pascal run-time support library. Most or the routines in PASLIB
support the Pascal built-in racilitie$, including routines for initialization, integer
arithmetic, date. and string manipulation, lets, range checking, the heap, and 110.
FJotIlilllJ Pout UJrtJriet provide numeric routines which implement the proposed IEEE
Floeting Point Standerd (Standard 7~ for Binary Floating-Point Arithmetic), and
higher-level mathematical algorithms. FPUb provides Sinole (32-bit), Double (64-bit),
end Extended (EK)-bit) floating-paint data types, a 64-bit Integer data type, conver$ion
from one arithmetic type to another (or to ASCll), arithmetic operations,
transcendental functions, end tools for handling exceptions. MllUt..ib provides, among
othert, algorithms such as extra elementary functions, lortino, extended conversion
routines, finencial anelyds, zeros of functions, and linear algebra.
(fIulckLrlJtll 1$ a unit for doing bit-mapped graphIcs. It consists at procedures,
functions, and data type~ you need t.o perform highly complex oraphic operation~ very
eaaily and vmy quickly. You can drew text characters in a number of' fonts, with

Intern8.ls

• Confiderd162

variations that include boldface, ite.lic. underlined. and outlined; you can draw
arbitrary or predefined shapes, either hollow or filled; you can draw rtraight lines of
any length and width; or you can draw any combination of these items, with a single
proceck.l'e ca1l.
The t:Je#top Lilrtrin provide window, graphic$" mouse, and menu routines used by
ell Office System applications. They ere not directly celled by any programs written
for the three run-time erNironmentJ discussed here, but. provide the hidden foundat iun
for both the QuickPort arid the ToolKit environment$~
lhe HlltAfJt;re lMerflJlCe ur,it lets you access Lisa hardware elements such as the
mouse" the cursor, the dhplay, the contrast control, the speeker" the keyboard., the
micro- and millhecond timers, and the hardware clock/calender.
The Stll!nlWd U'tit lets you do atring, cheracter, and file-name manipulation,
prompting, retrieval of messages from disk files., abort exec file proceSSing, and
conver~ion$

between number s end

string~.

The DPrimttJvet unit provides you witr, fast, efficient text-fHe input end output.
The PrO{TBIT1 Communi~ion unit allows programs to communicate with eactl ottler
and with the Workshop shell.
LUtJaJg allows you to examine and modify memory, set breakpoints, assemble and
disassemble instructions, and perform other functions for run-time debugging.
Mere Detail

QuickPc:rt: A prograrn which is to make full use of the capabilities of the Lise Office
Syatem will be structured as an endless loop, within which the program continually
polls the Window Manaoer for any events it should respond to. We will refer to suerl
e program as an Inte~ated Progr4/n An integrated program must handle such

esynctfonout events a$ the p"ogram's window being activated or deactivated, the
window being opened, closed, moved, resized, or needing update, the mouse button
ooing down or up, and 8 key going down or up. lhe program must also be a oood
citizen in Lise', multi-talking but. non-preemptive scheduling erwironment by
volunteering periodically to yield the CPU to any other process needing service.
These are just a few of the important cheracterhtie. of an integrated prooram. The
result of a prograrn following these and other guidelines will be that it exhibits the
teme conshtent" respoNive behavior as other Apple-written programs like LbeDraw.
QuickPort 1s a collection of' pieces which make writing programs for the orfiee
System's wir.dow erwironment as e8$Y as writing them for the Workshop', non-window
environment. NlTE: In order to differenttate the QuickPort modules from the
program which uses them, we will refer to the program itself as.& ~"arIl1J8 Progrs:m
QuickPort allows the vanilla program to be more traditionally structured, as if its user
interfacing were beino done through a tmart texl/graphics terminal; the vanilla
program presents its display to the user by e combination or text 110 calls (e.o.,
WrileLn/Ree.dLn) and QuickDraw calls (e.g., DrawString/PaintRect.). lhe QuickPort
modules handle all !\lent' from the Window Manager, provide for yieldino the CPU to
competing proceues at specific points, and in general shelter the program from th~

Internals

" Confident is1

sometimes tricky requirernents of writing arr integrated program for the Lise Office
Sy~tem.

QuickPort provides the vanilla program with a window, which may be divided into e
Text Panel and a QuickOraw Panel for displaying both textual and oraphlc
information. Each of lhe$e optione.l panels is configurable in size and loce.tion, and
may be independently $crolled horizontally or vertically. Text and Graphics windows
may be overlaid, $0 the resulting window presents a composite of both typet of
output. The window may be resized" moved, covered, or uncovered without the
vanilla program even being aware of $uch events. Textual and grephic information
may be exchanged between 8 vanilla prooram'$ document and other documents,
whether v&rlilla or integrated, by using the familiar Cut/Paste mechanism. Without
any effort on the part of the vanilla program, the end user h given a large measure
of control over the window's configuration end behavior, using mouse end menu
8ctions supported by QuickPort.
The user may request printing of either the text panel or the graphics panel. In
addition, vanilla prograrns mey produce printed output under program control by
writing to the -PRINTER logical device. Whereas, in the Workshop environment,
printing is Immediate (each lir.e printing as soon a$ the proOIam "writes" Itt in the
QuickPort/Desktop environment printing h all spooled. This means that the printed
output of e. vanilla program will be submitted to the Office system's PrintShop, which
determines 1rom the print queue when the document will be printed.
The T6).'t P8neJ emulates a terminal display which conesponds to the Pascal built-in
OUTPUT file, the built-in INPUT file, and the -CONSOLE and -KEYEOARD logical
devices. Apple provides emulators for the .·'Tl~"t' and StJFirJC terminals, and makes
it possible for you to either customize thern or create entirely new termirtal
emulators. These terminal emulators are actually filters which pre-process the
character output stream destined for the Stsnd81d TMmiMJ tlrlit,. which prO'Vide~ the
Text Panel display. Each emulator', job is to recognize the terminal-specific
character seQuences imbedded in the output stream which ere commands to the
terminal, end to call upon the Ste.nderd Terminal Unit to take the appropriate actiont.
A program may eliminate the filtering step, if dedred, by calling directly upon the
Standerd Terminal Unit for displey actions.
The Graphics Parle! allows your program to display graphics on a bltmep which 1s a
maximum of 720 pixels wide b.Y 364 pixels high--the same size 8$ Lisa'$ physical
screen bitmap. This panel can be resized by the user or under program control, and
can be scrolled horizontally and vertically t.o display different pert$ of the entire
bitmap. The Graphics Penel supports ~~ QulckOraw cell, including those related to
setting foreground and background colors 10r r;l'inted output. An application may
write anywhere in the coordinate plane or its graphic$ panel ('grafPort to use
QuickDr8w', t.erminology), without having t.o worry about where its window it placed
on the screen or what other wlndow$ are in front 01'1t. QuickOraw, with a little help
trom the Window M8naoer, keep$ the application', output 1rom oettinO out or the
C;ephics penel or from clobbering other windows.
l

,

Internals
/

" Confident 1 6)

The ToolKit: Ttle ToolKit is a set of libraries that provides standard behavior that
followt the de$ign principle. characterizing Lisa applications:
• Ext.enaive use of graphics, including window' and t.he mouse pointer.

• Use of pull-down rraenus for command$.
• Few or no operating modes.
• Data trand'er between document, by $imple cut and paste operations.
For exempJe, all Lile applications have windowl that can be "",oved eround the screen,
and that can usually be resi2ed end scrolled. The ToolKit takes care of all these
functions. The ToolKit also displays a menu bm for the active application, end
prO\lides a number of st.andard menu functions, such as savino, printing, and setting
8side.
However, the ToolKit is more than 8 set of libraries. Because the ToolKit is written
using Cla;cal, the ToolKit is almo't

8

complete program by itself.

YOll c:&rt,

in fact,

write a five-line main program, compile It, link it with the ToolKit, and run it. Wrtel
results it the Generic: Application.
The Generic Application has many of the It.anderd Lisa application chsracterittics~ A
piece of GeneriC Application stationary can be torn oN', and, when the new docurnent
h opened, it presents the U$er with a window with acroll ber$, split controls, size
control, and e. title bar. The moute pointer is handled correctly when it is over. V·IE'
window. The window can be moved, resized, and ,plit into multiple panes. There is e.
menu ber with a few standard functions, so that the generiC document can be saved,
printed, and aet aside. The single Generic Application proceu can manage any
number of documents. You cannot, however, do enything within the window, eside
from creating panes. The space within the window, along with the additional menu
ructiorls, is the responsibility of the reel application.
Therefore, when you writ.e a Lise application udng t.he ToolKit, you essentially write
extensions to the Generic Application. It is very easy to write extensions to any
Clatcal program. To insert your application's functions, you create a set· of
lubclasses, including methods to perforrTl the work or you application, and then you
write a simple main program, and compile and link it with the ToolKit.
Whenever necesseary, the ToolKit calls your application" routines. For example, if the
u~er scrolls the document, the ToolKit tells your program to redraw the changed
portions of the window. Your program does not. need to be concerned with when
redrawing is required.
One effect of C18sce.l is that you can write applicetions in tteps. You can begin by
doing the least amourt possible, and get an application that does very little, but will
run. You can then extend your application bit by bit, checking as you go. Thh
characteristic of Clascal makes it easy to extend the cepebilities of ToolKit programs,
even years arier the original program.
The TooIKit'$ debugger, Kit Bug, provides run-time debugging or ToolKit Clasce.l
programs. It allows you to do performance measurements, let breakpOints end traces,
.ingJe-step through your program one atotement at a time, and do high-level
examinetions of data objects.

Internals

II ConfidentiBl

The Oper~ing System: Tt,e Operating Systern ~rovides en environrrlent in whic,h
multiple processe$ can coexist, with the ability to communicate and shere de.ta. It
provides a file ryrtem for 110 and inf'orrnalion storage, and handles exceptions
(,oftware interrupts) and memory management.
Tt.e File Sj.··stem provides input and output. It accesses devices, volumes, and files.
Each object, whether a printer, dhk file, or any other' type d object, is referenced by
a pathname. Every 110 operation is performed as an uninterpreted byte stream. Using
the File Sy,tem, ell 110 h device-independenl. The File System altO provides devicespec1flc control operations.
A process consists of an ex ecutinQ prograrn and the data auocie.ted with it. Se\ler al
processes can exist at once, end will eppeer to run simultaneou$ly because the
processor is rrtUltiplexed among them. These processes can be broken into multiple
segments which ere aut.omatice.lly swapped into memory as needed. Communic~tion
between processes is accomp1istled through events and exceptions. An event is a
message sent from one process to another, or from a procen to itself, that is
delivered to the receiving process only when the process asks tor it. An exception is
a special type of event that forces itself on the receiving process. In addition to a
set of system-defined exception$ (errors), suet. as division by zero, you can use the
ayslem cell$ provided to define &ny olher exceptions you want.
,.1emol}" management routines handle data segments and code segments. A data
segment is a file that can be placed in memory and accessed directly. A code
segment is a swapping unit that you can define. If a process uses more memory
than the available ~AM, the OS will ,wap code segment, in and out of memory as
they ere needed.
PASlI8: PASL18 h the Pascal run-time $UPport library. It provides the r:t'ocedure$
end functions that ere bunt into the Pascal language, acts as the run-time interface
to t.he Operatino Sy,tem, end "complete," the 68C()() inrtruction ,et by providing
routines for the compiler-generated code to call upon in lieu 01' actue.1 hardware
instructions.
PASLIB routines ere celled with all parameter, passed on the stack. There is an
initialization routine to initialize necessary variables, libreries, and exception-handlers
end set up global tile buffer addresses, and a termination routine to kill processes.
You can do tour-byte integer arithmetic. Data can be moved, or scanned for a
pmticuler chef acter. String manipuletion routines include concatenating, copying,
inserting or deleting a substring, determining t.he position of a substring, end
compering strinQs for equelity. Set manipulation routines let you find set
intersections or differences, adjust t.he size of a let, end compere sets fer equality.
There ere range-checking and string range-checking routines. Heap routines let you
allocate memory in the heap, mark or release the heep, check available memory in
the heap, end check the heap reault. 110 routines let you read and write lines,
characters, strings, packed arreys of charecters, booleans, and integers, as well as
check for a keypress or an end-or-line, and send page marks. File 110 routine$

Internals
include reYr'l'iting,. resetting or closing 8 file, detecting an end-or-fHe, readinQ end
writing block$" and get, put, and seek procedures.
Floalng-Poirt umarie,: The Lise ~ovide$ arithmetic, elernentary functions, and
higher level mathematical algorithms in its intrinsic units FPLib and Mattt..ib, which
ere contained in the file IlSFPUB.
FPLib provides the same functionality as the SANE end Elems units on the Apple) I
end III, including:
• Arithmetic for all floating-point and Comp types.
• Conyer'ion~ between numerical types.
• Conversions between numerical types, ASCIl strings, and interrnediate forms.
• Control of rounding mode$ and nurr.erical exception handlino.
• Cornrnon elementary functions.
tvW.hLib provides the extra procedures available only on the Lise.:
• Extra environments procedures.
• Extra elementary functions.
• Mi$cell&nE!ou$ utility procedure;.
• Sorting.
• Free-forrnst conversion to ASCII.
• Correctly rounded conversion between binary and decimal.
• Finarlcie.l analysis.
• Zeros of functions.
• Line&r algebra.

QulckDraw: Virtually all of Lisa's graphics are performed by the QuickDraw unit.
You can draw text, lines, and shapes, and you can draw pictures combining these·
elements. Drawing can be done to many distinct "ports" on the screen, each of which
is e complete drawing environment. You can "clip" drawing to arbitrary areas, so
that you only draw where you want. You can drew to an off-screen buffer without
disturbing the screen, then quickly move your drawing to the screen.
Text character$ ere avilemle in a number of proportionally-spaced fonts. Any font
cart be drawn in any size--if 8 font isn't available in 8 particular size, QuickDraw
will .cele it to the specified dze. You can draw characters in any combinetion of
boldface, italic, underlined, outlined, or shadowed styles. Text can be condensed or
extended, and it can be justified (eligned with both e lett end a right. margin).
Straight IiMS can be drewn In eT¥ length and Width, and cen be solid-colored (bleck,
white, or shade~ of gray) or patterned.
ShlJptts defined by QuickDraw ere rectangle$, rectangle, with rounded corners, full
circles or ovals, wedge-shaped sections r:I circlet or ovals, and polygons. In addition,
you can describe any erbitrery shape you want. All ahapes can be drawn either
hollow (just an outline, which has all the widttl and pattern characteristics of other
linea) or solid (filled in with a color or pettern that you define).

J4-(ebrut!l1'}~84

Road 11ap-7

Internals

" Confident i 61

QuickDraw lets you combine any of these elements into a pictlle, which carl then bl:
8 dngle procedure call.
Three-tiimensiorl!ll graphics capabilities are also available, in a unit celled Graf3D"
which is layered on top of ttle QuickDraw routines. Gref3D lets you draw threedimen$ional object' in true perspective, using real veriables and world coordinates.
drewn--to erry scele--wit.h

The Hardware lrter1ace: The Hardware Interface unit lets you access lisa hardware
elements such as the mouse, the Cl4"SOI, the display, the speaker, the keyboerd, arid
the timer; and clocks.
"''/ou$'e routines deterrriine the location or the mouS!, set the frequency with which
$ottwere knowledge of the mouse location is updated, change the relationship between
physic a) mouee movement and the moverr,er.t. ot the cursor on the screen, and keep
track of how fer ttle mouse has moved since boot Ume.
Cursor routines let you define different CIZ$OrS, track mouse movements, and displery'
e busy cursor when an operation takes a long tin-Ie.
Screen-control routines can set t~,e size of the screen, and set contrast and
automatic fading levels.
Spt:4Aer routines allow you to find out arid set the speeker volume, and create

sounds.

Routines are provided to handle the different ke,·'bo8rdt available for the Lisa, 8S
well as the mouse button and plug, the dhkette buttons end insertion switches . . end
the power switch. You can find out which keyboard is attached, and set the ry'iten"J
to believe that a different physical keybosrd is connected. You can ctteck to see \
what keys (including the mouse button) ere currently being held down, look at or
return the events in the keyboard queue, and read and set the repeat retes ror
repeatable key,.
DlItfJ ~d time routines let you access the microtecond end millisecond timers end
check or set the date and time.
The Stends'd lklit: The Standard Unit (StdUnit) it an intrinsic unit providing a
number of standard, generally-useful furlctions. The functions are divided into 8l'eas
of functionality: character end rtring manipulation, file name manipulation, prompting,
retrieval of error message, from disk files, Workshop support, and conversions.

The unit provides types for standard strings and for sets of characters, definitions for
e nurraber of standard characters (such as  and <8S», and procedure, for case
conversion on characters and string', trimming blankl, and appending Itring~ and
cheracters.
File name manipulation functions let you determine it a pathname is a volume or
device name only, add file name extension, (such as ".TEXT"), .pUt a psthname into
its ttTee badc components (the device or volume, the file name, and the extension)
put the component, back together into a file name, and modify a fUe oeme given
optional defaults for missing volurrle, file, or extension components.

Road &47-8

Internals

II Confidential

Prompting procedures let you get characters, strings, file narnes, integers, yes or no
responses, and so fCtrth horn the console, providing for default values where
appropriate.
Special Work$~top functions let you stop the execution of an EXEC file in progreu
find out. the n~e of the boot and current proceu volumes, and open system file~,
looking at the prefix, boot and current process volumes when trying to access a file.
Conversior, routinet let you convert between INTEGERs (or LONGINT,) and ttrings.
l

The lPrimitives Unit: The IOPrimitives unit provides you with f(ut efficient
text-file input and output routine$ with the functionality of the Pales! 110 routine$.
It includes routines for reading characters or lines, and for wriUnO characters, lines,.
strings, and integers, plus the low-level routines on which the others are based.
l

The Prc:M78m ComnuniC8tions Unit: The PrOgTeITt Communications unit (ProgComm)
provides three mechanisms for communication between one progre.m and another eaT
between e program and the shell. The first two irwolve strings sent frorn e prograrn
to the ,hell; one telh the shell which program to run next, the other is a "return
$tring" that can be read by the exec file processor to tell an exec file, for ex empIe,
whether the prograrTl completed successfully'. The third mechanism involves reading
1l0rTl and writing to a lK byte communications buffer, global to the Workshop. Using
the unit, e. program can invoke another program and provide its input through the
buffer, without user intervention.

UtaBug: LbaBug provides commands for displaying and setting memory locations and
reghters, for assembling and disassembling instructions, for letting breakpoints and
uaces to trace progr&m execution, for manipulating the memory management
herdwe.re, and for measuring execution times using timing functions. Utility
commarlds are aho available to clear the screen, print either the main screen or the
LhaBug ~creen, change between decimal and hexadecimal, change the setting of trle
NMI key, and display the values of symbols.

Road Nap- 9

11f.1/

Internals

" Confidenti81

'hItlere t.o Go from Here
ihe Lisa development software is riot fully documented yet. The following is a list of
what it available" $ome of it only internally, as of this publication. Note the.t the
spring-release manuah will be organized differently from the current versions, and
will incorporate rr.uch of the information that is now in the internals documentation

or in seperate documents.

Pascal Reference ft.18nu81 for the Lisil

include$: QuickDr aw

Herdware Interface
FloEsting-Point Librery
Operating Systern Reference "18nL/8/ for the Lisa
l~ork.sftop

I.lser's Guide for the Lis8

Liss De\,.-eJopI7'J8nl S)·'ttem Internal! Doc'urnentstion
includes: Pascal Run-Time Library
Standard Unit

LhaBug
Floating-Point Librarie$

QuicJ\Port Application! L'ser GuideQuick-Port Programmer's GuideAn Introduction to ClssclJl
CJascsl SeJf-Stufi)·'

Toolf(it Reference f>.1an1J81

ToolKit Training Segments
Numeric! t-18nu81: A Guide to I"/sing the Apple ,.,:.·:l P8S'C61 SANE and Elems L'nits
FPLib provide$ the $o.me functionality ~ these unit$.
f1.18thLib Guide'"

*The$e manuals currently in Tough draft form.

17J./2

I

Floating-Poirt Lm eries
I ..
JEEE Numerics, Math Algorithms .....
Hel'"dwm'e lrter1'ace

Mou$e, Keyboard, Clocks, Speaker

r

StEWldsrd Unit

I ..

Strings" Prompts, Error M$Qs, milc

-

I..

lID Primitives
Fa~t Text. File 110

r

-

~

Prc:qam Communication

lnter-progrern and Shell Communication

r-1

..
f""'"
.--1

Pascal Ru1- Time Lib'f!1l'J

.., _
~
~~------------------------~I~~~~
~
'-______Iro
__,_H_e_~~/_S_u_i_n~g:$_'_M_8_t_h______~
..,

QuickDrf*N

_

~ ~~------------~--------------------~~~~
r--Bit-Map Graphics
...j

U.a Operating SyItem
Memory Mgmt~ File Sy$tem, Process Mgmt

FiglJ'e 1
The Workshop Run-Time Environment

~

to Figures 1, 2, & 3

Unit Name
Description of what

It

it does

Road

17/J~. 13

~1ap- J J

•I

1IIIIItlllllllllllll'"

i

1

QUICKR:RT PRlGRAM

•

,I

111LILIlll1111111111111

....

Floating-Point Lim-aries
IEEE Numerics, Math Algorithms

.......

Her~e

I

.......
~

I

...

I..

Irterface

,-

Clocks, Speaker

St.8nd8rd Unit
I Strings, Prompts, Enor Msgs, misc

I

.......&

.......

Pascal Roo-Time Litrery
110, Heap, Strings, Math

.......&
......

,......-!

j

.......

.-L

j

(

Soroc

+

VT100

+

~~

)
1~

Standard Terminal )

•

.....
.......

I
I

Prirt.er Suppcrl
-Printer

QuickPa"t

I

Virtual-Terminal Window

I

+

.......

......

....A

~

~

I
t

ToolKit
Generic Application, Bldg Blocks

+

.......

.....

~,

Oeaktop Lttraries

Window Mgr, Storage Mor, Font Mgr, Print Mgr

•

I

QuickDrf!NI
Bit-Map Graphics

~

....

~

....... I
--I

~t

Lila Operating system
Memory Mgmt, File System, Procen Mgrrt

•

,

~If~ft~ttfj~ffffj~jr~jf~~~{:·:4.~:·:·:l~·:~~:·~·:·~~~:':':~~~:jlt~~t~~II~~t~~~~11t~i~~~~tft~fJ
Figll'e 2
The QuickPort Run-Time Environment

Road ft.flJ{J-12

J

I'JrJi Jr JrJr Jr JrJr JrJrJrJr JrJr ~JrJrJrJr Jr Jr JrJr' • · • • • • • • , , • , , , , ,', , "JrJrJrJr Jr Jr Jr.t lr Jr lr Jr lr Jr JrJr Jr lr lr Jr JrJr Jr
.. ~~.~JtJt.~~.~Jt~JtJtJtJt~.Jt •• 1lD..KIT PR)GRAM ·~JtJtJtJtJt • .t:ififJtJt~Jt.lfJtJt.JtJtJt • .If.
r .. ~JtJtJt~!Jt~.~~.Jt~~~.~Jt~JtJtJt~~~~~~.~~~~~~~~~~~~~i

•• JtJtJtJtJtk~JtJtJtJt~Jt.JtJtJt~JtJtJt.
4

,..
Float ing-Poirt Ut..8ries

.....
-.

~

I'

IEEE Numerics. . Math Algorithms
1

HardwfJl'e IrUrface

--

......
...

...

.....

Clocks, Speaker

PtucaJ Rtrl-Time Utwsy

--.

110, Heap.. Strings, Math

+

...
......

...
'"'

~
~

ToolKit

Generic Application, Bldg Blocks

•

~ Kit9.Jg }-

Delktop Litweries

'"
~

....
.......

-

r

Window Mgr" Storage Mgr .. Font Mgr . Print Mgr
~t

QuickDrsw
~
~

..

Bit-Map

Gre.phic~

1

.....
.....
~.

r

Lisa Operating System
Memory Mgmt . . File SY$tem, Process Mgmt
~.

Il~f~~~~~~~~IL::.)ff~I}I~~tttr:·:t.i.~r·:?~:~~:·:·:·~:·~·~~~~f.·~·~~~~~~tI~ttttt~~~fttrrfff]
Fioure 3

The ToolKit Rurt-Time

Environ~nt

Road '''''ap-l}

Pasc:al C:ompiler Directives
The following cornpiler commands ere e:ve.ilable:
~

~+

or I"or SC-

Allow the % symbol in identifiers. The default· is ~.
Turn code generation on (+) or off (-). This is done on a
procedure-by-procedure basis. These comrnsnds should be writteri
between procedures; results ere unspecified if they are written
inside procedures. Tt.e default is ~+.
Turn the generation of procedure names in object code on (+) or clff
(-). These comme.nd$ should be 'wtr'J'itten between procedure~; result~
are unspecified if the').' are written inside prc1cedures. The default
is $0+.

SE rilenflfte

SI rilenene

SL rilentne

$L.+ or SL-

$)+

or s0-

b..

*=PI. or SCN-

Start making e Ihting of compiler errors as they are encounterecl.
Analogous to $L filen.e (,ee below). The default i~ rtCl errCiT
listing.
Disable~ handle- checkirlg so dereferenced handle~ (rflatter pcdnt.er~)
may be used in with staternents, on the left ,ide of assigrlrnent
stat.ements, end ir, expression$: involving procedure calh. The
default is $i+.
Start taking Sf)UrCe code fTorn file tilensne. When the end of ttll ~
file is reached., re-vert to the previous $ource file. If the filen&rne
begins wittl + or -, ttlere must be a space between $1 and the
filenarne (the space is not necessmy otherwise). Files may be $1
included up tel five l~/er$ deep.
Start Ihting the cornpilation on file filenene. If e listing is being
made already" that file is closed end saved prior to opening the

new file. The default is rec, listing. If the filenerrle begins witr, +
or -, there must be a space between Sl and the filename (the speC:t
is riot necessary otl'"ler~'ise).
The first + or - follo't'I'ing the SL turns the source listing on (+) or
off (-) without changing the list file. You must specify the listing
file before using $L+. The default is $l.+~ but no lifting h produced
if rio listing file t,as been specified.
Suppress register opitimization (-). The default is IJ+.
Optirniz8tion limited--use the old (2.0 release) optimization
mechanism, instead of the new one. The default is ttlf new one.
Turn integer overflow ctlecking on (+) or off (-). Overflow checking
is done after ell integer e.dd~ subtrect., 16-bit rrrultiply, divide,
negate, abs . and 16-bit square operations~ and after 32 to 16 bit
conver$ions. The default is $(W-.

II CtJnlJo'tnUsl

lntell"Is'1s
~

or SR-

Turn range e:hec¥ing on (+) or off (-). At present,. re.nge checkin~l Vii
done in assigrlrnent ste.tements and an·sy indexe~ and for strin9
ve.l!.le parsrneters. No rarlge checking is done for type longint. Trle

default is $R+.

$S

segnene

$J filenene
SJ+ or SJ$X+ or $X-

~IC

7-FebTlJ4ty-84

Start putting code rnodules into segment segnsne. The default
segrnent name is 8 string of blanks to designate the "blank
segment/' in which the mairl program and all built-in support code
ere alwe.)/s linked. All other code cara be placed into any segrrlent.
Search the file filenane for any' units subsequently' specified in the
IJses-clause. Does not apply to intrinsic-units.
Tell the syst.em riot to searctl IHTRItliIC.LIB for units }'ou use (-).
The default is SU+ - the system searches INTRINSIC .LIB first,
then your owrl libraries.
Turn autornatic run-tirne stack ex parlsion on (+) or off (-).
Run-time steck expansion is the insertiorl of an e)·.trs 4-byte
instruction per prc,(:edure to ensure that t.he Lisa's mernorymanagernent rTlec:~,anisrr, has rnapped in enrJlJgt", ste.ck space for the
ex ecution of the prc,cedure. With $X-, ex (.es:sive w;e of t.he stacl<
~., the procedure could cause a bus error. The defel.Jlt is $X+.
T~le $SETC comrr.and has the forrn:
{$S£TC m := ~}
or
{$'SETC 10 = ~}
'""here 10 is the identifier of 8. cornpile-time variable and ~ is a
compile-tirne expreuion. ~ is evaluated imrnedie~ ely. T~le
value of EXPR is assigned to 10.
Compile-tirne variables ere completely independent of progrern
variablesi even if a compile-time variable and a prograrrl variable
have the same identifier, they can nev'er be confused by the
compiler.
Note trle following pC,ints atrOUt. compile-time variebles:
• Corrlpile-time variables have no t.ypes, although their values do.
The only possible types are irteger and boolean.
• At any point in the program, a cornpile-time variatlle can have
a new value assigned to it by a $SETC command.

SIft, SEJ«

SELSEC

CClnditic,rl61 compilatic,n i~ controlled by the SIre, $EL5EC, arid
cornrilerlds, Wt",lCrl are used tel bracket sections of SOlfl" ce tt It..
'",'hether e. partic:ular brae·keted $ectielrt of a proglarrl h cornpil~'~
depend~ on the boolean velue of a compije-tirne e';rpression, WhlC h
can contairl C"Ctrnpi/e-time ~1·8J'iab/6S.

SEJ«

SD£C commands take no erguments. The SIFe
has the forrn:

The SFI SEC end
comrnend

{SIFC ~}

where EXPR is e compile-time expression "'t'ith e boolean value.
T~,e$e three command~ form constructions sirnilar t.o the Pascel
if - staternent, ex cept that the $E::t« corrlmand is al W&ys needecl Ci.t
the erld of the SIfC construction. .-] S£C is optione.1.
SIfC con5truc:tion~ cer, be rlested wjt~lin each CtthE'T to 10 le'.,;e1s.
Every SIF'C rnlJst have 6. metching $E::t«.
Conlplle-tirrle expres~ion~

appear in the ~ cornrnand ancl jr, thE
A cornpile-time expression is eVblueted by the
cornpiler e~ soon 6$ it is encountered in the text.
The only o~eror,d~ all(l~/ed in a compile-time exprezS'ion ere:

SIre

comrn~rld.

• Corrl~'ile-tirTie variables

• Constants of ttle type~ integer and boolean. (it"le~e are eho trie
onl~l pc'~sible types felr result~ of compile-tirne expres:sions.)
All Pbse:e.l elperat.Ctr~ ere allowed except as follows:
• The in operator b not allowed.
• The il operator h not allowed .
• The I c'perator i$ autornatically replaced b~J div.

7-F~brI.J81y-84

Cornpi/el C'irectives-."';

Fred FarsrTBl

Revisioo 1.0
Sept.en"tJer 28, 1983

Remove ,"i~U y, ~S"Ited bytes
1n the privacy of 'fOJI own offlce.

Pascal Code Cruncher's Handbook

Page 1

PASCAL
CODE CRUNCHER'S
HANDBOOK
Fred Forsman

Introduction
ihis document explains how to reduce the size of Pascal code by changes
at the Pascal source level. Thus what will be presented are source
transformations which result in semantically equivalent, but smeller
code.
~hile these transformations will produce smaller code, they ere unllkely
to produce code that is "better" in all senses. 5001etimes you 1,11111 be
trading orf clarity ror efficiency Since typically you will be changing
what was the rirst and obvious way of writln; your code. On the other
hand, your code may benerit (and actually become clearer) just from
having been thought about a second tlme. Nevertheless, if it is given
that you must reduce your code size, you may find these source
transfomations more palatable (and more m81ntainable) than rewriting in
assembly language.
Please note that this is a li~"in9 docunent, that is, no claims are made
that this is a complete or final list of source transrormation
techniQues. New techniQues will be added as I find out about them (so
it you are eware of some transrormations not mentioned here please let
ne know about them). Also, some or the techniques described will be
removed from this document when future compiler optimizations obviate
the need for them.
000

Thanks to Al Hoffman for his invaluable assistance in researching and
doc~entino much of the material presented here.
Thanks also to Ken
friedenbach and Rich Page.
6

Pascal Code Cruncher's Handbook

Page 2

How to find what code to crunch and how to
measure your progress
Given a Pascal unit which you want to crunch, you need to identify the
procedures which are most likely to benefit from crunching and you need
a mechani~ by which to measure the results or your efforts. The Pascal
code generatar writes information to the console on the size of the code
generated for each procedure and the size of the code for the unit beino
compiled. With a compile exec file such as the one below you can
redirect this information to a file, ror use in later analysis.
$EXEC {perform a compile}
$ { the first parameter (".o) specifies what file to ccnpile }

$ { if a second paremeter is specified, it is used for the output obj

file, otherwise we default to tI'".D.obj" }

$ { it a third peremeter is specified, the code generator's console

output is redirected to

1I~2.text",

othe!\lllSe default to "o.text"
}

$ { the intermediate file is put in a temp file on -peraport
P{Pascal}~

-peraport-temp
$IF \2 (> ., THEN
S{Sys-mQI}O{OutputRedirect}%2.text
$ELSE
S{Sys-mgr}O{OutputRedirect}o.text
$Et-()IF

o{Qui t Sys-mgr}

G{generate }-peraport-temp

SIF

~1

<>

II

THEN

%1

SELSE
".0
:Je()IF'

S{Sys-mgr}O{OutputRedirect}-console
O{Quit}
$EK)EXEC

Once you have the code generator's console output, the first step is to
identify tne easy targets for crunching: most often these will be the
larger routines (Code size ) 2~ bytes, or some similar criterion). The
above exec rile can then be used to verify that any changes you make
actually result in code size improvements.

Pascal Code Cruncher's Handbook

Page :3

If you are working on code that is not totally new, chances are that it
has undergone a number of major and minor changes. As code is modified,
"dead" code and variables are often left around inadvertently. These
unused objects can be discovered and removed by checklno the code wlth
the various cross reference utilities. (Whlle the Workshop linker will
remove dead code automatically it will not remove dead variables.)
for those of you who want to kn~ what the compiler is r~~ly doing, use
the DuMpObj utility to look at a disassembly of any of the procedures or

functions you are interested in.

Pascal Code Cruncher's Handbook

Page 4

How to crunch code: tecrlniques
Following are a nllnber of techniques for Pascal source transformation.
The fine print followlno the description of each techniQue attempts to
estimate the potential space savings, the difficulty ot implementation,
and probability of introducing errors.
1.

The first law of code crunching: don't use in-line code when a
procedure to do the same thino exists. The in-line code m~' be
raster, but space is more important in the vast majority or cases.
In order to apply this lew effectively you should KNOW WHAT IS
AYAIua.E IN n£ LIERMIES. Similarly you should be femilier with
what the language provides, particularly in the area of bUllt-in
procedures end functions.
USing exilting COOl ilpure gUn. The ~ Of dOing so ShOuld ~ "iniMl ~lnct h
~llV end l1Draries ~ld be ,nor. fr~ (or at .1HSt tneir ou;s ..,i 11 r>t Ttc:Ogniztcl ina
flxed JOCneT tNIn you:r pnvate oooe "''\lCln lS exlrC:1ztO less often).

2.

An extension of the above law is the creation procedures WhlCh
perform code sequences which are repeated often in your code (minor
differences can be handled by parameterization). One neme for thlS
technique is "factoring". Use or peremeters cen degrade the
optimization if the size of the code being 'actored is small. On
the other hand, if intrOduction of a paremeter will allow sharlng
or a· long sequence of code the extra overhead should be well worth
it. A word of werning: check to see whether your factoring really
paid o'f -- the code being factored out should not be smaller than
the procedure call (and any parameter passing) that replaces it. A
pOint to note is that factoring of even slngle statements can be
fruitrul, ror exemple:
A[F' (X)] : = A[f (X)] ... 1;
P'ctoring CWl be • eta ..,in in
Otnlr tec:rt'li~. 5:) it often

ItCA;

oHen s.ving Pm'e ~","YI C3n De a:t'Ii~.-.cl by any
lOC* W().q"t yoJr coot fOr ~ cooe s.equeras.
~ifficulty .., llkelytwood Of errors are 1QfJ, bUt ir.:rttit if pet'lMters fllJSt De
lntrOOJOed .

3.

,.,y

becanes

C8!J!5,

pays to

Make procedures that ere ~100 lines long - around 300 bytes of
code - to optimize allocation of variables to register. Shorter
routines do not have enough occurrences or veri abIes to make
register allocation worthwhile, and longer routines create more
opportunities for register optimization then there ere registers
available.
The Ml:U't t)f i"PrCJVMent 'JSing this teenni~ is nighly YC'itDll.

Di fficul ty is

Pascal Code Cruncher's Handbook

Page 5

ROdU&te; likelyrtOOO of errors is low.

4.

Avoid the use of global scalar (1 to 4 byte) variables whenever
possible - glObal verlebles ere never put int.o regist.ers.
Techniques applicable here include:

4a. Assign a frequently used global variable to a local variable, and
change ell references to be the local Quantity. Caution! Beware of
saving and restoring the global quantity around procedure cells
that might access the global Quantity.
The amount of improvement will be two to four bytes per reference,
with the greatest gain appearing on asslgnments like A;-A+l. There
1s an overhead cost to assign the local end save registers (4 to 14
bytes). Improvement will not occur if the registers have already
been assigned to locels that are used more frequently than the
global is.
~ M:U'\t Of i~r~t ,'..ISing
llkal~ Of errors 1S P'Ilg'l.

trlis tedYlique is r.lted 1OOVt. Difficul ty is low:

4b. Further leverage on (48) can be
temporary variable is reused in
for different global variables.
globels still heve a chance for

obtained if the same local
different parts of the procedure
In this way, less frequently used
optlmization into registers.

l~oueJIIInt is tvo or PIOft oytes per tOOi tional rtftrtnCe. lns
l15$i~. D1 fficul ty is ..aoerate; likelyhOOO Of errOfS 1$ ~

0 Dytts per

hiC1'U

nt'W

91OC8J

trw"t (Ia).

4c. Another, more reliable way of' converting a global to a locel is to
pass the global varleble as a var pe.rerneter to the routlne.
Parerneters ere treated like local variables.
l"PTOWNnt is tva Of PIOrt Dytts per reftr.-.ce, lesJ 8-10 D)'tt:5 per lIIXti tianLl par .... ter.
to f~i~tlI COf1)ttiuon a noted tOc:Ne. DiffiQJlty n:llikelytood Of errors 'iltrl

~ject

Vtr

46d.

parMt ters is lOW.

Hove 8 lerge main progrsn body into 8 main subroutine. Hove all
global variables that are only accessed b)' the main progrewn lnto
the subroutine.
Il'llpJ'0000000t is ~"l1y SNJ 1. since h
totlJ COde. DiHiculty ~ likelyhOOd Of

5.

Min progrWl' 00dy is U5UIJ 1)' a a.Mll part

errors are 10lIl.

Of tr'Je

In a moderate to large procedure, the nllnber of scaler (1 to <4
byte) local variables (and parameters) Should be kept to a minimum,
since there is competition for registers. Briefly used integer
quantities and loop variables# for example, should all be stored in
the serne variable (which mlght be appropriately named "tempint" or
some other generic name). Beware, Of course, that the varlables

Pascal Code Cruncher's Handbook

Page 6

usages are never simultaneous.
I~l~t. for ttd'I eadi tion&l 10ClJ vari8Cle that OYVl()1d$ ... existing 14t9ister. is
tYfJically tw ~tes per remera. Oi fhcul t:y i5 10lt; likel)'t'lOOd Of erron i5 N:lderate.

6.

Avoid, at ell costs, passing frequently used local variables as var
parameters or using them in nested procedures. (Also for
frequently accessed peremeters.) These actions inhibit the value
frern being located in a register. Replace P4Ssing IJS a ~··ar
p/!II8M!ter with assignnent to a new local variable, passing the new
local, then doing e. reverse assigrment. Replace fl/Jst8d procedure
us~ of the variable with passing the verieble as a non-var
parameter, use of the parameter inside the subroutine, then, if the
nested procedure changes the value, copy the peremeter into a new
variable at the end of the subroutlne copy it back into the main
local variable after the call. The following example illustrates
optimization of nested usage of A and 8:
~LPPER;

PRCX:ErtR: '-PPffi;
VAR A, B: INT!~;

VM. A, B, TEr'F: INTEGER;
~ L()aER( A, 8: INTE~);

PR:CEDI~ L~;

EEGIN
A :- B;

CDf'I1...~rt$

EEGIN
A :- B;

to-I)

T'EJ"F :. Ai
EN);

Et();

BEGIN

EEGIN

L0.6;

Lo.ER;
A :. TE1"F;

{other statements)
(frequent uses of A and 8}
00·,

{freQuent uses

of A

and 8}

EN);

Note that, in the above case, ir A is not rrequently used in the
subroutine, it could be eliminated as a paremeter and the
assignment could be made to TEMP directly:
~

EEGIN

L(),a£R(B: INTEGER);

'l'El"P :. B;
Eri).,

A final added techniQue that can be used with procedure calls is
to pass the local as a non-ver paremeter, chen;e the procedure to a
function, and assign the returned function result back to the lace!
variable.
~
~

PROC(VM N:INTEGER);

LOCAL;

F1..H:iICt1 PROC(N: INTEGER) : INTE~R;
f1..tCTI~ LOCAL (A. 8: INTEC"£R) : INjEGE~

Pascal Code Cruncher's Handbook

Page 7

PROC(A)

A

LOCAL;

A : c LOCAL ( A,B);

:=

PROC(A);

where A is a frequently used local variable used &$ a var parameter
to PROC, and used in nested procedure LOCAL. This method, although
limited in application, is elegant because no temporary-variable
assigrtnents have to be inserted.
l~rO'JeNnt is tvo or ..ort D)'tf:S per rtfe1~ Of tnt f1eqAntly used 1JW1101t in u-.e Min
prooeo..cre. Ius 2-e Dytu.peT otta ISsi~t stateMnt, IUCject to r'9ister COfIIptti tlort
as noteo 1OOVt. Since tr'I1S optiPllizatien crt De epplitO to vt:ry freqJently ~ \lVltOles
h t are IC*1Oa.ed by ~ CCIII'Piler. IV9t ~tiPlizations Of ~ to 40 or ..ore Dytes are
possiDle in IVoe pr'oceQJJ'e5. Oi ffi~l ~ .-.d liktlyr.ooo Of tl'TOfS vi ttl vv pv_ttr
SI.bS t i tu ti en ~ s 1011: "i f f1 c:u tty InO like 1yrl)Od of errors .., i tr'I nes ted pJ'OCitOJres 1S

ROOIra te to "1 t1' .

7.

Don't use the set construct to check ranges; instead use
ccrnperisons against the upper and lower bounds.
Getting,rid of ttII
~lt-endeO rlnge

s.

SIt construct is a SIC
ct"Jeod(). Di fficul t:; is

s.avin;s (typiOlJly V()I..nd 30 Oytes fOr thf usual
Plininal, IS are tr'f c:r.enoes Of tJ'10l'.

Do not pass multi-word (more than 4 bytes) data structures as
no~ver parameters unless necessary.
Change them to VFf<
per amet er s .
I...,r~t

is 12-1e Cytes saved tJy. not heVing COOt to copy tM perIMt:er ~nto local
Olffleul ty lS 1011; 1 U('l~ Of eTTors 1S ~ately

s t o r . 1n the calltC pr~e.

1011.

9.

Replace F~ loops with WilLEs and REPEATs. The equivalent ~ATs
and WHILEs ere typically 8 to 10 bytes shorter, even with the
explicit loop variable initialization and increments. REPEATs are
~ore efficient than WHILEs which are better than FORs.
Sometlmes
the savings will be greeter depending on the contents of the loops
and the termination conditlon.
SWlings are typically e to 10 bytes per oonfttruct. Difficulty end ChtnCeS Of e:rror art
1M1l (jat tltCe carl to get yo.rr t~ination conai tion correct -- beYare of oH-Dy-one

errors).

10. Convert arrey indexing in loops to pOinter arithmetic, when the
total number of indexing operations can be reduced. For exemple
FOR I :- 1 TO 100 DO A[I] :- 3
P :- IA; {A's origin is 1;
F~ I : - 1 TO 100 00

CDf't\·~rts

to

P is typed as AA[I]}

EEGIN

pA : _ 3;

P :- POINTER(ORD(P).SIZEOF({A's element type}));

Pascal Code Cruncher's Handbook

Page 8

Eti).,
I~CNePlent iil.lp to
the c-rll)' e 1eMrI t

or

tne

size is no t

Pf09TIfINl' is villing to

likelytlOOd

i~ operation (PlOre \INn trIe UTI.)' origin is I'alZUO
by te; M'J i ng:s can be even tI i tf'tT CJ'l p8:*t(I s true tur es 1 f
tOa .. ~ PtOfe contortions): oiffieul t)' is ..ooert.tt;

18 O)'tu per

of tn'on is ftOOe1t.tt.

11. Irs without ELSE parts that have a conjunctive conditional (IF a
AND b THEN ... ) ere more efficiently expressed as nested IFs (IF a
1l£N IF' b Tt£N ... ). In effect, this implements your own "short
circuit" boolean evaluation.
The savi. is typically. oytes fOr tect'I
try 1 tenORs •

~

eli"inattd. very nsy to i"PllMnt. .:kISt

GOn't

12. Avoid packed structures whenever possible. Remember, packing is
only useful when a large amount of data has to fit in a limited
space -- lt does not decrease the Slze of the code.
I",rOYMent is tIi~ly veritele Ina 0In De vest.

is 10'11 if

tri~

like

(10)

00 rot

PI~

Di ffic:uuy is 1011; likelyrc.od 0' errors
tree COde.

13. Repetition of expressions in the code should be removed by
pre-assigning a common expression value to a temporary variable.
If11P!'~t

is

tli~ly

veri.,lt.

Di ffiCIJUY is

~ .. tt;

liktl1"OOd

Of trTOlS

is

l~.

14. Convert procedure peremeters to global or local variables when the
serne actual value is always passed to the subroutine, end when
there is no recursion.
l~t

is 2-4 bytes per

'hOt' w.riecles

1~.

~r

pe.TlIMttr~.

s..Vt

of crHung

~ltvll a:3CSrtiSlr.g I'lf
Of errors is l~.

(see (6». Oi ffioul ty is JIIOOel'att; 1 iktl~

When groups or local or global variables ere carrnonly passed
tooether as parameters, and ere not 'hot' (asslQned to reglstersJ,
they could be combined into a single record, which would then be
passed as a var peremeter to the subroutine.
I~J O'8le1it is I bytts per par_til" vi tJ\ 1n overr.1d Of e trytes (yvni~~ ~ C8.11e-j
proctQJrt ~ 910'11 in sizt if it e.1rttay uses all reglstI1S). DiffiCUlt)' lS ~rate;
I

li~l)'hOOd

of ll'Tors is

l~.

16. If you have several instances or the seme string constant in ~'our
code declare it as a CONST, otnerwise tne compiler will store
.ultiple versions or the same constant.
T,.. savings oepenos on the sizt Of tr.t string W"Id the

17. Turn range checking

off

~ Of

occ:unrca. Easy to

~.

arter a surficient amount of testing has

Pascal Code Cruncner's Handbook

Page 9

occurred.
l~~t. is 0-0 Dytti. per reference or lrS~i9"'Nf'lt Of a r~ed ~ti ty;
t)' 11 too lOW; l1welytlO:)d of err~s 15 flJTly ruC1' Slnc:e .. sufflclent ...o..r'It of
tes t 1ng never OCQJTS.
1 oer ~l ng tr'Il S ~ on a pr~e-O)'-proc:eo..rre CXIrt f 1oera

Cllff~C:Ul

l.wl

oasis.

cons

Pascal Code Cruncherls Handbook

Page

10

How to cIlJl1Ch code: some case studies
The "0110111ing section presents scme case studies demonstrating scme of
the techniQues presented in the previous section. These exernples are
intended to demonstrate how some of the transformational techniques are
typically used and how a whole series of transformations may be applied
to a single body of code. The main purpose of the examples, however, is
to Olve a sense of the thought' J)Iocesses involved in crunching code.
If you have erry good "before" and "arter" exernples demonstrating how ,fat
code was reduced please feel free to contribute them. ''(OUI efforts may
provide ideas and inspiration to others.

CASE 1:
Following is the originel form of the body of a routine (SUUpCh in the
StdUnit) which converts lower case characters to upper case. The code
size for the oriQinal routine was 94 bytes.
IF Ch IN [I a l .. I Z I] 1r£N
SUJpCh : - ~ (CR) (Ch) - 32)

ELSE

SWpCh :- Ch;

The code above was replaced with the following, which replaced
range test with two comparisons. The code for this version of
procedure was 66 bytes -- a savings of 28 bytes (about 30%, or
nore, since these sizes include the overhead for the procedure
asSignment statements). The moral here is that SET OPERATIONS

the set
the
actually
and the
ARE

E)PENSlVE .
IF (Ia l {= Ch) ~ (Ch <= 1:1) Tt-EN
SUJpSh ::.: ~ (CR) (Ch) - 32)

ELSE
SllJr£h : - Ch;

The following change was then made which saved another 2 bytes (brlnging
the procedure size down to 64 bytes) by getting rid of the branch for
the ELSE logic on the IF statement.
SUJpCh : a Ch;
IF (Ia
Ch)
l

(:.:

AND (Ch

(=

IZI) THEN

Pascal Code Cruncher's Handbook
SUJpCh

:= ~

Page 11

(ORD (Ch) - 32):

A rurther Change -- breaking the AND in the IF into nested IFs -resulted in a 4 byte savings, leaving the procedure size at 60 bytes (en
improvement of 36% over the original 94 bytes). In effect this is
performing "short circui t boolean evaluation at the source level. The
source ror this version is es follows:
II

SUJpCh : = Ch;

IF 'e' <= Ch THEN
IF Ch (= 'z' THEN
SWpCh : = Of( (rR) (Ch) - 32);

Note that this lest transformation would not have worthwhile if we had
not already removed the ELSE pert of the IF Since the nested IFs would
heve requlred two ELSEs.

CASE 2:
Below is the body of the original version of SUUpStr which uppercases a
string.
F~

I :- 1 TO LDGiH (SA) 00
SA [I] :. SUJpSh (SA [I));

The following version -- convertlng the FOR loop to a WHILE -- saved 8
bytes.
I : = 1;
w-tI LE I <= LEtGTH (SA) 00

BEGIN

S"[I] := SUJpCh (SA[I));
I : = I + 1;

EN);

A further, time-oriented optimization would be to perform the
upper-caslng in reverse order with the call to LEt«iTH outside the loop,
Mhich also Simplifies the termination condition to a test for zero.

"*'

lin asil18:
~ropri.tt (wr.In the l~ DOOy vill De executtO at lnst on:t) • R£P[AT w111
saSJt tnOthU 2 by tIS . I tes ted h
U'U'H ~ truets vi tr'I tr\ret tIS t prOC»OUr'e5 (t1, t2, t3) as
fOllOW1:

procecM'e t:1;

ver

j : intt9U':
Mgin

Pascal Code Cruncher's Handbook
~r j :- 1 to
tOQ := bar;

Page 12

i dO

tnO;

procedJre t2;

vcr

j.: inttQe1:
Mgln
J :- 1:
""ill j (- i dO

be9in

fOe := t>ar;
j := j • 1;
end;

Ina:
prOC«laI t3:
YV

j,: integer;
Degln
J := 1:
I"ef)Ht

fOo := oar;
j := j • 1:

U"til j > i;
Ina;

12 (~I1.£) saved 8

bytes over

T~

(FOR),

ana

13 (~AT) s.avtO ,10

bytes over

11 (F~).

CASE 3:
A series of small transformations was applied to the followlng segment
of TrimLe~ding (which trims le~ding blanks and tabs from ~ string).

fOR I :- 1 TO ORO (SA[O]) 00
IF (SA [I] a SUSpace) OR (SA [I]
{ skip over

le~ding

ELSE

a

SUTab) THEN

spaces }

EEGIN
CELEiE (SA, 1, I - 1);
EXIT (TlimLe~ding);
Er();

we fell thru -

either

II

or ell blanks}

The first change was to change ORO (SA[Ol) to LENGTH (SA), WhlCh saved 4
bytes. (I must have thought I was being clever 1n the oI1ginel.)
Calling the built-in function saves code by lea~ing the errsy access to
the built-in.
The next change was to get rid of the ELSE in the FOR loop by reversing
the sense of the condition (which resulted in the code below). This
last change resulted in no code size change since a short branch was
removed but another logical operator was added. But this prepared us

Pascal Code Cruncher's Handbook

Page 13

for sOOle subsequent changes.
F~ I

:- 1 TO LEtGiH (S") 00

IF NOi ((S"[I] = SUSpace) OR (S"[I] • SUTeb)) THEN
BEGIN { delete leading as soon as we rind a nor~blenk char
CELETE (S", 1, I - 1);

EXIT (TrimLeading);

&I).

{ we fell thru -- either " or all blanks}
lhe next step was to apply de Horgan's lew (remember your boolean
algebra?) to simplify the conditional to the following fom which saved
2 bytes by reducing the number or boolean operations.
F~

1 : I: 1 TO Lft'GTH (S") 00

IF (S"[I] <> SUSpace) AND (S"[1) (> SUTeb) THEN
BEGIN { delete leading as soon as we find a non-blank char
t£LE1E (S", 1, 1 - 1);

EXIT (TrirnLeading);
EK).

{ we fell thru -- elther " or all blanks}
Now we have converted the conditionel into a form in which we can apply
our short-circuit evaluation transformatlon by converting the AND into
nested Ifs, which saves another 4 bytes.
F~

I : I: 1 TO

1.Et(iiH

(S") 00

IF (S"[I) (> SU$pace) THEN
IF (S"[I] <> SUieb) THEN
BEGIN { delete leading as soon as we rind a non-blank char }
Cf:LETE (S", 1, I - 1);

EXIT (TrimLeading);

Et()j

{ we fell thru -- either " or all blanks)
finally we convert the FOR construct to a WHILE which saved another 8
bytes.
I :- 1;
'-fil LE I <- LEN:iTH (S") 00

EEGIN

IF SA[I] <> SUSpace THEN
If'S· [I)

<)

SUTab THEN

BEGlN { delete leadlng as soon as we find a

nor~blank

char

Pascal Code Cruncher's Hancbook

Page 14

C£LETE (S", 1" I - 1);

EXIT (TrlmLeading)i

I
El'().

E1{);
::. I +

1;

{ we fell thru -

either 'I or all blanks}

CASE 4:
The following is applicable only to programs using ~ITEs and ~ITELNs,
but the general technique of factoring can be applied anywhere. The
section of code below prints out the defaults (volume, file neme, and
extenslon) for a file neme prompt.
IF DeNol {> " THEN
~ITE (' [', DeNol, ') I);
IF DefrN {> " THEN
~ITE (I [', DefF"N, '] ');
IF 0 efE xt <> " Tt£N
~ITE ('[', DerExt, 'J ');
The following factoring out of the expensive
in a savings of 168 bytes.

~ITE

operations resulted

WTit~efault (DefauItValue : SUStr);
EEGIN
IF Defaul tVe.l ue <)
1t£N
~ITE (' [ I, Defaul tVal ue! 'J ');

PROCEDURE

I

I

e();

WriteDefault (DeNol);

IArl t eOeraul t (Defrn);
Wrl teOefault (DefExt);

CASES:
"Factoring" of ccmnon code does not always pay off. Following is an
instance of how space was saved removing factoring. The SUStrTolnt
conversion routine had an internal procedure called BogusNumber WhlCh
set the value of the CState parameter to the appropriate error return
code and then exited from SUStrTolnt:
~m.RE

f£GIN

BogusNU"nber (CS : ConvNState);

Pascal Code Cruncher's Handbook

Page 15

CSt ate : = CS~
EXli (SUStrTolnt);
EN).,

Bogu$Number was called 6 times in the oriQinal SUStriolnt. By replacing
the calls to BOQusNumber with BEGIN CState ~. ErrCode; EXIT(SLGtriolnt)
END we got rid of the )0 byte BogusNumber routine and the size of
Sl5trTolnt when d~n frem 500 bytes to 360 bytes, a total saving of 170
bytes. The moral here is to D£O< YM F~iC:Fnt(i TO SEE THAT IT ~ALL Y
PAYS OFF.

T~)e

Last Wt-tole Earttl

Text File FOrrr)at
Fred Forsman

This is, the lat.est proposal for the definition of text files. In creating
this definition I had three (not always convergent) goals in mind.
1) 'Text files should support Pascal's model of files of type
TEXT as well as possible. -- that is, if a file was
'1II'1 tten b'~1 Pe.scal WRITEs and ~ITELNs it stlould be e
"-/e.lid t.ex.t flle wit.h as fe.w e:t.cept.ions as possible.
!hi. ir'tE~!i~

here is to gi'~ reasonablE- '-Upport to Pti.cal 'S TE'tT M:tlanis.~ as
It lS defHled In t~~ lWl~J~ -- \.'tille tt~ IH"~~ ~:e~ rIO ~tf\t~l'Ier't 5t.t( rl.Jt
ttl~ fClrr1 of TEXT tl1~~, a,i would t~c;t tt.at fllf:.t "'1"1 ttf:n "'1 tOOJt f:TTOn
will J'e~ult in vsli" te\:~ filp.s Of s~ sort. Thi~ is not to S8.~. ttlat s.ll
tCrtlH !-t'OOlO !'~l(lrt elJer~' ~veH.e f11e ttlQt (;81'1 t-e ~ner&.tE'O VIE'- J:'~·c:el
te):t 1/'0 .. At &. MHI1"JI'\. hc~'er .. tr.e ~e-.l run-tlM s~·t~. shOlJld t-: a=
8Ct;'.(lrr;)da~lT)o; S.!: I=-j~Httl~ in itE SJJppo:rt Of Pes.c9.1 TEfl liO, eno tt~ E!'di tor
st'IOI.illj sr,)IJld ~~<~ siMi lar t?Horts SiilCE i~ is trill? oeo.'ice PaO.a oHerl use,j tv
ins.pK:t t~).. t fi li'S. (~I"tr~r riJrlULj or SlbE!rrar,t).

2) To make the processing of text files as straightfc1l",,,,ard
end effi ci ent as

pOS.S1 t!l e.

3) To be compatible with the UCSD text file formats in the
Pe.S'cal systerr.s on the Apple II and Apple ///.
The f'JIIO'Jing defini tiro follo~- t~ 'Jew text fi le for~a~ fairly cl~ely.
Tt..:: Of"tt? err t',,'O ~"'i8tior~ Ck.....,' t pcl!·e e. lJer'j $erious ttl1'e€t.t to COfI1P€'tittillty
since they lnvollJp. ltrloTP'tal cas!~ whlCh ere rot likel'j to be enc>::..K'ltered or
~r.e!e.t'!'d in norml pr&..:tlC~.

The fo11Q',\!ing definition inv(ll'''e~ comprornises: to all of the atl~'\/e gC' 8.ls. 1t'lt'
detennination of which goal has been most violated I leave as an exercise to
the reader.
The definition of

8

text tile:

• A text file is a sequence of l024-byte Daoes.
• One l024-byte header page is present at the beginning of
the file. This is not considered to be pert of the
actual contents of the text file, but is used by the
editor to store formatting information, etc. Anyone
creating a header page should do so with nulls in all
1024 ~ytes, unless there is 8 good reason to do
otherwise. (The format and interpretation of the header
page will be described in e forthcoming document.)

Z-Oc tobel"-83

Ird err"t8.1 ;;-

•

Eect, text pegf (i.e., tt-,ose

foll'J"'~ing the heeljer page)
contains some nUil'l(ter of ccmplete lines of text and is
filled with null characters (ASCII 0) after tr,e last

line.
The Pascal nn-tiMe sy! te1'l StJ:lUld ensure ttli.t a.ll text files end lJi ttl a CR
......en CLO-:Ed, in par t icu 18J', deal ing IJi ttl the case W'tIere the las t 8C tion
before the CLOSf IJ&..S a'IRITE insteid of a ~ITEL.N. SiPlilar1y, the ft.n-tiM

sys teM smuld e.l~ ~urp. that ~ terl'lin~te vi t.h CRs even if inordinately
lor.g 1 i~· arE: vri tt~1 Dy a !.efies. Of VRITE~ vi t~oo1 eny VRJTEW· (nc!W,~

detel1'Urllng '-'len t.O l.nser t. .. ~ can De a. tnC6:~ 1~:Hin.~ wi th te,;t file~ at tt.e el..O(':KPfA[) lelJt?l
sl"lould r..:.t ~s~ tr..:.t .. firl'il CR-r\iJll alIJ8)'i e:~ists, ~:ir'9 ~urE: Mt to HKi
off ttle end Of page bJttU$. (.IIJr tOO1~ sroJld not Dlow ~ on irt\-al id in"Jt..

•

fi line is a sequence of zero or more chare.cters followe1j
Oy' a ['1\'. A line O"Ie'y' be "arbi trSl·il~J ICing" (1023 bytes

tr,e CR, with roorfl f'or a terminatino null
programs (such as development
system tools) may chol:Jse to consider as significant onl)'
tt-Ie first /Y' ct-Iaract.el·~ [where N is a reasonable and \I~ell
dlJC1.lnent ed number. i. e .,' ei t her 132 or 255).

long .
at

thE'

cOI..mting

end of the pag.:) but

T1'"..ePtSe=a.l run-ti~ S)'HeM snoulCl allow me reaoing EIf)3 writir.g Of
COl treIlly long ll~. 1ne cont.ents of a lC1'l9 line should be obtS.lMtllp.

a series. of READ::. irle ~tlorl of READLN ShOuld I)e to reed past the f"lt?xt
CR . retuITlir,,~ an IORESliLl \te.rnirt9 valt.Je if eh"al'81:ters 811@ s\(i~ in the

I"i&

prOC;~s.

of -aroitrarilv 1oo,J" lif)2s Should not be vie'.'ed as a ttl!'eat to tool
TOCtl~ !'lay r",0e rei60nitla r~s trictiM1 on I/tISt text file~
ttn?y ctoo.:.e to acc€'pt, as lor~ s:s tM'1 dC(,' t Dl~' up on otr.er text fi l~s.
T001~ Play ~r!.'! to ic,;rlt;lre the exce!$ or, lTJ~on&tlly long lines, giv.e 6-

SJ~I)rt

i~l~ntvr~.

wa,rTHng, or Slgnal

•

8t'I

error and ittOr t.

prooe~sl~.

A seglJence of spaces at the beginning of a line me.!/ be
compressed into a two-byte code, namely a OLE ChBr8cter

(ASCII 16) followed by a byte containing 32 plus the
nlll'lber of spaces represented.

• A null text file (i.e., one which has no contents -- as
rnioht be created by opening a file and then clOsing it
before anything is written to it) consists of only the
l024-byte header page.

2!-C'ctober-83

Te,rt File' FOrTnst-2

Pascal's Packing Algorithm
Packed Records

Packed records are very expensive in terms of the number of bytes of code
generated by the compiler to reference e particular field. In general, you
should avoid packing records unless there will be many more instances of the

%ecord than there are references to it. Packed records are packed in the
following bizarre wey:

1. fields are pecked as tightly as possible without crossing word boundries,
startino at the low-ordered bit of the first byte. (Note that in a
packed record, 8 character or O.. 2~5 fits into a byte.) Records will
always occupy ei ther one byte or an even nllflber of bytes.
Note that only scaler values and subre.nges are considered packable;
everything else must go on 8 word boundry.

For exemple, 4 booleans and a set ere pecked as follows:
?

BYTE

1

0

'7

ME

2

0

'7

ME

3

0

'7

ME

4

0

I I I I 1.. 1312 t 1 , I I I I I I I I , I I I I I I set I I I I I I I I I I
2. Any empty bytes are filled by

mOVing the previous field into the empty

byte if:
- The field fits into a byte.
- The field was not previously on a byte boundry.

"1

IVT£

1

0'

IVT£

2

0'

ME

3

O?

ME 4

0

I I I I I 1312111 I I I. I I I I 141 I I I I I I set I I I I I I I I 1I
3. Any

field that fits in e byte or word and does not shere that space with

other fields is now deSignated "unpacked".

Any field that is still considered "packed, .. end is closest to the high

end of a byte or word, is moved to the hiOh end

7

~ 1

0

7

~ 2

0

7

or

that space.

~ 3

,31 I I I I '211' I I I I I I I 14' I I I I I I set
~.

0

,

7

~ 4

0

IIIIIIIII

The last field is treated after steps 2 & 3 hsve been completed on the
other fields.

Packirt9- 1

Internals

II Confident is2

,. finally, bytes containing packed fields are flipped (bits reordered).
1

?

8V1l

11121

I I I I 131

0

?

8VTE3

07

8'm4

0

I I I I I I set I I I I I I I I I ,

The folla.-ling is a (slightly) simpler description of what eppeaTS to happen
when packed records are packed, if you don't need to know the actual process.
1. fields are pecked as tightly 8S possible without crossing word boundries,
startino at the hiotr-ordered bit of the first byte.
All pecked records take up either one byte or an even number of bytes.
Only boolean or subrange types can be packed; ell other types start on
word boundries, so steps 2 and 3 only apply to these types.
2. If 8 byte would be left empty (so the next field can start on a word
boundry), end there is more then one field in the previous byte, the lest
(low-ordered) field is moved into the empty byte.
3. The last (low-ordered) field in any byte with unused space is moved to
the low end of the byte. (This happens even if it's the only field in
the byte.)

Fields of unpacked records ere packed in order, stertino on word boundries,
except for booleans and subrenges that can fit in 8 byte. Values that don't
take up 8 full byte or word will be packed at the low-ordered end of that
spece.
The whole record will take up either one byte or en even number or bytes.
For example, 8 record containing 8 $ubranQe of O.. l~, two integers, and a
boolean would be pecked as follows:
7

8VT'£1

07

1VTE2

O?

1rr'T£3

O?

1VTE4

0

?

I'm

~

O?

ME 6

O?

IY1t 7

O?

IV1't 8

0

I I I I I O.. l~ I I I I I I I I. I II-4---1---"ilntfoert--i1 - - - - - - . .I
1--14---i---;nt~ger--f2---.~1

I I I I I I I lei I I I I I I I I I

• Confident :fa}

Packed

Arr5jS

Packed arrays ere also code-expensive, except for pecked arrays of char.
(These are treated as a special case, and the code associated with them is
canpact.)
lhe number of bits per element in a packed arrey is the smallest of 1,2,4,8 or
16 bits that will eccommodete the element. For exemple, e subrange of column
A requires the number of bits per element in column B:

.1L

~

O.. 2

2

0 .. 3
0 .. 4
O .. 10
0 .. 20
O.. 255
O.. 395

2
4
4
B
B
16

O .. 1

1

Booleans ere packed one boolean per bit. The packed errey 8S
occupy an even nllflber of bytes.
A packed errey[l .. ') of boolean would be pecked as follows:
1VTf1

?

f

0

7

BVTE 2

8

whole must

0

I I ,5141312111 I II I I I I I I

A packed arrey[1 .. 5) of [0 .. 6) would be packed as follows:
evn:l
07
Mt2
0
,'--(2-) -(-1)~I Ir---e(4-)--,-e(-3)....;.,

?

---I

7

BV1t3
e(5)

IIIII

o

7

evTE4

0

I I I (, I I I I
f

You can use the i operator to poke around inside arry packed value and thereby

discover what the packing algorithm (probably) is.

S1~

SUbranges

Signed subranges (e.o. -5 .. 14) ere packed in packed types (unlike UCSO Pascal,
~hich won't pack them). The ninimum field size for a signed subrange is the
ninimum number of bits needed to represent any number of the subrange in two's
complement form.
.
The m1nimlJrl field size is then subject to the rules for e pe.rticule:r packed
type. Far example, though -1 .. 2 only needs three bit~ if it's in e packed
arrey, it will take up four (see above table). If it's in e pecked record, on

Packi rtg- J

Internsls

II Conrident i e.1

the other hand, it might take up only three bits, or it m10ht use a whole

byte, depending on what's packed around it.

tIlTE

A variable of type -127 .. 128 takes up
A variable of type O.. n,
takes up
A variable of type
char
takes up

8 by't6.
8 word.
8 word.

PBcki. ng-4

PASLIB PrOCedlJre Irlterface
(Workshop Release 1.0)
PASLIB is the Pascal run-time support 1i brery. It provides the procedures and
functions that are built into the Pascal language, acts as the run-time interface to
the Operating System. and "completes" the 68X() instruction set by providing routines
for the compiler-ger,erated code to call upon in lieu of actual hardware inttructions.
The interface to PASLIB is very tightly coupled with the Pa$c~ compiler . end
is very likely to be changed to improve performance and reduce code size. for
this reason, only call these routines fran assembly language if you absolutely
and posi tively have to; stay in Pascal as much as possible wtlen dealing wi th
PASLIB. Most of these routines support the Pescal buil t-in procedures,. which
are described in detail in the Pa.sc"5l Reference /1anusl.

There ere e. few converltions for using these routines . whictl must be follOY-Jed
to ensure correct results and successful execution. All the routines ere
called with parefTteters passed on the stack. The pecrMleters are pushed c!ntel
the steck in the order of the peremeter list shown in each routine. 'ST.LI
indicates a four-byte parerneter, 'ST .W' two-byte.. 'ST .8' one-byte (stored in
the upper byte of a word), and 'ST.S' a set. The parameters passed will be
popped by these routines before return. The function results, if any, will be
returned on the stack after the parerneters are popped out. Note that the
functiorrtype routines do not expect room for the function result to be
reserved on the stack before the call. Also note that these routines do not
check for room on the stack; the caller must guarantee enough room on the
steck for saved registers. The celler should follow the Pasc~ procedure
preamble code for expanding the stack before calling these routines. Standard
register preservation conventions are followed except in the routines
indicated. Refer to the ~0rkshop User's 6~~de for the usage of the special
registers and the stack frame allocation.
.

Contents
1. Initialization and Termination Routines .......... 2

2. Integer Ari ttlnetic Routines .................... 3
3. Oat e. Move and Scan Rout i nes . • . • . • • • . • . . . . . . • . . . 4
-4 . Stri ng Me.ni pul at i on Rout i nes . . . . . . • . • . . . . . . . . . . 6

~ . Stri ng Canper i son Rout i nes •..•..•.•.•.•....... e
6. Set Mani pulat i on Rout i nes ....••.•........•.... B
7. Hi scell aneous Rout i nes . . . . . . • . . • . • . • • . . • . . • •. 10
8. Range Check Rout i nes .......•.....•.••....... 11
9. Heap Rout i nes . . . • . . . . . . . . • . . . . • . . • . . • . . . . .. 12
10. Read and Write Routines ...................... 15

11. rile 110 Routines ........................... 22

PIbLlB-l

Internsls

II Confi den t i 81

1. Initialization and lamination Routines:

~_E£GIH,

~_EN),

~_lHIT, ~_1m1

None of these routines have parameters, return values, or destroy any
registers.
Every main progr~n must have the following beginning and ending sequences
celling these routines:

beginning sequence
no-op for liseBug, to look like standard module
head

% E£GIN

JSR
LIt'f<

A6, #$O:xxJ

t1JVE .l

(A7)+, A6

LIt«

A5,#$OOOO

SLeA.l

$C010( A~), A7

~

~~_INIT

i

set up global frerne for main progrern
variables for units, etc. passed by loader
main program code goes he.re

.
~
'.l~LK
~

%_'Tm1

A5

; er,di ng sequence

%_Ef'l)

RTS
lJ~LK

A6

i

no-op for LiseBug, to look like standard mody'l"
tail

RTS

Note that the size of the progrern global variables allocated to the loader
is offset +16 from register A5.
%_BEGIN - Beginning routine. Currently a no-oPi reserved for future
extensions.
~_END

~_INIT

- Ending routine.

Currently

8 nO-0Pi

reserved for future extensions.

- Initializes PASLIB internal glObal data for each process:

1. Sets up an r-line trap routine, which signals a "sys_terminate"
exception if an f-line trap is encountered in the user cod~
terminating the proorem.
2. Sets up global input end output rile buffer addresses. These
buffers are used for screen, keyboard, exec files and output
redirection. The address locations are rixed on the staCk: the
input buffer address is offset +8 from register A'; the output
buffer address is offset +12. They are set up to point to global

PIlSLI8-2

Interns2s

II Confidt,iti62

file buffers in the shared data area of PASLIB.
3. Initializes the OS exception handlers.
4. Initializes the Pascal heap local variables.

NOTE: The %_INIT routine will restart at step 5 if the calling process
is 8. resident process.
5. Initializes the PASLIB local variables.
6. If the . floating-point library IOSFPLIB is linked, it is

initialized.

%_1ERM - Terminate. If the process is resident, it j~nps to step 5 of
%_INIT (see abO\le), if not, it calls the OS routine IIHit_End" to
terminate the process. Control does not return aft.er this cell.

2. Integer Arittnetic Routines: U_tU..4, '-I_DIV4, U_11D4
~_MUL4

- Multiply two 4-byte integers
Pareroet ers: S1.l - Argllflent 1

51.l - ArgllTlent 2

Returns:

ST.l - Product

Registers used:

All registers ere preserved.

The mul tiplicet1or, algor1 ttln is as follOn's:

-argument l's upper word is multiplied by argument 2's-lower word.
-argument 2'$ upper word is multiplied by argument lis lower word.
-these two products ere added, and the sum is put in the result's
upper word.
-the two arguments' lower words ere multiplied, and this value is
put in the result's lower word.

PiOLIB-3

Internsls

II Cor-Iriden t i6L

%I_DIY4 - Divide two 4-byte integers
Parameters: SI.L - Dividend
ST.L - Divisor
Returns:

ST.L -

Registers used:

Quotient

All registers are preserved.

The division is performed by subtracting the dividend frem the.

divisor 31 times (f'or each of the 32 bits except the sign bit).
%1_M0D4 - Remainder

fr~n

the division of two 4-byte integers

Parerneters: S1.L - Dividend
S1.L - Divisor
Returns:

SI . L - Rernai nder

Registers used:

All registers are preserved.

The division is performed in trle S8ne w8Y as: %I_DIV4,. above.

3. Data Move end Scan Routines:

~_KJVEl,

~_tlNER,

~_nllC, ~_S)I£, ~_SCfHi

%_HOVEl - Hoveleft

Parerneters:

51.L -

from

Address

ST.L - To Address
51.W -

tilSTlber of bytes to

mO\le

Returns:
Registers used: 00, 01, 02,

F(J,

Al, A2

nllTlber of bytes to move is 7 or less, they 8Ie mO\led a b)/te
at 8 time. If the source address + 2 is the destination address,
the data is moved one word at a time. If there 8Ie more than 7
bytes to be moved, then data is moved e long word at 8 time. If
the ending address is a byte address" the trailing byte is moved.

If the

PllSLI8-4

InternBls

II Confident15}

.'--''DVER - Mover i ght
ParSlleters:

5T. L - frCJn Address
ST.l - To Address

ST.W - Number of bytes to move

Returns:
Regi ster s used:

OO~

F()~

Al~

A2

Data is moved one byte at a time.

Par ernet ers: ST. L - Address to fi 11
ST .W - Number of bytes
ST.W - Fill character
~etllI'ns

to fill

:

Regi sters used:

D:)~

Dl~

F(),

A2

Fills the address with the given character one byte at a time.

'-_SCANE - Scan equal
Parameters:

5T.W - Length to
ST .W - Character

scan
to scan for
ST.L - Address to scan

Returns:

ST.W -

The position of the character (0 being the
first)

Registers used: All registers ere preserved.

Scans the string for the given character, one byte at a time.
Note that "length to scan" can be negative, and the scan will go
in the lower address direction.

27-J8nusry-84

PfCLIB-5

Intern8.ls
%_SC~

.. Confidenti8}

- Scan not equal
Pererneters: 5T.W - Length to scan
ST.W - Character to scan for
ST.L - Address to scan
Returns:

ST.W - The first character position that is not equel
to the character to scan for (0 being the
first)

Registers used: All registers ere preserved.
Scans the string for the first character not equal to the given
character, one byte at a time.
Note that "Length to scan" can be negative, and the scan will go
in the lower address direction.

All the string manipulation routines ere performed one byte at a time.
%_CAT - Concatenate
Parameters: S1.L - Address of 1st string
ST.l - Address of 2nd string
ST.L - Address of Nth string
ST.L - Address to put result
51.1,11 - N

Returns:
Registers used: All registers are preserved.
Copies all the given strinQs to the result string.

27-J8nU8ry-84

PRSLI8--6

Internals

II

COI'?fi dent i 8.J

'-_POS - Position of one string in another
Par ernet er s: 5T. L - Address of substri no

ST.L - Address of main string

Ret urns:

ST.W - Position

Registers used; All registers are preserved.
Compares the substring with the main string until a match is

found.

If no match is found, 0 is returned.

%_COPy - Copy a substring

Parameters: S1.L - Source string address
ST.W - Starting index
ST.W - Size to copy
ST.L - Address of result

Returns:
Regi st.ers used: All regi sters ere preserved.

If the number or bytes to copy is 0, or if the source string is
lonQer than the number of bytes to copy, the result string has 0
lenth.
%_DEL - Delete e substring frern a string

Parerneters: ST.l - Address of string
ST.W - Position to start deleting
Sl.W - Number bytes to delete
Returns:
Registers used: 00, 01, 02, 03,

~,

Al, A2

"_INS - Insert one string in another
Parameters: ST.l - Address or string to insert
51.l - Address of main string
ST.~

- Position in main string to insert

Returns:
Regi sters used: 00, 01, 02, 03, WJ, Ai, A2

PICLl8-i

Internals

II

Confidential

All the string comparison routines are performed one byte at a time.
- String equal
- String not equel
%S_LE - String less than or equal
%S_GE - String greeter then or equal
~_LT - String less than
%S_GT - String greeter then

~_EO
~_NE

Parameters: ST.L - Address of first string
ST.L - Address of second string
Returns:
Registers

ST.B - Boolean result
u$ed~

All registers are preserved.

6. Set Manipulation Routines: '_INTER, '_SIN:I, '_OO~, '_DIfF, '_R:>Iff,
,_Rt'ta:, '_~J, '_5£llL, '_SUL£, '_SETEQ,
~_SE1l£

'The format of a set on the stac.k is:

+---------+ high address
I 15 - 0 I
+---------+
, 31 - 16 1

+--------+
+---------+
Ilast wordl
+---------+
I # ftytes I
+------+

l~

address

Interns}s

• Confident 16 ..~

% INTER - Set intersection:

setl AND set2
Set uni on: set 1 ~ set2
%:OIfF - Set difference: setl AND (NOT set2)
~_RDlff - Reverse set difference:
(NOT setl) AND set2
%-lJucr~

-

Peremeters: Sl.S - First set
5T.S - Second set
Returns:

51.5 - Result set

Registers used: All registers are preserved.
%_SING - Singleton set
Parameters: ST.W - Singleton value

Returns:

Sl.S - Result set

Registers used: All registers are preserved.

Parerneters: ST.W - MinimLlo value
ST . W - Max imurn val ue

Returns:

ST.S - Result set

Registers used: All registers ere preserved.

Returns the set representation of the values from minimllfl to
If' min1mlSO is greater than rnaxirnllTl . . a null set 1s
returned.

maximLlo.

%_ADJ -

Set adjust
Parameters: 51.S - Set
ST.W - Desired size in bytes
Returns:

51.5' - Adjusted set without size word

Registers used: All registers ere preserved.
Changes the size of a set to the given size.

If the set is larger
than the desired size, the extra values ere thrown out; if the set
is smaller than the desired size, extra fields are added and
initialized to O.

Pib'LIB-9

Internsls

" COilfidenti61

%_SETNE - Set inequality test
~_SETEO - Set equality test
% SET(£: - Set inclusion test (returns true if set2 is the serne as or
included in setl)
% SETLE - Set inclusion test (returns true if set 1 is the serne as or

-

included in set2)

Parameters: ST.S - first set

51.S - Second set

Returns:

ST.W - Boolean Result

Registers used: All registers are preserved.

%_G01OXY - Move the cursor to a specified location
Parameters: S1.W - X coordinate
ST.W - Y coordinate
Returns:

Regi sters used: 00, 01, 02, 03,

~,

Al, A2

%_GOTOX''( sends the following escape sequence

the cursor position: Est

to

the screen to move

=

Y+32
X... 32
Y values ere between 0 and 31; X values betwe.en 0 and 79.

If the.

coordinate given is outside these bounds, it is set equal to the

boundry val ue .

%Ji)lO -

Globa} ooTO code se(Jnent remover
Parameters: ST.L - Pointer to the desired last-segment jump table
Returns:
Registers used: AO
Jumps from a nested routine to the first-level process.

Internals

II Conrident 18;'

%_HAL T - Hal t
If the process is resident,. it goes to step ~ of the %_INIT
routine. If not, it calls "teminate_process" with the value
event_ptr as nil. Control does not return after this call.

8. Range Check Routines: '_FDO<,

of

,_SJDt<

%_RCHCK - Range check, to check the bounds of subrange type variables
Paremeters: ST.W - Value to check
ST.W - Lower bound
ST.W - Upper bound
Returns:
Registers used: All registers ere preserved.
Note that if the check fails, this routine causes the system
exception 'SYS_VALUE_OOB' to be signalled and the message 'VALl~
RANGE ERROR' to be displayed before the process is forced to enter
the debugger. If the process: has nelt declared an exception
handler for this exception, the system default handler is entered
after the debugger returns control. The system def'esul t h&:"ldl er

terminates the process.
~_SRCHK

- String range check, to check a string index against its length
Parerrneters:

ST.B - Value to cheek: O.. 2~~

ST.W - Upper bound
Returns:
Registers used: All registers ere preserved.
Note that if the check fa1ls, th1s rout1ne causes the system
exception 'SYS_VALUE_OOS' to be signalled and the message 'ILLEGA~
STRING INDEX' to be displayed before the process is forced to
enter the debugger. If the process has not declared an exception
handler for this exception, the system default handler is entered
efter the debugger returns control. The system default handler

terminates the process.

PflSLI8-11

II COI'?fi dent j 51

Intern61s

9. Heap Routines: ,_tEW,

,_~,

%_t£W - The New procedure.

t.J£lSE, t_tEHAV,

t_t£~

Allocate memory in the Pa,cal heap.

Parameters: ST.L - Address of pointer
ST.W - Number of bytes needed
Returns:
Registers used:
~Ie_t£\~

OO~

Dl, 02, 03,

~,

Ai, A2

sets the address of the pointer to nil.

%_NEW checks whether the heap has been initialized (whether a dets
segment has been allocated) via the boolean Heaplnited. If

Heaplnited is

tals~

8

call is made to the GrowHeap function to

create and initialize a 'new heap'. If GrowHeap is unsuccessful
(returns talsej then %_NEW is exited with the pOinter set to nil.

The Gr~eap function ini ti81izes a 'new heap' by calling the
PLI ni tHeap prc,cedure. GrONheap passes PLlni tHeap the sizE: of
the Pascal heap data segement, the memory size (HeapOelte) end
the logical data segment number (LDSN = 5). PLlnitHeap then
creetes a privete data segment with the pathname PascalLHeap;
and assigns the segment pOinter address to the pointers
HeapStart and Heapptr. PLlnitHeap sets the pOinter HeapEnd to
point to the end of the segment (HeapStert + segment size 256) .

Before assigning an address to the pOinter, %_NEW determines
whether there is enough room on the heap (i.e. in the data
segment) for the variable. ~_NEW makes a second call to the
GrowHeap fur.ction. If GrMieap is unsuccessful,. then "_r-f::W is
exited with the pOinter set to nil.
The GrM'\eap function calls the GetSa'eFmnount procedure to
determine the maximlln nl.lnber of bytes by which the heap cen be
increased (the amount of system memory available to the calling
process). If tttis ernount is greater than the current size of
the heap,. then GrowHeap will double the size of the heap,
otherwise GrowHeap will increase the heap to the meximllTl emount
available. The pointer HeapEnd is 1ncr~ented by the amount of
increase.

%_NEW then sets the address of the pOinter to the address of
Heapptr, which pOints to the next tree area on the heap. The
address of Heep:'tr is increased by the size of the variable that
was placed on the heap.

PflSLI8-12

Internals

%_M~

- The Hark procedure.

Paremeters:

ST.L -

ST.W -

Hark the Pascal heap.
Address of pOinter to be marked
of bytes needed

N~nber

Returns:
Regi sters used: 00, 01, 02, 03, A:>, Al, A2

%_MARK checks whether the heap has been initialized via the
boolean Heaplnited. If Heaplnited is false/ 8 call is me.de to tt"le
GrowHeap function to create and initialize a 'new heap'. If trlE'

function is unsuccessful (returns talse) then

%_M~

is exited.

Ttfe GrM1eap function is described under %J'£W, &IO\1e.
%_HARK

sets the address of the pOinter to the address of Heepptr,

which pOints to the next free area on the heap.

%_RELSE - The Release procedure. Release the Pascal heap.

Parameters:

ST.L -

Address of pOinter to release to.

Returns:
Regi sters used: 00/ 01, 02, D3,

F(),

Al, A2

%_RELSE checks whether the heap has been initialized vie the
boolean Heaplnited. If Heaplnited is taln,.

call is

8

m~de

tel the

GrowHeap function to create and in1 tie.li ze a new heap'. If
GrowHeap is unsuccessful (returns false) then %_~LSE is exi ted.
I

7he GrowHe.ap function is described under %J'EW/ above.

If the pointer does not point within the heap (i.e., address
memory between HeapStert and Hea,:£nd), an error will resul t and
the procedure will be exited.
If the pointer is less than He~nd minus He aJX)e 1ta/ (where
HeapDelta is the original size of the heap) the heap is reduced in
size by HeapOelte.
%_RELSE sets HeapPtr (which points to the next free area on the
heap) to the address of the pOinter.

PflSLIB-J}

Interr181s

%J1EMAY - The Hemavail function.
Pererneters:
~eturns

Memory Available in the Pascal tleap.

None.

:

~egisters

used: All registers ere preserved.

oenerates a call to the %_PHWordsAvail function, which
determines the amount of words available.

~_HEMAY

checks whether the heap has been initialized via
the boolean Heaplnited. If Heaplnited is false, a call is made to

%_PHWords~~ail

the GrM-feap function to create and initialize a 'ne"'J heap'. If

GrowHeap is unsuccessful (ret urns false) then %_PH.JJordsAvs.i 1 is
exited.
The GrowHeap function is described under %_t£w,

e.bOVI?.

% PH,IIordsAvai 1 determines the maximllf\ nllnber of words 8'~ai 1abl e
(the ernount left in the heap data segnent minus the maximLlT'l EJoount
of system memory available) and the current nllTiber of lLGN words

available (the maximLlTl nllTlber of words you can get by the chosen
I f the max imLlO
number of words available is greater then the current nllTlber of
LDSN words available, then the current number of LDSN words
available is returned, otherwise the maximum number of words
available is returned.

LDSN mi nlJS the nunber of words already used).

%_HEAPRES - The HeapResult function.

Parameters: ST.W - Heap result
~eturns

:

Registers used: All registers ere preserved.
Refer to the A'orkshop User's Guide for the values of the heap
result.
generates a call to the ~-'+ieapRes function.
is assigned the integer value of HErrResult.

~J-£~S

~-'''ie~e~

PfIS'L18-14

Internals

II Conficienti!S:2

10. Reed and Write Routines: '_KE1PR:SS, *_LN, *_C, *_STR, *_~, *_1,
*_8, '_PfG:, ~_C, ~_I, ~_STR, ~_P1O:,
~_LN, '_EIllN

All the read end write rOIJtines take 'file address' as a parameter" which
is the address of the file variable. The address of the Pascal standard
input is in offset 8 from register A5; the address of output is in offset
12 from AS.

%_KEYPRESS - The Keypress function.
Parerneters:

ST.L - File address

Returns:

ST.B - Boolean Result

Registers used: All registers are preserved.

Note that the file address is not used in the current implementation.
%_KEYPRESS generates a cell to the %_PKeyPress function and
ret urns the resul t of %_PKe'yPress 8S its resul t.
The %_PKe'yPress function determines whether any keys hsve. be.en

pressed. It returns true if the look-ahead buffer is full"
otherwise it returns false.
~_LN

- WriteLn

Parameters: ST.L - Address of output file
Returns:
Regi sters used: DO, 01, 02, 03,

~,

Al, A2

cells the FWr1teln procedure, passing it the address of the
file. FWriteln calls the FWriteChar procedure, passing it an
ASCII  (end-or-line) to be appended to the string.

~_LN

PflSLI8-15

Internals
~_c

-

• Confic/entj82

Wri teChar.

Di,spley 8 character on the console.

Parameters:

ST.L - Address of output file
Sl.B - Character to be output
ST.W - Size of field to print

Returns:
Regi st ers used: 00, 01, 02, 03,

~,

Al, A2

%W_C calls the f~iteChar and DutCh procedures to write 8
character to the file. ~_C passes OatCh the character to be
written and the address of the output file. DutCh then calls
F\lJri teChar to \IIl-i te the character to the file.
The default field size is 1. If the field size is greater than 1,
~_C calls fWriteChar to write out the appropriate number of
spaces, then calls DutCh, which calls FWriteChar to write the
character.
~_STR

- write string
Parameters:

ST.L - Address of output file
ST.L - Address of string
ST.W - Size of field to print

Returns:
Regi sters used: 00, 01, 02, 03, AO, At A2
If the string size is greater than 255 characters, then %W_STR
truncates it to 255.
%W_STR then compares the field size (N1hW1dth) to the specified
string size. If the field size is less than or equal to zero,
it's set to the strino size. If the field size is less than the
string size (but greater than zero), then the string size is set

to the field size. If the field size is greater than the string
size, then 8 cell is made to the FWriteChar procedure to write out
[MirlWidth minus string size] spaces.
STR then cells FWriteChar to write out the string with the
specified string size.

~

PllSLI!F16

Internals
~_P~

• Confidc,'"itJ.62

- Wri te a pecked array of' characters

Parameters: Sl.L
ST.L
ST.W
S1.W

-

Address of output file
Address of string
Actual length
Size of field to print

Returns;

Regi sters used:

00" 01" 02" 03, f(), Al, A2

The effect of 'JaJ_PFO: is the, same as calling
n~ber

specifed f'ield size equal to the
~_l

~_STR

with the

of elements in the arrey.

- Wri te an integer'

Paremeters;

ST.L - Address of output file
ST.L - Value to print

ST.W - Size of field
Returns;
Reg) sters used: 00" 01" 02, 03,

~,

Al, A2

canpares the field size (MinWidth) to the size of the
integer. If the field size is oreater then the size of the
integer, then ~.w_I calls the F'Wri teChar procedure to wri te out
[MirlHidth minus integer size) spaces.

~_l

I then calls fWriteChar to write out the integer with the
specified integer size.

~

27-Jsnuuy-84

PfOLl8-17

Internals'
~_B

" Confident 18}

- Write a boolean
Parerneters:

5T. L - Address of output fi Ie
Sl.B - Value to print
Sl.W - Size of field

Returns:
Registers used: 00, 01, 02, 03, FlO, Al, A2

%W_B calls the ~~_STR procedure, passing it the string to be
written, the size of the string, and the address of the output
file.

If 'value to print' is zero,. ~_B passes the string 'fHLSE' to
%W_STR, with a string size of ~.
If' 'value to print' is 1,
with a string size of 4.

~_B

passes the string 'm.£' to

~_STR~

%W_STR then writes the string to the output file.
%_PAGE - Page procedure

Parameters:

SI.L - Address of output file

~eturns:

Regi sters used: 00, 01, 02, 03,

~,

Al, A2

,._PF(L writes ttle ASCII character 'FF' to the output file by

calling the DutCher procedure. DutCher is passed the character to
be written (e.g. 'FF') and the address of the output file.

Interns}s
~_c

-

• Confident i5}
Rea~he.r

Parameters: 51.L - file Address

ST.B - the character read

Returns:

Registers used: 00, 01, 02, 03, AD, Al, A2

reads 8 character from the speci tied tile by calling the IrCrj
function, then returns the character on the stack.

~_C

InCh calls the fReacChar function, passing it the file

6dctres.~.

FReadChar verifies that the file has been opened, calls the
fGet procedure, reads the character that is placed in the

wi ndow

InCh.
~_LN

buffer area

by

FGet., and passes the character back t.o

- ReadLn
Par ernet ers:

5T.l - Address of input ,.i 1e

Returns:
Regi ster s used: DO, 01, 02, 03, AO, AI, A2
~_LN

reads a line

fr~n

the specified file

procedure, passing it the file address.

by

calling the FReadLn

FReadLn verifies that the file has been opened and then calls

the FGet procdure to reed each character on the line until EOLN

is true.

When EOLN 1s true, f'ReadLn

returns to
~_PAOC

resets EOLN to false and

~_LN.

- Read Packed Array ot Character
Parameters: ST.l - file Address

ST . L - Array Address
51.\11- Size or array in bytes

Returns:
Registers used: 00, 01,

O~ 03~

AO, Al, A2

The effect is the ssne as cellinQ

~_STR

whose specified field is

the nunber of elements in the array.

27-.JanullI)'-84

PfOL18-19

Internals

II Confident161

%R_S1R - Read String

Parameters: ST.L - File Address
ST.L - StrinQ Address
ST.W - Max size of string
Returns:
Registers used: 00, 01, 02, 03,

~,

Al, A2

first verifies that EOLN is ralse, otherwise %R_S1R returns
to the calling routine.

~_STR

then generates a loop which reads a character from the file
the IrCh procedure (described under %R_C, aboveL then
checks wt'lether EOLN is true. If EOLN is true, %R_STR retlJIns to
the calling routine. If EOLN is tals~ ~_STR reads the character
end returns to the beginning of the loop to read the next
character.

~_STR

by calling

After Inch returns 8 character, %R_STR checks whether the
char ac t er is a R.BJJT (ASl: I I OLE ') or BFCKSPA:E (FS: I I as
If
the character is ei ther of the two, %R_STR processes the character
accordingly and then reads the next character. If the characte~
is not RL££lJT or 8FD or space, %R_I returns to the beginning of the loop to reed
the next character. If the character is not (~) or space, %R_I
exits the first loop.
Next, ~_I determines whether the character read is a sign
character (1+1 or 1_'). If it is, ~_I enters the second loop and
calls Inch to read the next character. If the character is not a

PflSL 18- a')

II Confident)82

Internals
sign

ct"laracter~

'S<_I enters the second loop bypassing the call to

IrCh.

The cheracter is then checked to see if it's a RUBOUT or BACKSP~[
. characteri if' it is, the character is processed accordingly arId
~. ~_I returns to the beginning of the first loop.
The character is checked once more to determine if it is a valid
integer value (0 i character 1 9). If it is, ~_I returns to tt"ltbeginning of the second loop and cells Inch to read the next
character.

If the character is not a valid integer, then %R_I checks to see

if any characters read previously have been valid integers (~y
checking register D6). If no characters have been valid integers
(D6

= OL

then

~_I g~ner&tes 6rt I~esul terror.

If the

read previously have been valid integers (06 =lL then
:returns to the calling routine wi th an ir.teger resul t.

cher&ctel"~·
~_I

%_EOUN - End of line predicate
Persmeters: ST.L - file address
Returns:

S1'.B - Boolean Result

Registers used: All registers ere preserved.
% EOLN returns true it the end of a line has been reached in the
specified file.

PtiSLIB-21

Internals
11. file

II

lA)

Routines:

~_FaRT,

~_FEiET,

~_I(J£S,

'_££T, '_R1T, t.Jptm, '_SEEX

~_Cl.OSE,

~_EIF,

Confidenti~

~_Bl.JCro, ~_~,

%_REWRT - Rewrite a file
Parameters: ST.L - File Address
ST.L - Address of Name String
ST.W - Kind: -2=text, -l=file,
record

>O=n~nber

of words per

Returns:
Regi sters used: 00, 01, 02, 03,

~,

Al, A2

Crea.tes and opens a new fi 1e.
%_REWR1first initializes the file's FIB (file identification
blocK) by making a call to FInit and pe~sing it the file type vie
the parameter reoBytes. Once the file type is determined~ the
value of fRecSize is initialized. The values of recBytes and
fRecSize and the file types ere:
recBytes
-2
-1

o

>0

file type
text
untyped
interactive
typed

fRecSi ze
-1

o

-1
value in recB}/tes

Ott-Ier irnportant fIB entries are ini tialized as follows:
FlsOpen := false
The file is marKed as not open
FNewFile := talse
The file is nnerked as not new
(i.e. no creation of new files)
FEOf
:c true
End Of File is set to true
End Of Line is set to true
FEOLN
: = true
The file is merked as not modified
FModified:- talse
FlsOS
:= true
The file is marked as an OS File

%_REWRi then calls fOpen.

Within FOpen:

A check is made to determine whether the file has been opened
by referencing the boolean FlsOpen. If FIsOpen is true, en
IOResult error will occur; if not, it is set to true.
FOpen therl determines whether the filenMie is one of the
character devices a:t£OLE" KEYBJ~" or RO=nuritber of words

pel-

record

Returns:
Regi sters used: 00, 01, 02, 03... (to..

Al,

A2

Opens an existing rile.
%_RESET behaves in the same manner as %_REWRT, by making calls to
procedures Flrli t and FOpen. However, ~_RESET does raclt create a

temporary rile (FNewFile is ralse). It attempts to open the
existing file and if it is unsuccessful will issue an IOResult
error.

Before exiting FOpen~ '_RESET makes a call to the fReset procedure
which in turn calls the fGet procedure. This has the effect of
ad\lancing the rile posi tion to the first record of ttle file.

PfISLl5-23

Internals

" Confidentis2

%_CLOSE - Close a file
Perfroeters:

5T. L - fi le Address
5T.W - Mode: O=t.m1AL, l=Lo:K, 2=Pt..R:iE, 3=CRLtOi

Returns:
Registers used: DO, 01, 02, 03, AO, Al, A2

If the file is

8 character device (e.o. console, keyboard) or if
the file is not open (flSOpen is talse), the close procedure has
no effect.

CRltCH and LOCK Options:

If the close option is either CRLtCH or LOCK, and the file is a
text file that had been opened by RESET (fNewfile is false) 8
check will be made to determine if the number of blocks is odd.
If it is, 8 null block will be written to the end of the file.
I

If a previously existing file was opened by REWRITE (fNewfile
is true) it will be killed (i .e. deleted). Its ternporary
file,> which was killed by fOpen, is unkillecf using ttle original
file nerne as the new file name.
I

~...£

Option:

If the file was created by ~ITE, the temporary file will
have already been killed in fOpen.

The PURGE option will kill the original file provided it was
opened by ~SET (Ft~ewF' i 1e is tal se) .
tmNAL

Option:

If the file was created by REWRITE, the temporary file will
have already been killed 1n rOpen.
The original file is left untouched.

InternGls

II Confident 16..'

'_EOf - End

of

file predicate

Pererneters: 5T.l - file address
Returns:

ST.B - Boolean Result

Registers used; All registers ere preserved.
Detects the end of a file
FEOF.

by

referencing the fIB boolean entr)',

%_BLKRD - Blockread
Pezerneters: ST.L - file Address
ST. L - Buffer address
- Number of blocks

to read
ST.W - Block Number, -1 = Sequential
ST.W - OOReed, 0 c write, 1. read
•••••
ST.~

••••••
Returns:

ST.W -

Nwber of blocks actually read

Regi sters used: DO, 01, 020# 03, AO, AI, A2

generates a call to the fBlockIO function, passing the
parsneters listed above. Theboolearl variable OoRead is set to
true for Blockread and ralse for Blockwrite.

~_BLKRD

Within fSlockIO:
If the file is not open (FIsOpen=false) end the number of
blocks to transfer is less than zero, fBlockIO will generate
IOResult error and the file will not be processed.

arl

If" the file 1s the character device CCI'5OLE or KEYBJFR), en
IOResult erior will be generated and the tile will not be
processed.

If the file is the character device PRINTER, the block number
to start the transfer (R3LCO<) is set to -1.
It the boolean D~eed is true, FBlockIO reads blocks fran the
tile via a READ_DATA cell, otherwise FBlockIO writes blocks to
the tile via a WRITE_DATA call.

Before these OS calls can be made, the mode and offset must be
determined.

PliSLl8-25

Internals

" Confidentisl

If the block number to start the transfer (RBLOCK) is less than
zero, the mode is SEOUE~rrIAL and the offset is zero, otherwise
the mode is ABSOLUTE and the offset is calculated as:
ard4(rblock) • FBlkSize
where rBlkSize is the Standard Disk Block Len~th (~12)
The nlll\ber of blocks actually read or transf!.rred is calculate.d

as:

FBloCkIO := actual div FBlkSize
where •actual' is the nllnber of bytes transferred
~~_DATA or ~ITE_OATA OS calls.
EOf (fEOf)
~_BLK~

-

by the

is set to true when the last block is read.

Block~lII'i te

File Address
ST.L - Bufrer address
ST.W - Number of blocks to write
ST.~ - Block Number, -1 • Sequential
ST.W - Oci(ead, 0 • write, 1- read
•••••

Parerneters: 51.L -

••••••

Returns:

ST.W - NlInber of Blocks actually written

behaves in the serne manner as ~_Bl.KR), except it passes
D~ead with a value or false when calling
FBlockIO.

~_BLK~

the boolean variable

%_IORES - IOResult
Per ernet er s:

None

Returns:

ST.W - ICResult

Registers used: All registers are preserved.
Rerer to the

NDrkshop Un:r'$ Guidil

for the values of

I~esult.

Returns an integer value that reflects the status of the last
completed 110 operation. Note that the code 0 indicates
successful completions, positive codes indicate errors, end
negative codes 9Ie wernings.

Interl"~s1$

II Confidentie2
'-_ICRS ma~~es e call to function fI~esul t, which in turns
references the variable l~slt. The variable l~s:lt is essigr,ed.
values by the procedure %_SETIORSLT. This procedure is called ~/
FPLib and appestext only.

%_GEi - Read the next record in a tile

Parameters: ST.L - file Address
Returns:
Registers used:
~_PUi

OO~

Ol~ 02~

03,

AO~

Al~

A2

- Write the current record in a file

Parameters: ST.l - file Address
Returns:
Regi sters used: 00, 01, 02, 03,

~,

Al, A2

If ~_PUi is called immediately after a file is opened with
%_RESET, the ~ will write the second record of the file (since
the %_RESEi sets the current position to the first record and
%_PUT advances the posltion before writing).
~_U:I~

- Compute the address of fA

Parerneter&: ST.L - Address of file
Returns:

ST.L - Address of FA

Registers used: All registers are preserved.

PIOLI8-2i

Interr18.1 s

" Confir:ient181

%_SEEK - Allows access to an arbitrary record in a tile.
Parameters: Sl.L - Address of file
ST.W - Record number to seek
Returns:
Regi st ers used: 00, 01, 02, 03, AO, Al, A2
If the record number specified does not exists,
1) % SEEK causes the next (LT to access t.he last record ira the

last block of the file.
2) % SEEK causes the next PUT to append the record to the end
of the file.

PllSLl8-28

PPaslibC Unit:
Privileged PASLIB Calls
The unit PPas1ibC provides you with several useful low-level system furlctions.
However, they.e not for 6\·'er~·'(J"e! They are tricky, in some cases have global
erfects on the entire rystern, and should be used with caution.
In order to use these routines, you "lust use the units SYSCALL and PPaslibC:
lEES

{*-1 SysC811} SYS:ALL,
~lit£} M)l.IIDU;
Thh gives you accen to the routines lilted below. Tnele routines ere conte.irled in
lOSPASLIB.OBJ, so pTograrrl$ usir,g them reQuire no edditiorlal inputs to the Linker.

'$lJ

procedure BlocklDini t;

Ini tielizes all shared PASLIB deta. Opens inputfile end outputtile,.
associatirlg them wi th the filename -a:t6OLE.
BlocklDinit must be called by every shell before performing any lID; it

will only be executed by the first shell that cells it.

It is called by the s.ystEn.shell at boot time, once for the entire syster.l.
procedure BlockIOdisinit;
PASlIB cleanup. BlockIOdisinit closes the console only for the fir$t srlell
that celled the BlockIOin1t procedure.

procedure

L~aslib

(var

mTntIn:

integer);

where:
err,.,.

is the error ntJnber returned if the procedure has any problems.
(See Appendix A or the ~I)r*sft(jp User's Guide for ara
explanation of the error COdes.)
Locks the PASLIBI se~ent in memory so it won' t be swapped out. Used by
the filer for unmounting the boot device.
procedure LQdf)asIOlib (vsr err.... : integer);

where:
t ermua

is the error n\.lftber returned if the procedure has any probl em~ .
"·Locks the PASIOLIB se~ent in memory so it won' t be swapped out. Used by
the filer for unmounting the boot device.
I

FF'l1sJibC-J

Internals

II

Confldenti6.1

procedure HovEConsole (var errnun: integer; applconsole: consoledest);
where:
mTnua
is the error nl.ll\ber returned if' the procedure has any problem$.
applconsole tells where to move the console. (Consoledest is an
enumerated type of: elsereen, mainsereen, xsoroeA, xsorocB~
1'01 der, spare 1, spe.:re2, spare3.)
Noves the console to the main screen, an alternate screen, or an external
terminal connected throlJgh RS232A or RS232B. The tile nernes ere:
Alternate Screen
-ALTCOHSOlE-X
Ne.i n Scr een
-ftAIttXtfiOl.E-X
External RS232A Terminal RS232A-X
External RS2328 Terminal RS232B-X
procedure

Exe~set

(var err,..: integer; execfile: pathnsne; stopexec:

boolean);

where:
ennUi

is the error nLlTlber returned if the procedure has any probl ems.
execfile is the exec file nerne.
stopexec tells whether to open or stop the exec file.
TRUE = stop; FALSE = open.
If stopexec is TRLE, Ex~set closes the inp'Jt file and
reopens it, associating it with the temporary exec file. It
then generates two calls to the ~8dchar function to read and
save the temporary filet s first character into the variable
gtirstchar, and the next character into greadahead. Ex~eset
then sets the boolean gexecf1ag to TRUE.
If stopeX8C is FALSE, ExedReset calls the Resetinput procedure,
which closes and reopens the input file, associating it with
-aJ6OlE. Ex~.S8t then sets the boolean gexecflag to FALSE.
Opens or stops an exec file.
ExedReset is called once by the Exec Command Interpreter, to open and read
from the exec temporary file end reopen the input file to the console.

fwaction Exeenag: boolean;
Tells whether an exec file is op8n. TR£. op8n; FALSE • closed.
ExecFlag references the input file FIB boolean entry fS(I' Itl.f'.

Intnnals

II Confidential

proceclJre OutputRedirect

(VBI eITnlJll:

integer; outfile: pathnflne; stopoutput:

boolean);

where:
ennui

1 s the error nllnber returned 1f the procedure has any probl em~ .
outrile is the file name.
atopoutput tells whether to close, the file or leave it open.
TRUE a close; fALSE a leave open.
If stopoutput is TRUE, DutputRedirect calls the Resetout~
procedure, which closes and reopens the output file,
.

associating it with ....(IH;()L£.
If stopoutput is FALSf,. OutputRedirect closes the output file
end reopens it., associ~t.ino it with the filename outfile.
Redirects output to a file.
ftllCt 1 on rut putRfl ag: bool earl;

1el1s whether output tlas been redirected to a file. lRLE = output file
open (outplJt redirected);
~putRflag

FALSE· closed (output not redirected).

references the output file rIe boolean entry fSlWlBUf.

procedure [)SleslibCall (ver ProcPerell: dsProcPe:r_);

where:
d9>r()(9arse = record

case ProcCode : dsProcCode or
dsResProg : (RProcessld : longint); faust be called
before the process starts running.}

dsSof'tPwbtn : iSPButton : boolean); (result)
d9>ri ntDev
: PzOevi ce : e_n8IIe);
dsSetCPrefix: errnta: INItD:R; (result)
prefix : pettnne);
dsEntOisk
: (DiskEvent : boolean);
dsCiTrenLiseCar : (toTrCW')Slate : boolean);
(to turn on or ott translation tar C _ Itoh}
end;

d9>rod:ode

a

dsResProg
dsSor~tn

(dsResProg, dsSor~tn, dsPrintDev, dsSetCPrerix,
dsEntf)i skI dsCi Trenli s&:sr);

passes the process IO of e. process that is going to be:
resident to PASLIB.
returns the soft power button setting. If the button is
pressed, it returns TRUE; if not, it returns FALSE.

Interns1 S'

II Confide,7t i 81

passes the physi cal device neme or ttle corresponding
logical device -mINTER to P~LIB.
dsSettPrefix passes the globel prefix volt.me n~ne to PASLIB. If en
error has occlJrIed.. it is returned in ennui.
dsEntf)isk
tells PASlIB to enat.le (if OiskEvent is TRlE) or diseble
(i r DisJrEvent is F'ALSE) the autanatic mounting and
.

dsPrintdev

ejecting of a diskette.
dsCoTranliseCsr tells PASLIB to turn on (if toTrenslate is TRlE) or off
(if toTranslate is fALSE) the Lisa character translation
for 8 C. Itoh printer for the calling process. The
default setting is on.
[S)aslit£a11 is a new call in the PPaslibC unit that corrrnunicates to and
from PASLIB abol.Jt the run-time support for the system or the calling

process.

It has a variant-record parameter for indicating various

f'unctiIJns. Note that mlJst of these functions dictate system betlsvlor; tt'ley
al·e not safe for any process to call except the Lisa character translation

function.

FPaslibC-4

Rich Page
Apple Computer, Inc.
May 4.1983
lhecutfon Environment or the Lisa PIsca1 Compiler

Registers:
IXl-WAD-Al
IXl-D31AD-Al
04-D71A3-A4
AS

16

User temporaries
Compiler temporaries
CompUeruses for kals cl pointers
PDuller to 8iobal fmme
Pointer .., k£a1 frame
Pointer to lOp of smct

. 1.7
010bal Frame:
The global fmme consists rL two segments:
1) The Jump Table Segment
2) The Stack Segment (first rI N segments)
The global frame is Jayed out as fbllows:

Jump Table

Segment Table

SP!mJJ~

AS~

Data Pointer Table
Shared Main Prcpm Parameters
Private Main Prcpm Paramelers
Main Pqram 010bals

Regular Unit Olobals
Intrinsic UDit GJobals

A6~
A7~

DJnamk Use!! Stack

The Jump Tible is a an array or 6 byte JMPs used to
uansfer controt be tween segments of the prcwam and
the regular unit5 used by the prcpm. This is built by
the Linter from Entry points and Ex1e mats reference lists.

Tha Segment Table Is a structure which defines each r::i
me 2gmenlS at the pqram and the regular uni1S. This
Is used by dle Loader to swap in segments. For each ci
the segments. the Segme ttt Table ptOIides a file address.
size of cOOe (pacted & unpacked sizes) and the logical
address (le. segment number).
Tha DaIa Pointer Table Is an array of 4 byte pointers
which is used 10 refere nee global data !or intrinsic units.
This structure Is built bribe Loader and referenced by
compiled cOOe.

Tha .Private Main Pqram Parameters Is an area initialized
by Ihe loader and referenced by a:zmpiled cOOe. This area
clJlIains pointers 10 INPUT and OUTPUT t11e buffers and
other information such as the size of the regular unit globals.
Carrently this area Is Sloo bytes.
The Main Pqram Olobals is ~e global data allo:ated by
die compiler for the pqram.
. The Regular Unit Olobals Is the combination rI all global
da1a tequired by the regular unf15 used brllle program.

The Inuinsic UnitOlobals is the private global data which
Is required by1he in1rinsic units used by the program.
.

The Users Dyuamic SlaCk is lhat area which is used by Ibe
~am for kra1 frames. ~mporary data and pra:edure
Unkages (both paal and assembly language).

IDitially the Loader a11a:ates enough space 10 cover these
areas and the user min SlICk requirements. The sys1em alm
. eDfcrces a upper Umit (fe. max Slaet).
CDi'npiJe Ex«utiDn El'lvironmlnl-2

La::al Frame:
The lccal frame consJSIS oF the following:
1) Function result and parameters
2) Static and dynamic lints
3) Uals and compiler 1emporiries
4) DynamJc Slack area
. The la:al frame is Jared OUI as follows:

PuDCIkm Result •

Parame1e'rs ••
Stade LInt •••
ReIUmAddre~

Dynamfc.:LInt
Lca1s
QrmpUer Temps
Dynamic SlaCk Area

.,

..

• Two at rOur bite fwictlon result. Present only for func1icms.
... N bf1es depending an the parame1er 1fsI.
.~ Present cmly for non level 1 prcx:edures and parame1ers. .
. ..
.
The Ja:al ftame Is aIJecated by the cmnpiler and allows the
.compiled co:Se 10 reference kx:als. pmm1ers, static llnb. ..

.

The dynamic lint (fe. OldA6) is pushed by1he LINK A6
IDstruction which allcx:ates space for Ja:als and compUer 1emps.
.

.

The static lint is pushed by1he caDer as part of 1he parameter
.lfsL The stade lint is a copy the patents A6 (fe. kx21 frame).
Omlpiler 1emJXftrles are used 10 implement COD5trUC1S such
as non kral go1OS and expremons computed by the compiler
which happen 10 not be in registers. These expressions may
include for loop limits or with ezpressicms.

I

Parametric prcx:edures and functions appear as follOws:
Address of

pra:I~ body

. _
Zero or SlaUC Jfnt
Note zero is used for level 1 pm:edures.

I
•

The compilet rommunicates the space requirements for each
pro:edure by preceding each UNK A6.#-size with one of the
following sequences:
.

TST.W

e(A1)

MOVEL

A7,AtJ
#size,AO
(AD)

SUBL .

TST.W

The o&t used in the tlrst case or 1he size in the second reflect
Ihe sum of the prcadures stalle and dynamic requirements.
This sum is inflated bl at least SlOO bytes 10 allow assembly
language procedures 10 use a small amount or stack space at
low can (ie. they need not chect~ Note the cOOe for automatic
SIaCt upansloo can be contm1led with a compile oplicm.
JSRs, JMPs, LEAs and PEAs:
These instructions are used 10 uansfer control and obtain the
addre5S r:l a pro:edute or f'unctio!l. These 1nmlcticms exist in
duee forms an ri which CttUpy 4 bytes each:
1) Wilhin I ~gment PC' relative
. 2) References 10 regular Sl!gmeDU: Offsets from AS
3) References 10 intrinsic segmeDlS: IU Trap instructions

The fust form is simply a reference 10 a pra:edure from within .
1be same ~t which uses the PC relative addressing mode.

The second form is a reference to a pra:edure which is not in
the same segment but Is ccmtalned in a segment of the pqram
or a regular uniL This II Imp1eme nled by using an o&t from
AS 10 refereta Ihe pra:edure 1htough the Jump Table.
The 1hird form is a reference 10 a pra:edure which is contained
in u inlriDsic segment Cie. in an intrinsic unit). This form is
implemented by using Line 1010 np mechanism 10 compreSS
!be opcode and 24 bit 1~ca1 address into I 4 byte instruction.

III each dille abcPle cues 1he compiler emits references the
desired pra:edure or function and the linter OlnSUCUts the
apptopiate addressing mode ftr JSRs. .Ms, LEAs and ~

S!ructure of Co1e for aPaDl Prcl.'edure or Function:
The code euiiued by Ihe compiler contains Ihree COIlSUUCt5 which
can be controlled via compile time options. These are 15 follows:
1) Auu:madc stack expanslcm.
2) Range checking far values. fDdexes and strfngs.
.3) Oebusgung
info (ie.the pra:edure Dame).
.
.

.

The code fbr a l)'pical pro:edure wm loot as ro~:

m.w

e(A7)
. Tests for sufficient Slack space
LINr
A6.#.
AUcates space for lcrals
body rf the pra:edure or f\mcdon
UNLK
A6
Restores previous ml frame
RTS
Exit sequence
BIght byte pnndure name and
two bJ1e data size. This is lhe .
optional de bugging Information.
amtant data area for SIrings ! sets

The em sequence emitted by the compiler Is dependent on the
Dumber rI by1es of parameters. If there are DO parameters then
the RTS is used as shown above. The compiler emits one of lhe
following sequences when pa.rame1ers must be dele1ed:
Case #1: 2, 6 or 8 b),!!s of paramters
MOVE.L
(A1)+ ,AD
ADCQ.W
#m,!7

JMP

(AD)..

Case #2: 4 by!s or parameters
MOVE.L
(A1)+ I..A1)

RTS

Case #3: more than 8 bytes of pe.ramet!rs
MOVE.L
(A7)+ ,AD
ADD.W
#_,A7

JMP

(AD)

2
2
2
obytes total

2
2
4b)1es 10Ial

2
4

2

Tby1es UJtal

Segmenta tion &, Large constan ~ passed by value:
Since the 68lIl is not remrtab1e. (Ie. use a 6SJ10 instead) me
data (Ie. stack and heaps) for a given pqram must be present
while 1he pqram is execu~ Since code segments must be
swapped !nUl memory as needed and set and string constants
are SIOred with 1he code. large constants passed by value pose
a problem. Currently. we ~.thi5 problem by having the
compiler use the inMlction TST.B (Ai) to check 10, see if me
Ibe ac\Ual value parameter is in memory. If the TST.B (Ai)
Cluses a fault lhen the system loads 1he segment containing the
addressinAL

.

When copying strings the compiler emits code which depends
ODly ~ the size of the destination. This may cause the code
10 read beyond lhe end of a segment The system allows fat
this bJ mapping code segments ID COYer size + 256 by1e5. The
heap segments aOO have an additiona1256 bytes.

Shell-Writer's Guide
This document contains informatiorr you rleed to know to y,erite e shell for the Li~e.
It describes the things e. shell must do when it starts up and ~Iherr it terrriinates. To
use this document, you should be farr.ilie.r with the OpeT6ting S}"stem R6ferenc-e
1t1snuaJ and heve some knowledge of Pascal. To do any graphics, you will have to
use. QUlckDraw" detcribed in the P6SCsJ Reference ~1anLisl. You ma;' also want to lJSc
calls in the Pas lib Call and PPaslibC units.
The 9/ltem..ahell
When the OS is booted" it starts the 'root process, which searches the boot dis~~ for ~
shell celled '1YItem.lhelJ'. The ayltem.lhell b autometically rterted,o and will be the
ancestor of all other shell proceues (see Figure 1). All shells mu~t be "plugcompetible" with each ot.her so that any shell cen be the IYstem.lhell wit-hell/. speciel
tupport frorn the as. In this W8')', e turn-key boot disk could be prepared that didn't
include e $elector $hell.
l

Root process

Syst&n.IheU

(Envlro .,.., Its wlt'lCtJw)

Office System

os Shell

still more

MtraDos)

hlls

FJ~l

Process Picture

7-FebruBl)/-!J4

St~JJ-('Vrjte!"s·

G/Jide-l

" Confjdentis.}

If y'OIJr shell is tt"le first process (t.tle, system.lhellt YOLI must make the followlng
$)t'stern initiahzation calls. Normally, the selector shell takes care of this for YC.'J.
Startup:

prucebe BlockDlnit; Initializes Pascal 110. (Note: if you don't hav'e.
the privileged PASLIB interrace, declare 81ocklOinit external.)

p-ocedse PMinit (ver enex-: Weger); Initializes pararneter rnernory.
(Note: you have to be able to link against the prrrn unit to
make this call.)
ftn:iion en8ble[)bg (on: boolean): booleen; Activates LisaBug if yCllJ
want to use it.
Jrocedtse telNMIkey (keyCap: irteger); Makes Lise.8ug accessible
through the NMI key.
TerrrlinatiClrl: ~ocedse BlockllOidnit; PASLI8 cleanup. (Note: if 'yOU don't have
t.he privileged PASLIB interface" declare BlocklOlnit ex te:ne1.J
To tell if

yOIJr

shell is the system. shell, call:

irloJlfocen (OSErr., ~_Id., PInf'o)
If Plnt'o..father_id is 1 (the root process).. then you're in the tytlem.sheU.
ihe Et'y. . ·ironrnents window is the standard syst.ernshell It scans the directory of U'le
startl.Jp dhk. for filer. whose nan"les begin with 'shell.'. For your shell to be recognized
end 8\,1ailable frorn the Environments window" the narrle of its object file must start
VI ith 'shell:.

Imerproceu Communication

Event channels are used for communication between processes. The root process and
the select.or shell expect information from their son processes through a
SYS_SON_TERM event channel" telling why the son terminated, and whether the father
should rest-ert t.he son" select or nert another shell, turn the power off.. or reste.rt t.he
machirle. The OS guarantees that this event will always be sent back to the father of
a terminated proceS$ via the local event channel, even if the son procen was
unwillingl'y' aborted.
At Shel1 Startup

F ATHER: A process that starts a shell must do the following:
1) Establish a local event chennel t.o allow it.s Ion t.o communicate with it
((PEN_EVENT_~.

2) Start the son shell (MAJ, to make the operating system call to
TERMINATE_ PRlCESS to open e.n event. channel, I_evertblk (en array of longints).
lhe first entry of this block ('_evert.b1kC1J ) contains the event that tells the shell~~
father what to do. The chosen meanings for these values are:
l--Rest8l't same shell (thell crashed and needs t.o be rest.arted). 10 avoid infinite
loops of ST ART - CRASH - REST ART - CRASH... , the user will be at,le t.e,

intervene when the selector shell is reached.
2--Select. e.r.other shell (SELECT_ANlTt-ER command).

3--Stert the specified .hell. The remaining longints in the event text blc.ck
('_eventbUri2_9] ) are interpreted as a packed arrey [1 ..32) of characters (Wittl
no lengt.h fieldt contajning the file name or the shell to be started. The
unuted portion of the eTTay is packed with spaces.
4-- Turn rT'18.chine off ( .....hite power button clicked" or ~R_OFF comrTlsnd).
5--Reboot the machine.
other -- Unspecified.
It will be the Job of the shell's terminate exception handler (which is just a procedure
the shell owns) to Querantee that the proper SYS_~_TERM event text is set before
the shell actually terminates. It cen do this by calling TERMlNATE_PRlCESS, one erf
whose parameters is e. pointer to thh block.

Shell-klT/teT'S Gu/d~-'

"

F ATHER: The

Confide-niis}

of the shell U",at just. terminated should:
1) Pea'r,'s.ken because it ha$ received the SYS_93N_TERM event vis its local
fet~ler

event channel.
2) Check the e'v'ent text to see what to do.
EX8fTlllel

Following ere code segments from t'oth a father shell and 8 son shell showing the
start-up and termination of the son.
These constarlt end type definitions are used throughout. the following
CONS;
aRe-.i tv t

= 1;

eselect~~t~

8S'ter tAno tr'ler
etJff = 4:

TYPE
{

~i!

tT lX

(Res tar t PIe )
(Sll e-: t trIO trJer Slie 11 )
(~.rt. tr'Ie Shell f)Mej in tM tveit text )

= 2:

= 3;

(Turn off Li$8.)

= 5:

ef(t$it

example~:

(Re~t.

is ....wierlt rt:eOrO

= RfCORO

the ..~ir.e

~iCh .11OYS u!.

)

to ..:k1rH!- the

~ed err~ Of

ctc

Cf\Sl er..

VilLE i(a32 00 BEGIN
l' ftWIe[ i) c"

(spIC=e)
~CO] :c ct~(i-1);

Tlet RGI"
('tuff

EXIT(Stuf~);

!NO:

fnIM: patl'mne);

lengtn filla)

(IF)

fr...e[i] :c blOCk.rest[i):

i :c i • 1;

!NO;

(\tilL.!)
fNIM[Ol :- CN'(32);
!NO; (Stufftw.e)

(stuff length

'i~ld)

IEGI" (hl u..oop)
fI"Itr~

:= ";

••' eh nlr'1e ;: • t .

'-':-nW :- ..

~ir'_EIJen t J~tn (OS!TT , ttl) _Cl'1_f"rfne ,

'!J_Chen_Te fr'U1, e:<_nMe , rece j ve) ;

se 1.C~ 11 (tnIM);
REPEAT
ftal,(t _ Prooess (osEn' . proc I O.
IF (~Err (= 0) THEN SEGIN

'''*''Ie. en 0')' • tv_CIW'\_rt fnuf\) ;

va.itList.ltnQth := 1;

rJ ChIn r.fnUr!t;
wei t_flJtnt_CtrI(osfTr ,ve.itList:-vnioo, It\.',.ptr);
wej tList.refrJJll'l[O) :c

(~Ode for fattler shell Dringir.g
Kl11_ProoesS(OSfrr .prOCJO);

~

son ,tarts here}

.

IF tv.J'tT . eouerit_text[O l=C*ll_ttrPI TtEN (C*UtCI tendNlte,.PTccts!}
ELSE

HextTOOo :a ...,.ptr . ....,..t_t'xtUl

Hl!xtToOo

!NO;
~!E

(MOe

:~

8S1!leetfn:)ther;

the process SUCOtSSfully)

HextToDo OF

~HtaJ·t: (00 nothing):
~ 1ectArY.'tther:
1te tShe 11 ( fnMe);

se

este.rtMother: StuHNaM(r.'.ptr .event_text, fnMe)~ (9tt nIrIe of Htxthll out of
eDff: ShJ~(lOff):
(I--turn the Mctunt Off)
tRtset: S'tUtt»8t(lRtstt);
(5-reset the MCtline)

EHD:

OTt£RWISf Sl!leethl1:
(case HextToDo)

00 I L He 11 FrleztsC)Jer:
END; (ShIll u:.op )

event_t~.;t)

"

SON: Ttlis prc,cedure mskes the

nec:es~ary

calls for the $tert.-up of

t\

Confidenti~J

shell.

PROCEOVRf 9'\e 11 In it;

~rr: IKTEGER;
PInfo: ProclnfoRec;

VAR

SEGI"

info-prOC~Ss(oserr,"y_lD,PInfo);

IF Plnfo. fattier 10

8100kIOini
PtHni t;

IF
!NO;

END;

t:

= 1 (root)

Tt£H BEGI"

(frOf\ PPtiLi~)
(frI)M Prt1)

Er«tl~ T~H

(st&reOW'd ttlI

S'et1f11key(33);

keyc~}

(IF)

(ShellInit)

Ttlis code shows the shut.down of

the Sts_Terminete

exce~ltic,n

reason for terminating.
PROCw.~

e. shell. If" the

StU~

procedure h declared 8S
fat~ler its

handler, it will properly communicate to its

9'tIJttY.M'l ('t.tIy: IHTEGER):

lVPE
'M

blOCk: tri)(;

t:te xthll :eJlMo!;

(

tf')e

YVitnt record)

1: IHT[QfR;

{ for the fcYr loop }

OStrr: lKTEGfR;

{ required peraMeter for tne call to ten.inate.process

SfGIH
aloc~.tvOl~[11 := ~f;
IF ,,~. : astartTrdscrli T~toI

!£CtIN

HtxtShtl1 :- 'shel1.rlixt';
(cop~ strirrg wi tnout 1eng ttl field)

END;
END;

~
~OR

1 := 1 TO lerqtn(nextshtU) D) bloek.rHt[i 1 := nextShell[i];

i := lengtn(nextsntll) • 1 TO "ex enane 00 D10Ck.rest(i] := ' ':

tt",ir... te"prcc:ess(~ , tt lOOk.~' 1k);
{StIJ~n}

-

I

•



Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.3
Linearized                      : No
XMP Toolkit                     : Adobe XMP Core 4.2.1-c043 52.372728, 2009/01/18-15:56:37
Create Date                     : 2011:07:14 20:16:30-08:00
Modify Date                     : 2011:07:15 14:45:31-07:00
Metadata Date                   : 2011:07:15 14:45:31-07:00
Producer                        : Adobe Acrobat 9.45 Paper Capture Plug-in
Format                          : application/pdf
Document ID                     : uuid:b57bad06-282e-4c3a-91f4-615d83d1d583
Instance ID                     : uuid:04312775-7aa5-4f5d-8795-63e0d2d93cc1
Page Layout                     : SinglePage
Page Mode                       : UseNone
Page Count                      : 87
EXIF Metadata provided by EXIF.tools

Navigation menu