Jump to content

Assembly Language Programming for OS/2 Presentation Manager: Difference between revisions

From EDM2
m Category
Ak120 (talk | contribs)
No edit summary
Line 1: Line 1:
Original Work by [[Micho Durdevich]]
Original Work by [[Micho Durdevich]]


<h2>Introduction</h2>
== Introduction ==
The aim of this article is to sketch a methodology for developing nice OS/2 Presentation Manager applications in assembly language. Our recommended tools are Watcom assembler (WASM), linker (WLINK) and IBM resource compiler RC. Of course, this means that Watcom environment and IBM Developer Toolkit/2 should be installed.


<p>The aim of this article is to sketch a methodology for developing nice OS/2 Presentation Manager
It is truly a pleasure to work with a well-documented, simple and elegant API set of the OS/2  
applications in assembly language. Our recommended tools are Watcom assembler (WASM), linker (WLINK) and
IBM resource compiler RC. Of
course, this means that Watcom environment and IBM Developer Toolkit/2 should be
installed.</p>
 
<p>It is truly a pleasure to work with a well-documented, simple and elegant API set of the OS/2  
operating system. No matter in which programming language we work, it is anyway a good idea to  
operating system. No matter in which programming language we work, it is anyway a good idea to  
check how a given programming scheme looks in assembly. Hence, we propose the following <i>criterion  
check how a given programming scheme looks in assembly. Hence, we propose the following ''criterion of higher elegance'':
of higher elegance</i>: </p>


<p><b>Assembly Test.</b> A given execution environment and programming model are considered  
'''Assembly Test.''' A given execution environment and programming model are considered ''q-acceptable'', if it is possible to perform clean and nice assembly language programming of all tasks, without introducing some extra complications (beyond those that are in the nature of assembly paradigm).
<i>q-acceptable</i>, iff it is possible to perform clean and nice assembly  
language programming of all tasks, without introducing some extra complications  
(beyond those that are in the nature of assembly paradigm).</p>


<h2>Calling OS/2 Functions in Assembly</h2>
== Calling OS/2 Functions in Assembly ==


<p>Let us consider an arbitrary 32-bit OS/2 API, say OS2SampleFunction, and suppose that it  
Let us consider an arbitrary 32-bit OS/2 API, say OS2SampleFunction, and suppose that it takes n arguments, say {arg_1, ... , arg_n}. Then the assembly language call of this routine looks like this:  
takes n arguments, say {arg_1, ... , arg_n}. Then the assembly language call of this routine  
looks like this:  
<pre>    push dword arg_n                    ; Arguments are push-ed in the reverse
<pre>    push dword arg_n                    ; Arguments are push-ed in the reverse
         ...                              ; order.  
         ...                              ; order.  
Line 31: Line 20:
     add        esp, 0xN                ; Clean up the stack space, here N=4*n.  
     add        esp, 0xN                ; Clean up the stack space, here N=4*n.  
</pre>   
</pre>   
<div>Normally, the return code of such a function is stored in the eax-register. In the ideal situation,
only registers that have to do something with return values of functions should be allowed to
change across the API calls. Unfortunately, at the moment not all OS/2 APIs satisfy this property
(implying, strictly speaking, that the API system fails to
satisfy completely our Test!) so one should be very careful
when storing something in registers and then making an external call.</div></p>


Normally, the return code of such a function is stored in the eax-register. In the ideal situation, only registers that have to do something with return values of functions should be allowed to change across the API calls. Unfortunately, at the moment not all OS/2 APIs satisfy this property (implying, strictly speaking, that the API system fails to satisfy completely our Test!) so one should be very careful when storing something in registers and then making an external call.


<h2>Creating a Standard Window</h2>
== Creating a Standard Window ==


<p>Here is a piece of the assembly code, responsible for the creation of a standard window.  
Here is a piece of the assembly code, responsible for the creation of a standard window. The main functions are WinRegisterClass and WinCreateStdWindow. The interface to this window is carried out with the help of a ''window routine'', which is specified as an argument in the call to WinRegisterClass.
The main functions are WinRegisterClass and WinCreateStdWindow. The interface  
to this window is carried out with the help of a <i>window routine</i>, which is specified as an  
argument in the call to WinRegisterClass.</p>
<pre>    push      0x00000000                ; @ first initialize the interface!
<pre>    push      0x00000000                ; @ first initialize the interface!
     call      WinInitialize  
     call      WinInitialize  
Line 55: Line 36:
     add      esp, 0x00000008            ; its handle.  
     add      esp, 0x00000008            ; its handle.  
     mov      hmq, eax
     mov      hmq, eax


     push      0x00000000
     push      0x00000000
Line 85: Line 65:
</pre>
</pre>


<p>The above WinCreateStdWindow procedure actually does the job of two separate WinCreateWindow  
The above WinCreateStdWindow procedure actually does the job of two separate WinCreateWindow  
calls: It creates the frame window (eax holds the handle to it) and it also creates  
calls: It creates the frame window (eax holds the handle to it) and it also creates the client window as a child of the frame (hwndClient is filled with the client window handle, after a succesful completion of the function). In the case of more subtle windows (for example if we want to mix WPS stuff with PM functions) it is necessary to use two separate WinCreateWindow calls in order to have a full control over both frame and client windows.  
the client window as a child of the frame (hwndClient is filled with the client window
This is discussed in our WPS programming article.
handle, after a succesful completion of the function). In the case of more subtle windows
(for example if we want to mix WPS stuff with PM functions) it is necessary to use two  
separate WinCreateWindow calls in order to have a full control over both frame and client windows.  
This is discussed in our WPS programming article. </p>


<p>The window dispatch loop looks as follows:</p>
The window dispatch loop looks as follows:
<pre>@loopdispatch:
<pre>@loopdispatch:


Line 129: Line 105:


</pre>
</pre>
<p>The dispatched messages are then handled by the main (or another, associated) window procedure.</p>


<h2>Example: Quantum Rectangles</h2>
The dispatched messages are then handled by the main (or another, associated) window procedure.
 
== Example: Quantum Rectangles ==


<h3>Program Description</h3>
=== Program Description ===


<p>This sample program creates a simple PM window, and paints rectangular areas of the window with  
This sample program creates a simple PM window, and paints rectangular areas of the window with the help of WinInvalidateRect function. The colors of the rectangles and their sizes are randomly chosen, using a simple but very powerful random number generator. As an illustration for coding a pull-down menus, we introduce a control dialog, allowing us to specify the go/stop state, and also the speed of these fluctuating rectangles.
the help of WinInvalidateRect function. The colors of the rectangles and their  
sizes are randomly chosen, using a simple but very powerful random number  
generator. As an illustration for coding a pull-down menus, we introduce a  
control dialog, allowing us to specify the go/stop state, and also the speed of  
these fluctuating rectangles.</p>


<p>In developing this sample we were principally motivated by elegant random-rectangles samples  
In developing this sample we were principally motivated by elegant random-rectangles samples  
for Windows, by Adam Stanislav&nbsp;[2].</p>
for Windows, by Adam Stanislav [2].


<h3>Painter Thread</h3>
===Painter Thread===


<p>In order to perform paintings of rectangles, we create a cyclic thread.</p>
In order to perform paintings of rectangles, we create a cyclic thread.
<pre>    push      0x00001000                ; The thread stack size, one page here!  
<pre>    push      0x00001000                ; The thread stack size, one page here!  
     push      0                          ; Thread flags                       
     push      0                          ; Thread flags                       
Line 156: Line 128:
     add      esp, 0x00000014            ; Clean up the stack                                     
     add      esp, 0x00000014            ; Clean up the stack                                     
</pre>
</pre>
<p>The thread procedure cyclic_painter is simply invalidating randomly chosen rectangles of the window
paint area. This in its turn, causes the corresponding WM_PAINT message to be sent to the main
window procedure, where the actual paintings occur. A simpler way to perform rectangle drawings
in given intervals of time is to create a timer, and then put slightly modified cyclic_painter code
within WM_TIMER section of the main window procedure. This is how we proceed in the WPS version of
quantum rectangles.</p>


<h3>Random Number Generator</h3>
The thread procedure cyclic_painter is simply invalidating randomly chosen rectangles of the window paint area. This in its turn, causes the corresponding WM_PAINT message to be sent to the main window procedure, where the actual paintings occur. A simpler way to perform rectangle drawings in given intervals of time is to create a timer, and then put slightly modified cyclic_painter code within WM_TIMER section of the main window procedure. This is how we proceed in the WPS version of quantum rectangles.


<p>As we already mentioned, our program has a built-in random number generator.  
===Random Number Generator===
As we already mentioned, our program has a built-in random number generator.  
It is interesting, and also of a separate value, to describe here a beautiful   
It is interesting, and also of a separate value, to describe here a beautiful   
mathematics behind this simple subroutine:</p>
mathematics behind this simple subroutine:


<pre>    mov      eax, 0x4019CF16
<pre>    mov      eax, 0x4019CF16
Line 177: Line 144:
</pre>
</pre>


<p>The code above is an example of a so-called multiply-with-carry (MWC) random  
The code above is an example of a so-called multiply-with-carry (MWC) random number generator. We refer to [5] for more detailed explanations, and reviews of various types of random number generators.
number generator. We refer to [5] for more detailed explanations, and reviews of various types  
of random number generators. </p>


<p>What happens here is that we apply iteratively the following transformation T:  
What happens here is that we apply iteratively the following transformation T:  
<center>T{2<sup>32</sup>x+y} = Ay+x</center><div>where x, y and A are 32-bit  
<center>T{2<sup>32</sup>x+y} = Ay+x</center><div>where x, y and A are 32-bit  
integers (A=0x4019CF16 in the code above).</div></p>
integers (A=0x4019CF16 in the code above).</div>


<p>More generally, we can consider transformations of the form:
More generally, we can consider transformations of the form:
<center>T{Bx+y} = Ay+x</center><div>
<center>T{Bx+y} = Ay+x</center><div>
where A,B are natural numbers, A &lt; B, and (x,y) take values from the set <b>S</b> defined as the  
where A,B are natural numbers, A &lt; B, and (x,y) take values from the set <b>S</b> defined as the  
Line 191: Line 156:
&quot;cornerless&quot; product</div>
&quot;cornerless&quot; product</div>
<center><b>S</b>={0,...,A-1}x{0,...,B-1}\{(A-1, B-1)}</center><div>
<center><b>S</b>={0,...,A-1}x{0,...,B-1}\{(A-1, B-1)}</center><div>
Let us observe that all these pairs can naturally be viewed as 2-digit numbers in the system with base B.</div></p>  
Let us observe that all these pairs can naturally be viewed as 2-digit numbers in the system with base B.</div>


<p>Let us now define M=AB-1, and let <b>R</b>[M] be the <i>residue ring</i> modulo M.  
Let us now define M=AB-1, and let <b>R</b>[M] be the ''residue ring'' modulo M.  
Clearly, we can make a natural identification  
Clearly, we can make a natural identification <b>S</b>=<b>R</b>[M] and in what follows we will not really distinguish between these two objects.  
<b>S</b>=<b>R</b>[M] and in what follows we will not really distinguish between these two objects.  
Let us denote by <b>G</b>[M] the group of invertible elements of the ring <b>R</b>[M].  
Let us denote by <b>G</b>[M] the group of invertible elements of the ring <b>R</b>[M].  
These elements are represented by residues relatively prime with M. As a simple  
These elements are represented by residues relatively prime with M. As a simple  
example, if M=8 then <b>R</b>[M] has 4 invertible elements: 1, 3, 5, 7 and the  
example, if M=8 then <b>R</b>[M] has 4 invertible elements: 1, 3, 5, 7 and the  
multiplication table for <b>G</b>[M] looks as follows:</p>
multiplication table for <b>G</b>[M] looks as follows:


<center>
<center>
<table border="1" cellspacing="3" id="tabla-4">
<table border="1" cellspacing="3" id="tabla-4">
 
   <tr>
   <tr>
     <td>1</td><td>3</td><td>5</td><td>7</td>
     <td>1</td><td>3</td><td>5</td><td>7</td>
Line 209: Line 172:
   <tr>
   <tr>
     <td>3</td><td>1</td><td>7</td><td>5</td>
     <td>3</td><td>1</td><td>7</td><td>5</td>
   </tr>
   </tr>
   <td>5</td><td>7</td><td>1</td><td>3</td>
   <td>5</td><td>7</td><td>1</td><td>3</td>
Line 215: Line 177:
   <tr>
   <tr>
   <td>7</td><td>5</td><td>3</td><td>1</td>
   <td>7</td><td>5</td><td>3</td><td>1</td>
   </tr>
   </tr>
</table>
</table>
</center>
</center>
<p>It is nice--we obtained a famous Klein 4-element group :) </p>


<p>Returning to the general discussion, let us view <b>S</b> as a  
It is nice - we obtained a famous Klein 4-element group :)
left <b>R</b>[M]-module, by means of the left regular
representation. A simple but very important observation is that
the action of the random-operator T is <i>nothing but the left module
multiplication</i> by A. Within the ring <b>R</b>[M] the numbers A and B are


<i>mutually inverse</i>, in other words A=B<sup>-1</sup> in <b>R</b>[M].  
Returning to the general discussion, let us view <b>S</b> as a left <b>R</b>[M]-module, by means of the left regular representation. A simple but very important observation is that
Let <b>C</b> be the cyclic  
the action of the random-operator T is ''nothing but the left module multiplication'' by A. Within the ring <b>R</b>[M] the numbers A and B are ''mutually inverse'', in other words A=B<sup>-1</sup> in <b>R</b>[M].  
subgroup of <b>G</b>[M] generated by A. It is of principal interest to answer  
Let <b>C</b> be the cyclic subgroup of <b>G</b>[M] generated by A. It is of principal interest to answer how <b>S</b> decomposes into irreducible components (also coinciding with orbits of the action of <b>C</b>) with respect to the action of <b>C</b>. These components correspond to our pseudorandom sequences.
how <b>S</b> decomposes into irreducible components (also coinciding with  
orbits of the action of <b>C</b>) with respect to the action  
of <b>C</b>. These components correspond to our pseudorandom sequences.</p>


<p>In order to figure out the size of a given orbit, let us consider an arbitrary  
In order to figure out the size of a given orbit, let us consider an arbitrary element F in <b>S</b>. Let D be the maximal common denominator between F and M. Let <b>S</b><sub>F</sub> be the (cyclic) submodule of <b>S</b> generated by F. It is easy to see that a natural identification <center><b>S</b><sub>F</sub> = <b>R</b>[M/D]</center>
element F in <b>S</b>. Let D be the maximal common denominator between F and M. Let
<b>S</b><sub>F</sub> be the (cyclic) submodule of <b>S</b> generated by F. It is  
easy to see that a natural identification
<center><b>S</b><sub>F</sub> = <b>R</b>[M/D]</center>


<div>holds. This is because</div>  
<div>holds. This is because</div>  
<center><b>R</b>[M]/<b>I</b>[D] = <b>R</b>[M/D]</center>
<center><b>R</b>[M]/<b>I</b>[D] = <b>R</b>[M/D]</center>
<div>where <b>I</b>[D] is the ideal of <b>R</b>[M] generated by M/D. The ideal  
<div>where <b>I</b>[D] is the ideal of <b>R</b>[M] generated by M/D. The ideal  
<b>I</b>[D] consists exactly of elements that annihilate F.</div></p>
<b>I</b>[D] consists exactly of elements that annihilate F.</div>


<p>It follows that the size of the orbit {<b>C</b>F} is the degree of A in the factor-ring
It follows that the size of the orbit {<b>C</b>F} is the degree of A in the factor-ring
<b>R</b>[M/D]. So, in general, the structure of the orbits is considerably complex. For  
<b>R</b>[M/D]. So, in general, the structure of the orbits is considerably complex. For  
example, if M=32, A=3, B=11 we have  
example, if M=32, A=3, B=11 we have  
Line 251: Line 200:
<b>C</b>=<b>{</b>1, 3, 9, 11, 17, 19, 25, 27<b>}</b>  
<b>C</b>=<b>{</b>1, 3, 9, 11, 17, 19, 25, 27<b>}</b>  
</center>
</center>
<div>and <b>S</b> splits into the following orbits:</div> </p>
<div>and <b>S</b> splits into the following orbits:</div>


<p align="center">
<p align="center">
Line 264: Line 213:
<b>{</b>2, 6, 18, 22<b>}</b> <b>{</b>10, 14, 26, 30<b>}</b>
<b>{</b>2, 6, 18, 22<b>}</b> <b>{</b>10, 14, 26, 30<b>}</b>


</center></p><p>
</center></p>
From the point of view of random number sequences, we are interested only in  
From the point of view of random number sequences, we are interested only in the ''low digits'' of elements in each orbit. Here digits are understood in terms of the base-B number system. These digits form the actual pseudorandom sequence (during a cycle, a given digit will in general repeat many times, while the full numbers in the orbit are, by nature of things, always different). A very important question is whether the resulting pseudorandom sequence is sufficient to reconstruct the whole orbit. Let us denote by (r<sub>i</sub>) the sequence of low digits associated to the sequence of orbit elements
the <i>low digits</i> of elements in each orbit. Here digits are understood in terms  
of the base-B number system. These digits form the actual pseudorandom sequence (during a cycle, a  
given digit will in general repeat many times, while the full numbers in the orbit are, by  
nature of things, always different). A very important question is whether the resulting  
pseudorandom sequence is sufficient to reconstruct the whole orbit. Let us denote by (r<sub>i</sub>)
the sequence of low digits associated to the sequence of orbit elements
<center>z<sub>i</sub>=B<sup>i</sup>z,&nbsp;&nbsp;&nbsp&nbsp;z=z<sub>0</sub>.</center>
<center>z<sub>i</sub>=B<sup>i</sup>z,&nbsp;&nbsp;&nbsp&nbsp;z=z<sub>0</sub>.</center>
<div>The above equality, of course, is written in <b>R</b>[M]. In terms of standard integers (in <b>Z</b>)  
<div>The above equality, of course, is written in <b>R</b>[M]. In terms of standard integers (in <b>Z</b>) it gives</div>  
it gives</div>  


<center>z<sub>i+1</sub>=Bz<sub>i</sub>+r<sub>i+1</sub>(1-AB).</center>
<center>z<sub>i+1</sub>=Bz<sub>i</sub>+r<sub>i+1</sub>(1-AB).</center>
Line 280: Line 222:
<div>Therefore, knowing the sequence (r<sub>i</sub>) and the initial element z<sub>0</sub>  
<div>Therefore, knowing the sequence (r<sub>i</sub>) and the initial element z<sub>0</sub>  
of our orbit, we can reconstruct the whole orbit. The above recurrent formula also  
of our orbit, we can reconstruct the whole orbit. The above recurrent formula also  
implies that the period of the pseudorandom  
implies that the period of the pseudorandom sequence is always equal to the length of the corresponding orbit. Indeed, if l<sub>i</sub> are high digits of z<sub>i</sub> then we have</div>
sequence is always equal to the length of the corresponding orbit. Indeed, if l<sub>i</sub> are high
digits of z<sub>i</sub> then we have</div>


<center>
<center>
Line 292: Line 232:
</p>
</p>


<p>Now, if M is a <i>prime</i>, then the theory simplifies. Every non-zero F will be invertible  
<p>Now, if M is a <i>prime</i>, then the theory simplifies. Every non-zero F will be invertible (as <b>R</b>[M] is a field iff M is prime) and all non-trivial orbits will have  
(as <b>R</b>[M] is a field iff M is prime) and all non-trivial orbits will have  
the same number of elements--the degree L of A in <b>R</b>[M] (number of elements in  
the same number of elements--the degree L of A in <b>R</b>[M] (number of elements in  
<b>C</b>). According to the Lagrange theorem, the number L is a divisor of the  
<b>C</b>). According to the Lagrange theorem, the number L is a divisor of the  
Line 313: Line 252:
random_var[4] variables.</div></p>  
random_var[4] variables.</div></p>  
   
   
=== How To Compile ===


<h3>How To Compile</h3>
The creation of the executable file is quite simple. Just 3 steps. Assembling, linking  
 
<p>The creation of the executable file is quite simple. Just 3 steps. Assembling, linking  
and resource-compiling. Explicitly,  
and resource-compiling. Explicitly,  


Line 324: Line 262:
</pre>
</pre>


<div>Here, the linking info is stored in the file qhello.lnk and the resource info is within qhello.rc  
Here, the linking info is stored in the file qhello.lnk and the resource info is within hello.rc file. Don't forget to check the size of the program (take into account the pre-compiled icon size, too) :)
file. Don't forget to check the size of the program (take into account the pre-compiled icon  
size, too) :)</div></p>


<p> The binary with the full source code can be found at our download area. </p>
The binary with the full source code can be found at our download area.
<h2>Concluding Remarks</h2>


<p>As we have seen, it is conceptually very simple to code OS/2 PM in assembly language.  
==Concluding Remarks==
However it does not mean that assembly programming is easy or trivial. True simplicity  
As we have seen, it is conceptually very simple to code OS/2 PM in assembly language.  
is always connected with something non-trivial at a deeper level (here it is a good time to  
However it does not mean that assembly programming is easy or trivial. True simplicity is always connected with something non-trivial at a deeper level (here it is a good time to  
recall of the true simplicity of quantum mechanics, as revealed for example in Feynman's book [6]).  
recall of the true simplicity of quantum mechanics, as revealed for example in Feynman's book [6]).  
It is logical to expect that a language with a higher expressive power requires a higher-level  
It is logical to expect that a language with a higher expressive power requires a higher-level  
knowledge in order to properly use it. And here, in our context, such a knowledge means knowing the  
knowledge in order to properly use it. And here, in our context, such a knowledge means knowing the internals of the machine, and understanding what is really happening... Invaluable  
internals of the machine, and understanding what is really happening... Invaluable  
scientific aspect of programming directly in the language of Machine.
scientific aspect of programming directly in the language of Machine.</p>
 
<h2>References</h2>
<p> <b>[1]</b> [http://webster.cs.ucr.edu The Art of Assembly Language Programming and HLA]. By Randall Hyde. An extensive and beautiful assembly language tutorial + related topics. </p>
 
<p> <b>[2]</b> [http://www.geocities.com/SiliconValley/Heights/7394 Whiz Kid Technomagic]. By Adam Stanislav. A wealth of assembly language sample programs, for Windows. Includes the mentioned random rectangles program for Windows.</p>
 
<p> <b>[3]</b> [http://www.int80h.org FreeBSD Programming in Assembly  Language], by Adam Stanislav.</p>
 
<p> <b>[4]</b> [http://grc.com/smgassembly.htm Assembly Language Windows
Applications]. By Steve Gibson. Highly recommended source of valuable informations and links regarding assembly language programming for Windows. Includes a Small Is Beautiful Starter Kit.</p>
 
<p> <b>[5]</b> [http://stat.fsu.edu/~geo/diehard.html Random Number CDROM],
by George Marsaglia. A package consisting of truly random bits, selected random number generator topics, and a software system to test true randomness.</p>


<p> <b>[6]</b> Feynman's Lectures in Physics: By Richard Feynman. Books 8/9-Quantum Mechanics.</p>
==References==
# [http://webster.cs.ucr.edu The Art of Assembly Language Programming and HLA]. By Randall Hyde. An extensive and beautiful assembly language tutorial + related topics.
# [http://www.geocities.com/SiliconValley/Heights/7394 Whiz Kid Technomagic]. By Adam Stanislav. A wealth of assembly language sample programs, for Windows. Includes the mentioned random rectangles program for Windows.
# [http://www.int80h.org FreeBSD Programming in Assembly  Language], by Adam Stanislav.
# [http://grc.com/smgassembly.htm Assembly Language Windows Applications]. By Steve Gibson. Highly recommended source of valuable informations and links regarding assembly language programming for Windows. Includes a Small Is Beautiful Starter Kit.
# [http://stat.fsu.edu/~geo/diehard.html Random Number CDROM], by George Marsaglia. A package consisting of truly random bits, selected random number generator topics, and a software system to test true randomness.
# Feynman's Lectures in Physics: By Richard Feynman. Books 8/9-Quantum Mechanics.


[[Category: PM Articles]]
[[Category: PM Articles]]

Revision as of 01:47, 12 March 2016

Original Work by Micho Durdevich

Introduction

The aim of this article is to sketch a methodology for developing nice OS/2 Presentation Manager applications in assembly language. Our recommended tools are Watcom assembler (WASM), linker (WLINK) and IBM resource compiler RC. Of course, this means that Watcom environment and IBM Developer Toolkit/2 should be installed.

It is truly a pleasure to work with a well-documented, simple and elegant API set of the OS/2 operating system. No matter in which programming language we work, it is anyway a good idea to check how a given programming scheme looks in assembly. Hence, we propose the following criterion of higher elegance:

Assembly Test. A given execution environment and programming model are considered q-acceptable, if it is possible to perform clean and nice assembly language programming of all tasks, without introducing some extra complications (beyond those that are in the nature of assembly paradigm).

Calling OS/2 Functions in Assembly

Let us consider an arbitrary 32-bit OS/2 API, say OS2SampleFunction, and suppose that it takes n arguments, say {arg_1, ... , arg_n}. Then the assembly language call of this routine looks like this:

     push dword arg_n                    ; Arguments are push-ed in the reverse
        ...                              ; order. 
        ...
     push dword arg_1
     call       OS2SampleFunction
     add        esp, 0xN                 ; Clean up the stack space, here N=4*n. 

Normally, the return code of such a function is stored in the eax-register. In the ideal situation, only registers that have to do something with return values of functions should be allowed to change across the API calls. Unfortunately, at the moment not all OS/2 APIs satisfy this property (implying, strictly speaking, that the API system fails to satisfy completely our Test!) so one should be very careful when storing something in registers and then making an external call.

Creating a Standard Window

Here is a piece of the assembly code, responsible for the creation of a standard window. The main functions are WinRegisterClass and WinCreateStdWindow. The interface to this window is carried out with the help of a window routine, which is specified as an argument in the call to WinRegisterClass.

    push      0x00000000                 ; @ first initialize the interface!
    call      WinInitialize 
    add       esp, 0x00000004 
    mov       hab, eax

    push      0x00000000
    push      eax                        ; From the previous procedure...
    call      WinCreateMsgQueue          ; Create the message queue, and return
    add       esp, 0x00000008            ; its handle. 
    mov       hmq, eax

    push      0x00000000
    push      CS_SIZEREDRAW              ; Diverse styles of the class...
    push      offset main_window_proc    ; The main window procedure, handling
    push      offset cls_client          ; all messages.    
    push      hab
    call      WinRegisterClass
    add       esp, 0x00000014
 
wincreateflags = (FCF_SYSMENU+FCF_TITLEBAR+FCF_MINBUTTON+FCF_ICON)
wincreateflags = wincreateflags+FCF_SIZEBORDER+FCF_MENU
wincreateflags = wincreateflags+FCF_SHELLPOSITION+FCF_TASKLIST

    mov       flCreate, wincreateflags

    push      offset hwndClient
    push      RES_CLIENT 
    push      0x00000000                     
    push      (CS_SIZEREDRAW+CS_SYNCPAINT)
    push      offset windows_message 
    push      offset cls_client
    push      offset flCreate
    push      (WS_VISIBLE+WS_ANIMATE)
    push      HWND_DESKTOP
    call      WinCreateStdWindow
    add       esp, 0x00000024
    mov       hwndFrame, eax                        

The above WinCreateStdWindow procedure actually does the job of two separate WinCreateWindow calls: It creates the frame window (eax holds the handle to it) and it also creates the client window as a child of the frame (hwndClient is filled with the client window handle, after a succesful completion of the function). In the case of more subtle windows (for example if we want to mix WPS stuff with PM functions) it is necessary to use two separate WinCreateWindow calls in order to have a full control over both frame and client windows. This is discussed in our WPS programming article.

The window dispatch loop looks as follows:

@loopdispatch:

    push      0x00000000
    push      0x00000000
    push      0x00000000
    push      offset qmsg
    push      hab
    call      WinGetMsg
    add       esp, 0x00000014
    
    cmp       eax, 0
    jz @exitdispatch

    push      offset qmsg
    push      hab
    call      WinDispatchMsg
    add       esp, 0x00000008
    
    jmp short @loopdispatch              ; We are still online, go ahead and get a  
                                         ; new message...

@exitdispatch:
    push      hwndFrame
    call      WinDestroyWindow           ; Destroy the frame window...
    add       esp, 0x00000004

    push      hmq
    call      WinDestroyMsgQueue         ; Destroy the message queue... 
    add       esp, 0x00000004 
 
    push      hab 
    call      WinTerminate               ; And finally destroy the associated PM
    add       esp, 0x00000004            ; threads.

The dispatched messages are then handled by the main (or another, associated) window procedure.

Example: Quantum Rectangles

Program Description

This sample program creates a simple PM window, and paints rectangular areas of the window with the help of WinInvalidateRect function. The colors of the rectangles and their sizes are randomly chosen, using a simple but very powerful random number generator. As an illustration for coding a pull-down menus, we introduce a control dialog, allowing us to specify the go/stop state, and also the speed of these fluctuating rectangles.

In developing this sample we were principally motivated by elegant random-rectangles samples for Windows, by Adam Stanislav [2].

Painter Thread

In order to perform paintings of rectangles, we create a cyclic thread.

    push      0x00001000                 ; The thread stack size, one page here! 
    push      0                          ; Thread flags                      
    push      0                          ; Parameter to be passed to the thread
    push      offset cyclic_painter      ; Thread routine                       
    push      offset thread_id           ; Thread id variable                   
    call      DosCreateThread                                                     
    add       esp, 0x00000014            ; Clean up the stack                                    

The thread procedure cyclic_painter is simply invalidating randomly chosen rectangles of the window paint area. This in its turn, causes the corresponding WM_PAINT message to be sent to the main window procedure, where the actual paintings occur. A simpler way to perform rectangle drawings in given intervals of time is to create a timer, and then put slightly modified cyclic_painter code within WM_TIMER section of the main window procedure. This is how we proceed in the WPS version of quantum rectangles.

Random Number Generator

As we already mentioned, our program has a built-in random number generator. It is interesting, and also of a separate value, to describe here a beautiful mathematics behind this simple subroutine:

    mov       eax, 0x4019CF16
    mul       random_var
    add       eax, random_var[4]
    mov       random_var, eax
    adc       edx, 0
    mov       random_var[4], edx

The code above is an example of a so-called multiply-with-carry (MWC) random number generator. We refer to [5] for more detailed explanations, and reviews of various types of random number generators.

What happens here is that we apply iteratively the following transformation T:

T{232x+y} = Ay+x
where x, y and A are 32-bit integers (A=0x4019CF16 in the code above).

More generally, we can consider transformations of the form:

T{Bx+y} = Ay+x

where A,B are natural numbers, A < B, and (x,y) take values from the set S defined as the

"cornerless" product
S={0,...,A-1}x{0,...,B-1}\{(A-1, B-1)}
Let us observe that all these pairs can naturally be viewed as 2-digit numbers in the system with base B.

Let us now define M=AB-1, and let R[M] be the residue ring modulo M. Clearly, we can make a natural identification S=R[M] and in what follows we will not really distinguish between these two objects. Let us denote by G[M] the group of invertible elements of the ring R[M]. These elements are represented by residues relatively prime with M. As a simple example, if M=8 then R[M] has 4 invertible elements: 1, 3, 5, 7 and the multiplication table for G[M] looks as follows:

1357
3175
5713
7531

It is nice - we obtained a famous Klein 4-element group :)

Returning to the general discussion, let us view S as a left R[M]-module, by means of the left regular representation. A simple but very important observation is that the action of the random-operator T is nothing but the left module multiplication by A. Within the ring R[M] the numbers A and B are mutually inverse, in other words A=B-1 in R[M]. Let C be the cyclic subgroup of G[M] generated by A. It is of principal interest to answer how S decomposes into irreducible components (also coinciding with orbits of the action of C) with respect to the action of C. These components correspond to our pseudorandom sequences.

In order to figure out the size of a given orbit, let us consider an arbitrary element F in S. Let D be the maximal common denominator between F and M. Let SF be the (cyclic) submodule of S generated by F. It is easy to see that a natural identification

SF = R[M/D]
holds. This is because
R[M]/I[D] = R[M/D]
where I[D] is the ideal of R[M] generated by M/D. The ideal I[D] consists exactly of elements that annihilate F.

It follows that the size of the orbit {CF} is the degree of A in the factor-ring R[M/D]. So, in general, the structure of the orbits is considerably complex. For example, if M=32, A=3, B=11 we have

C={1, 3, 9, 11, 17, 19, 25, 27}

and S splits into the following orbits:

{1, 3, 9, 11, 17, 19, 25, 27} {5, 7, 13, 15, 21, 23, 29, 31}

{4, 12} {8, 24} {20, 28}

{0} {16}

{2, 6, 18, 22} {10, 14, 26, 30}

From the point of view of random number sequences, we are interested only in the low digits of elements in each orbit. Here digits are understood in terms of the base-B number system. These digits form the actual pseudorandom sequence (during a cycle, a given digit will in general repeat many times, while the full numbers in the orbit are, by nature of things, always different). A very important question is whether the resulting pseudorandom sequence is sufficient to reconstruct the whole orbit. Let us denote by (ri) the sequence of low digits associated to the sequence of orbit elements

zi=Biz,  &nbsp z=z0.
The above equality, of course, is written in R[M]. In terms of standard integers (in Z) it gives
zi+1=Bzi+ri+1(1-AB).
Therefore, knowing the sequence (ri) and the initial element z0

of our orbit, we can reconstruct the whole orbit. The above recurrent formula also

implies that the period of the pseudorandom sequence is always equal to the length of the corresponding orbit. Indeed, if li are high digits of zi then we have

li+1=[ri - Ari+1]B

where [ ]B denotes the projection in R[M] =| {0, ... , B-1}.

Now, if M is a prime, then the theory simplifies. Every non-zero F will be invertible (as R[M] is a field iff M is prime) and all non-trivial orbits will have the same number of elements--the degree L of A in R[M] (number of elements in C). According to the Lagrange theorem, the number L is a divisor of the order of the group <nobr>G[M]=R[M]\{0}</nobr>. In other words, <nobr> L|(AB-2).</nobr>

If, furthermore, P=(M-1)/2 is a prime (primes M satisfying this additional property are called safeprimes) then <nobr>L={1, 2, P, 2P=M-1}</nobr>. In particular, if L=P then we will have only two non-trivial orbits.

To conclude, let us go back to our random number generator. It corresponds to the following specifications:

A=0x4019CF16, B=232, P=0x200CE78AFFFFFFFF, M=0x4019CF15FFFFFFFF.

So we have two possible pseudorandom sequences digits, each of period P=L. Note that the case of the single orbit is exculded because A has the squre root in R[M] and hence the whole G[M] is square-rootable. Which one will run depends on the initial value for global random_var and

random_var[4] variables.

How To Compile

The creation of the executable file is quite simple. Just 3 steps. Assembling, linking and resource-compiling. Explicitly,

wasm qhello.asm
wlink @qhello
rc qhello qhello.exe

Here, the linking info is stored in the file qhello.lnk and the resource info is within hello.rc file. Don't forget to check the size of the program (take into account the pre-compiled icon size, too) :)

The binary with the full source code can be found at our download area.

Concluding Remarks

As we have seen, it is conceptually very simple to code OS/2 PM in assembly language. However it does not mean that assembly programming is easy or trivial. True simplicity is always connected with something non-trivial at a deeper level (here it is a good time to recall of the true simplicity of quantum mechanics, as revealed for example in Feynman's book [6]). It is logical to expect that a language with a higher expressive power requires a higher-level knowledge in order to properly use it. And here, in our context, such a knowledge means knowing the internals of the machine, and understanding what is really happening... Invaluable scientific aspect of programming directly in the language of Machine.

References

  1. The Art of Assembly Language Programming and HLA. By Randall Hyde. An extensive and beautiful assembly language tutorial + related topics.
  2. Whiz Kid Technomagic. By Adam Stanislav. A wealth of assembly language sample programs, for Windows. Includes the mentioned random rectangles program for Windows.
  3. FreeBSD Programming in Assembly Language, by Adam Stanislav.
  4. Assembly Language Windows Applications. By Steve Gibson. Highly recommended source of valuable informations and links regarding assembly language programming for Windows. Includes a Small Is Beautiful Starter Kit.
  5. Random Number CDROM, by George Marsaglia. A package consisting of truly random bits, selected random number generator topics, and a software system to test true randomness.
  6. Feynman's Lectures in Physics: By Richard Feynman. Books 8/9-Quantum Mechanics.