TweetFollow Us on Twitter

XCMD Chat
Volume Number:4
Issue Number:11
Column Tag:HyperChat™

XCMD Cookbook

By Donald Koscheka, Apple Computer, Inc.

on HyperChat

A Nice Chat

While doing the Sunday crossword puzzle recently, I was hit with a very interesting thought. One of the clues in this particular puzzle called for a synonym for “small talk”. The answer was “chat”. This struck me as odd because in many ways HyperTalk is very much the preferred object oriented programming language for the Macintosh. One of the earliest object oriented languages, as you know, is called “SmallTalk”. By calling this column “HyperChat”, Fred makes a rather obscure reference to HyperTalk’s philosophical roots. Chat implies a looseness of speech, a vernacular that is easy to master. That is exactly what HyperTalk is - an easy to grasp interface to the Macintosh Toolbox. What HyperTalk lacks in power, it certainly makes up for in ease of understanding!

At the opposite end of the spectrum is Assembly language programming. This much maligned language conjures all sorts of anxieties in the minds of otherwise fearless programmers. Yet most professional programmers will admit that an understanding of assembly language can improve one’s ability to write efficient code in a higher-level language as well as better understand those mysterious looking dumps that one gets when suddenly presented with a memory dump from TMON or MACSBUG.

Worse yet, those of us who choose to work in higher level languages provide a great disservice to the assembly language programmer by not showing them how to interface with our languages. HyperTalk documentation is certainly sparse in describing how an assembly language programmer can write an XCMD in assembly.

Assembly Interface

I started writing this month’s column hoping to be of service to the assembly language programming community. I wasn’t very far along when I realized that this column offers a second service, at no extra charge to the reader.

The process of showing you how to interface to HyperCard in assembly language also introduces the Pascal and C programmer to debugging in Macsbug or TMON (Forth programmers take heart: Jörg Langkowski’s article in the December, 1987 issue of Mactutor provides you with the information you’ll need to write XCMDs; even if you don’t program in Forth-like languages, you should read Jörg’s column; his insights into the Macintosh are often astonishing).

The most important reason to code in Assembly language is that it provides a rich opportunity to improve on the more generic code generated by Pascal and C compilers. Consider the following string comparison in Pascal:

len: INTEGER;
Match : Boolean;
Str1  : Str255;
Str2  : Str255;

Str1 := ‘Hello World’;
Str2 := ‘GoodBye Cruel World’;


IF Length(Str1) <> Length( Str2 ) THEN 
 match := FALSE
ELSE
BEGIN
 Match := True;  { assume they will match}
 k := 1;

 While (k <= Length( Str1)) AND (match) DO
 IF Str1[k] <> Str2[k] THEN 
 match := False
 ELSE
 k := k + 1;
END;

Listing 1. String Comparisons in Pascal

String compares can be made more efficient than this in Pascal. I chose this example for its simplicity. In comparing strings, we must consider the end points, if the strings are not the same length, they are not equal. If you haven’t been programming in Assembly language, you may not see how this routine could be made more efficient. One measure of a program’s efficiency is a count of the number of bytes of instructions needed to execute the program. If you compile listing 1 and dump the object code, you would discover that the while loop requires 82 bytes of instructions to execute. Assembly language programmers know by instinct that 82 bytes is too much code to perform a single string compare.

An assembly language equivalent of the while loop in listing 1 can be shrunk by an order of magnitude as in listing 2. If you’re trying to speed up a particularly slow loop, a few bytes of well-written assembler might be just what the doctor ordered. But optimizing code is just one reason to familiarize yourself with assembly language. A more compelling reason for the high-level language is that an understanding of assembler will help you make sense of your TMON or MacsBug dumps.

 ; A0, A1 point to the 2 strings
 Move.b (A0)+, D1; get the length of string 1
 Move.b (A1)+, D2; get the length of string 2
 Cmp.b  D1,D2  ; are they the same length?
 Beq  CompareChars ; yes, go ahead and compare them
 Move #0, D0; set the result to false
 Bra  Done; and exit

CompareChars     ; compare Str1<->Str2
 Cmp.b  (A0)+,(A1)+; do the characters match?      
 Beq  Done; yes, see if we’re at end of string
 Dbra D1, CompareChars
 Move #1, D0; they match, set the result true

DONE  sne D0       ; Result is true if strings match,          
 false otherwise

Listing 2. String Compare in Assembler

Entering XCMDs

The real trick to writing an XCMD in assembly language is understanding that HyperCard expects to see an XCMD that was generated by the Pascal compiler. This implies that parameters are pushed on the stack from left to right and that subroutines are responsible for removing the pushed parameters from the stack. XCMDs receive only one parameter so the push order isn’t important. What is important is remembering to remove that parameter from the stack before returning to HyperCard. Listing 3 is the assembly language interface for XCMDs. The fields in the paramBlock record are identical to the Paramblock record in Pascal or C.

On entry to a subroutine in assembly language, the last item on the stack is the return address of the calling routine. Normally, when we are done with the subroutine, an rts (return from subroutine) instruction will pop this return address off the stack and into the Program Counter resuming execution at the instruction pointed to by that location. This won’t do for Pascal routines since convention dictates that we also remove the parameters from the stack. One way to do this would be to pop the return address into a temporary register, say D0, remove the parameters from the stack by adding the size of the parameters to the stack pointer and then pushing the contents of D0 onto the stack and executing an RTS. A more efficient method exists: Pop the return address into an address register, say A0. Unbias the stack parameters by adding 4 to the stack (the size in bytes of the parameter block pointer). Finally, since register A0 contains the return address, execute the Jmp Indirect instruction on A0: Jmp (A0).

Globals in XCMDs

If your XCMD requires local variables, you’re going to need a place to store them. Assembly language XCMDs bear the same restriction placed on high-level languages: you don’t have access to the globals. A simple solution would be to allocate a handle large enough to store all your globals and keep that handle available in an address register. This works fine if the data is very static but not very well otherwise since you could easily run out of registers while manipulating even a small number of handles. Pascal and C use a more efficient approach, one that you’ve already seen if you’ve done any debugging in TMON or Macsbug.

On entry to the subroutine, we know that the stack pointer, register A7, already points to the next available space on the stack (the bottom of the stack). Why don’t we allocate our data on the stack by pointing an address register, say A6, to the bottom of the stack, subtracting the number of bytes that we need for our locals from A7 effectively growing the stack by the amount we need (the stack grows downward). Now A6 points to our local variables and A7 continues its role as stack pointer below our local stack frame (figure 1 ).

The process of creating a stack frame can be performed with one assembly language instruction: link. Used judiciously, the link instruction buys us a whole lot more: it saves the old value of the address register and gives a reference point to the parameters passed by the caller.

By executing link A6,#LocalSize, before doing anything else, we set up up a stack frame at the stack bottom. If stacksize were set to zero, we wouldn’t actually allocate any stack space for globals, but the instruction would still provide a payback. Because nothing else was put on the stack between the call to this routine and our link instruction, A6 also doubles as a pointer to our parameters! First, 0(A6) contains the previous value of A6 (can you think of anything this might be useful for?), next 4(A6) is the return address, and 8(A6) is the paramblock pointer passed to us by HyperCard. By putting 8(A6) into A3, we save the pointer to our parameters in an address register.

The offsets defined in the parameter block equates now become offsets off A3 for each field. The first field in the record is paramCount(A3) the count of the number of parameters in the params array. Accessing the handles in the params array poses another question. The first handle in the array is at params(A3). Getting to the other handles in the params array requires a straightforward application of arithmetic. By definition, handles occupy 4 bytes in the Mac. Any array element, i, is at offset (i-1)*4 byte in the array. We subtract 1 from the element number because array indices count from 0 not from 1. If we put the array index into D0, subtract 1 and multiply by 4 we have the offset from the beginning of the array. All we need to do is add this number to params[A3] and we have the handle. The 68000 has just an instruction: indexed addressing with offset. Here is how this instruction can be used to get the third parameter in the list:

Moveq     #3, D0   ; Access the third parameter in the list 
Sub.w     #1, D0   ; arrays count from 0, not 1
Asl.w     #2, D0   ; shift left by 2 is same as multiply by 4! 
Move.l    params(A3,D0.w), A0 ; A0 now holds the third handle 

Since stack frames are oriented from the highest memory location they occupy to the lowest, local variables are always referred to by negative offsets. In Pascal, the following declaration

VAR
myInt   : INTEGER;
myLong  : LongINt;
myRect  : Rect;

would have the following counterpart in assembly language:

myInt        EQU -4        ; locals start at offset -4 in the frame
myLong  EQU myInt-2; Integers are 2 bytes
myRect      EQU myLong-4  ; longs are 4 bytes
LocalSize EQU myRect-8  ; rectangles are 8 bytes.
LocalSize is equal to 14 bytes.  The stack frame is set up to read:
LINK    A6,#LocalSize; create the local variable pool.
Move.w  (A0),D0

If you’re having a bit of difficulty with this material, try writing a simple XCMD in Pascal or C and disassembling it in TMON or Macsbug. You can do this by invoking the Debugger call as the first statement in you XCMD.

Exiting the XCMD

Leaving the XCMD requires a little house cleaning. First, we restore the registers that were saved onto the stack. Next, we execute an unlink (UNLK) instruction to undo the last Link instruction. At this point, the stack looks just like it did when we entered the XCMD. More importantly (A7) is the return address of the calling routine. Popping this value into A0 allows us to save the return address in a safe place so that we can remove the parameters from the stack. We know how much space the parameters take. The stack contains only one parameter, XCmdBlkPtr, whose length is four bytes. Adding 4 to A7 shrinks the stack to the right size. Now all that’s left is to Jmp to the location pointed to in A0 and we’re done!

Conclusion

If you’re already programming in assembly language, this article is enough to get you started with XCMDs, especially if you’re not familiar with Pascal calling conventions. If you’re a Pascal or C programmer, the above discussion should help you to debug your code by explaining some of the assembly code you may have been looking at in TMON or Macsbug. In any case, understanding how compilers take your statements and convert them into machine executable code is a great way to learn more about the inner-workings of your programs and those seemingly mysterious bugs that just are not obvious in your Pascal or C source code. Hopefully, I’ve been able to fill some gaps in your debugging skills with this information. If the information in this article was useful, please let me know, I’ll be happy to offer more information on assembly language and debugging techniques.


;******************************
;* File: SimpleXCMD.a*
;* *
;* A simple XCMD written in *
;* Assembly language to show*
;* how XCMDs are written in *
;* assembler...  *
;* -------------------------- *
;* By:  Donald Koscheka   *
;* Date:16 July, 1988*
;******************************

;******************************
;* Build Sequence
;*
;* asm -w SimpleXCMD.a
;* link  -rt XCMD=1200 -sn Main=SimpleXCMD
;* SimpleXCMD.a.o
;* -o “YourStackName”
;******************************

;***  ParamBlock structure***
paramCountEQU    0   
params  EQU paramCount+2
returnValue EQU  params+( 16 * 4 )     
passFlagEQU returnValue + 4 
entryPointEQU    passFlag + 2   
request EQU entryPoint + 4  
result  EQU request + 2
inArgs  EQU result + 2
outArgs EQU inArgs + ( 8 * 4 )
pBlkSizeEQU outArgs + (4 * 4 )

;*** ------------------ ***
;*** THE LOCAL VARIABLES  ***
;*** (WILL GO ON STACK)   ***
;*** Note that the stack frame***
;*** counts backwards from 0***
;*** so that the value of ***
;*** LocalSiz will always be  ***
;*** negative    ***

LOCALS  EQU 0
LASTLOCAL EQU    LOCALS
LOCALSIZEQU LASTLOCAL
;*** ------------------ ***


SimpleXCMDMAIN   EXPORT
;******************************
;* In:
;*
;* 0(A7) == Return Address
;* 4(A7) == ParamBlockPtr
;* 
;* Link A6 to create a stackframe
;* that points to these vars.
;******************************

 ;*** Set Up Stack Frame
 LINK   A6,#LOCALSIZ ; Size of the local frame
 MOVEM.LD5-D7/A3/A4,-(SP) ; save some registers
 
 ;*** Get Pointer to paramblock
 MOVE.L 8(A6), A3; Point to parameters
 CLR.L  returnValue(A3) ; set to “empty”
 TST.W  paramCount(A3)  ; Any Parameters?
 BEQ    DONE; no, just return
 
   ;*** Insert your code here.  If your XCMD doesn’t take any 
 ;*** parameters eliminate the atest on paramcount ...
 
DONE    ;*** Prepare for Return to HyperCard
 MOVEM.L(SP)+,D5-D7/A3/A4 ; restore registers
 UNLK   A6; wipe out stack frame
 MOVE.L (A7)+, A0; get the return address
 ADD.L  #4, A7   ; unbias the stack
 JMP    (A0); return to HyperCard
 END

Listing 3. SimpleXCMD in Assembly Language

end HyperChat
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.