TweetFollow Us on Twitter

Anchored Variables
Volume Number:1
Issue Number:8
Column Tag:Programmer's Forum

"Modula-2 and Anchored Variables"

By Tom Taylor, Software Engineer, Modula-2 Corp., Provo, Ut.

"Modula-2 and Anchored Variables"

The programming language Modula-2 supports a little known but extremely powerful feature called "anchored variables." Anchored variables allow one to specify in the variable's declaration the absolute address of the variable and override the compiler's allocation method. This feature was intended to allow access to device registers on computers with memory mapped I/O (like on a PDP-11 where the original Modula-2 compiler was developed). It also allows the Modula-2 programmer on the Macintosh to access the Mac's operating system global variables very conveniently and cleanly.

In this article, we will look at two examples of anchored variable usage. In the first, we will try a small example to show that anchored variables really do work. In the second example, we'll actually develop a useful module based on anchored variables. These examples have been programed using MacModula-2 by Modula Corporation. However, with minor changes to the programs (probably the import statements), these programs should run using any Modula-2 system.

Anchored variables are "anchored" to a specific address by specifying that address in brackets immediately following the variable name in a variable declaration and before specifying the variable's type. For example:

VAR
     FinderName [2E0h]
     : ARRAY [0..16] OF CHAR;

This statement tells the compiler to allocate the variable FinderName starting at hex location 2E0h. Location 2E0h just happens to contain a Mac style string with the name of the current finder. The following program, will print out the name of the currently installed finder:

MODULE PrintFinder;
    FROM Terminal IMPORT
             ClearScreen, Write,
             Read, WriteLn, WriteString;

VAR
    FinderName [2e0h] :
             ARRAY [0..16] OF CHAR;
    i : CARDINAL;
    ch : CHAR;

BEGIN
    ClearScreen;
    WriteString("Current finder is: ");
    FOR i := 1 TO ORD(FinderName[0]) DO
          Write(FinderName[i]);
    END;
    WriteLn;
    Read(ch);
END PrintFinder.

Volume Control Block Queue

This next example is slightly more useful. It demonstrates the use of anchored variables in traversing the Volume Control Block queue and returning information about any disk (or volume) visible on the desktop (inserted in a drive or ejected) at the time your program was launched. This technique is used, for example, in the MacModula-2 compiler and linker when they search for imported files. This feature allows users of single drive Macs to build programs that are spred out over a number of disks by having those disks visible on the desktop at the time the compiler or linker is launched. The compiler or linker will search each disk found on the desktop by traversing the VCB queue until the desired import file is found or the end of the queue is reached.

The following example actually consists of three modules:

1) a Definition Module that defines the records, types, global variables, and procedures that are available for use by any program.

2) An Implementation Module that contains the code for the procedures defined in the Definition Module.

3) A simple Program Module that uses the procedures we have written and demonstrates some of the information available from the Volume Control Blocks.


DEFINITION MODULE VolumeTracer;

FROM MacSystemTypes IMPORT LongCard, Ptr;

EXPORT QUALIFIED VCB, VolumesOnLine,                                 
                                               GetVolumeInfo;

TYPE
        QElemPtr = POINTER TO VCB;

     VCB = RECORD
                          qLink: QElemPtr;
                                         (* next queue entry *)
                         qType:  INTEGER;
                                         (* not used *)
                        vcbFlags: INTEGER;
                                        (* bit 15=1 if dirty *)
                        vcbSigWord: INTEGER;
                                       (* always $D2D7 *)
                       vcbCrDate: LongCard;
                                      (* date volume initialized *)
                       vcbLsBkUp: LongCard;
                                     (* date of last backup *)
                      vcbAtrb: INTEGER;
                                    (* volume attributes *)
                      vcbNmFls: INTEGER;
                                    (* # of files in directory *)
                      vcbDirSt: INTEGER;
                                   (* directory's first block *)
                      vcbBlLn: INTEGER;
                                  (* length of file directory *)
                     vcbNmBlks: INTEGER;
                                  (* # of allocation blocks *)
                    vcbAlBlkSiz: LongCard;
                                  (* size of allocation blocks *)
                    vcbClpSiz: LongCard;
                                 (* # of bytes to allocate *)
                   vcbAlBlSt: INTEGER;
                                (* first block in block map *)
                   vcbNxtFNum: LongCard;
                                (* next unused file number *)
                   vcbFreeBks: INTEGER;
                                (* number of unused blocks *)
                   vcbVN: ARRAY [0..27] OF CHAR;
                               (* vol name Str255 format *)
                   vcbDrvNum: INTEGER;
                               (* drive number *)
                   vcbDRefNum: INTEGER;
                              (* driver reference number *)
                  vcbFSID: INTEGER;
                              (* file system identifier *)
                  vcbVRefNum: INTEGER;
                             (* volume reference number *)
                 vcbMAdr: Ptr;
                            (* location of block map *)
                 vcbBufAdr: Ptr;
                           (* location of volume buffer *)
                vcbMLen: INTEGER;
                           (* # of bytes in block map *)
               vcbDirIndex: INTEGER;
                          (* used internally *)
              vcbDirBlk: INTEGER;
                          (* used internally *)
END;

PROCEDURE VolumesOnLine(): CARDINAL;
                     (* Returns the maximum number of
                         volumes currently recognized by the
                         Mac operating system. *)

PROCEDURE GetVolumeInfo(VAR volume :
                  VCB; whichVol : CARDINAL);
                              (* Returns the current VCB block for
                                 volume "whichVol"  The variable
                               "whichVol" must be between 1 and
                                 the result of the procedure of
                                "VolumesOnLine()".  Otherwise,
                                  the "volume" info is undefined. *)

END VolumeTracer.
IMPLEMENTATION MODULE VolumeTracer;

TYPE
        QHdrPtr   = POINTER TO QHdr;
        QHdr        = RECORD
        qFlags : INTEGER;
                          (* queue flags *)
        qHead  : QElemPtr;
                          (* first queue entry *)
        qTail   : QElemPtr;
                          (* last  queue entry *)
END;

VAR
        VCBQHdr  [0356h] : QHdr;
                                           (* VCB queue header *)

PROCEDURE VolumesOnLine(): CARDINAL;
VAR
       ptr : QElemPtr;
       count : CARDINAL;
BEGIN
       ptr := VCBQHdr.qHead;
       count := 0;
       WHILE ptr # NIL DO
               INC(count);
               ptr := ptr^.qLink;
       END;
       RETURN count;
END VolumesOnLine;

PROCEDURE GetVolumeInfo(VAR volume :
           VCB; whichVol : CARDINAL);
VAR
        ptr : QElemPtr;
        count : CARDINAL;
BEGIN
        ptr := VCBQHdr.qHead;
        count := 0;
        WHILE (ptr # NIL) AND
               (count # whichVol) DO
        INC(count);
        IF count = whichVol THEN
                  volume := ptr^;
                  END;
        ptr := ptr^.qLink;
        END;
END GetVolumeInfo;

END VolumeTracer.

MODULE ListVolumes;
FROM VolumeTracer IMPORT
           VCB, VolumesOnLine, GetVolumeInfo;
FROM InOut IMPORT WriteString, ClearScreen,  WriteLn, WriteCard, WriteInt, 
Write, Read;
  
VAR
        i, maxVols : CARDINAL;
       vcb : VCB;
       ch : CHAR;
  
PROCEDURE PrintVolName;
VAR
       i : CARDINAL;
BEGIN
       FOR i := 1 TO ORD(vcb.vcbVN[0]) DO
              Write(vcb.vcbVN[i]);
              END;
       WriteLn;
END PrintVolName;

BEGIN
        ClearScreen;
       WriteString
                     ("Number of volumes on-line: ");
       maxVols := VolumesOnLine();
       WriteCard(maxVols,0);
       WriteLn; WriteLn;
       FOR i := 1 TO maxVols DO
              GetVolumeInfo(vcb,i);
              WriteString('Volume Name: ');
              PrintVolName;
             WriteString
                        ('Number of files in volume: ');
             WriteInt(vcb.vcbNmFls,0);
             WriteLn;
             WriteString('Drive Number: ');
             WriteInt(vcb.vcbDrvNum,0);
            WriteLn;
            WriteLn;
     END;
Read(ch);
END ListVolumes.

Figure 1. Typical VCB Queue

This is only one simple example of a typical use of anchored variables. Many times, Inside Macintosh will mention some variable that can be accessed from assembly language. The Window Manager, for example, mentions that putting a WindowPtr in the variable GhostWindow, will cause that window to never be the front window. In order to find the addresses of such variables, such as GhostWindow, one need simply paw through ToolEqu.TXT or SysEqu.TXT. Both of these source files are included with the MDS system by Apple. Not only have I used GhostWindow as an anchored variable in my applications, I have also used anchored variables to access the information set by the Finder when a program is launched.

By taking advantage of the power of anchored variables, you will be able to create very readable programs that use some of the Mac's low-level features.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

TinkerTool 5.4 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Tinderbox 6.3.1 - Store and organize you...
Tinderbox is a personal content management assistant. It stores your notes, ideas, and plans. It can help you organize and understand them. And Tinderbox helps you share ideas through Web journals... Read more
Parallels Desktop 10.2.2 - Run Windows a...
Parallels Desktop is simply the world's bestselling, top-rated, and most trusted solution for running Windows applications on your Mac. With Parallels Desktop for Mac, you can seamlessly run both... Read more
Adobe Premiere Pro CC 2015 9.0.1 - Digit...
Premiere Pro CC 2015 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Premiere Pro customer). Premiere Pro CS6 is still available for... Read more
Adobe After Effects CC 2015 13.5.1 - Cre...
After Effects CC 2015 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
Adobe Creative Cloud 2.2.0.129 - Access...
Adobe Creative Cloud costs $49.99/month (or less if you're a previous Creative Suite customer). Creative Suite 6 is still available for purchase (without a monthly plan) if you prefer. Introducing... Read more
Tower 2.2.3 - Version control with Git m...
Tower is a powerful Git client for OS X that makes using Git easy and more efficient. Users benefit from its elegant and comprehensive interface and a feature set that lets them enjoy the full power... Read more
Apple Java 2015-001 - For OS X 10.7, 10....
Apple Java for OS X 2015-001 installs the legacy Java 6 runtime for OS X 10.11 El Capitan, OS X 10.10 Yosemite, OS X 10.9 Mavericks, OS X 10.8 Mountain Lion, and OS X 10.7 Lion. This package is... Read more
Adobe Muse CC 2015 2015.0.1 - Design and...
Muse CC 2015 is available as part of Adobe Creative Cloud for as little as $14.99/month (or $9.99/month if you're a previous Muse customer). Muse CS6 is still available for purchase (without a... Read more
Adobe Illustrator CC 2015 19.1.0 - Profe...
Illustrator CC 2015 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Illustrator customer). Illustrator CS6 is still available for... Read more

Mazes of Karradash (Games)
Mazes of Karradash 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: The city of Karradash is under attack: the monsters of the Shadow Realms are emerging from the depths.No adventurer is... | Read more »
Battle Golf is the Newest Game from the...
Wrassling was a pretty weird - and equally great - little wressling game. Now the developers, Folmer Kelly and Colin Lane, have turned their attention to a different sport: golfing. This is gonna be weird. [Read more] | Read more »
Qbert Rebooted has the App Store Going...
The weird little orange... whatever... is back, mostly thanks to that movie which shall remain nameless (you know the one). But anyway it's been "rebooted" and now you can play the fancy-looking Qbert Rebooted on iOS devices. [Read more] | Read more »
Giant Monsters Run Amok in The Sandbox...
So The Sandbox has just hit version number 1.99987 (seriously), and it's added a lot more stuff. Just like every other update, really. [Read more] | Read more »
Fish Pond Park (Games)
Fish Pond Park 1.0.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.0 (iTunes) Description: Nurture an idyllic slice of tourist's heaven into the top nature spot of the nation, furnishing it with a variety of... | Read more »
Look after Baby Buddy on your Apple Watc...
Parigami Gold is the new premium version of the match three puzzler that includes Apple Watch support and all new content. You won't simply be sliding tiles around on your wrist, the Apple Watch companion app is an all new mini-game in itself. You'... | Read more »
Swallow all of your opponents as the big...
Eat all of the opposition and become the largest ball in Battle of Balls now available in the App Store and Google Play. Battle of Balls pits you against other opponents in real time and challenges you to eat more balls and grow larger than all of... | Read more »
PAC-MAN Championship Edition DX (Games)
PAC-MAN Championship Edition DX 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: It’s Your World. EAT IT! Get ready for more ghost chain gobbling and frantic action in PAC-MAN® CE-DX! The... | Read more »
incurve (Games)
incurve 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Get ready for 2 different gravities Goal is to hit as many white dots on your way up.When you're touching the screen, the dots have a... | Read more »
Crossy Road has its Own Merch Store Now....
Do you like Crossy Road? I mean do you really like Crossy Road? Well then you're in luck! Hipster Whale has opened up a Crossy Road store, so you can show off your fandom via official T-shirts. [Read more] | Read more »

Price Scanner via MacPrices.net

Sale! 13″ 1.6GHz/256GB MacBook Air for $1099,...
B&H Photo has the 13″ 1.6GHz/256GB MacBook Air on sale for $1099 including free shipping plus NY tax only. Their price is $100 off MSRP, and it’s the lowest price available for this model. Read more
iPad mini 4 To Be Upgraded To iPad Air 2 Spec...
There’s a certain inevitability about making Apple product predictions this time of year. Come September, we can pretty reliably count on the release of refreshed iPhones, along with the iOS 9... Read more
Apple restocks refurbished Mac minis for up t...
The Apple Store has restocked Apple Certified Refurbished 2014 Mac minis, with models available starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: - 1.4GHz... Read more
13-inch 2.5GHz MacBook Pro on sale for $899,...
Best Buy has the 13″ 2.5GHz MacBook Pro available for $899.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $200 off MSRP. Price is... Read more
21-inch 2.9GHz iMac on sale for $1299, save $...
Best Buy has the 21″ 2.9GHz iMac on sale today for $1299.99 on their online store. Choose free shipping or free local store pickup (if available). Their price is $200 off MSRP, and it’s the lowest... Read more
Free Image Sizer 1.3 for iOS Offers Photo Edi...
Xi’An, China based G-Power has announced the release of Image Sizer 1.3 for the iPhone, iPad, and iPod touch, an important update to their free photo editing app. Image Sizer’s collection of easy to... Read more
Sale! 13″ 1.6GHz/128GB MacBook Air for $899,...
B&H Photo has the 13″ 1.6GHz/128GB MacBook Air on sale for $899 including free shipping plus NY tax only. Their price is $100 off MSRP, and it’s the lowest price available for this model. Read more
13-inch Retina MacBook Pros on sale for $100...
Best Buy has 13-inch Retina MacBook Pros on sale for $100 off MSRP on their online store. Choose free shipping or free local store pickup (if available). Prices are for online orders only, in-store... Read more
Will BMW’s i3 Electric Vehicle Be The Automo...
The German-language business journal Manager Magazin’s Michael Freitag reports that Apple and the German performance/luxury automaker Bayerishe Motoren Werke (BMW) are back at far-reaching... Read more
Sale! $250 off 15-inch Retina MacBook Pro, $2...
B&H Photo has lowered their price for the 15″ 2.2GHz Retina MacBook Pro to $1749, or $250 off MSRP. Shipping is free, and B&H charges NY sales tax only. They have the 27″ 3.3GHz 5K iMac on... Read more

Jobs Board

*Apple* Customer Experience (ACE) Leader - A...
…management to deliver on business objectives Training partner store staff on Apple products, services, and merchandising guidelines Coaching partner store staff on Read more
Project Manager - *Apple* Pay Security - Ap...
**Job Summary** The Apple Pay Security team is seeking a highly organized, results-driven Project Manager to drive the development of Apple Pay Security. If you are Read more
*Apple* TV Product Design Internship (Spring...
…the mechanical design effort associated with creating world-class products with the Apple TV PD Group. Responsibilities will include working closely with manufacturing, Read more
*Apple* Watch SW Application Project Manager...
**Job Summary** The Apple Watch software team is looking for an Application Engineering Project Manager to work on new projects for Apple . The successful candidate 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.