1 /* This tests the somewhat obscure 32-bit Intel aam and aad instructions */
2 /* by Vince Weaver (vince _at_ deater.net ) */
3 
4 #include <stdio.h>
5 
parity(int v)6 int parity(int v) {
7 
8     int i;
9     int p = 1;
10 
11     for (i = 0; i < 8; i++)
12       p ^= (1 & (v >> i));
13     return p;
14 }
15 
main(int argc,char ** argv)16 int main(int argc, char **argv) {
17 
18   printf("test begins\n");
19   unsigned short i,out;
20   unsigned int flags;
21   int cf __attribute__((unused)),pf,af __attribute__((unused)),zf,sf;
22   int of __attribute__((unused));
23 
24   /* test AAM */
25 
26   for(i=0;i<65535;i++) {
27     // printf("%d, %d, %d\n",i,(i&0xff)/10,(i&0xff)%10);
28     out=i;
29     __asm__ __volatile__ ("mov %2 ,%%ax\n"
30 			  "aam\n"
31 			  "pushf\n"
32 			  "mov %%ax, %0\n"
33 			  "pop %%eax\n"
34 			  "mov %%eax, %1\n"
35 			  :"=r"(out), "=r"(flags)  /* outputs */
36 			  :"r"(out)     /* input */
37 			  :"%eax"     /* clobbered */
38     );
39     cf=!!(flags&0x1);
40     pf=!!(flags&0x4);
41     af=!!(flags&0x10);
42     zf=!!(flags&0x40);
43     sf=!!(flags&0x80);
44     of=!!(flags&0x800);
45 
46   //    printf("%d, %d, %d, ",i,(out>>8)&0xff,out&0xff);
47   //  printf("%x CF=%d PF=%d AF=%d ZF=%d SF=%d OF=%d\n",
48   //	   flags,cf,pf,af,zf,sf,of);
49 
50     if (zf && ((out&0xff)!=0)) {
51       printf("Error with aam (zf)!\n");
52     }
53     if (pf != parity(out&0xff)) {
54       printf("Error with aam (pf)!\n");
55     }
56     if (sf != !!(out&0x80)) {
57       printf("Error with aam (sf)!\n");
58     }
59 
60 
61     if ( ((out>>8)&0xff) != ((i&0xff)/10)) {
62       printf("Error with aam!\n");
63     }
64     if ( (out&0xff) != ((i&0xff)%10)) {
65       printf("Error with aam!\n");
66     }
67 
68   }
69 
70   /* test AAD */
71 
72   for(i=0;i<65535;i++) {
73     //    printf("%x, %d\n",i, ((((i>>8)&0xff)*10)+(i&0xff))&0xff );
74     out=i;
75     __asm__ __volatile__ ("mov %2 ,%%ax\n"
76 			  "aad\n"
77 			  "pushf\n"
78 			  "mov %%ax, %0\n"
79 			  "pop %%eax\n"
80 			  "mov %%eax, %1\n"
81 			  :"=r"(out), "=r"(flags)  /* outputs */
82 			  :"r"(out)     /* input */
83 			  :"%eax"     /* clobbered */
84 );
85 
86     cf=!!(flags&0x1);
87     pf=!!(flags&0x4);
88     af=!!(flags&0x10);
89     zf=!!(flags&0x40);
90     sf=!!(flags&0x80);
91     of=!!(flags&0x800);
92 
93     //       printf("%x, %d ",i,out);
94     //   printf("%x CF=%d PF=%d AF=%d ZF=%d SF=%d OF=%d\n",
95     //	   flags,cf,pf,af,zf,sf,of);
96 
97     if (zf && ((out&0xff)!=0)) {
98       printf("Error with aad (zf)!\n");
99     }
100     if (pf != parity(out&0xff)) {
101       printf("Error with aad (pf)!\n");
102     }
103     if (sf != !!(out&0x80)) {
104       printf("Error with aad (sf) %d %d!\n",sf,!!(out&0x80));
105     }
106 
107     if ( out != ( ((((i>>8)&0xff)*10)+(i&0xff))&0xff) ) {
108        printf("Error with aad!\n");
109     }
110   }
111 
112   printf("test completed\n");
113   return 0;
114 
115 }
116