TweetFollow Us on Twitter

Toolbox from Ada
Volume Number:5
Issue Number:3
Column Tag:Ada Additions

Calling the Mac ToolBox from Ada

By Jerry N. Sweet, Laguna Hills, CA

[Jerry Sweet is a member of the technical staff at Meridian Software Systems, Inc. Meridian is located at 23141 Verdugo Drive, Suite 105, Laguna Hills, CA 92653. Their phone number is (714) 380-9800.]

Abstract

This report gives an overview of the techniques and tricks needed to write AdaVantage programs that call Macintosh native system facilities, Specifically, how to build "double-clickable" applications with AdaVantage is discussed

Introduction

Meridian plans to introduce an Ada binding for the Macintosh Toolbox facilities later. This report has been written to help those who who have special system programming needs or who need to create Macintosh Toolbox interfaces immediately. Readers should possess an understanding of how to use the AdaVantage compiler, a reading knowledge of 68000 assembly language, MPW C, and Macintosh Pascal, a familiarity with Inside Macintosh, and an understanding of the whys and wherefores of object code linkage.

Making Calling Conventions Match

The Macintosh AdaVantage compiler uses C calling conventions. The Macintosh operating system uses Pascal calling conventions or specialized (assembly language) calling conventions that are different from the C calling conventions. This means that to write Ada code that interfaces to the Macintosh system facilities, a combination of C code interfaces and machine code insertions must be used.

One might assume that a liberal application of pragma interface is all that is required to gain access to the Toolbox. Unfortunately, that is not the entire story, because many of the Toolbox routines do not exist in object form such that they can be linked with an Ada subprogram. This means that the linker will report unresolved symbols for many or most interface routines, leaving the programmer wondering what object library was omitted in the linkage or wondering what else might have gone wrong.

The solution to this problem is to write one’s own “glue” routines that force the Toolbox routines to become available in a linkable form. Glue routines are so called because they create a bridge (i.e. “glue”) between two typically very different collections of software. This is relatively easy to do with very small C subprograms that may be named in interface pragmas. Alternatively, but not so easily in many cases, machine code insertions may be used.

The most compelling reason for using glue routines written in C is that MPW C provides a ready set of object code libraries and a corresponding set of “include” files ( .h files) that permit C programs to use most of the Macintosh system facilities directly (i.e. a C language Toolbox binding is already defined). However, most of the C function definitions contained in these include files use a Macintosh-specific extension to the C language that generates in-line machine code for the Toolbox A-line traps and at the same time translates the calling conventions automatically from C to Pascal (“Pascal external” definitions). Because these function definitions are bound directly at compile time, rather than at link time, they cannot be referenced by Ada programs. To make these function definitions available to Ada programs via pragma interface , small “wrapper” routines can be written in C that simply call the in-line routines.

Another reason for using glue routines written in C wherever possible as opposed to Ada machine code insertion routines is that one does not then have to figure out the stack offsets of the various subprogram parameters and function results and then write 68000 machine code to push and to pop the parameters.

Consider this example of an in-line C function definition, as defined in the MPW C include file quickdraw.h :

/* 1 */

pascal void InitGraf(globalPtr)

 Ptr globalPtr;
 extern 0xA86E;
/* This definition causes an in-line machine instruction */
/* to be generated at the point of the call to this      */
/* function.  This is conceptually similar to applying   */
/* Ada’s pragma inline to a machine code insertion       */
/* routine.                                              */

and here is an example of the corresponding wrapper routine that one would write in C to make InitGraf accessible to an Ada program:

/* 2 */

#include <quickdraw.h>
void MSS_InitGraf ( globalPtr )
 Ptr globalPtr;
{ 
 InitGraf ( globalPtr );
}       
/* This definition causes a subprogram entry to be emitted */
/* to the object file so that MSS InitGraf is accessible   */
/* to an Ada program via pragma interface.                 */

and here an example of the corresponding Ada procedure specification and interface pragma that would appear in a package specification:

--3

package QuickDraw is
  -- lengthy sequence of type definitions
 type GrafPtr is ... 
 procedure InitGraf ( thePort : out GrafPtr );
private
 pragma interface (c, InitGraf, “MSS_InitGraf”);
end QuickDraw;

If one were to omit the pragma interface and substitute a machine code insertion routine in the package body, it would look something like this:

--4

with machine code;

package body QuickDraw is

 procedure InitGraf ( thePort : out GrafPtr ) is
 begin
  -- MOVE.L  8(A6), -(A7) ; push thePort
 machine code.instruction’(val => 16#2F2E#);
 machine code.instruction’(val => 16#0008#);
  -- FCB     0A86EH       ; InitGraf A-line trap
 machine code.instruction’(val => 16#A86E# - 16#1_0000#);
  --           note: the trickiness about subtracting
  --           16#1_0000# is needed because the compiler
  --           requires a signed 16-bit value, and A86E
  --           is greater than ‘last of that range.
  --           The subtraction works because the 
  --           computation is universal.
  -- ADDQ.L   4, A7       ; pop thePort
 machine code.instruction’(val => 16#588F#);
 end InitGraf;

end QuickDraw;

Note that C, machine code, and even Pascal may play somewhat fast and loose with data types. This can present some interesting challenges for Ada application writers who wish to take advantage of Ada’s strong typing capabilities. It is not really very difficult to translate the Toolbox’s Pascal data definitions to Ada, but some care must be exercised to ensure that data containers of the correct sizes are used. For example, Macintosh Pascal’s integer and MPW C’s int types are 16 bits wide, whereas AdaVantage’s integer is 32 bits wide. AdaVantage’s 16-bit integer type is called short_integer. To avoid confusion, it is really best to use explicit range definitions instead:

--5

        type Int8  is -2**7  .. (2**7)  - 1;
        type Int16 is -2**15 .. (2**15) - 1;
        type Int32 is -2**31 .. (2**31) - 1;

Getting the parameter modes right is very important. Because there is no cross-checking in the data type or subprogram definitions between the interface subprogram and its Ada counterpart, it is easy to pass a parameter by value mistakenly when it must be passed by reference, or worse, to pass the wrong parameter type. Pascal var parameters are expressed in Ada as out or in out parameters. It is a little bit harder to tell from the C definition of a subprogram what the proper Ada mode should be. For example, a C struct * parameter is really an Ada record type parameter of mode in, since AdaVantage always passes records by reference.

It should be noted that Ada functions cannot have mode out parameters. Those Macintosh system functions that take Pascal var parameters must be expressed in Ada as procedures with two out parameters. This requires a slightly different method of expressing the glue code. For example, consider the definition of GetNextEvent from Inside Macintosh

FUNCTION GetNextEvent (eventMask: INTEGER;
VAR theEvent: EventRecord ) : BOOLEAN;

This would have to be expressed in Ada as:

--6

package Events is
 procedure GetNextEvent (
 eventMask : in EventID;
 theEvent  : out EventRecord;
 result    : out Boolean
 );
  -- Pascal functions with VAR parameters must be 
 -- expressed as procedures in Ada.
private
 pragma interface (c, GetNextEvent, “MSS_GetNextEvent”);
end Windows;

The C glue code corresponding to this is:

/* 7 */

#include <events.h>

void MSS_GetNextEvent ( eventMask, theEvent, result )
 short eventMask;
 EventRecord *theEvent;
 Boolean *result;
{ 

 *result = GetNextEvent ( eventMask, theEvent );
}

Compilation and Linkage Issues

To create an application, the steps required for compilation and linkage are:

1. Prior to any compilations, a newlib command is absolutely required in a new folder. This only needs to be done once per each folder in which AdaVantage compilations are to take place. The newlib command creates an AdaVantage program library named ada.lib and an auxiliary directory, :ada.aux: .

2. If other Ada component libraries are required, the appropriate lnlib commands must be applied to link them into the local library. For example, if package Bit from the AdaVantage Utility Library is used, then something like this command must be given:

--8

lnlib  {MeridianAdaRoot}adautil:ada.lib

This command only needs to be given once per library.

3. Ada compilations may be performed either by pulling down the AdaVantage menu and selecting Ada or by typing the ada command. If machine code insertions are used, then the ada -g option should be given if references are made to the frame pointer, A6. In the Ada dialog box, this corresponds to the Use MacsBug button in the More Options dialog. This option ensures that LINK and UNLINK instructions are generated at subprogram entries and exits so that parameters can be referenced via the frame pointer.

Normal rules for Ada compilation ordering hold, as always. However, as a point of possible interest, pragma interface is a substitute for the body of a subprogram. Because pragma interface definitively decouples an Ada subprogram specification from its body, one is in effect permitted to compile the “body” (in C or assembly) before the specification, which would not be permitted in “pure” Ada.

It should be noted that the MPW tools dealing with automatic recompilations, such as CreateMake, do not really provide adequate support for Ada. Makefiles may be created by hand if the order of compilation is known. The targets and dependencies should be either the .atr or .c.o files that result from AdaVantage compilations, as in this example:

#9

AUX = :ada.aux:  
ADA = ada -g  
obj = .c.o  

prog ƒƒ  {AUX}prog{obj}
 bamp -app prog  

prog ƒƒ  prog.r  
 rez prog.r -o prog -append  
 setfile -a B prog  

{AUX}prog{obj} ƒ  {AUX}pkg{obj} prog.ada  
 {ADA}  prog.ada  

{AUX}pkg{obj} ƒ  pkg.ads pkg.adb  
 {ADA}  pkg.ads pkg.adb

Note: the ƒ symbol is created by holding down the Option key and pressing the f key. Also note: AdaVantage truncates all output file names to eight characters, excluding the extension; for example, the object file corresponding to compilation of quickdraw.ads and quickdraw.adb is :ada.aux:quickdra.c.o (note the truncated w in quickdraw). Furthermore, it is not always possible to predict what an output file name will be, because if compilation unit names collide in the first eight characters, a file with a name such as aaaaaaaa.c.o may be produced. After hand-compiling a unit, its object file name may be determined with the lslib -l option. The BuildProgram operation (invoked with the command-B key) should not be used with AdaVantage, because it turns on “echo” mode for MPW shell scripts, which causes each line of the ada command, which is implemented as a shell script, to be printed as the line is executed. This slows down compilations considerably. Instead of using BuildProgram, create a two-line shell script called domake that contains these lines:

#10

make -f Makefile > tmp
tmp

Running the domake command has the effect of running BuildProgram without echoing each MPW command script line as it executes.

Helpful hint: when continuing a long MPW command line with “” characters (Option-d), select all lines in the continuation before pressing Enter.

4. The C or assembly language subprograms corresponding to Ada interface subprograms may be compiled either before or after their corresponding Ada compilation units, since no information from the C or assembly language compilations is used in Ada compilations; it is only at link time (when bamp is invoked) that the C or assembly language code modules are required.

5. For each Ada package that contains instances of pragma interface, the auglib command must be applied to augment the library entry for the package with the name of the C or assembly language object module containing the implementations of the interface subprograms. This must be done only once, following the first compilation of the package. For example:

ada -g quickdraw.ads quickdraw.adb
auglib quickdraw quickdrawGlue.c.o
c quickdrawGlue.c

The information attached to the library package is supplied to the object linker when bamp is invoked. To see the augment information associated with a particular library unit, use the lslib -l option.

It is possible to use auglib so that an augmenting code module is linked in whenever any library unit from a particular program library is linked with some Ada program. This is done by specifying the library unit name all with auglib, as in this example:

auglib all MasterGlue.c.o

Again, this only needs to be done once, and then the information is kept permanently, or at least until it is explicitly removed with auglib -r. Refer to the AdaVantage Compiler User’s Guide for additional information about auglib.

Special note: because of a “feature” of bamp, full path names for augmenting object module names should be specified. This is because if a component program library that has been augmented is linked to a program library in another directory, bamp may not be able to find the augumenting code module unless the entire path was specified when the auglib command was given. For example, this is a more appropriate auglib command form to apply:

auglib all ‘directory‘MasterGlue.c.o

The backquoted directory command inserts the path of the current working directory into the command line.

6. To link an application, use the bamp -app option. Without the -app option, the program is linked as an MPW tool, which may not be what is desired.

There are additional bamp options that may be useful to apply to a program to be linked as an application; refer to the AdaVantage Compiler User’s Guide for a list of the available options.

7. All Macintosh files possess two “forks”: a resource fork and a data fork. In the case of the executable file for a Macintosh application program, the resource fork contains CODE resources for the executable code and other kinds of resources for icons, dialog boxes, and so on. A complete treatment of resources and forks is given in Inside Macintosh. To connect resources to an executable application, rez, the resource compiler, may be used. The rez command may be invoked even prior to running bamp. The ada and bamp commands only affect a file’s CODE resources, while rez affects all others. Non-CODE resource descriptions are typically kept in a file whose extension is .r.

Note that misapplying rez could result in strangely behaving or unuseable applications. If a problem with a program’s resources occurs, it is best to delete the entire executable program file and then relink with bamp and re-rez with rez.

The default MPW application icon (hand writing in diamond) applies unless one supplies a custom icon resource of resource type ICN#. Resources may be customized with the resedit program, for example to modify icons, without recompiling with ada or relinking with bamp. However, if an icon is changed, the desktop must be “rebuilt” to put the change into effect. Rebuilding the desktop resets the Finder’s otherwise permanent records of file attributes so that icon resource changes are made visible. To rebuild the desktop, hold down the command and option keys as one reboots (when pulling down Restart in the Special menu)

8. To mark an executable program file as a Macintosh application, the “bundle” file attribute must be set. This is done with the setfile command, as in this example:

 setfile -a B sample

Note that the “B” above must be a capital B.

Setting the file type to APPL is not sufficient to identify an executable program file as a Macintosh application; the bundle attribute must be used if non- CODE resources are supplied with an application.

It is possible to create an application by using bamp -app without associating additional resources with the program or setting the bundle attribute, if Text_IO is used to interact with the user. The style of interaction that is then used is not typical of Macintosh applications, however.

Conclusion

By following the recommendations given in this report, “double-clickable” Macintosh application programs can be written in Ada. Although at present, a bit more effort is required to create an Ada application than is required to create a Pascal or C application, the introduction of the Ada Toolbox binding later in 1988 should ameliorate that.

Acknowledgements

This report was developed originally for a seminar on Macintosh Ada given October 9, 1988 by Edward V. Berard, President of EVB Software Engineering, Inc. At the time that this report was being written, Mr. Berard contributed a list of discussion points and some key definitions.

Bibliography

•Inside Macintosh, Addison-Wesley, 1985.

• Macintosh Technical Notes #164 and #166, Apple Computer, Inc., 1987.

• MPW 2.0.2 Reference Manual, Apple Computer, Inc., 1987.

• MPW C 2.0.2 Reference Manual, Apple Computer, Inc., 1987.

• Reference Manual for the Ada Programming Language (ANSI/MIL-STD-1815A-1983), United States Department of Defense, 1983.

• Meridian AdaVantage Compiler User’s Guide, Meridian Software Systems, Inc., 1988.

• AdaVantage Product Release Notes, Meridian Software Systems, Inc., 1988.

• The C Programming Language, Kernighan & Ritchie, Prentice-Hall, 1978.

 
AAPL
$112.65
Apple Inc.
+3.24
MSFT
$47.52
Microsoft Corpora
+1.78
GOOG
$511.10
Google Inc.
+6.21

MacTech Search:
Community Search:

Software Updates via MacUpdate

BBEdit 11.0.2 - Powerful text and HTML e...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
ExpanDrive 4.2.1 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Adobe After Effects CC 2014 13.2 - Creat...
After Effects CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous After Effects customer). After Effects CS6 is still available... Read more
Command-C 1.1.7 - Clipboard sharing tool...
Command-C is a revolutionary app which makes easy to share your clipboard between iOS and OS X using your local WiFi network, even if the app is not currently opened. Copy anything (text, pictures,... Read more
Tidy Up 4.0.2 - Find duplicate files and...
Tidy Up is a complete duplicate finder and disk-tidiness utility. With Tidy Up you can search for duplicate files and packages by the owner application, content, type, creator, extension, time... Read more
Typinator 6.3 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
GraphicConverter 9.5 - Graphics editor w...
GraphicConverter is an all-purpose image-editing program that can import 200 different graphic-based formats, edit the image, and export it to any of 80 available file formats. The high-end editing... Read more
Toast Titanium 12.0.1 - The ultimate med...
Toast Titanium goes way beyond the very basic burning in the Mac OS and iLife software, and sets the standard for burning CDs, DVDs, and now Blu-ray discs on the Mac. Create superior sounding audio... Read more
QuickBooks 2015 16.0.2.1422 R3 - Financi...
Save 20% on QuickBooks Pro for Mac today through this special discount link QuickBooks Pro 2013 helps you manage your business easily and efficiently. Organize your finances all in one place, track... Read more
Remotix 3.0.6 - Access all your computer...
Remotix is a fast and powerful application to easily access multiple Macs (and PCs) from your own Mac. Features: Complete Apple Screen Sharing support - including Mac OS X login, clipboard... Read more

Latest Forum Discussions

See All

The Hit List — Simply Powerful Tasks, To...
The Hit List — Simply Powerful Tasks, To-Dos, Projects, & Reminders 2.0 Device: iOS iPhone Category: Productivity Price: $9.99, Version: 2.0 (iTunes) Description: >> LAUNCH SPECIAL: The Hit List 2 for iPhone is ONLY $9.99... | Read more »
Mahjong Journey Review
Mahjong Journey Review By Jennifer Allen on December 18th, 2014 Our Rating: :: STEADY MATCHINGiPad Only App - Designed for the iPad Aimed at the more laid back gamer, Mahjong Journey isn’t for everyone, but those looking for some... | Read more »
Emoji Type - custom keyboard with predic...
Emoji Type - custom keyboard with predictive emojis 0.4.0 Device: iOS iPhone Category: Utilities Price: $.99, Version: 0.4.0 (iTunes) Description: Emoji Type is custom keyboard for iOS 8 that auto suggests emojis as you type. ABOUT... | Read more »
Game of the Year 2014 – 148Apps Staff Pi...
The end of 2014 is almost here, which can only mean one thing. Okay it can mean a lot of things, but in this specific context it means Game of the Year lists! Which is why the 148Apps staff have all picked their favorites from the past year. And why... | Read more »
UponPixels Review
UponPixels Review By Jennifer Allen on December 18th, 2014 Our Rating: :: CREATIVE TYPOGRAPHYUniversal App - Designed for iPhone and iPad Add cool typography and objects to your photos with the easy to use UponPixels.   | Read more »
The Vikings are Coming! CastleStorm’s Ne...
The Vikings are Coming! CastleStorm’s New Update Adds a Survival Mode Posted by Jessica Fisher on December 18th, 2014 [ permalink ] | Read more »
Duet Display (Productivity)
Duet Display 0.3.3 Device: iOS Universal Category: Productivity Price: $9.99, Version: 0.3.3 (iTunes) Description: Duet Display allows you to use your iPad or iPhone as an extra display. Developed by a team of ex-Apple engineers,... | Read more »
Dragon Quest III Review
Dragon Quest III Review By Jennifer Allen on December 18th, 2014 Our Rating: :: DATED BUT NOT WITHOUT MERITUniversal App - Designed for iPhone and iPad A walk down memory lane isn’t foolproof for Dragon Quest III, but it has its... | Read more »
8 KEMCO JRPGs Are Just $0.99 in Celebrat...
8 KEMCO JRPGs Are Just $0.99 in Celebration of the Holidays Posted by Jessica Fisher on December 18th, 2014 [ permalink ] KEMCO has announc | Read more »
Brothers in Arms 3: Sons of War Review
Brothers in Arms 3: Sons of War Review By Jennifer Allen on December 18th, 2014 Our Rating: :: FUN BUT PUSHYUniversal App - Designed for iPhone and iPad Brothers in Arms 3: Sons of War could be great fun, but its plethora of... | Read more »

Price Scanner via MacPrices.net

Save up to $400 on MacBooks with Apple Certif...
The Apple Store has Apple Certified Refurbished 2014 MacBook Pros and MacBook Airs available for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
Save up to $300 on Macs, $30 on iPads with Ap...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
iOS and Android OS Targeted by Man-in-the-Mid...
Cloud services security provider Akamai Technologies, Inc. has released, through the company’s Prolexic Security Engineering & Research Team (PLXsert), a new cybersecurity threat advisory. The... Read more
KMI MIDI K-Board Great Gift for Amateur &...
The K-Board is a MIDI Nano keyboard for music creation for iPad, Android, And computers; the easiest way to make music with iPads & Android tablets, and Mac, Windows, or Linux computers. Ultra-... Read more
Amazon offers 15-inch 2.2GHz Retina MacBook P...
 Amazon.com has the 15″ 2.2GHz Retina MacBook Pro on sale for $1699 including free shipping. Their price is $300 off MSRP. Stock is limited, so act now if you’re interested. Read more
Holiday sales continue: MacBook Pros for up t...
 B&H Photo has new MacBook Pros on sale for up to $300 off MSRP as part of their Holiday pricing. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1699... Read more
Holiday sale: Mac minis available for up to $...
 B&H Photo has new 2014 Mac minis on sale for up to $80 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 1.4GHz Mac mini: $459 $40 off MSRP - 2.6GHz Mac mini: $629 $70 off... Read more
Google Search App For iOS Gets A Major Makeov...
Google has given iOS users an early Christmas present with a substantial update of it’s not-very-often-upgraded Google Search app. Google Search has been my go-to tool for Web searches since it was... Read more
ShopKeep Apple Pay And Chip Card Reader Avail...
ShopKeep, a cloud-based technology provider to more than 10,000 small business owners to manage retail shops and restaurants with iPads, has released its new Apple Pay and chip card reader. This... Read more
Holiday sale! 27-inch 5K iMac for $2299, save...
 B&H Photo has the 27″ 3.5GHz 5K iMac in stock today and on sale for $2299 including free shipping plus NY sales tax only. Their price is $200 off MSRP, and it’s the lowest price available for... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.