home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / oxcc1433.zip / SRC / OXCCAI.C < prev    next >
C/C++ Source or Header  |  1995-11-06  |  123KB  |  5,782 lines

  1. /*
  2.     oxccai.c -- v1.430 ANF to intel asmcode generator
  3.  
  4.     Copyright (c) 1995
  5.     Norman D. Culver dba
  6.     Oxbow Software
  7.     1323 S.E. 17th Street #662
  8.     Ft. Lauderdale, FL 33316
  9.     (305) 527-1663 Voice
  10.     (305) 760-7584 Fax
  11.     (305) 760-4679 Data
  12.     norman.culver@channel1.com
  13.     All rights reserved.
  14.  
  15.  * Redistribution and use in source and binary forms are permitted
  16.  * provided that: (1) source distributions retain this entire copyright
  17.  * notice and comment, and (2) distributions including binaries display
  18.  * the following acknowledgement:  ``This product includes software
  19.  * developed by Norman D. Culver dba Oxbow Software''
  20.  * in the documentation or other materials provided with the distribution
  21.  * and in all advertising materials mentioning features or use of this
  22.  * software.
  23.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  24.  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  25.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  26.  
  27. */
  28. #define MAJOR_VERSION 1
  29. #define MINOR_VERSION 433
  30.  
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <stdio.h>
  34. #include <setjmp.h>
  35. #include <time.h>
  36.  
  37. #define SUPPORT_LONG_DOUBLE 0
  38. #define SUPPORT_LONG_LONG 1
  39.  
  40. #define NEED_FUNCTHUNK 1
  41. #define NEED_ANFDEFS 1
  42. #include "oxanf.h"
  43.     
  44. #define PROG oxccai
  45. #define USING_FRAMEWORK 1
  46. #define HOST_IS_LITTLE_ENDIAN 1
  47. #define REALLY_NEED_OFFSETS 0
  48. #define FUNCDATA (iv->category+1)
  49.  
  50. #define VFPRINTF(a,b) vfprintf(stderr,a,b)
  51. #define PERROR prerror
  52. #define PWARN prwarn
  53. #define PRINTF info
  54. static void prerror(const char *, ...);
  55. static void prwarn(const char *, ...);
  56. static void info(const char *, ...);
  57. int cfeprintf(const char *, ...);
  58.  
  59. #define FILEWRITE(buf, cnt)\
  60. {if(!iv->errors){if(fwrite(buf, 1, cnt, iv->outfile) != cnt)iv->errors = 12;}}
  61.  
  62. #define ROUNDING(a,b) ((b-(a&(b-1)))&(b-1))
  63. #define ROUNDUP(a,b) a += ROUNDING(a,b)
  64.  
  65. #define KEYEQ(a,b) ((a)[0] == (b)[0] && (a)[1] == (b)[1])
  66. #define KEYLT(a,b) (((a)[1] < (b)[1]) || ((a)[1] == (b)[1] && (a)[0] < (b)[0]))
  67. #define MIN(a,b) (((a) < (b)) ? (a) : (b))
  68.  
  69. /* ======================== CONCATENIZATION MACROS ==================== */
  70.  
  71. #define    _cat2_(a, b)    a##b
  72. #define _cat_(a, b)    _cat2_(a, b)
  73. #define Global(a) _cat_(PROG, a)
  74.  
  75. #define _pname2_(x)    #x
  76. #define _pname1_(x)    _pname2_(x)
  77. #define pName        _pname1_(PROG)
  78.  
  79.  
  80. /* ============== ENDIAN MACROS (input format is litle endian) ==== */
  81.  
  82. #if HOST_IS_LITTLE_ENDIAN
  83. #define GL(a) a
  84. #define GS(a) a
  85. #define PL(a) a
  86. #define PS(a) a
  87. #else
  88. #endif
  89.  
  90. /* =================== INPUT DATA FORMATS ========================== */
  91.  
  92. #define INFILE_SYMNUM 1
  93. #define OUTFILE_SYMNUM 2
  94.  
  95. /* ====================== STRUCTURES AND TYPEDEFS ======================== */
  96. typedef struct _jl {
  97.     struct _jl *next;
  98.     void *p;
  99.     char *q;
  100.     long *plabelval;
  101.     long offset;
  102. } *PJL;
  103.  
  104. typedef struct _el {
  105.     struct _el *next;
  106.     long spot;
  107.     short symnum;
  108. } *PEL;
  109.  
  110. typedef struct _afile {
  111.     unsigned char *file_p;
  112.     PopI header_p;
  113.     PopI size_p;
  114.     unsigned char *symtext_p;
  115.     unsigned char *prog_p;
  116.     unsigned char *data_p;
  117.     unsigned char *switch_p;
  118.     unsigned char *decl_p;
  119.     unsigned char *maxtemp_p;
  120.     unsigned char *seg_p;
  121.     unsigned char **symaddr;
  122.     unsigned char **decladdr;
  123.     unsigned long thunk_offset;
  124.     unsigned long bss_offset;
  125.     int maxtemp;
  126.     int maxtempclass;
  127.     void *datatbl;
  128.     short *symtran;
  129.     unsigned short *decltran;
  130.     int filenum;
  131.     int numsyms;
  132.     int numdecls;
  133.     int numrelocs;
  134.     int numsegs;
  135. } *Pafile;
  136.  
  137. typedef struct _iv {
  138.     int category;
  139.     FILE *outfile;
  140.     char *outname;
  141.     char *infile_name;
  142.     int remove_infile;
  143.     int argc;
  144.     char **argv;
  145.  
  146.     unsigned char **symaddr;
  147.     unsigned char **decladdr;
  148.  
  149.     struct _nodeO *ob_usedhead;
  150.     struct _nodeO *ob_usedtail;
  151.     struct _nodeO *ob;
  152.     unsigned char *ob_buf;
  153.     int ob_bufcnt;
  154.     int ob_nodecnt;
  155.     struct _nodeO *first_ob;
  156.  
  157.     struct _nodeC *cod_usedhead;
  158.     struct _nodeC *cod_usedtail;
  159.     struct _nodeC *cod;
  160.     unsigned char *cod_buf;
  161.     int cod_nodecnt;
  162.     int cod_bufcnt;
  163.     struct _nodeC *first_cod;
  164.     struct _nodeC *regcode;
  165.     long regsave;
  166.     long stksiz;
  167.  
  168.     int numfiles;
  169.     int lastlabel;
  170.     int labelnum;
  171.     int botlabel;
  172.     int errors;
  173.     int numsyms;
  174.     int numdecls;
  175.     int numsegs;
  176.     int maxtemp;
  177.     int maxtempclass;
  178.     unsigned long total_size;
  179.     unsigned long thunk_offset;
  180.     unsigned long bss_offset;
  181.     long first_temp;
  182.     long killop;
  183.     long numnested;
  184.     long lastline;
  185.     void *reloctbl;
  186.     void *newreloctbl;
  187.     void *extrntbl;
  188.     void *gbltbl;
  189.     void *symtbl;
  190.     void *labeltbl;
  191.     void *newlabeltbl;
  192.     void *tmptbl;
  193.     void *segtbl;
  194.     void *functbl;
  195.     void *finalsymtbl;
  196.     void *finalstringpack;
  197.     long finalpacksize;
  198.     void *datatbl;
  199.     void *builtintbl;
  200.     int in_builtin;
  201.     int has_structret;
  202.     int temps_written;
  203.  
  204.     PJL jbuf;
  205.     void *jbufstart;
  206.     int jmpcnt;
  207.     int jbufcnt;
  208.     long out_offset;
  209.     long func_offset;
  210.     int extmark;
  211.     short markedsym[10];
  212.     char *markedbuf[10];
  213.     int filenum;
  214.     Pafile files[1024];
  215.     char debug;
  216.     char only_debug;
  217.     char strip;
  218.     char listing_wanted;
  219.     char target_assembler;
  220.     char target_hardware;
  221.     char target_debugger;
  222.     char target_os;
  223.     char memory_model;
  224.     char obj_format;
  225. } *Piv;
  226.  
  227. struct _gloval {
  228.     char *symname;
  229.     int symnum;
  230.     unsigned char *p;
  231.     Pafile pf;
  232. };
  233. struct _dkey {
  234.     unsigned long offset;
  235.     long pad;
  236. };
  237. struct _dval {
  238. unsigned long size;
  239. unsigned char *p;
  240. unsigned char *prevp;
  241. long locid;
  242. short fileno;
  243. };
  244. struct _rkey {/* key area of reloctbl node */
  245.     unsigned long spot;
  246.     long fileno;
  247. };
  248. struct _rval {/* value area of reloctbl node */
  249.     unsigned char *p;
  250.     unsigned long base;
  251.     long offset;
  252.     short rsym;
  253.     unsigned char opcode;
  254.     char rsize;
  255.     short fileno;
  256. };
  257.  
  258.  
  259. /* Internal User API */
  260. static void *Cmalloc(int category, unsigned amount);
  261. static void *Ccalloc(int category, unsigned nelems, unsigned elemsize);
  262. static void *Crealloc(int category, void* buf, unsigned newsize);
  263. static void Cfree(int category, void* buf);
  264. static void Cfreecat(int category);
  265. static int Cmemrange(int category, unsigned* minp, unsigned* maxp);
  266. static int Cusedrange(int category, unsigned* minp, unsigned* maxp);
  267. static void Ctotrange(unsigned* minp,unsigned* maxp);
  268. static int Cnewcat(void);
  269. static void Cguard(int category);
  270. static void* NewSymTable(int category, int nbins);
  271. static int SymFind(void *tbl, void *key, void *result);
  272. static int SymFindRange(void *tbl, void *key, void *result);
  273. static void *SymInsert(void *tbl, void *key, void *value, int datsiz);
  274. static int StringInsert(void *tbl, char *string, void *result);
  275. static int StringFind(void *tbl, char *string, void *result);
  276. static void SymDelete(void *tbl, void *key);
  277. static int SymHead(void *tbl);
  278. static int SymNext(void *tbl);
  279. static void SymGetMark(void *tbl, void *markptr);
  280. static int SymMarkNext(void *tbl, void *mark);
  281. static void SymSetMark(void *tbl, void *markptr);
  282. static void SymKey(void *tbl, void *keyptr);
  283. static void SymValue(void *tbl, void *datptr);
  284. static void *seg_find(Piv iv, int id);
  285. static char *filenameof(char *path);
  286. static char *propernameof(Piv iv, char *name);
  287.  
  288. /* END: User API */
  289.  
  290. /* ====================== PUT UNIQUE CODE HERE ========================= */
  291. static void *do_stmt(Piv iv, unsigned char *p);
  292. static void *do_expr(Piv iv, unsigned char *p);
  293. static void do_bracket(Piv iv, unsigned char *p, unsigned char *q);
  294. static void *do_something(Piv iv, unsigned char *p);
  295. extern char *ctime();
  296.  
  297. /* ===================== ASMCODE OUTPUT GENERATOR ======================= */
  298. #define DUMP(args...) fprintf(((Piv)iv)->outfile, ## args)
  299. #define QDUMP(arg) fputs(arg, ((Piv)iv)->outfile)
  300. #define QDUMPC(arg) fputc(arg, ((Piv)iv)->outfile)
  301.  
  302. #define SOURCE 0
  303. #define DESTINATION 1
  304. #define USE_ADDR (0x0001)
  305. #define NEEDS_CONVERSION (0x0002)
  306.  
  307. #define BWORD (1)
  308. #define SWORD (2)
  309. #define LWORD (3)
  310.  
  311. #define INDIRECT (0x01)
  312. #define INDEXED (0x02)
  313.  
  314. /* WARNING ONLY GCC WILL COMPILE THIS */
  315. #define ENCODE(args...) \
  316. {iv->cod->ee = (struct _nodeE){## args}; link_cod(iv);}
  317.  
  318. typedef struct _nodeE
  319. {
  320.     unsigned short inst;
  321.     unsigned char size;
  322.     unsigned char s1;
  323.     unsigned char s1m;
  324.     unsigned char s2;
  325.     unsigned char s2m;
  326.     unsigned char d1;
  327.     unsigned char d1m;
  328.     unsigned char d2;
  329.     unsigned char d2m;
  330.     unsigned char cdat;
  331.     long dat;
  332.     void *ptr;
  333. } NODEE, *PNODEE;
  334.  
  335. typedef struct _nodeC
  336. {
  337.     struct _nodeC *next;
  338.     struct _nodeE ee;
  339. } NODEC, *PNODEC;
  340.  
  341. typedef struct _nodeO 
  342. {
  343.     struct _nodeO *next;
  344.     unsigned char *p;
  345.     ND d;
  346.     ND l;
  347.     ND r;
  348.     PNODEC startinst;
  349.     PNODEC endinst;
  350. } NODEO, *PNODEO;
  351.  
  352. static char *notice = 
  353.     "  Generated by Oxbow Software Asmcode Backend `oxccai' version %d.%d\n\n";
  354.  
  355. static char *opnames[] = {"",
  356.   "aaa","aad","aam","aas","adc","add","and","arpl",
  357.   "bound","bsf","bsr","bswap","bt","btc","btr","bts",
  358.   "call","cbw","cdq","clc","cld","cli","clts",
  359.   "cmc","cmp","cmps","cmpxchg","cwd","cwde",
  360.   "daa","das","dec","div",
  361.   "enter","esc",
  362.   "hlt",
  363.   "idiv","imul","in","inc","ins",
  364.   "int","into","invd","invlpg","iret","iretd","iretdf","iretf",
  365.   "ja","jae","jb","jbe","jc","jcxz","je","jecxz","jg","jge","jl","jle","jmp",
  366.   "jna","jnae","jnb","jnbe","jnc","jne","jng","jnge","jnl","jnle","jno","jnp",
  367.   "jns","jnz","jo","jp","jpe","jpo","js","jz",
  368.   "lar","lds","lea","leave","les","lfs",
  369.   "lgdt","lgs","lidt","lldt","lmsw","lock",
  370.   "lods","loop","loope","loopne","loopnz","loopz",
  371.   "lsl","lss","ltr",
  372.   "mov","movs","movsx","movzx","mul",
  373.   "neg","nop","not",
  374.   "or","out","outs",
  375.   "pop","popa","popf","push","pusha","pushf",
  376.   "rcl","rcr","ret","retf","retn","rol","ror",
  377.   "rep","repe","repne","repnz","repz",
  378.   "sahf","sal","sar","sbb","scas","shl","shr",
  379.   "seta","setae","setb","setbe","setc","sete","setg","setge","setl","setle",
  380.   "setna","setnae","setnb","setnbe","setnc","setne","setng","setnge","setnl",
  381.   "setnle","setno","setnp","setns","setnz","seto","setp","setpe","setpo",
  382.   "sets","setz","sgdt","sidt","sldt","smsw",
  383.   "stc","std","sti","stos","str","sub",
  384.   "test",
  385.   "verr","verw",
  386.   "wait","wbinvd",
  387.   "xadd","xchg","xlat","xlatb","xor",
  388.  
  389.   "fabs","fadd","faddp","fbld","fbstp","fchs","fclex",
  390.   "fcom","fcomp","fcompp","fcos",
  391.   "fdecstp","fdisi",
  392.   "fdiv","fdivp","fdivr","fdivrp","feni","ffree","fiadd",
  393.   "ficom","ficomp","fidiv","fidivr","fild","fimul","fincstp","finit",
  394.   "fist","fistp","fisub","fisubr",
  395.   "fld","fld1","fldcw","fldenv","fldlg2","fldln2","fldl2e","fldl2t","fldpi","fldz",
  396.   "fmul","fmulp",
  397.   "fnclex","fndisi","fneni","fninit","fnop","fnsave","fnstcw","fnstenv","fnsts",
  398.   "fpatan","fprem","fprem1","fptan","frndint","frstor","fsave",
  399.   "fscale","fsin","fsincos","fsqrt","fst","fstcw","fstenv",
  400.   "fstp",
  401.   "fstsw","fsub","fsubr",
  402.   "ftst","fucom","fucomp","fucompp","fwait","fxam","fxch","fxtract",
  403.   "fyl2x","fyl2xpi","f2xmi"
  404. };
  405. enum  {        
  406.   aaa=1,aad,aam,aas,adc,add,and,arpl,
  407.   bound,bsf,bsr,bswap,bt,btc,btr,bts,
  408.   call,cbw,cdq,clc,cld,cli,clts,
  409.   cmc,cmp,cmps,cmpxchg,cwd,cwde,
  410.   daa,das,dec,DIV,
  411.   enter,esc,
  412.   hlt,
  413.   idiv,imul,in,inc,ins,
  414.   INT,into,invd,invlpg,iret,iretd,iretdf,iretf,
  415.   ja,jae,jb,jbe,jc,jcxz,je,jecxz,jg,jge,jl,jle,jmp,
  416.   jna,jnae,jnb,jnbe,jnc,jne,jng,jnge,jnl,jnle,jno,jnp,
  417.   jns,jnz,jo,jp,jpe,jpo,js,jz,
  418.   lar,lds,lea,leave,les,lfs,
  419.   lgdt,lgs,lidt,lldt,lmsw,lock,
  420.   lods,loop,loope,loopne,loopnz,loopz,
  421.   lsl,lss,ltr,
  422.   mov,movs,movsx,movzx,mul,
  423.   neg,nop,not,
  424.   or,out,outs,
  425.   pop,popa,popf,push,pusha,pushf,
  426.   rcl,rcr,ret,retf,retn,rol,ror,
  427.   rep,repe,repne,repnz,repz,
  428.   sahf,sal,sar,sbb,scas,shl,shr,
  429.   seta,setae,setb,setbe,setc,sete,setg,setge,setl,setle,
  430.   setna,setnae,setnb,setnbe,setnc,setne,setng,setnge,setnl,
  431.   setnle,setno,setnp,setns,setnz,seto,setp,setpe,setpo,
  432.   sets,setz,sgdt,sidt,sldt,smsw,
  433.   stc,std,sti,stos,str,sub,
  434.   test,
  435.   verr,verw,
  436.   WAIT,wbinvd,
  437.   xadd,xchg,xlat,xlatb,xor,
  438.  
  439.   fabs,fadd,faddp,fbld,fbstp,fchs,fclex,
  440.   fcom,fcomp,fcompp,fcos,
  441.   fdecstp,fdisi,
  442.   fdiv,fdivp,fdivr,fdivrp,feni,ffree,fiadd,
  443.   ficom,ficomp,fidiv,fidivr,fild,fimul,fincstp,finit,
  444.   fist,fistp,fisub,fisubr,
  445.   fld,fld1,fldcw,fldenv,fldlg2,fldln2,fldl2e,fldl2t,fldpi,fldz,
  446.   fmul,fmulp,
  447.   fnclex,fndisi,fneni,fninit,fnop,fnsave,fnstcw,fnstenv,fnsts,
  448.   fpatan,fprem,fprem1,fptan,frndint,frstor,fsave,
  449.   fscale,fsin,fsincos,fsqrt,fst,fstcw,fstenv,
  450.   fstp,
  451.   fstsw,fsub,fsubr,
  452.   ftst,fucom,fucomp,fucompp,fwait,fxam,fxch,fxtract,
  453.   fyl2x,fyl2xpi,f2xmi,
  454.   ENDCODES,
  455.   ALIGN,PUSHREGS,POPREGS,LABEL,LINE,FUNCNAME,LINEFEED
  456. };
  457. static char *udatnames[] = {"",
  458. "%al","%ah","%ax","%eax","%bl","%bh","%bx","%ebx","%cl","%ch","%cx","%ecx",
  459. "%dl","%dh","%dx","%edx","%sp","%esp","%bp","%ebp",
  460. "%si","%esi","%di","%edi","%ss","%ds","%es","%fs","%gs","","",""
  461. };
  462. static char *datnames[] = {"",
  463. "al","ah","ax","eax","bl","bh","bx","ebx","cl","ch","cx","ecx",
  464. "dl","dh","dx","edx","sp","esp","bp","ebp",
  465. "si","esi","di","edi","ss","ds","es","fs","gs","","",""
  466. };
  467. enum {
  468. AL=1,AH,AX,EAX,BL,BH,BX,EBX,CL,CH,CX,ECX,DL,DH,DX,EDX,SP,ESP,BP,EBP,
  469. SI,ESI,DI,EDI,SS,DS,ES,FS,GS,CONST,VARNAME,LOCATION
  470. };
  471.  
  472. static char uwordsize[] = {' ','b','w','l'};
  473. static char dwordsize[] = {' ','b','w','d'};
  474.  
  475. static long
  476. symnumof(Piv iv, char *symb)
  477. {
  478. struct _gloval *valp;
  479.  
  480.     if(StringFind(iv->gbltbl, symb, &valp))
  481.         return (long)valp->pf->symtran[valp->symnum];
  482.     return 0;
  483.  
  484. }
  485. static void
  486. buildin(Piv iv, char *symb, unsigned char code)
  487. {
  488. long key[2];
  489.  
  490.     if((key[0] = symnumof(iv, symb)))
  491.     {
  492.         key[1] = 0;
  493.         SymInsert(iv->builtintbl, key, &code, 1);
  494.     }
  495. }
  496.  
  497.  
  498. static void
  499. install_builtins(Piv iv)
  500. {/* USE THIS TO INSTALL WHATEVER BUILTINS ARE IN THE TARGET INTERPRETER */
  501. #define BUILDIN(a,b) buildin(iv,#a,b)
  502.  
  503.     iv->builtintbl = NewSymTable(iv->category, 191);
  504.  
  505.     BUILDIN(alloca,0);
  506.  
  507. #undef BUILDIN
  508. }
  509. static long
  510. final_strofs(Piv iv, char *string)
  511. {
  512. long *result;
  513.  
  514.     if(StringFind(iv->finalsymtbl, string, &result))
  515.         return result[2];    
  516.     return 0;
  517. }
  518. static short
  519. final_symnum(Piv iv, short symnum)
  520. {
  521. long *result;
  522.  
  523.     if(StringFind(iv->finalsymtbl, iv->symaddr[symnum], &result))
  524.         return result[1]-1;
  525.     return 0;
  526. }
  527. static void
  528. make_final_symtab(Piv iv)
  529. {
  530. int i;
  531.     iv->finalsymtbl = NewSymTable(iv->category, 0);
  532.     if(SymHead(iv->gbltbl))
  533.     {
  534.         i = 0;
  535.         while(SymNext(iv->gbltbl))
  536.         {
  537.         long *result;
  538.         struct _gloval *valp;
  539.  
  540.             SymValue(iv->gbltbl, &valp);
  541.             if(*(valp->p))
  542.             {
  543.                 if(!StringInsert(iv->finalsymtbl, valp->symname, &result))
  544.                 {/* New Entry */
  545.                     result[1] = ++i;
  546.                 }
  547.             }
  548.         }
  549.     }
  550. }
  551. static void *
  552. new_nodeO(Piv iv)
  553. {
  554. PNODEO p;
  555.  
  556.     if(iv->ob_bufcnt < sizeof(NODEO))
  557.     {/* Allocate a new chunk of linked list space */
  558.       iv->ob_bufcnt = 4080;
  559.       iv->ob_buf = Ccalloc(FUNCDATA, 1, iv->ob_bufcnt);
  560.     }
  561.     p = (PNODEO)iv->ob_buf;
  562.     iv->ob_buf += sizeof(NODEO);
  563.     iv->ob_bufcnt -= sizeof(NODEO);
  564.     ++iv->ob_nodecnt;
  565.     return p;    
  566. }
  567. static void
  568. link_ob(Piv iv)
  569. {/* Attach to the used list */
  570.  
  571.     if(!iv->ob_usedhead)
  572.     {
  573.         iv->ob_usedhead = iv->ob;
  574.         iv->ob_usedtail = iv->ob;
  575.     }
  576.     else
  577.     {
  578.         iv->ob_usedtail->next = iv->ob;
  579.         iv->ob_usedtail = iv->ob;
  580.     }
  581.     iv->ob = new_nodeO(iv);
  582. }
  583. static void *
  584. new_nodeC(Piv iv)
  585. {
  586. PNODEC p;
  587.  
  588.     if(iv->cod_bufcnt < sizeof(NODEC))
  589.     {/* Allocate a new chunk of linked list space */
  590.       iv->cod_bufcnt = 4080;
  591.       iv->cod_buf = Ccalloc(FUNCDATA, 1, iv->cod_bufcnt);
  592.     }
  593.     p = (PNODEC)iv->cod_buf;
  594.     iv->cod_buf += sizeof(NODEC);
  595.     iv->cod_bufcnt -= sizeof(NODEC);
  596.     ++iv->cod_nodecnt;
  597.     return p;    
  598. }
  599. static void
  600. link_cod(Piv iv)
  601. {/* Attach to the used list */
  602.  
  603.     if(!iv->cod_usedhead)
  604.     {
  605.         iv->cod_usedhead = iv->cod;
  606.         iv->cod_usedtail = iv->cod;
  607.     }
  608.     else
  609.     {
  610.         iv->cod_usedtail->next = iv->cod;
  611.         iv->cod_usedtail = iv->cod;
  612.     }
  613.     iv->cod = new_nodeC(iv);
  614. }
  615. static PNODEC
  616. gen_inst(Piv iv, PNODEO pnode)
  617. {
  618. unsigned char opcode;
  619. unsigned char *p;
  620. PND d,l,r;
  621.  
  622.         d = &pnode->d;
  623.         l = &pnode->l;
  624.         r = &pnode->r;
  625.         p = pnode->p;
  626.         opcode = *p;
  627.  
  628.         switch(opcode)
  629.         {
  630.             /* 0 ADDRESS MODE */
  631.             case regainop:
  632.             case grabop:
  633.                 break;
  634.             case retvoidop:
  635.                 ENCODE(jmp, LWORD, s1: LOCATION, dat: iv->botlabel);
  636.                 break;
  637.  
  638.             /* 1 ADDRESS MODE */
  639.             case jmploopop:
  640.             case jmpcontinueop:
  641.             case jmpbreakop:
  642.             case jmpgotoop:
  643.                 ENCODE(jmp, LWORD, s1: LOCATION, dat: pnode->d.data->Uulong);
  644.                 break;
  645.             case ljmptrueop:
  646.             case ljmpfalseop:
  647.             case jmptrueop:
  648.             case jmpfalseop:
  649.                 break;
  650.             case retdataop:
  651.                 break;
  652.  
  653.             /* 2 ADDRESS MODE */
  654.             case getvalop:
  655.             case derefop:
  656.             case assignop:
  657.             case duptmpop:
  658.             case truthop:
  659.             case negop:
  660.             case complop:
  661.             case notop:
  662.             case copyop:
  663.             case castop:
  664.             case clrdatop:
  665.             case compsavop:
  666.             case totmpop:
  667.             case retstructop:
  668.             case switchop:
  669.             case argop:
  670.                 break;
  671.  
  672.             /* 3 ADDRESS MODE */
  673.             case plusop:
  674.             case minusop:
  675.             case mulop:
  676.             case divop:
  677.             case lshop:
  678.             case rshop:
  679.             case modop:
  680.             case orop:
  681.             case xorop:
  682.             case andop:
  683.                 break;
  684.             case eqop:
  685.             case neqop:
  686.             case ltop:
  687.             case gtop:
  688.             case leop:
  689.             case geop:
  690.                 break;
  691.             case getbitfieldop:
  692.             case putbitfieldop:
  693.                 break;
  694.             case callfuncop:
  695.                 break;
  696.  
  697.             default:
  698.                 break;
  699.         }
  700.         return iv->cod_usedtail;
  701. }
  702. static int
  703. get_size(int type, int size)
  704. {
  705.     switch(type)
  706.     {
  707.         case    D_ARRAY:
  708.         case    D_STRUCT:
  709.         case    D_FUNCTION:
  710.             return 4;
  711.  
  712.         default:
  713.             return size;
  714.     }
  715.     return 0;
  716. }
  717. static void
  718. set_op(PND pnd, PopA ptr, unsigned char otype)
  719. {
  720. unsigned char optype  = otype & 0xe0;
  721. unsigned char isize = otype & 0x1f;
  722.  
  723.     pnd->data = (DATUM *)ptr;
  724.     if(optype <= OPIMMED4)
  725.     {
  726.         pnd->dtype = optype >> 5;
  727.         pnd->quals = Q_CONST;
  728.         pnd->size = isize;
  729.         pnd->opsize = get_size(pnd->dtype, isize);
  730.         pnd->atype = A_IMMED;
  731. #if 0
  732.         switch(pnd->dtype)
  733.         {
  734.             case D_SIGNED:
  735.             {
  736.                 if(isize > 8)
  737.                 {
  738.                     memcpy(&pnd->data, ptr, isize);
  739.                 }
  740.                 else if(isize == 8)
  741.                 {
  742.                     pnd->data.Udouble = *((double*)ptr);
  743.                 }
  744.                 else
  745.                 {
  746.                 long l[2];
  747.                     l[0] = 0;
  748.                     l[1] = 0;
  749.                     if(isize == 4)
  750.                         l[0] = *((long*)ptr);
  751.                     else if(isize == 2)
  752.                         l[0] = *((short*)ptr);
  753.                     else if(isize == 1)
  754.                         l[0] = *((char*)ptr);
  755.                     if(l[0] < 0)
  756.                         l[1] = -1;
  757.                     pnd->data.Udouble = *((double*)l);
  758.                 }
  759.                 break;
  760.             }
  761.             case D_UNSIGNED:
  762.             case D_POINTER:
  763.             {
  764.                 if(isize > 8)
  765.                 {
  766.                     memcpy(&pnd->data, ptr, isize);
  767.                 }
  768.                 else if(isize == 8)
  769.                 {
  770.                     pnd->data.Udouble = *((double*)ptr);
  771.                 }
  772.                 else
  773.                 {
  774.                 unsigned long l[2];
  775.                     l[0] = 0;
  776.                     l[1] = 0;
  777.                     if(isize == 4)
  778.                         l[0] = *((unsigned long*)ptr);
  779.                     else if(isize == 2)
  780.                         l[0] = *((unsigned short*)ptr);
  781.                     else if(isize == 1)
  782.                         l[0] = *((unsigned char*)ptr);
  783.                     pnd->data.Udouble = *((double*)l);
  784.                 }
  785.                 break;
  786.             }
  787.             case D_FLOAT:
  788.             {
  789.                 if(isize == 4)
  790.                 {
  791.                     pnd->data.Udouble = *((float*)ptr);
  792.                 }
  793.                 else if(isize > 8)
  794.                 {
  795. #if SUPPORT_LONG_DOUBLE
  796.                     pnd->data.Ulongdouble = *((long double)ptr);
  797. #else
  798.                     pnd->data.Udouble = 0.0;
  799. #endif
  800.                 }
  801.                 else
  802.                 {
  803.                     pnd->data.Udouble = *((double*)ptr);
  804.                 }
  805.                 break;
  806.             }
  807.         }/* END: switch */
  808. #endif
  809.     } /* END: OPIMMED */
  810.     else
  811.     {
  812.     unsigned short type = GS(ptr->dtype);
  813.         pnd->dtype = type & 0xff;
  814.         pnd->quals = (type >> 8) & 0xff;
  815.         pnd->size = GL(ptr->dsize);
  816.         pnd->opsize = get_size(pnd->dtype, pnd->size);
  817.         pnd->atype = GS(ptr->atype);
  818.  
  819.         if(optype == OPAUTO)
  820.         {
  821.             if(GL(ptr->pofs) >= 0)
  822.             {
  823.                 pnd->atype &= ~A_AUTO;
  824.                 pnd->atype |= A_PARAM;
  825.             }
  826.         }
  827.     }
  828. }
  829. static void *
  830. decode_anf(Piv iv, unsigned char *p)
  831. {
  832. void *dptr;
  833. void *lptr;
  834. void *rptr;
  835.  
  836.     if(iv->debug >= '1')
  837.         cfeprintf("DECODE inst(%u) `%s'\n", *p, oxgenops[*p]);
  838.  
  839.     if(*p == 0)
  840.         return POP->next;
  841.  
  842.     iv->ob->p = p;
  843.     switch(*p)
  844.     {
  845.         case regainop:
  846.         case grabop:
  847.         case retvoidop:
  848.         {/* 0 address mode */
  849.             break;
  850.         }
  851.         case jmploopop:
  852.         case jmpcontinueop:
  853.         case jmpbreakop:
  854.         case jmpgotoop:
  855.         case ljmptrueop:
  856.         case jmptrueop:
  857.         case ljmpfalseop:
  858.         case jmpfalseop:
  859.         case funcstartop:
  860.         case funcstopop:
  861.         case retdataop:
  862.         {/* 1 address mode */
  863.             dptr = (p+8);
  864.             set_op(&iv->ob->d, dptr, p[1]);
  865.             break;
  866.         }
  867.         case getvalop:
  868.         case derefop:
  869.         case assignop:
  870.         case duptmpop:
  871.         case truthop:
  872.         case aliastmpop:
  873.         case negop:
  874.         case complop:
  875.         case notop:
  876.         case copyop:
  877.         case clrdatop:
  878.         case compsavop:
  879.         case totmpop:
  880.         case retstructop:
  881.         case switchop:
  882.         case argop:
  883.         case castop:
  884.         {/* 2 address mode */
  885.             dptr = (p+8);
  886.             lptr = (((char*)dptr) + (p[1] & 0x1f));
  887.             set_op(&iv->ob->d, dptr, p[1]);
  888.             set_op(&iv->ob->l, lptr, p[2]);
  889.             break;
  890.         }
  891.         case plusop:
  892.         case minusop:
  893.         case mulop:
  894.         case divop:
  895.         case modop:
  896.         case orop:
  897.         case xorop:
  898.         case andop:
  899.         case eqop:
  900.         case neqop:
  901.         case ltop:
  902.         case gtop:
  903.         case leop:
  904.         case geop:
  905.         case lshop:
  906.         case rshop:
  907.         case getbitfieldop:
  908.         case callfuncop:
  909.         case putbitfieldop:
  910.         {/* 3 address mode */
  911.             dptr = (p+8);
  912.             lptr = (((char*)dptr) + (p[1] & 0x1f));
  913.             rptr = (((char*)lptr) + (p[2] & 0x1f));
  914.             set_op(&iv->ob->d, dptr, p[1]);
  915.             set_op(&iv->ob->l, lptr, p[2]);
  916.             set_op(&iv->ob->r, rptr, p[3]);
  917.             break;
  918.         }
  919.         default:
  920.         {
  921.             return POP->next;
  922.         }
  923.     }/* END: switch(*p) */
  924.  
  925.     /* Save pointers to the machine instructions generated by this ANF code */
  926.     iv->ob->startinst = iv->cod;
  927.     iv->ob->endinst = gen_inst(iv, iv->ob);
  928.  
  929.     if(iv->cod != iv->ob->startinst)
  930.     {/* instructions were generated */
  931.         link_ob(iv);
  932.     }
  933.     return POP->next;
  934. }/* END: decode_anf() */
  935.  
  936. static void *
  937. skip_bracket(unsigned char *p)
  938. {
  939. long opcode = *p;
  940. int opcount = 0;
  941.  
  942.     for(;;)
  943.     {
  944.         if(*p == opcode)
  945.             ++opcount;
  946.         else if(*p == endop && GL(POP->data) == opcode)
  947.         {
  948.             if(--opcount == 0) {
  949.                 return p;
  950.             }
  951.         }
  952.         else if(*p == endfileop || *p == endallop)
  953.         {
  954.             PERROR(pName ": Malformed input file3=%u=%p",*p, p);
  955.         }
  956.         p = POP->next;
  957.     }
  958.     return 0;
  959. }
  960. static void *
  961. do_arrayelem(Piv iv, unsigned char *p)
  962. {/* Arrange output for the stack machine */
  963. void *sp = p;
  964. unsigned char *q = skip_bracket(p);
  965. void *sadims[10];
  966. void *sadimsq[10];
  967. void *spdims[10];    
  968. void *spdimsq[10];
  969. int sacnt, spcnt, i;
  970.  
  971.     /* Scan over the bracket and pick up the dimension computations */
  972.     sacnt = spcnt = 0;
  973.     p = POP->next;
  974.     while(p < q)
  975.     {
  976.         if(*p == arraydimsop)
  977.         {
  978.         void *qq = skip_bracket(p);
  979.             sadims[sacnt] = p;
  980.             sadimsq[sacnt++] = qq;
  981.             p = qq;
  982.         }
  983.         else if(*p == ptrdimsop)
  984.         {
  985.         void *qq = skip_bracket(p);
  986.             spdims[spcnt] = p;
  987.             spdimsq[spcnt++] = qq;
  988.             p = qq;
  989.         }
  990.         p = POP->next;
  991.     }
  992.     /* Dump the dimension computations in stack order */
  993.     for(i = spcnt-1; i >= 0; --i)
  994.     {
  995.         do_bracket(iv, spdims[i], spdimsq[i]);
  996.     }
  997.     for(i = sacnt-1; i >= 0; --i)
  998.     {
  999.         do_bracket(iv, sadims[i], sadimsq[i]);
  1000.     }
  1001.  
  1002.     /* Dump the remainder of the array element bracket */
  1003.     p = sp;
  1004.     sacnt = spcnt = 0;
  1005.     p = POP->next;
  1006.      while(p < q)
  1007.     {
  1008.         if(*p == arraydimsop)
  1009.             p = ((Pop)sadimsq[sacnt++])->next;
  1010.         else if(*p == ptrdimsop)
  1011.             p = ((Pop)spdimsq[spcnt++])->next;
  1012.         else
  1013.             p = do_something(iv, p);
  1014.     }
  1015.     return ((Pop)q)->next;
  1016. }
  1017. static int
  1018. funcret_used(PopT op, unsigned char *p)
  1019. {
  1020. long tmpnum;
  1021.     if(        op->dtype == 0
  1022.         &&    op->dsize == 0)
  1023.     {
  1024.         return 1;                        /* void function */
  1025.     }
  1026.     tmpnum = op->tmpnum;
  1027.  
  1028.     while(*p != funcexitop)
  1029.     {
  1030.         if(*p && *p <= (unsigned char)100)
  1031.         {
  1032.         unsigned char *qp = p+8;
  1033.             if(*p == callfuncop)
  1034.             {/* function using same temp */
  1035.                 if(GL(((PopT)qp)->tmpnum) == tmpnum)
  1036.                 {
  1037.                     return 1;        /* not used earlier */
  1038.                 }
  1039.             }
  1040.             else
  1041.             {
  1042.                 if((p[1]&0xe0) == OPRET)
  1043.                 {
  1044.                      if(GL(((PopT)qp)->tmpnum) == tmpnum)
  1045.                     {
  1046.                         return 0;            /* ret used */
  1047.                     }
  1048.                 }                
  1049.                 qp += p[1]&0x1f;
  1050.                 if((p[2]&0xe0) == OPRET)
  1051.                 {
  1052.                     if(GL(((PopT)qp)->tmpnum) == tmpnum)
  1053.                     {
  1054.                         return 0;            /* ret used */
  1055.                     }
  1056.                 }
  1057.                 qp += p[2]&0x1f;
  1058.                 if((p[3]&0xe0) == OPRET)
  1059.                 {
  1060.                     if(GL(((PopT)qp)->tmpnum) == tmpnum)
  1061.                     {
  1062.                         return 0;            /* ret used */
  1063.                     }
  1064.                 }
  1065.             }
  1066.         }
  1067.         p = POP->next;
  1068.     }
  1069.     return 1;                    /* ret not used */
  1070. }
  1071. static unsigned char
  1072. check_for_builtin(Piv iv, unsigned char *p, int flag)
  1073. {
  1074. short symnum;
  1075. long key[2];
  1076. unsigned char *result;
  1077.  
  1078.     if(flag == 0)
  1079.     {
  1080.         symnum = GS(((PopA)(p+20))->symnum);
  1081.     }
  1082.     else if(flag == 1)
  1083.     {
  1084.         symnum = GS(((PopI)(p+16))->s.symnum);
  1085.     }
  1086.     else if(flag == 2)
  1087.     {
  1088.         symnum = GS(POPI->s.symnum);
  1089.     }
  1090.     else return 0;
  1091.  
  1092.     key[0] = symnum;
  1093.     key[1] = 0;
  1094.     if(SymFind(iv->builtintbl, key, &result) == 1)
  1095.         return *result;
  1096.     return 0;
  1097. }
  1098. static void *
  1099. do_funcall(Piv iv, unsigned char *p)
  1100. {
  1101. void *sp = p;
  1102. unsigned char *q = skip_bracket(p);
  1103. int argcnt, i, dump;
  1104. void *argloads[100];
  1105. void *argloadsq[100];
  1106. char *callop = 0;
  1107. unsigned char builtin = 0;
  1108.  
  1109.     /* Scan over the bracket and pick up argument loads */
  1110.     argcnt = 0;
  1111.     p = POP->next;
  1112.     while(p < q)
  1113.     {
  1114.         if(*p == getvalop && callop == 0)
  1115.         {
  1116.             builtin = check_for_builtin(iv, p, 0);
  1117.         }
  1118.         else if(*p == callfuncop)
  1119.             callop = p;
  1120.         else if(*p == argloadop)
  1121.         {
  1122.         void *qq = skip_bracket(p);
  1123.             argloads[argcnt] = p;
  1124.             argloadsq[argcnt++] = qq;
  1125.             p = qq;
  1126.         }
  1127.         p = POP->next;
  1128.     }
  1129.  
  1130.     /* Check out whether the function return is used */
  1131.     dump = funcret_used((PopT)(callop+8), q);
  1132.  
  1133.     /* Calling an interpreter builtin ?? */
  1134.     if(builtin)
  1135.     {
  1136.         iv->in_builtin = 1;
  1137.  
  1138.         /* Dump the argument loads in order */
  1139.         /* The ARG instruction will be suppressed because iv->in_builtin > 0 */
  1140.         for(i = 0; i < argcnt; ++i)
  1141.         {
  1142.             do_bracket(iv, argloads[i], argloadsq[i]);
  1143.         }
  1144.     }
  1145.     else
  1146.     {
  1147.         /* Generate the CALLSETUP instruction */
  1148.         p = sp;
  1149.         p = POP->next;
  1150.         while(p < q)
  1151.         {
  1152.             if(*p == argloadop)
  1153.                 break;
  1154.             else
  1155.                 p = do_something(iv, p);
  1156.         }            
  1157.  
  1158.         /* Dump the argument loads in order */
  1159.         for(i = 0; i < argcnt; ++i)
  1160.         {
  1161.             do_bracket(iv, argloads[i], argloadsq[i]);
  1162.         }
  1163.         /* Generate the CALL instruction */
  1164.     }
  1165.     return ((Pop)q)->next;
  1166. }
  1167. static void *
  1168. do_cond(Piv iv, unsigned char *p)
  1169. {
  1170. unsigned char *q = skip_bracket(p);
  1171.  
  1172.     p = POP->next;
  1173.     while(p < q)
  1174.     {
  1175.       p = do_something(iv, p);
  1176.     }
  1177.     return ((Pop)q)->next;
  1178. }
  1179. static void *
  1180. do_twopath(Piv iv, unsigned char *p)
  1181. {
  1182. unsigned char *q = skip_bracket(p);
  1183.  
  1184.     p = POP->next;
  1185.     while(p < q)
  1186.     {
  1187.       p = do_something(iv, p);
  1188.     }
  1189.     return ((Pop)q)->next;
  1190. }
  1191. static void *
  1192. do_logical(Piv iv, unsigned char *p)
  1193. {
  1194. unsigned char *q = skip_bracket(p);
  1195.  
  1196.     p = POP->next;
  1197.     while(p < q)
  1198.     {
  1199.       p = do_something(iv, p);
  1200.     }
  1201.     return ((Pop)q)->next;
  1202. }
  1203. static void *
  1204. do_binop(Piv iv, unsigned char *p)
  1205. {
  1206. unsigned char *q = skip_bracket(p);
  1207.  
  1208.     p = POP->next;
  1209.     while(p < q)
  1210.     {
  1211.       p = do_something(iv, p);
  1212.     }
  1213.     return ((Pop)q)->next;
  1214. }
  1215. static void *
  1216. do_strelem(Piv iv, unsigned char *p)
  1217. {
  1218. unsigned char *q = skip_bracket(p);
  1219.  
  1220.     p = POP->next;
  1221.     while(p < q)
  1222.     {
  1223.       p = do_something(iv, p);
  1224.     }
  1225.     return ((Pop)q)->next;
  1226. }
  1227. static void *
  1228. do_ptrelem(Piv iv, unsigned char *p)
  1229. {
  1230. unsigned char *q = skip_bracket(p);
  1231.  
  1232.     p = POP->next;
  1233.     while(p < q)
  1234.     {
  1235.       p = do_something(iv, p);
  1236.     }
  1237.     return ((Pop)q)->next;
  1238. }
  1239. static void *
  1240. do_argload(Piv iv, unsigned char *p)
  1241. {
  1242. unsigned char *q = skip_bracket(p);
  1243.  
  1244.     p = POP->next;
  1245.     while(p < q)
  1246.     {
  1247.       p = do_something(iv, p);
  1248.     }
  1249.     return ((Pop)q)->next;
  1250. }
  1251. static void *
  1252. do_preincr(Piv iv, unsigned char *p)
  1253. {
  1254. unsigned char *q = skip_bracket(p);
  1255.  
  1256.     p = POP->next;
  1257.     while(p < q)
  1258.     {
  1259.       p = do_something(iv, p);
  1260.     }
  1261.     return ((Pop)q)->next;
  1262. }
  1263. static void *
  1264. do_postincr(Piv iv, unsigned char *p)
  1265. {
  1266. unsigned char *q = skip_bracket(p);
  1267.  
  1268.     p = POP->next;
  1269.     while(p < q)
  1270.     {
  1271.       p = do_something(iv, p);
  1272.     }
  1273.     return ((Pop)q)->next;
  1274. }
  1275. static void *
  1276. do_compound(Piv iv, unsigned char *p)
  1277. {
  1278. unsigned char *q = skip_bracket(p);
  1279.  
  1280.     p = POP->next;
  1281.     while(p < q)
  1282.     {
  1283.       p = do_something(iv, p);
  1284.     }
  1285.     return ((Pop)q)->next;
  1286. }
  1287. static void *
  1288. do_unop(Piv iv, unsigned char *p)
  1289. {
  1290. unsigned char *q = skip_bracket(p);
  1291.  
  1292.     p = POP->next;
  1293.     while(p < q)
  1294.     {
  1295.       p = do_something(iv, p);
  1296.     }
  1297.     return ((Pop)q)->next;
  1298. }
  1299. static void *
  1300. do_expr(Piv iv, unsigned char *p)
  1301. {
  1302. unsigned char *q = skip_bracket(p);
  1303.  
  1304.     if(iv->debug >= '2')
  1305.         cfeprintf("EXPR inst(%u) `%s'\n", *p, oxgenops[*p]);
  1306.  
  1307.     while(p < q)
  1308.     {
  1309.         switch(*p)
  1310.         {
  1311.             case    arrayelemop:
  1312.                 p = do_arrayelem(iv, p);
  1313.                 break;
  1314.             case    funcallop:
  1315.                 p = do_funcall(iv, p);
  1316.                 break;
  1317.             case    condop:
  1318.                 p = do_cond(iv, p);
  1319.                 break;
  1320.             case    twopathop:
  1321.                 p = do_twopath(iv, p);
  1322.                 break;
  1323.             case    logicalop:
  1324.                 p = do_logical(iv, p);
  1325.                 break;
  1326.             case    binopop:
  1327.                 p = do_binop(iv, p);
  1328.                 break;
  1329.             case    strelemop:
  1330.                 p = do_strelem(iv, p);
  1331.                 break;
  1332.             case    ptrelemop:
  1333.                 p = do_ptrelem(iv, p);
  1334.                 break;
  1335.             case    argloadop:
  1336.                 p = do_argload(iv, p);
  1337.                 break;
  1338.             case    preincrdecop:
  1339.                 p = do_preincr(iv, p);
  1340.                 break;
  1341.             case    postincrdecop:
  1342.                 p = do_postincr(iv, p);
  1343.                 break;
  1344.             case    compoundop:
  1345.                 p = do_compound(iv, p);
  1346.                 break;
  1347.             case    unopop:
  1348.                 p = do_unop(iv, p);
  1349.                 break;
  1350.                 p = POP->next;
  1351.                 break;
  1352.             default:
  1353.                 p = do_something(iv, p);
  1354.                 break;
  1355.         }
  1356.     }
  1357.     return ((Pop)q)->next;
  1358. }
  1359. static void *
  1360. do_expstmt(Piv iv, unsigned char *p)
  1361. {
  1362. unsigned char *q = skip_bracket(p);
  1363.  
  1364.     p = POP->next;
  1365.     while(p < q)
  1366.     {
  1367.       p = do_something(iv, p);
  1368.     }
  1369.     return q;
  1370. }
  1371. static void *
  1372. do_ifstmt(Piv iv, unsigned char *p)
  1373. {
  1374. unsigned char *q = skip_bracket(p);
  1375.  
  1376.     p = POP->next;
  1377.     while(p < q)
  1378.     {
  1379.       p = do_something(iv, p);
  1380.     }
  1381.     return ((Pop)q)->next;
  1382. }
  1383. static void *
  1384. do_ifelsestmt(Piv iv, unsigned char *p)
  1385. {
  1386. unsigned char *q = skip_bracket(p);
  1387.  
  1388.     p = POP->next;
  1389.     while(p < q)
  1390.     {
  1391.       p = do_something(iv, p);
  1392.     }
  1393.     return ((Pop)q)->next;
  1394. }
  1395. static void *
  1396. do_switchstmt(Piv iv, unsigned char *p)
  1397. {
  1398. unsigned char *q = skip_bracket(p);
  1399.  
  1400.     p = POP->next;
  1401.     while(p < q)
  1402.     {
  1403.       p = do_something(iv, p);
  1404.     }
  1405.     return ((Pop)q)->next;
  1406. }
  1407. static void *
  1408. do_whilestmt(Piv iv, unsigned char *p)
  1409. {
  1410. unsigned char *q = skip_bracket(p);
  1411.  
  1412.     p = POP->next;
  1413.     while(p < q)
  1414.     {
  1415.       p = do_something(iv, p);
  1416.     }
  1417.     return ((Pop)q)->next;
  1418. }
  1419. static void *
  1420. do_dostmt(Piv iv, unsigned char *p)
  1421. {
  1422. unsigned char *q = skip_bracket(p);
  1423.  
  1424.     p = POP->next;
  1425.     while(p < q)
  1426.     {
  1427.       p = do_something(iv, p);
  1428.     }
  1429.     return ((Pop)q)->next;
  1430. }
  1431. static void *
  1432. do_forstmt(Piv iv, unsigned char *p)
  1433. {
  1434. unsigned char *q = skip_bracket(p);
  1435.  
  1436.     p = POP->next;
  1437.     while(p < q)
  1438.     {
  1439.       p = do_something(iv, p);
  1440.     }
  1441.     return ((Pop)q)->next;
  1442. }
  1443. static void *
  1444. do_asmstmt(Piv iv, unsigned char *p)
  1445. {
  1446. unsigned char *q = skip_bracket(p);
  1447.  
  1448.     p = POP->next;
  1449.     while(p < q)
  1450.     {
  1451.       p = do_something(iv, p);
  1452.     }
  1453.     return ((Pop)q)->next;
  1454. }
  1455. static void *
  1456. do_initstmt(Piv iv, unsigned char *p)
  1457. {
  1458. unsigned char *q = skip_bracket(p);
  1459.  
  1460.     p = POP->next;
  1461.     while(p < q)
  1462.     {
  1463.       p = do_something(iv, p);
  1464.     }
  1465.     return ((Pop)q)->next;
  1466. }
  1467. static void *
  1468. do_anfblock(Piv iv, unsigned char *p)
  1469. {
  1470. unsigned char *q = skip_bracket(p);
  1471.  
  1472.     p = POP->next;
  1473.     while(p < q)
  1474.     {
  1475.       p = do_something(iv, p);
  1476.     }
  1477.     return ((Pop)q)->next;
  1478. }
  1479. static void *
  1480. do_stmt(Piv iv, unsigned char *p)
  1481. {
  1482. void *q;
  1483.  
  1484.     if(iv->debug >= '2')
  1485.         cfeprintf("STMT inst(%u) `%s'\n", *p, oxgenops[*p]);
  1486.  
  1487.     q = POP->next;
  1488.     switch(*p)
  1489.     {
  1490.         case labelop:
  1491.             ENCODE(LABEL, dat: GL(POP->data));
  1492.             break;
  1493.         case gfuncdefop:
  1494.         case sfuncdefop:
  1495.         case funcexitop:
  1496.             PERROR(pName ": Malformed input file1=%u=%p",*p, p);
  1497.             break;
  1498.         case nestedfuncdefop:
  1499.         {
  1500. #if 0
  1501.             if(iv->listing_wanted)
  1502.             {
  1503.                 obuf[0] = NFUNC;
  1504.                 *((char**)&obuf[1]) = iv->symaddr[GS(POPI->funcdef.symnum)];
  1505.                 link_ob(iv);
  1506.             }
  1507. #endif
  1508.             iv->numnested += 1;
  1509.             break;
  1510.         }
  1511.         case nestedfuncexitop:
  1512.         {
  1513.             break;        
  1514.         }
  1515.         case anfblockop:
  1516.             q = do_anfblock(iv, p);
  1517.             break;
  1518.         case expstmtop:
  1519.             q = do_expstmt(iv, p);
  1520.             break;
  1521.         case ifstmtop:
  1522.             q = do_ifstmt(iv, p);
  1523.             break;
  1524.         case ifelsestmtop:
  1525.             q = do_ifelsestmt(iv, p);
  1526.             break;
  1527.         case switchstmtop:
  1528.             q = do_switchstmt(iv, p);
  1529.             break;
  1530.         case whilestmtop:
  1531.             q = do_whilestmt(iv, p);
  1532.             break;
  1533.         case dostmtop:
  1534.             q = do_dostmt(iv, p);
  1535.             break;
  1536.         case forstmtop:
  1537.             q = do_forstmt(iv, p);
  1538.             break;
  1539.         case asmstmtop:
  1540.             q = do_asmstmt(iv, p);
  1541.             break;
  1542.         case initstmtop:
  1543.             q = do_initstmt(iv, p);
  1544.             break;
  1545.         case lineop:
  1546.             iv->lastline = GL(POP->data);
  1547.             ENCODE(LINE, dat: iv->lastline);
  1548.             break;
  1549.         default:
  1550.             break;
  1551.     }
  1552.     return q;
  1553. }
  1554. static void *
  1555. do_something(Piv iv, unsigned char *p)
  1556. {
  1557.  
  1558.     if(*p < labelop)
  1559.         return decode_anf(iv, p);
  1560.     else if(*p >= condop && *p <= unopop)
  1561.         return do_expr(iv, p);
  1562.     else
  1563.         return do_stmt(iv, p);
  1564. }
  1565. static void
  1566. do_bracket(Piv iv, unsigned char *p, unsigned char *q)
  1567. {
  1568.     p = POP->next;
  1569.     while(p < q)
  1570.     {
  1571.       p = do_something(iv, p);
  1572.     }
  1573. }
  1574. static void
  1575. dump_unix_codes(Piv iv)
  1576. {
  1577. PNODEC pcod = iv->cod_usedhead;
  1578.  
  1579.     while((pcod = pcod->next))
  1580.     {
  1581.     PNODEE p = &pcod->ee;
  1582.       if(p->inst)
  1583.       {
  1584.         if(p->inst > ENDCODES)
  1585.         {
  1586.             switch(p->inst)
  1587.             {
  1588.                 case    ALIGN:
  1589.                 {
  1590.                     DUMP("\t.align %d", p->size);
  1591.                     if(p->dat)
  1592.                         DUMP(",0x%lx", p->dat);
  1593.                     QDUMPC('\n');
  1594.                     break;
  1595.                 }
  1596.                 case    PUSHREGS:
  1597.                 {
  1598.                 int bits = p->dat;
  1599.                 int which = 31;
  1600.                     while(bits)
  1601.                     {
  1602.                         if(bits & 0x80000000)
  1603.                             DUMP("\tpushl\t%s\n", udatnames[which]);
  1604.                         bits <<= 1;
  1605.                         --which;
  1606.                     }
  1607.                     break;
  1608.                 }
  1609.                 case    POPREGS:
  1610.                 {
  1611.                 int bits = p->dat;
  1612.                 int which = 0;
  1613.                     while(bits)
  1614.                     {
  1615.                         if(bits & 1)
  1616.                             DUMP("\tpopl\t%s\n", udatnames[which]);
  1617.                         bits >>= 1;
  1618.                         ++which;
  1619.                     }
  1620.                     break;
  1621.                 }
  1622.                 case    LABEL:
  1623.                 {
  1624.                     DUMP("L%lu:\n", p->dat);
  1625.                     break;
  1626.                 }
  1627.                 case    LINE:
  1628.                 {
  1629.                     DUMP("//LINE:%lu\n", p->dat);
  1630.                     break;
  1631.                 }
  1632.                 case    FUNCNAME:
  1633.                 {
  1634.                     DUMP("_%s:\n", (char*)p->ptr);
  1635.                     break;
  1636.                 }
  1637.                 case LINEFEED:
  1638.                 {
  1639.                     QDUMPC('\n');
  1640.                     break;
  1641.                 }
  1642.                 default:
  1643.                     break;
  1644.             }
  1645.         }
  1646.         else
  1647.         {
  1648.             QDUMPC('\t');
  1649.             QDUMP(opnames[p->inst]);
  1650.             QDUMPC(uwordsize[p->size]);
  1651.             if(p->s1)
  1652.             {
  1653.                 QDUMPC('\t');
  1654.                 if(p->s1 == CONST)
  1655.                 {
  1656.                     DUMP("$%ld",p->dat);
  1657.                 }
  1658.                 else if(p->s1 == VARNAME)
  1659.                 {
  1660.                     QDUMPC('_');
  1661.                     QDUMP(p->ptr);
  1662.                 }
  1663.                 else if(p->s1 == LOCATION)
  1664.                 {
  1665.                     DUMP("L%lu", p->dat);
  1666.                 }
  1667.                 else
  1668.                 {
  1669.                     if(p->s1m & INDIRECT)
  1670.                         QDUMPC('*');
  1671.                     if(p->s1m & INDEXED)
  1672.                     {
  1673.                         if(p->dat)
  1674.                             DUMP("%ld(", p->dat);
  1675.                         else
  1676.                             QDUMPC('(');
  1677.                     }
  1678.                     QDUMP(udatnames[p->s1]);
  1679.                     if(p->s1m & INDEXED)
  1680.                         QDUMPC(')');
  1681.                 }
  1682.             }
  1683.             if(p->d1)
  1684.             {
  1685.                 if(p->s1)
  1686.                     QDUMPC(',');
  1687.                 else
  1688.                     QDUMPC('\t');
  1689.                 if(p->d1 == CONST)
  1690.                 {
  1691.                     DUMP("$%ld",p->dat);
  1692.                 }
  1693.                 else if(p->d1 == VARNAME)
  1694.                 {
  1695.                     QDUMPC('_');
  1696.                     QDUMP(p->ptr);
  1697.                 }
  1698.                 else
  1699.                 {
  1700.                     if(p->d1m & INDIRECT)
  1701.                         QDUMPC('*');
  1702.                     if(p->d1m & INDEXED)
  1703.                     {
  1704.                         if(p->dat)
  1705.                             DUMP("%ld(", p->dat);
  1706.                         else
  1707.                             QDUMPC('(');
  1708.                     }
  1709.                     QDUMP(udatnames[p->d1]);
  1710.                     if(p->d1m & INDEXED)
  1711.                         QDUMPC(')');
  1712.                 }
  1713.             }    
  1714.             QDUMPC('\n');
  1715.         } /* END: < ENDCODES */
  1716.       }/* END: if(p->inst) */
  1717.     }/* END: while(pcod->next) */
  1718. }
  1719. static void
  1720. start_unix_func(Piv iv, unsigned char *p)
  1721. {
  1722. char *funcname = iv->symaddr[GS(POPI->funcdef.symnum)];
  1723. int autosize = GL(POPI->funcdef.hidden_offset);
  1724. int tempmax = GS(POPI->funcdef.tempmax);
  1725. int stksiz = autosize + (tempmax*8);
  1726.  
  1727.     iv->regsave = 0;
  1728.     iv->botlabel = ++iv->lastlabel;
  1729.     iv->stksiz = stksiz;
  1730.  
  1731.     ENCODE(ALIGN, 2);
  1732.     ENCODE(FUNCNAME, ptr: funcname);
  1733.     ENCODE(push, LWORD, s1: ESP);
  1734.     ENCODE(mov, LWORD, s1: ESP, d1: EBP);
  1735.     ENCODE(PUSHREGS, LWORD);
  1736.     iv->regcode = iv->cod_usedtail;
  1737.     if(stksiz > 0)
  1738.         ENCODE(sub, LWORD, s1: CONST, d1: ESP, dat: stksiz);
  1739. }
  1740. static int
  1741. count_bits(int bits)
  1742. {
  1743. int cnt = 0;
  1744.     if(bits)
  1745.     {
  1746.         while(bits)
  1747.         {
  1748.             if(bits & 1)
  1749.                 ++cnt;
  1750.             bits >>= 1;
  1751.         }
  1752.     }
  1753.     return cnt;
  1754. }
  1755. static void
  1756. end_unix_func(Piv iv, unsigned char *p)
  1757. {
  1758.     ENCODE(LABEL, dat: iv->botlabel);
  1759.     if(iv->regsave)
  1760.     {
  1761.     int savcnt = count_bits(iv->regsave);
  1762.  
  1763.         iv->regcode->ee.dat = iv->regsave;
  1764.         if(iv->stksiz)
  1765.           ENCODE(lea, LWORD, s1: EBP, s1m: INDEXED, d1: ESP, dat: -(4*savcnt));
  1766.         ENCODE(POPREGS, LWORD, dat: iv->regsave);
  1767.     }
  1768.     ENCODE(leave);
  1769.     ENCODE(ret);
  1770.     ENCODE(LINEFEED);
  1771.  
  1772.     dump_unix_codes(iv);
  1773. }
  1774. static void
  1775. reset_funcdata(Piv iv)
  1776. {
  1777. #if 0
  1778.     iv->obuf = (char*)&iv->obufstart;
  1779.     iv->obufstart = 0;
  1780.     iv->obufcnt = 0;
  1781.     iv->func_offset = 0;
  1782.     iv->jbuf = (PJL)&iv->jbufstart;
  1783.     iv->jmpcnt = 0;
  1784.     iv->jbufcnt = 0;
  1785.     iv->jbufstart = 0;
  1786.     iv->extbuf = (PEL)&iv->extbufstart;
  1787.     iv->extcnt = 0;
  1788.     iv->extbufcnt = 0;
  1789.     iv->extbufstart = 0;
  1790.     iv->stackdepth = 0;
  1791.     iv->maxdepth = 0;
  1792.     iv->mindepth = 0;
  1793. #endif
  1794.     iv->numnested = 0;
  1795.     iv->cod_bufcnt = 0;
  1796.     iv->ob_bufcnt = 0;
  1797.     iv->cod_usedhead = 0;
  1798.     iv->ob_usedhead = 0;
  1799.     iv->first_cod = 0;
  1800.     iv->first_ob = 0;
  1801.     Cfreecat(FUNCDATA);
  1802. }
  1803. static void *
  1804. dumpa_unix_func(Piv iv, unsigned char *p)
  1805. {
  1806.     iv->ob = new_nodeO(iv);        /* setup first intermediate output node */
  1807.     link_ob(iv);                /* null node never unlinked */
  1808.     iv->first_ob = iv->ob_usedtail;
  1809.  
  1810.     iv->cod = new_nodeC(iv);    /* setup first code node */
  1811.     link_cod(iv);                /* null node never unlinked */
  1812.     iv->first_cod = iv->cod_usedtail;
  1813.  
  1814.     start_unix_func(iv, p);
  1815.     if((p = POP->next))
  1816.     {
  1817.         for(;;)
  1818.         {
  1819.             if(*p == funcexitop)
  1820.             {
  1821.                 end_unix_func(iv, p);
  1822.                 break;
  1823.             }
  1824.             else
  1825.                 p = do_something(iv, p);
  1826.         }
  1827.     }
  1828.     reset_funcdata(iv);
  1829.     return p;
  1830. }
  1831. static int
  1832. isa_reloc_loc(Piv iv, long offset, char **psymb, int *poffs)
  1833. {
  1834. long key[2];
  1835. struct _rval *vp;
  1836. struct _dval *dp;
  1837. unsigned char *p;
  1838. Pafile pf;
  1839.  
  1840.     key[0] = offset;
  1841.     key[1] = 0;
  1842.     if(SymFind(iv->newreloctbl, &key, &vp))
  1843.     {
  1844.         p = vp->p;
  1845.         pf = iv->files[vp->fileno];
  1846.         *poffs = vp->offset;
  1847.         if(*p == extlocop)
  1848.         {
  1849.             if(vp->rsym <= 0)
  1850.                 return 0;
  1851.             *psymb = pf->symaddr[vp->rsym];
  1852.             return 1;
  1853.         }
  1854.         else
  1855.         {
  1856.             key[0] = vp->base;
  1857.             if(SymFind(iv->datatbl, &key, &dp))
  1858.             {
  1859.                 p = dp->p;
  1860.                 switch(*p)
  1861.                 {
  1862.                     case    datablockop:
  1863.                     case    bssblockop:
  1864.                     case    thunkblockop:
  1865.                         *psymb = pf->symaddr[GS(POPI->s.symnum)];
  1866.                         return 1;
  1867.                     case    mallocblockop:
  1868.                     case    stringblockop:
  1869.                         *psymb = (void*)vp->base; /* must concoct a symbol */
  1870.                         return 2;
  1871.                 }
  1872.             }
  1873.             return 0;
  1874.         }
  1875.     }
  1876.     return 0;
  1877. }
  1878. static void
  1879. dump_unix_header(Piv iv)
  1880. {
  1881.     DUMP("\t.file\t\"%s\"\n_oxcc_compiled:\n\n",
  1882.         filenameof(iv->symaddr[1]));
  1883. }
  1884. static void
  1885. dump_unix_globals(Piv iv)
  1886. {
  1887.     if(SymHead(iv->gbltbl))
  1888.     {
  1889.         while(SymNext(iv->gbltbl))
  1890.         {
  1891.         struct _gloval *valp;
  1892.         unsigned char opcode;
  1893.  
  1894.             SymValue(iv->gbltbl, &valp);
  1895.             if((opcode = *(valp->p)))
  1896.             {
  1897.                 if(opcode == glodatop || opcode == glofuncop)
  1898.                 {
  1899.                     DUMP(".globl _%s\n", valp->symname);
  1900.                 }            
  1901.             }
  1902.         }
  1903.     }
  1904. }
  1905. static void
  1906. dump_unix_bss(Piv iv)
  1907. {
  1908.     if(SymHead(iv->datatbl))
  1909.     {
  1910.         while(SymNext(iv->datatbl))
  1911.         {
  1912.         unsigned char *p;
  1913.         long size;
  1914.         unsigned char opcode, prevopcode = 0;
  1915.         unsigned long *key;
  1916.         struct _dval *val;
  1917.             SymKey(iv->datatbl, &key);
  1918.             SymValue(iv->datatbl, &val);
  1919.             p = val->p;
  1920.             opcode = *p;
  1921.             if(val->prevp)
  1922.                 prevopcode = *(val->prevp);
  1923.             size = val->size;
  1924.             if(opcode == bssblockop)
  1925.             {
  1926.                 if(prevopcode == globssop)
  1927.                 {
  1928.                   DUMP(".comm _%s,%ld\n",
  1929.                       iv->symaddr[GS(POP->data2)], size);
  1930.                 }
  1931.                 else
  1932.                 {
  1933.                   DUMP(".lcomm _%s,%ld\n",
  1934.                       iv->symaddr[GS(POP->data2)], size);
  1935.                 }
  1936.             }
  1937.         }
  1938.     }
  1939. }
  1940. static int
  1941. dump_zero_bytes(Piv iv, unsigned char **pcp, int *pcnt, int cw)
  1942. {
  1943. unsigned char *cp = *pcp;
  1944.  
  1945.     if(*cp == 0)
  1946.     {
  1947.     int cnt;
  1948.     int zcnt = 0;
  1949.         cnt = *pcnt;
  1950.         while(*cp++ == 0 && cnt-- > 0)
  1951.             ++zcnt;
  1952.         if(zcnt > 3)
  1953.         {
  1954.             if(cw)
  1955.                 DUMP("\n  .space  %d", zcnt);
  1956.             else
  1957.                 DUMP("  .space  %d", zcnt);
  1958.             *pcp += zcnt;
  1959.             *pcnt -= zcnt;
  1960.             return 1;
  1961.         }
  1962.     }
  1963.     return 0;
  1964. }
  1965. static int
  1966. dump_zero_shorts(Piv iv, unsigned short **pcp, int *pcnt, int cw)
  1967. {
  1968. unsigned short *cp = *pcp;
  1969.  
  1970.     if(*cp == 0)
  1971.     {
  1972.     int cnt;
  1973.     int zcnt = 0;
  1974.         cnt = *pcnt;
  1975.         while(*cp++ == 0 && cnt-- > 0)
  1976.             ++zcnt;
  1977.         if(zcnt > 3)
  1978.         {
  1979.             if(cw)
  1980.                 DUMP("\n  .space  %d", zcnt*2);
  1981.             else
  1982.                 DUMP("  .space  %d", zcnt*2);
  1983.             *pcp += zcnt;
  1984.             *pcnt -= zcnt;
  1985.             return 1;
  1986.         }
  1987.     }
  1988.     return 0;
  1989. }
  1990. static int
  1991. dump_zero_longs(Piv iv, unsigned long **pcp, int *pcnt, int cw)
  1992. {
  1993. unsigned long *cp = *pcp;
  1994.  
  1995.     if(*cp == 0)
  1996.     {
  1997.     int cnt;
  1998.     int zcnt = 0;
  1999.         cnt = *pcnt;
  2000.         while(*cp++ == 0 && cnt-- > 0)
  2001.             ++zcnt;
  2002.         if(zcnt > 3)
  2003.         {
  2004.             if(cw)
  2005.                 DUMP("\n  .space  %d", zcnt*4);
  2006.             else
  2007.                 DUMP("  .space  %d", zcnt*4);
  2008.             *pcp += zcnt;
  2009.             *pcnt -= zcnt;
  2010.             return 1;
  2011.         }
  2012.     }
  2013.     return 0;
  2014. }
  2015. static void
  2016. dump_unix_bytes(Piv iv, unsigned char *cp, int cnt)
  2017. {
  2018. int first=0, width = 0;
  2019.     while(cnt > 0)
  2020.     {
  2021.         while(width <= 75 && cnt > 0)
  2022.         {
  2023.             if(dump_zero_bytes(iv, &cp, &cnt, width))
  2024.                 break;
  2025.             if(width == 0) {
  2026.                 width = QDUMP("  .byte  ");
  2027.                 first = 0;
  2028.             }
  2029.             if(!first++)
  2030.                 width += DUMP("0x%x", *cp++);
  2031.             else
  2032.                 width += DUMP(",0x%x", *cp++);
  2033.             --cnt;            
  2034.         }
  2035.         QDUMPC('\n');
  2036.         width = 0;
  2037.     }
  2038. }
  2039. static void
  2040. dump_unix_shorts(Piv iv, unsigned short *cp, int cnt)
  2041. {
  2042. int first=0, width = 0;
  2043.     while(cnt > 1)
  2044.     {
  2045.         while(width <= 73 && cnt > 0)
  2046.         {
  2047.             if(dump_zero_shorts(iv, &cp, &cnt, width))
  2048.                 break;
  2049.             if(width == 0) {
  2050.                 width = QDUMP("  .word  ");
  2051.                 first = 0;
  2052.             }
  2053.             if(!first++)
  2054.                 width += DUMP("0x%x", *cp++);
  2055.             else
  2056.                 width += DUMP(",0x%x", *cp++);
  2057.             cnt -= 2;            
  2058.         }
  2059.         QDUMPC('\n');
  2060.         width = 0;
  2061.     }
  2062.     if(cnt > 0)
  2063.         dump_unix_bytes(iv, (unsigned char *)cp, cnt);
  2064. }
  2065. static void
  2066. dump_unix_longs(Piv iv, unsigned long *cp, int cnt, long offset)
  2067. {
  2068. int first = 0, width = 0;
  2069. int rtyp;
  2070. char *psymb;
  2071. int extra;
  2072.  
  2073.     while(cnt > 3)
  2074.     {
  2075.         while(width <= 69 && cnt > 0)
  2076.         {
  2077.             if(dump_zero_longs(iv, &cp, &cnt, width))
  2078.                 break;
  2079.             if(width == 0) {
  2080.                 width = QDUMP("  .long  ");
  2081.                 first = 0;
  2082.             }
  2083.             if(!first++)
  2084.             {
  2085.                 if((rtyp = isa_reloc_loc(iv, offset, &psymb, &extra)))
  2086.                 {
  2087.                     if(rtyp == 1)
  2088.                     {
  2089.                         if(extra == 0)
  2090.                         {
  2091.                         width += DUMP("_%s", psymb);
  2092.                         }
  2093.                         else if(extra < 0)
  2094.                         {
  2095.                         width += DUMP("_%s%d", psymb,extra);
  2096.                         }
  2097.                         else
  2098.                         {
  2099.                         width += DUMP("_%s+%d", psymb,extra);
  2100.                         }
  2101.                     }
  2102.                     else
  2103.                     {
  2104.                         if(extra == 0)
  2105.                         {
  2106.                         width += DUMP("_$%p", psymb);
  2107.                         }
  2108.                         else if(extra < 0)
  2109.                         {
  2110.                         width += DUMP("_$%p%d", psymb,extra);
  2111.                         }
  2112.                         else
  2113.                         {
  2114.                         width += DUMP("_$%p+%d", psymb,extra);
  2115.                         }
  2116.                     }
  2117.                 }
  2118.                 else
  2119.                 {
  2120.                     width += DUMP("0x%lx", *cp++);
  2121.                 }
  2122.             }
  2123.             else
  2124.             {
  2125.                 if((rtyp = isa_reloc_loc(iv, offset, &psymb, &extra)))
  2126.                 {
  2127.                     if(rtyp == 1)
  2128.                     {
  2129.                         if(extra == 0)
  2130.                         {
  2131.                         width += DUMP(",_%s", psymb);
  2132.                         }
  2133.                         else if(extra < 0)
  2134.                         {
  2135.                         width += DUMP(",_%s%d", psymb,extra);
  2136.                         }
  2137.                         else
  2138.                         {
  2139.                         width += DUMP(",_%s+%d", psymb,extra);
  2140.                         }
  2141.                     }
  2142.                     else
  2143.                     {
  2144.                         if(extra == 0)
  2145.                         {
  2146.                         width += DUMP(",_$%p", psymb);
  2147.                         }
  2148.                         else if(extra < 0)
  2149.                         {
  2150.                         width += DUMP(",_$%p%d", psymb,extra);
  2151.                         }
  2152.                         else
  2153.                         {
  2154.                         width += DUMP(",_$%p+%d", psymb,extra);
  2155.                         }
  2156.                     }
  2157.                 }
  2158.                 else
  2159.                 {
  2160.                     width += DUMP(",0x%lx", *cp++);
  2161.                 }
  2162.             }
  2163.             offset += 4;
  2164.             cnt -= 4;            
  2165.         }
  2166.         QDUMPC('\n');
  2167.         width = 0;
  2168.     }
  2169.     if(cnt > 0)
  2170.         dump_unix_shorts(iv, (unsigned short*)cp, cnt);
  2171. }
  2172. static void
  2173. dump_unix_strings(Piv iv)
  2174. {
  2175.     QDUMP("\n.data\n");
  2176.     if(SymHead(iv->datatbl))
  2177.     {
  2178.         while(SymNext(iv->datatbl))
  2179.         {
  2180.         unsigned char *p;
  2181.         long size;
  2182.         unsigned char opcode;
  2183.         unsigned long *key;
  2184.         struct _dval *val;
  2185.  
  2186.             SymKey(iv->datatbl, &key);
  2187.             SymValue(iv->datatbl, &val);
  2188.             p = val->p;
  2189.             opcode = *p;
  2190.             size = val->size;
  2191.             if(opcode == stringblockop)
  2192.             {
  2193.                 DUMP("_$%lx:\n", GL(POP->data1));
  2194.                 dump_unix_bytes(iv, p+24, size);
  2195.             }
  2196.         }
  2197.     }
  2198. }
  2199. static void
  2200. dump_unix_data(Piv iv)
  2201. {
  2202. long mark[2];
  2203.  
  2204.     QDUMPC('\n');
  2205.     if(SymHead(iv->datatbl))
  2206.     {
  2207.         while(SymNext(iv->datatbl))
  2208.         {
  2209.         unsigned char *p;
  2210.         long size;
  2211.         unsigned char opcode;
  2212.         unsigned long *key;
  2213.         struct _dval *val;
  2214.         long offset;
  2215.  
  2216.             SymGetMark(iv->datatbl, mark);
  2217.             SymKey(iv->datatbl, &key);
  2218.             SymValue(iv->datatbl, &val);
  2219.             p = val->p;
  2220.             opcode = *p;
  2221.             size = val->size;
  2222.             offset = GL(POP->data1);
  2223.             if(opcode == datablockop)
  2224.             {
  2225.                 if(size > 3)
  2226.                   DUMP(".align 2\n_%s:\n",
  2227.                     iv->symaddr[GS(POP->data2)]);
  2228.                 else if(size > 1)
  2229.                   DUMP(".align 1\n_%s:\n",
  2230.                       iv->symaddr[GS(POP->data2)]);
  2231.                 dump_unix_longs(iv, (long*)(p+24), size, offset);
  2232.             }
  2233.             else if(opcode == mallocblockop)
  2234.             {
  2235.                 DUMP(".align 2\n_$%lx:\n", offset);
  2236.                 dump_unix_longs(iv, (long*)(p+24), size, offset);
  2237.             }
  2238.             SymSetMark(iv->datatbl, mark);
  2239.         }
  2240.     }
  2241. }
  2242. static void
  2243. dump_unix_funcs(Piv iv)
  2244. {
  2245. Pafile pf;
  2246. unsigned char *p;
  2247. int i;
  2248.  
  2249.     reset_funcdata(iv);
  2250.  
  2251.     QDUMP("\n\n.text\n");
  2252.     for(i = 0; i < iv->numfiles; ++i)
  2253.     {
  2254.         iv->filenum = i;
  2255.         pf = iv->files[i];
  2256.         p = pf->file_p;
  2257.  
  2258.         while(*p != endfileop)
  2259.         {
  2260.             if(*p == labelop)
  2261.             {
  2262. #if 0
  2263.                 DUMP("L%u:\n", GL(POP->data);
  2264. #endif
  2265.             }
  2266.             else if(*p == gfuncdefop || *p == sfuncdefop)
  2267.             {
  2268.                 p = dumpa_unix_func(iv, p);
  2269.             }
  2270.             else if(*p == anfblockop)
  2271.             {
  2272.                 PERROR(pName ": Sorry, Outer anf blocks not handled.\n");
  2273.             }
  2274.             p = POP->next;
  2275.         }
  2276.     }
  2277. }
  2278. static void
  2279. gen_unix_output(Piv iv)
  2280. {
  2281. long tim = time(0);
  2282. char *date = ctime(&tim);
  2283.  
  2284.     DUMP("// `%s'     %s// ", iv->outname, date);
  2285.     DUMP(notice,MAJOR_VERSION,MINOR_VERSION);
  2286.     QDUMP("\n\n");
  2287.  
  2288.     dump_unix_header(iv);
  2289.     dump_unix_globals(iv);
  2290.     dump_unix_strings(iv);
  2291.     dump_unix_data(iv);
  2292.     dump_unix_funcs(iv);
  2293.     dump_unix_bss(iv);
  2294. }
  2295. static void
  2296. gen_dos_output(Piv iv)
  2297. {
  2298. long tim = time(0);
  2299. char *date = ctime(&tim);
  2300.     DUMP(";  `%s'     %s\n;", iv->outname, date);
  2301.     DUMP(notice,MAJOR_VERSION,MINOR_VERSION);
  2302.     QDUMP("\n\n");
  2303. }
  2304. static int
  2305. gen_output(Piv iv, char *outpath)
  2306. {/* Assembler output */
  2307. char *cp;
  2308. Pafile pf;
  2309. int i;
  2310. char outname[256];
  2311.  
  2312.     strcpy(outname, outpath);
  2313.     pf = iv->files[0];
  2314.     iv->target_assembler = pf->header_p->hdr.target_assembler;
  2315.     iv->target_hardware = pf->header_p->hdr.target_hardware;
  2316.     iv->target_debugger = pf->header_p->hdr.target_debugger;
  2317.     iv->target_os = pf->header_p->hdr.target_os;
  2318.     iv->memory_model = pf->header_p->hdr.memory_model;
  2319.     iv->obj_format = pf->header_p->hdr.obj_format;
  2320.     if((cp = strrchr(outname, '.')))
  2321.     {
  2322. #if 0
  2323.         if(iv->target_assembler == UNIX || iv->target_assembler == GAS)
  2324.             strcpy(cp, ".s");
  2325.         else strcpy(cp, ".asm");
  2326. #endif
  2327.     }
  2328.     else
  2329.     {
  2330.         if(iv->target_assembler == UNIX || iv->target_assembler == GAS)
  2331.             strcat(outname, ".s");
  2332.         else
  2333.             strcat(outname, ".asm");
  2334.     }
  2335.     for(i = 1; i < iv->argc; ++i)
  2336.     {
  2337.       if(!strcmp(outname, iv->argv[i]))
  2338.       {
  2339.         PERROR(pName ": ERROR output file `%s' is same as input file\n", outname);
  2340.       }
  2341.     }
  2342.     if(!(iv->outfile = fopen(outname, "wb")))
  2343.     {
  2344.         PERROR(pName ": Cannot open output file %s\n", outname);
  2345.     }
  2346.     iv->outname = filenameof(outname);
  2347.  
  2348.     make_final_symtab(iv);
  2349.  
  2350.     if(iv->target_assembler == UNIX || iv->target_assembler == GAS)
  2351.         gen_unix_output(iv);
  2352.     else
  2353.         gen_dos_output(iv);
  2354.         
  2355.     fclose(iv->outfile);
  2356.     iv->outfile = 0;    
  2357.     return iv->errors;
  2358. }
  2359. /* ======================= END ASMCODE OUTPUT GENERATOR ==================== */
  2360.  
  2361. /* ===================== GENERIC CODE BELOW THIS POINT ================== */
  2362. static jmp_buf run_env;
  2363. static void
  2364. prerror(const char *fmt, ...)
  2365. {
  2366.     VFPRINTF(fmt, (char *)(((int *)(&fmt))+1));
  2367.     longjmp(run_env, 3);
  2368. }
  2369. static void
  2370. prwarn(const char *fmt, ...)
  2371. {
  2372.     VFPRINTF(fmt, (char *)(((int *)(&fmt))+1));
  2373. }
  2374. static void
  2375. info(const char *fmt, ...)
  2376. {
  2377.     vfprintf(stdout, fmt, (char *)(((int *)(&fmt))+1));
  2378. }
  2379. /* ========================= MULTI HEAP MALLOC ========================== */
  2380. #define LOCAL static
  2381.  
  2382. #if USING_FRAMEWORK
  2383. #define THEWELL(a) mallocC(local_category, a)
  2384. static int local_category;
  2385. static int num_instance;
  2386. extern void *mallocC(int, int);
  2387. extern void freecat(int);
  2388. extern void oxlink_clear_bss();
  2389. extern int NewMallocCategory();
  2390. #endif /* USING_FRAMEWORK */
  2391.  
  2392. #define BASE_CATEGORY 0
  2393. #define MEMORY_BUG 0
  2394. #define PRINT_RAWDATA 0
  2395.  
  2396. #if MEMORY_BUG == 1
  2397. #define MPRINTF printf
  2398. #else
  2399. #define MPRINTF(args...)
  2400. #endif
  2401.  
  2402. #define PAGESIZE (4096)    /* can use `pagesize' function in OS */
  2403. #define ALIGNMENTM (sizeof(unsigned long))
  2404. #define MAL_MAXLEVEL (12)
  2405. #define ROUNDINGM(a) ((ALIGNMENTM-(a&(ALIGNMENTM-1)))&(ALIGNMENTM-1))
  2406. #define ALLOCSIZE (4096)
  2407. #define FRNTGUARD (0x544e5246UL)
  2408. #define BACKGUARD (0x48434142UL)
  2409. #ifndef THEWELL
  2410. #define THEWELL do_sbrk
  2411. #endif
  2412. #define NUMTYPES 3
  2413. #define SIZEH 0
  2414. #define FREEH 1
  2415. #define USEDH 2
  2416.  
  2417. #define SKIPVARS NodePM update[MAL_MAXLEVEL+1];NodePM node,prev;int level
  2418.  
  2419. #define DELETENODE(TYPE) \
  2420. {for(level=0;level<=bp->TYPE##level; level++)\
  2421. {if(update[level]->fptr[level] == node)\
  2422. update[level]->fptr[level] = node->fptr[level];else break;}\
  2423. while(bp->TYPE##level>0 && bp->TYPE##header->fptr[bp->TYPE##level]==_NILLL)\
  2424. bp->TYPE##level--;free_Mnode(bp,node,TYPE);}
  2425.  
  2426. #define INSERT() \
  2427. {while(level >= 0){\
  2428. node->fptr[level] = update[level]->fptr[level];\
  2429. update[level]->fptr[level] = node;level--;}}
  2430.  
  2431. #define SETLEVEL(TYPE) \
  2432. {level = getMlevel(bp, bp->TYPE##level);\
  2433. while(bp->TYPE##level < level)update[++bp->TYPE##level]=bp->TYPE##header;}
  2434.  
  2435. #define FINDKEY(TYPE, KEYVAL)\
  2436. {node = bp->TYPE##header;\
  2437. for(level = bp->TYPE##level; level >= 0; level--){\
  2438. while(node->fptr[level]->key < KEYVAL)\
  2439. node = node->fptr[level];\
  2440. update[level] = node;}prev=node;node=node->fptr[0];}
  2441.  
  2442. #define DETACH(SN)\
  2443. {SN->bptr->fptr=SN->fptr;if(SN->fptr)SN->fptr->bptr=SN->bptr;}
  2444.  
  2445. #define UNLINK(SN, N)\
  2446. {if(!sp->fptr&&sp->bptr->bptr<=(AddrP)(MAL_MAXLEVEL+1))dsize[N]=sp->size;\
  2447. DETACH(SN);free_addr(bp,SN);}
  2448.  
  2449. #define CHECKGUARDS(MSG)\
  2450. {if(bp->guarded){\
  2451. unsigned *p2;\
  2452. p2 = (void*)((char*)address+cursize-ALIGNMENTM);\
  2453. if(*address != FRNTGUARD)\
  2454. PERROR(pName #MSG ":%d: corrupted at 0x%x\n", bp->bincat, addr);\
  2455. if(*p2 != BACKGUARD)\
  2456. PERROR(pName #MSG ":%d: corrupted by 0x%x\n", bp->bincat, addr);}}
  2457.  
  2458. #if MEMORY_BUG == 1
  2459. #define HEAPCHECK \
  2460. {void *lastaddr;\
  2461. if(category > 0){\
  2462. Cguard(category);\
  2463. if((lastaddr = Cheapcheck(category, NULL))){\
  2464. FINDKEY(USEDH, (unsigned)lastaddr-ALIGNMENTM)\
  2465. MPRINTF("bad heap at %x c:%u size=%u\n", lastaddr, category, node->value);\
  2466. (void)print_rawdata(lastaddr-ALIGNMENTM, node->value);\
  2467. abort();}}}
  2468. #else
  2469. #define HEAPCHECK
  2470. #endif
  2471.  
  2472. struct _catlocs {
  2473.     void *addr;
  2474.     struct _catlocs *fptr;
  2475. };
  2476.  
  2477. typedef struct _nodeM
  2478. {
  2479.     unsigned key;
  2480.     unsigned value;
  2481.     unsigned levels;    /* must always be after value */
  2482.     struct _nodeM *fptr[1];
  2483. } NodeM, *NodePM;
  2484.  
  2485. typedef struct _addr
  2486. {
  2487.     struct _addr *fptr;
  2488.     struct _addr *bptr;
  2489.     NodePM maddr;
  2490.     unsigned size;
  2491. } *AddrP;
  2492.  
  2493. struct _bins {
  2494.     unsigned bits;
  2495.     unsigned nbits;
  2496.     NodePM SIZEHheader;
  2497.     int SIZEHlevel;
  2498.     NodePM FREEHheader;
  2499.     int FREEHlevel; 
  2500.     NodePM USEDHheader;
  2501.     int USEDHlevel;
  2502.  
  2503.     unsigned bincat;
  2504.     unsigned maxloc;
  2505.     unsigned minloc;
  2506.     struct _catlocs *catlocs;
  2507.     struct _bins *fptr;
  2508.     NodePM freenodes[NUMTYPES][MAL_MAXLEVEL+2];
  2509.     struct _addr *freeaddrlocs;
  2510.     char *chunkbase[NUMTYPES];
  2511.     int chunksize[NUMTYPES];
  2512.     int guarded;
  2513.     int addrbump;
  2514. };
  2515.  
  2516. static struct _bins zbp;
  2517. static struct _bins *hmap[1009];
  2518. static struct _nodeM _nilll = {0xffffffff,0,0,{0}};
  2519. static struct _nodeM *_NILLL = &_nilll;
  2520. static unsigned maxloc;
  2521. static unsigned minloc;
  2522. static struct _bins *freebinlocs;
  2523. static struct _catlocs *freecatlocs;
  2524. static char *binbase;
  2525. static int binsize;
  2526. static int chunksizes[] = {ALLOCSIZE,3*ALLOCSIZE,2*ALLOCSIZE};
  2527.  
  2528.  
  2529. static long randtbl[32]    = { 0L,
  2530.     0x9a319039L, 0x32d9c024L, 0x9b663182L, 0x5da1f342L, 
  2531.     0xde3b81e0L, 0xdf0a6fb5L, 0xf103bc02L, 0x48f340fbL, 
  2532.     0x7449e56bL, 0xbeb1dbb0L, 0xab5c5918L, 0x946554fdL, 
  2533.     0x8c2e680fL, 0xeb3d799fL, 0xb11ee0b7L, 0x2d436b86L, 
  2534.     0xda672e2aL, 0x1588ca88L, 0xe369735dL, 0x904f35f7L, 
  2535.     0xd7158fd6L, 0x6fa6f051L, 0x616e6b96L, 0xac94efdcL, 
  2536.     0x36413f93L, 0xc622c298L, 0xf5a42ab8L, 0x8a88d77bL, 
  2537.     0xf5ad9d0eL, 0x8999220bL, 0x27fb47b9L
  2538. };
  2539.  
  2540. static  long *fptr    = &randtbl[4];
  2541. static  long *rptr    = &randtbl[1];
  2542.  
  2543. /* ======================== START OF CODE =========================== */
  2544. #if PRINT_RAWDATA == 1
  2545. static char
  2546. hexbyte(unsigned int c)
  2547. {
  2548. char x = c & 0xf;
  2549.  
  2550.     return x + ((x>9) ? 55 : 48);
  2551. }
  2552. static void
  2553. print_rawdata(void *rawdata, long size)
  2554. {
  2555. unsigned long vaddr = 0;
  2556. unsigned char *d = rawdata;
  2557. int i,j;
  2558. char addr[9];
  2559. char hex1[24];
  2560. char hex2[24];
  2561. char side1[9];
  2562. char side2[9];
  2563.  
  2564.     addr[8] = 0;
  2565.     hex1[23] = 0;
  2566.     hex2[23] = 0;
  2567.     side1[8] = 0;
  2568.     side2[8] = 0;
  2569.     while(size > 0)
  2570.     {
  2571.     unsigned long qaddr = vaddr;
  2572.         memset(addr, '0', 8);
  2573.         memset(hex1, ' ', 23);
  2574.         memset(hex2, ' ', 23);
  2575.         memset(side1, ' ', 8);
  2576.         memset(side2, ' ', 8);
  2577.         i = 7;
  2578.         while(qaddr)
  2579.         {
  2580.             addr[i--] = hexbyte(qaddr);
  2581.             qaddr >>= 4;
  2582.         }
  2583.         for(i=0,j=0; i < 8; ++i)
  2584.         {
  2585.             if(--size >= 0)
  2586.             {
  2587.             unsigned int c = *d++;
  2588.                 if(isprint(c))
  2589.                     side1[i] = c;
  2590.                 else
  2591.                     side1[i] = '.';
  2592.                 hex1[j++] = hexbyte(c>>4);
  2593.                 hex1[j++] = hexbyte(c);
  2594.                     ++j;
  2595.             }
  2596.             else break;
  2597.         }
  2598.         for(i=0,j=0; i < 8; ++i)
  2599.         {
  2600.             if(--size >= 0)
  2601.             {
  2602.             unsigned int c = *d++;
  2603.                 if(isprint(c))
  2604.                     side2[i] = c;                    
  2605.                 else
  2606.                     side2[i] = '.';
  2607.                 hex2[j++] = hexbyte(c>>4);
  2608.                 hex2[j++] = hexbyte(c);
  2609.                 ++j;
  2610.             }
  2611.             else break;
  2612.         }
  2613.         VPRINTF("%s  %s%s%s  %s%s%s\n",addr,hex1," | ",hex2,side1,"|",side2);
  2614.         vaddr += 16;
  2615.     }
  2616. }
  2617. #endif
  2618.  
  2619. /*
  2620.  * Returns a really good 31-bit random number.
  2621.  */
  2622. static long
  2623. lrandom()
  2624. {
  2625. long i;
  2626.     
  2627.     *fptr += *rptr;
  2628.     i = (*fptr >> 1) & 0x7fffffffUL;
  2629.     if(++fptr > &randtbl[31])
  2630.     {
  2631.         fptr = &randtbl[1];
  2632.         ++rptr;
  2633.     }
  2634.     else
  2635.     {
  2636.         if(++rptr > &randtbl[31])  
  2637.             rptr = &randtbl[1];
  2638.     }
  2639.     return( i );
  2640. }
  2641. #if !USING_FRAMEWORK
  2642. static void *
  2643. do_sbrk(unsigned amount)
  2644. {
  2645. void *address;
  2646.  
  2647.     address = sbrk(amount);    /* OR WHATEVER TO ACCESS THE OPERATING SYSTEM */
  2648.     if(address == (void*)-1)
  2649.     {
  2650.         PERROR(pName "\nsystem out of memory, requested %u bytes\n", amount);
  2651.     }
  2652.     return address;
  2653. }
  2654. #endif
  2655.  
  2656. static struct _catlocs *
  2657. new_catloc(void)
  2658. {
  2659. struct _catlocs *p;
  2660.     if((p=freecatlocs))
  2661.     {
  2662.         freecatlocs = p->fptr;
  2663.         return p;
  2664.     }
  2665.     if(binsize < sizeof(struct _catlocs))
  2666.     {
  2667.         binbase = THEWELL(4096);
  2668.         binsize = 4096;
  2669.     }
  2670.     binsize -= sizeof(struct _catlocs);
  2671.     p = (void*)binbase;
  2672.     binbase += sizeof(struct _catlocs);
  2673.     return p;
  2674. }
  2675. static void
  2676. free_catloc(struct _catlocs *p)
  2677. {
  2678.     p->fptr = freecatlocs;
  2679.     freecatlocs = p;
  2680. }
  2681. static void *
  2682. new_chunk(struct _bins *bp, int size, int type)
  2683. {
  2684. char *p;
  2685.      if(bp->chunksize[type] < size)
  2686.     {
  2687.         if(bp->bincat == 0) {
  2688.             bp->chunkbase[type] = THEWELL(chunksizes[type]);
  2689.             bp->chunksize[type] = chunksizes[type];
  2690.         }
  2691.         else {
  2692.         struct _catlocs *cl;
  2693.             bp->chunkbase[type] = Cmalloc(0,chunksizes[type]-zbp.guarded);
  2694.             bp->chunksize[type] = chunksizes[type]-zbp.guarded;
  2695.             cl = new_catloc();
  2696.             cl->addr = bp->chunkbase[type];
  2697.             cl->fptr = bp->catlocs;
  2698.             bp->catlocs = cl;
  2699.         }
  2700.     }
  2701.     bp->chunksize[type] -= size;
  2702.     p = bp->chunkbase[type];
  2703.     bp->chunkbase[type] += size;
  2704.     return p;
  2705. }
  2706. static void *
  2707. new_Mnode(struct _bins *bp, int levels, int type)
  2708. {
  2709. int size;
  2710. NodePM p;
  2711.  
  2712.     if((p=bp->freenodes[type][levels]))
  2713.     {
  2714.         bp->freenodes[type][levels] = p->fptr[0];
  2715.         p->value = 0;
  2716.         return p;
  2717.     }
  2718.      size = sizeof(struct _nodeM) + levels * sizeof(void*);
  2719.     p = new_chunk(bp, size, type);
  2720.     p->levels = levels;
  2721.     p->value = 0;
  2722.     return p;    
  2723. }
  2724. static void
  2725. free_Mnode(struct _bins *bp, NodePM p, int type)
  2726. {
  2727.     p->fptr[0] = bp->freenodes[type][p->levels];
  2728.     bp->freenodes[type][p->levels] = p;
  2729. }
  2730. static struct _addr *
  2731. new_addr(struct _bins *bp)
  2732. {
  2733. struct _addr *p;
  2734.     if((p=bp->freeaddrlocs))
  2735.     {
  2736.         bp->freeaddrlocs = p->fptr;
  2737.         return p;
  2738.     }
  2739.     return new_chunk(bp, sizeof(struct _addr), FREEH);
  2740. }
  2741. static void
  2742. free_addr(struct _bins *bp, struct _addr *p)
  2743. {
  2744.     p->fptr = bp->freeaddrlocs;
  2745.     bp->freeaddrlocs = p;
  2746. }
  2747. static struct _bins *
  2748. new_bins(void)
  2749. {
  2750. struct _bins *p;
  2751.     if((p=freebinlocs))
  2752.     {
  2753.         freebinlocs = p->fptr;
  2754.         return p;
  2755.     }
  2756.      if(binsize < sizeof(struct _bins))
  2757.     {
  2758.         binbase = THEWELL(4096);
  2759.         binsize = 4096;
  2760.     }
  2761.     binsize -= sizeof(struct _bins);
  2762.     p = (struct _bins*)binbase;
  2763.     binbase += sizeof(struct _bins);
  2764.     return p;
  2765. }
  2766. static void
  2767. free_bins(struct _bins *p)
  2768. {
  2769.     p->fptr = freebinlocs;
  2770.     freebinlocs = p;
  2771. }
  2772. static int
  2773. getMlevel (struct _bins *p, int binlevel)
  2774. {
  2775. int level = -1;
  2776. int bits = 0;
  2777.  
  2778.     while(bits == 0)
  2779.     {
  2780.         if (p->nbits == 0)
  2781.         {
  2782.             p->bits = lrandom();
  2783.             p->nbits = 15;
  2784.         }
  2785.         bits = p->bits & 3;
  2786.         p->bits >>= 2;
  2787.         p->nbits--;
  2788.  
  2789.         if(++level > binlevel)
  2790.             break;
  2791.     }
  2792.     return (level > MAL_MAXLEVEL) ? MAL_MAXLEVEL : level;
  2793. }
  2794.  
  2795. static void
  2796. init_bins(struct _bins *bp, int category)
  2797. {
  2798. int i;
  2799. int binnum = category % 1009;
  2800.  
  2801.     bzero(bp, sizeof(struct _bins));
  2802.     bp->bincat = category;
  2803.     bp->minloc = 0xffffffff;
  2804.     bp->fptr = hmap[binnum];
  2805.     hmap[binnum] = bp;
  2806.     bp->SIZEHheader = new_Mnode(bp, MAL_MAXLEVEL+1, SIZEH);
  2807.     bp->FREEHheader = new_Mnode(bp, MAL_MAXLEVEL+1, FREEH);
  2808.     bp->USEDHheader = new_Mnode(bp, MAL_MAXLEVEL+1, USEDH);
  2809.  
  2810.     for(i = 0; i <= MAL_MAXLEVEL; ++i)
  2811.     {
  2812.         bp->SIZEHheader->fptr[i] = _NILLL;
  2813.         bp->FREEHheader->fptr[i] = _NILLL;
  2814.         bp->USEDHheader->fptr[i] = _NILLL;
  2815.     }
  2816. }
  2817.  
  2818. static struct _bins*
  2819. getcat(int category)
  2820. {
  2821. struct _bins *hbp;
  2822.  
  2823.     hbp = hmap[category % 1009];
  2824.     while(hbp)
  2825.     {
  2826.         if(hbp->bincat == category)
  2827.             return hbp;
  2828.         hbp = hbp->fptr;
  2829.     }
  2830.     return 0;
  2831. }
  2832. static struct _bins *
  2833. initcat(int category)
  2834. {
  2835. struct _bins *bp;
  2836.  
  2837.     if(category == 0)
  2838.     {
  2839.         bp = &zbp;
  2840.         if(zbp.SIZEHheader == 0)
  2841.             init_bins(bp, category);
  2842.         return bp;
  2843.     }
  2844.     /* do this to set zbp.guarded properly on startup */
  2845.     if(zbp.SIZEHheader == 0)
  2846.         initcat(0);
  2847.  
  2848.     if((bp = new_bins()))
  2849.     {
  2850.         init_bins(bp, category);
  2851.         return bp;
  2852.     }
  2853.     return 0;
  2854. }
  2855. static void *
  2856. getspace(struct _bins *bp, unsigned size, unsigned *remainder)
  2857. {
  2858. unsigned desired;
  2859. void *address;
  2860.   
  2861.     desired = ((size+ALLOCSIZE-1)/ALLOCSIZE)*ALLOCSIZE;
  2862.     if(bp->bincat == 0)
  2863.     {
  2864.         address = THEWELL(desired);
  2865.         *remainder = desired - size;
  2866.     }
  2867.     else
  2868.     {
  2869.     struct _catlocs *cl;
  2870.  
  2871.         if((desired-size) > zbp.guarded)
  2872.             desired -= zbp.guarded;
  2873.         
  2874.         address = Cmalloc(0, desired);
  2875.         *remainder = desired - size;
  2876.  
  2877.         /* save the gross allocations for the category */
  2878.         cl = new_catloc();
  2879.         cl->addr = address;
  2880.         cl->fptr = bp->catlocs;
  2881.         bp->catlocs = cl;
  2882.     }
  2883.     /* maintain address range info */
  2884.     if((unsigned)address < bp->minloc)
  2885.         bp->minloc = (unsigned)address;
  2886.     if(((unsigned)address + desired) > bp->maxloc)
  2887.         bp->maxloc = (unsigned)address + desired;
  2888.      if(bp->minloc < minloc)
  2889.          minloc = bp->minloc;
  2890.      if(bp->maxloc > maxloc)
  2891.          maxloc = bp->maxloc;
  2892.     return address;
  2893. }
  2894. static void
  2895. addto_sizelist(struct _bins *bp, AddrP ap)
  2896. {
  2897. SKIPVARS;
  2898.  
  2899.     /* INSERT IN SIZE LIST */
  2900.     FINDKEY(SIZEH, ap->size)
  2901.  
  2902.     if(node->key == ap->size)
  2903.     {/* size node exists */
  2904.         ap->fptr = (AddrP)node->value;
  2905.         ap->bptr = (AddrP)&node->value;
  2906.         if(ap->fptr) ap->fptr->bptr = ap;
  2907.         node->value = (unsigned)ap;
  2908.     }
  2909.     else
  2910.     {/* create new size node */
  2911.         SETLEVEL(SIZEH)
  2912.         node = new_Mnode(bp, level, SIZEH);
  2913.         node->key = ap->size;
  2914.         node->value = (unsigned)ap;
  2915.         ap->fptr = 0;
  2916.         ap->bptr = (AddrP)&node->value;
  2917.         INSERT()
  2918.     }
  2919. }
  2920. static void
  2921. addto_freelist(struct _bins *bp, void *addr, unsigned size)
  2922. {
  2923. SKIPVARS;
  2924. AddrP ap,sp;
  2925. unsigned dsize[2];
  2926.  
  2927.     /* GET NEW ADDR STRUCT */
  2928.     ap = new_addr(bp);
  2929.     ap->size = size;
  2930.  
  2931.     dsize[1] = dsize[0] = 0; /* sizenode deletion markers */
  2932.  
  2933.     /* CHECK FREE LIST */
  2934.     FINDKEY(FREEH, (unsigned)addr)
  2935.  
  2936.     /* CHECK FOR MERGE OR INSERT */
  2937.     if(prev->value && prev->key+((AddrP)prev->value)->size == (unsigned)addr)
  2938.     {/* merge with previous block */
  2939.         ap->size += ((AddrP)prev->value)->size;
  2940.  
  2941.         if(prev->key + ap->size == node->key)
  2942.         {/* merge with previous and next block */
  2943.             sp = (AddrP) node->value;;
  2944.             ap->size += sp->size;
  2945.  
  2946.             /* delete size struct for next block */
  2947.             UNLINK(sp, 0)
  2948.  
  2949.             /* delete next block */
  2950.             DELETENODE(FREEH);
  2951.         }
  2952.         /* delete size struct for prev block */
  2953.         sp = (AddrP)prev->value;
  2954.         UNLINK(sp, 1)
  2955.  
  2956.         /* set new address struct */
  2957.         prev->value = (unsigned)ap;
  2958.         ap->maddr = prev;
  2959.     }
  2960.     else if(node->value && (char*)addr + size == (void*)node->key)
  2961.     {/* merge with next block */
  2962.         sp = (AddrP) node->value;;
  2963.         node->key = (unsigned)addr;
  2964.         ap->size += sp->size;
  2965.  
  2966.         /* unlink size struct for next block */
  2967.         UNLINK(sp,0)
  2968.  
  2969.         /* set new address struct */
  2970.         node->value = (unsigned)ap;
  2971.         ap->maddr = node;
  2972.     }
  2973.     else
  2974.     {/* insert in free list */
  2975.  
  2976.         SETLEVEL(FREEH)
  2977.         node = new_Mnode(bp, level, FREEH);
  2978.         node->key = (unsigned)addr;
  2979.         node->value = (unsigned)ap;
  2980.         ap->maddr = node;
  2981.         INSERT()
  2982.     }
  2983.     addto_sizelist(bp, ap);
  2984.  
  2985.     /* Remove sizenodes eliminated by merge */
  2986.     if(dsize[0])
  2987.     {
  2988.         FINDKEY(SIZEH, dsize[0])
  2989.         if(node->value == 0)
  2990.           DELETENODE(SIZEH)
  2991.     }
  2992.     if(dsize[1])
  2993.     {
  2994.         FINDKEY(SIZEH, dsize[1])
  2995.         if(node->value == 0)
  2996.           DELETENODE(SIZEH)
  2997.     }
  2998. }
  2999.  
  3000. LOCAL void* 
  3001. Cmemalign(int category, unsigned alignment, unsigned req)
  3002. {
  3003. SKIPVARS;
  3004. NodePM fnode;
  3005. unsigned remainder;
  3006. unsigned *address;
  3007. struct _bins *bp;
  3008. unsigned mask, size;
  3009.  
  3010.  
  3011.     if(!(bp = getcat(category)))
  3012.       if(!(bp = initcat(category)))
  3013.         return 0;
  3014. HEAPCHECK
  3015.     if(req == 0)
  3016.         req = ALIGNMENTM;
  3017.     else
  3018.         req += ROUNDINGM(req);
  3019.     size = req += bp->guarded;
  3020.  
  3021.     if(alignment)
  3022.     {
  3023.         alignment += ROUNDINGM(alignment);
  3024.         if(alignment > ALIGNMENTM)
  3025.         {
  3026.             mask = alignment -1;
  3027.             size = req + alignment + bp->guarded;
  3028.         }
  3029.         else
  3030.         {
  3031.             alignment = 0;
  3032.         }
  3033.     }
  3034.  
  3035.     /* check sizelist for candidate */
  3036.     FINDKEY(SIZEH, size)
  3037.     fnode = node;
  3038. trynext:
  3039.     if(node->key != 0xffffffff)
  3040.     {/* found an appropriately sized block */
  3041.     AddrP sp = (AddrP)node->value;
  3042.  
  3043.         if(!sp && node == fnode)
  3044.         {
  3045.         NodePM q;
  3046.             q = node->fptr[0];
  3047.             DELETENODE(SIZEH)
  3048.             node = q;
  3049.             goto trynext;
  3050.         }
  3051.         if(!sp)
  3052.         {/* no available space at this size */
  3053.             node = node->fptr[0];
  3054.             goto trynext;
  3055.         }
  3056.  
  3057.         /* extract some space from this block */
  3058.         remainder = node->key - size;
  3059.         address = (void*)sp->maddr->key;
  3060.         sp->maddr->key += size;
  3061.         DETACH(sp);
  3062.  
  3063.         if(node->value == 0)
  3064.         {/* no more blocks of this size, delete sizenode */
  3065.             if(node != fnode)
  3066.               FINDKEY(SIZEH, size)
  3067.             DELETENODE(SIZEH)
  3068.         }
  3069.  
  3070.         if(remainder == 0)
  3071.         {/* no remaining space,the node in freelist is exhausted, delete it */
  3072.             FINDKEY(FREEH, sp->maddr->key)
  3073.             DELETENODE(FREEH)
  3074.             free_addr(bp, sp);
  3075.         }
  3076.         else
  3077.         {/* space remains in block, move it to new size loc */
  3078.             sp->size = remainder;
  3079.             addto_sizelist(bp, sp);
  3080.         }
  3081.     }
  3082.     else
  3083.     {
  3084.         address = getspace(bp, size, &remainder);
  3085.         if(remainder)
  3086.           addto_freelist(bp, ((char*)address)+size, remainder);
  3087.     }
  3088.     if(alignment)
  3089.     {
  3090.     unsigned diff;
  3091.         if((diff = (unsigned)address & mask))
  3092.         {/* move address forward */
  3093.         char *naddress;
  3094.         unsigned lose;
  3095.             lose = alignment - diff;
  3096.             naddress = (char*)address + lose;
  3097.             addto_freelist(bp, address, lose);
  3098.             address = (unsigned*)naddress;
  3099.         }
  3100.     }
  3101.     if(bp->guarded)
  3102.     {
  3103.       *address = FRNTGUARD;
  3104.       *((unsigned*)(((char*)address)+req-ALIGNMENTM)) = BACKGUARD;
  3105.  
  3106.     }
  3107.  
  3108.     FINDKEY(USEDH, (unsigned)address)
  3109.  
  3110.     if(node->key == (unsigned)address) {
  3111.       PERROR(pName "allocC:%d: bookkeeping nodes are corrupted at:0x%x\n",
  3112.           category, address);
  3113.     }
  3114.     SETLEVEL(USEDH)
  3115.     node = new_Mnode(bp, level, USEDH);
  3116.     node->key = (unsigned)address;
  3117.     node->value = req;
  3118.     INSERT()    
  3119.  
  3120.     return address+bp->addrbump;
  3121. }
  3122. LOCAL void*
  3123. Ccalloc(int category, unsigned cnt, unsigned elem_size)
  3124. {
  3125. unsigned size = cnt * elem_size;
  3126. void* buf;;
  3127.  
  3128.   if((buf = Cmalloc(category, size)))
  3129.       bzero(buf, size);
  3130.   return buf;
  3131. };
  3132. LOCAL void
  3133. Cfree(int category, void* addr)
  3134. {
  3135. unsigned cursize;
  3136. unsigned *address;
  3137. struct _bins *bp;
  3138. SKIPVARS;
  3139.     if(addr)
  3140.     {
  3141.         if(!(bp = getcat(category))) {
  3142.             PERROR(pName "Cfree:%d: non-existant category at:0x%x\n",category,addr);
  3143.         }
  3144. HEAPCHECK
  3145.         address = (void*) ((unsigned*)addr - bp->addrbump);
  3146.         FINDKEY(USEDH, (unsigned)address)
  3147.         if(node->key != (unsigned)address) {
  3148.           PERROR(pName "Cfree:%d: bogus address=0x%x\n", category, addr);
  3149.         }
  3150.         cursize = node->value;
  3151.         CHECKGUARDS(Cfree)
  3152.         DELETENODE(USEDH)
  3153.  
  3154.         addto_freelist(bp, address, cursize);
  3155.     }
  3156.     else PERROR(pName "Cfree:%d: null pointer\n", category);
  3157. }
  3158. LOCAL void* 
  3159. Crealloc(int category, void* addr, unsigned newsize)
  3160. {
  3161. SKIPVARS;
  3162. unsigned cursize;
  3163. unsigned *address;
  3164. struct _bins *bp;
  3165. NodePM onode;
  3166.  
  3167.     if(addr == 0) 
  3168.         return Cmalloc(category, newsize);
  3169.     else
  3170.     {
  3171.         if(!(bp = getcat(category))) {
  3172.            PERROR(pName "reallocC:%d: non-existant category at:%x\n",category,addr);
  3173.         }
  3174. HEAPCHECK 
  3175.         if(newsize == 0)
  3176.             newsize = ALIGNMENTM;
  3177.         else
  3178.             newsize += ROUNDINGM(newsize);
  3179.         newsize += bp->guarded;
  3180.  
  3181.         address = (void*)(((char*)addr)-(bp->guarded/2));
  3182.         FINDKEY(USEDH, (unsigned)address)
  3183.         if(node->key != (unsigned)address) {
  3184.           PERROR(pName "reallocC:%d: bogus address=0x%x\n", category, addr);
  3185.         }
  3186.         cursize = node->value;
  3187.         node->value = newsize;
  3188.         onode = node;
  3189.  
  3190.         CHECKGUARDS(reallocC)
  3191.  
  3192.         if(newsize == cursize)
  3193.             return addr;
  3194.         if(newsize > cursize)
  3195.         {/* check if block can be extended */
  3196.         void *taddr = ((char*)address) + cursize;
  3197.         unsigned extendsize = newsize-cursize;
  3198.  
  3199.             /* check freelist for an available block at the right address */
  3200.             FINDKEY(FREEH, (unsigned)taddr)
  3201.             if(node->key == (unsigned)taddr)
  3202.             {
  3203.             AddrP sp = (AddrP)node->value;
  3204.                 if(sp->size >= extendsize)
  3205.                 {/* BLOCK CAN BE EXTENDED INTERNALLY */
  3206.                     node->key += extendsize;
  3207.                     sp->size -= extendsize;
  3208.                     DETACH(sp)
  3209.                     if(sp->size == 0)
  3210.                     {/* the extension block is used up, delete this node */
  3211.                         free_addr(bp, sp);
  3212.                         DELETENODE(FREEH)
  3213.                     }
  3214.                     else
  3215.                     {/* shift the remainder in the sizelist */
  3216.                         addto_sizelist(bp, sp);
  3217.                     }
  3218.                     /* SUCCESS */
  3219.                     if(bp->guarded)
  3220.                     {
  3221.                         *((unsigned*)(((char*)address)+newsize-ALIGNMENTM))
  3222.                             = BACKGUARD;
  3223.                     }
  3224.                     return addr;
  3225.                 }
  3226.             }
  3227.             /* HERE WE COULD CHECK OTHER SOURCES OF SPACE */
  3228.  
  3229.             /* can't extend block, malloc some new space */
  3230.             if((taddr = Cmalloc(category,newsize-bp->guarded)))
  3231.             {
  3232.                 memmove(taddr,addr,cursize-bp->guarded);
  3233.                 onode->value = cursize;
  3234.                 Cfree(category, addr);
  3235.             }
  3236.             /* SUCCESS */
  3237.             return taddr;
  3238.         }
  3239.         else
  3240.         {/* shrink block */
  3241.             if(bp->guarded)
  3242.             {
  3243.                 *((unsigned*)(((char*)address)+newsize-ALIGNMENTM))
  3244.                     = BACKGUARD;
  3245.             }
  3246.             addto_freelist(bp, ((char*)address)+newsize, cursize-newsize); 
  3247.             return addr;
  3248.         }
  3249.       }
  3250. }
  3251. LOCAL void
  3252. Cfreecat(int category)
  3253. {
  3254. struct _bins *bp;
  3255.  
  3256.     if(category == 0)
  3257.         return;
  3258.  
  3259.     if((bp = getcat(category)))
  3260.     {
  3261.     struct _catlocs *cl = bp->catlocs;
  3262.     struct _bins *hbp;
  3263.     struct _bins *prev;
  3264.  
  3265.         while(cl)
  3266.         {/* Space allocated to the category is moved to category 0 */
  3267.         void *ql = cl->fptr;
  3268.  
  3269.             Cfree(0, cl->addr);
  3270.             free_catloc(cl);
  3271.             cl = ql;
  3272.         }
  3273.         /* space for the _bins struct is placed on a free list */
  3274.         hbp = hmap[category % 1009];
  3275.         prev = 0;
  3276.         while(hbp)
  3277.         {
  3278.             if(hbp->bincat == category)
  3279.             {
  3280.                 if(prev == 0)
  3281.                     hmap[category % 1009] = hbp->fptr;
  3282.                 else
  3283.                     prev->fptr = hbp->fptr;
  3284.                 free_bins(hbp);
  3285.                 return;
  3286.             }
  3287.             prev = hbp;
  3288.             hbp = hbp->fptr;
  3289.         }
  3290.     }
  3291. }
  3292. LOCAL int
  3293. Cmemrange(int category, unsigned *min, unsigned *max)
  3294. {
  3295. struct _bins *bp;
  3296.  
  3297.     if((bp = getcat(category)))
  3298.     {
  3299.         *min = bp->minloc;
  3300.         *max = bp->maxloc;
  3301.         return 1;
  3302.     }
  3303.     return 0;
  3304. }
  3305. LOCAL int
  3306. Cusedrange(int category, unsigned *min, unsigned *max)
  3307. {
  3308. struct _bins *bp;
  3309. NodePM node;
  3310. int level;
  3311.  
  3312.     if((bp = getcat(category)))
  3313.     {
  3314.         node = bp->USEDHheader;
  3315.         *min = node->fptr[0]->key;
  3316.         for(level = bp->USEDHlevel; level >= 0; level--)
  3317.           while(node->fptr[level]->key < 0xffffffff)
  3318.             node = node->fptr[level];
  3319.         *max = node->key;
  3320.         return 1;
  3321.     }
  3322.     return 0;
  3323. }
  3324. LOCAL void
  3325. Ctotrange(unsigned *min, unsigned *max)
  3326. {
  3327.     *min = minloc;
  3328.     *max = maxloc;
  3329. }
  3330. LOCAL void
  3331. Cguard(int category)
  3332. {
  3333. struct _bins *bp;
  3334.  
  3335.     if(!(bp = getcat(category)))
  3336.       if(!(bp = initcat(category)))
  3337.           return;
  3338.  
  3339.     if(!bp->guarded)
  3340.     {
  3341.         bp->guarded = 2*ALIGNMENTM;
  3342.         bp->addrbump = 1;
  3343.     }
  3344. }
  3345. LOCAL void*
  3346. Cheapcheck(int category, void *start)
  3347. {
  3348. struct _bins *bp;
  3349. NodePM node,prev;
  3350. unsigned *p1,*p2;
  3351.  
  3352.     if((bp = getcat(category)))
  3353.     {
  3354.         if(bp->guarded)
  3355.         {
  3356.             prev = 0;
  3357.             node = bp->USEDHheader;
  3358.             while(        (node = node->fptr[0]) != (NodePM)0xffffffff
  3359.                     &&    node->key != 0xffffffffUL)
  3360.             {
  3361.                 if((void*)node->key > start)
  3362.                 {
  3363.                     p1 = (unsigned*)node->key;
  3364.                     if(*p1 != FRNTGUARD)
  3365.                     {
  3366.                         if(prev)
  3367.                             return (char*)prev->key+ALIGNMENTM;
  3368.                         else
  3369.                             return (void*)1;
  3370.                     }
  3371.                     p2 = (unsigned*)(((char*)p1)+node->value-ALIGNMENTM);
  3372.                     if(*p2 != BACKGUARD)
  3373.                         return (char*)node->key+ALIGNMENTM;
  3374.                 }
  3375.                 prev = node;
  3376.             }
  3377.         }
  3378.     }
  3379.     return 0;
  3380. }
  3381. LOCAL void* 
  3382. Cmalloc(int category, unsigned size)
  3383. {
  3384.     return Cmemalign(category, 0, size);
  3385. }
  3386.  
  3387. LOCAL void* 
  3388. Cvalloc(int category, unsigned bytes)
  3389. {
  3390.   return Cmemalign (category, PAGESIZE, bytes);
  3391. }
  3392. LOCAL unsigned
  3393. Cmallocsize(int category, void* addr)
  3394. {
  3395. struct _bins *bp;
  3396. SKIPVARS;
  3397.  
  3398.     if(addr && (bp = getcat(category)))
  3399.     {
  3400.     unsigned address = (unsigned)((unsigned*)addr - bp->addrbump);
  3401.         FINDKEY(USEDH, address)
  3402.         if(node->key == address)
  3403.             return node->value - bp->guarded;
  3404.     }
  3405.     return 0;
  3406. }
  3407.  
  3408. LOCAL int
  3409. Cnewcat()
  3410. {
  3411. static unsigned int cat = BASE_CATEGORY;
  3412.     return ++cat;
  3413. }
  3414.  
  3415.  
  3416. /* ====================== END MULTI-HEAP MALLOC ============================ */
  3417.  
  3418. /* ====================== SYMBOL TABLE HANDLERS ============================ */
  3419.  
  3420. typedef struct _key
  3421. {
  3422.     unsigned long k[2];
  3423.     unsigned long hv;
  3424. } KEY, *KEYP;
  3425.  
  3426. typedef struct _nodeS
  3427. {/* 44 bytes -- adjust size to suit application */
  3428.     unsigned long value[5];    /* 16 bytes */
  3429.     unsigned long key[2];    /* 8 bytes */
  3430.     struct _nodeS *fptr[4];    /* 16 bytes */
  3431. } NodeS, *NodePS;
  3432.  
  3433. typedef struct _pbuf
  3434. {/* symbol table object */
  3435.     int    nbins;            /* number of bins in dictionary */
  3436.     int lastbin;        /* for seq access */
  3437.     NodePS lastptr;        /* ditto */
  3438.     int category;        /* heap number */
  3439.     char *chunkbase;    /* node allocation base */
  3440.     int chunksize;        /* number of bytes available in current chunk */
  3441.     NodePS freelist;    /* list of freed nodes for allocation */
  3442.     int level;            /* sorted level */
  3443.     int bits;            /* sorted bits */
  3444.     int bitcnt;            /* sorted bitcnt */
  3445.     NodePS header;        /* sorted header */
  3446.     NodePS bins[0];        /* bins if hashed dictionary */
  3447. } *PbufP;
  3448.  
  3449. #define SYM_MAXLEVEL 12
  3450. #define TBL ((PbufP)tbl)
  3451.  
  3452. static struct _nodeS _nnil = {{0,0,0,0},{0xffffffff,0xffffffff},{0,0,0,0}};
  3453. static struct _nodeS *_NNIL = &_nnil;
  3454.  
  3455. static int
  3456. getSlevel (PbufP tbl)
  3457. {
  3458. int level = -1;
  3459. int bits = 0;
  3460.  
  3461.     while (bits == 0)
  3462.     {
  3463.         if (tbl->bitcnt == 0)
  3464.         {
  3465.             tbl->bits = lrandom();
  3466.             tbl->bitcnt = 15;
  3467.         }
  3468.  
  3469.         bits = tbl->bits & 3;
  3470.         tbl->bits >>= 2;
  3471.         tbl->bitcnt--;
  3472.  
  3473.         if(++level > tbl->level)
  3474.             break;
  3475.     }
  3476.     return (level > SYM_MAXLEVEL) ? SYM_MAXLEVEL : level;
  3477.  
  3478. }
  3479.  
  3480. static void
  3481. hash(void *key, KEY *cat)
  3482. {
  3483.     cat->k[0] = ((unsigned long*)key)[0];
  3484.     cat->k[1] = ((unsigned long*)key)[1];
  3485.     cat->hv = ((cat->k[0] ^ cat->k[1]) * 1103515245UL) + 12345;
  3486. }
  3487. static void
  3488. sym_hash(unsigned long *key, char *symb)
  3489. {
  3490. int len = strlen(symb);
  3491. int i;
  3492.     for(i = 0; i < len; ++i)
  3493.       ((unsigned char *)key)[i & 7] ^= symb[i];
  3494.     key[0] = ((key[0] ^ key[1]) * 1103515245UL) + 12345;
  3495.     key[1] = len;
  3496. }
  3497. static void *
  3498. new_Snode(PbufP tbl, int levels)
  3499. {
  3500. NodePS p;
  3501. int size;
  3502.     if(levels <= 3)
  3503.     {
  3504.         if(tbl->freelist)
  3505.         {
  3506.             p = tbl->freelist;
  3507.             tbl->freelist = p->fptr[0];
  3508.             p->fptr[0] = 0;
  3509.             return p;
  3510.         }
  3511.     }
  3512.     size = sizeof(struct _nodeS) + ((levels-3) * sizeof(void*));
  3513.     if(tbl->chunksize < size)
  3514.     {
  3515.         tbl->chunkbase = Ccalloc(tbl->category, 1, 4080);
  3516.         tbl->chunksize = 4080;
  3517.     } 
  3518.     tbl->chunksize -= size;
  3519.     p = (NodePS)tbl->chunkbase;
  3520.     tbl->chunkbase += size;
  3521.     return p;
  3522. }
  3523. static void
  3524. free_Snode(PbufP tbl, NodePS node)
  3525. {
  3526.     bzero(node, sizeof(struct _nodeS));
  3527.     node->fptr[0] = tbl->freelist;
  3528.     tbl->freelist = node;
  3529. }
  3530.  
  3531. static void*
  3532. NewSymTable(int category, int nbins)
  3533. {
  3534. PbufP tbl;
  3535.  
  3536.     tbl = Ccalloc(category, 1, nbins*sizeof(NodePS) + sizeof(struct _pbuf));
  3537.     if(nbins == 0)
  3538.     {/* sorted dictionary */
  3539.     int i;
  3540.         tbl->header = new_Snode(tbl, SYM_MAXLEVEL+1);
  3541.         for(i = 0; i <= SYM_MAXLEVEL; ++i)
  3542.             tbl->header->fptr[i] = _NNIL;
  3543.     }
  3544.     tbl->nbins = nbins;
  3545.     tbl->category = category;
  3546.     return tbl;
  3547. }
  3548. static int
  3549. SymFind(void *tbl, void *key, void *result)
  3550. {
  3551. NodePS node;
  3552.  
  3553.     if(tbl && key)
  3554.     {
  3555.       if(TBL->nbins)
  3556.       {/* hashed dictionary */
  3557.       KEY cat;
  3558.  
  3559.         hash(key, &cat);
  3560.         if((node = TBL->bins[cat.hv % TBL->nbins]))
  3561.         {
  3562.             do {
  3563.                 if(        node->key[0] == cat.k[0]
  3564.                     &&    node->key[1] == cat.k[1])
  3565.                 {
  3566.                     if(result)
  3567.                       *((NodePS *)result) = node;
  3568.                     TBL->lastbin = cat.hv % TBL->nbins;
  3569.                     TBL->lastptr = node;
  3570.                     return 1;
  3571.                 }
  3572.              } while((node = node->fptr[0]));
  3573.         }
  3574.         return 0;
  3575.       }
  3576.       else
  3577.       {/* sorted dictionary */
  3578.       int level;
  3579.  
  3580.         node = TBL->header;
  3581.         for(level = TBL->level; level >= 0; level--)
  3582.         {
  3583.           while( KEYLT(node->fptr[level]->key, ((unsigned long*)key)) )
  3584.             node = node->fptr[level];
  3585.         }
  3586.         node = node->fptr[0];
  3587.  
  3588.         TBL->lastptr = node;
  3589.         if(result)
  3590.             *((NodePS *)result) = node;
  3591.         return (KEYEQ(node->key, ((unsigned long*)key))) ? 1 : 0;
  3592.       }
  3593.     }
  3594.     return -1;
  3595. }
  3596. static int
  3597. SymFindRange(void *tbl, void *key, void *result)
  3598. {/* assumes 4 byte key and value (the value can be bigger) */
  3599. NodePS node;
  3600.  
  3601.     if(tbl && key)
  3602.     {
  3603.       if(TBL->nbins)
  3604.       {/* hashed dictionary */
  3605.         return 0;
  3606.       }
  3607.       else
  3608.       {/* sorted dictionary */
  3609.       NodePS prev;
  3610.       int level;
  3611.  
  3612.         node = TBL->header;
  3613.         for(level = TBL->level; level >= 0; level--)
  3614.         {
  3615.           while ( node->fptr[level]->key[0] < ((unsigned long*)key)[0] )
  3616.             node = node->fptr[level];
  3617.         }
  3618.         prev = node;
  3619.         node = node->fptr[0];
  3620.  
  3621.         if( node->key[0] == ((unsigned long*)key)[0] )
  3622.         {
  3623.             TBL->lastptr = node;
  3624.             if(result)
  3625.                 *((NodePS *)result) = node;
  3626.             return 1;
  3627.         }        
  3628.         if( ((unsigned long*)key)[0] < prev->key[0]+prev->value[0] )
  3629.         {
  3630.             TBL->lastptr = prev;
  3631.             if(result)
  3632.                 *((NodePS *)result) = prev;
  3633.             return 1;
  3634.         }
  3635.         return 0;
  3636.       }
  3637.     }
  3638.     return -1;
  3639. }
  3640. static void *
  3641. SymInsert(void *tbl, void *key, void *value, int datsiz)
  3642. {
  3643. NodePS node;
  3644.  
  3645.     if(tbl && key)
  3646.     {
  3647.       if(TBL->nbins)
  3648.       {/* hashed dictionary */
  3649.       KEY cat;
  3650.       NodePS *binp;
  3651.         hash(key, &cat);
  3652.         node = new_Snode(tbl, 0);
  3653.         TBL->lastbin = cat.hv % TBL->nbins;
  3654.         TBL->lastptr = node;
  3655.         binp = &TBL->bins[TBL->lastbin];
  3656.         if(value && datsiz)
  3657.           memcpy(node, value, MIN(datsiz,16));
  3658.         node->key[0] = cat.k[0];
  3659.         node->key[1] = cat.k[1];
  3660.         node->fptr[0] = *binp;
  3661.         *binp = node;
  3662.         return node;
  3663.       }
  3664.       else
  3665.       {/* sorted dictionary */
  3666.       int level;
  3667.       NodePS update[SYM_MAXLEVEL+1];
  3668.  
  3669.         node = TBL->header;
  3670.         for (level = TBL->level; level >= 0; level--)
  3671.         {
  3672.           while ( KEYLT(node->fptr[level]->key,((unsigned long*)key)) )
  3673.             node = node->fptr[level];
  3674.           update[level] = node;
  3675.         }
  3676.  
  3677.         level = getSlevel(tbl);
  3678.  
  3679.         while(TBL->level < level)
  3680.             update[++TBL->level] = TBL->header;
  3681.  
  3682.         node = new_Snode(tbl, level);
  3683.  
  3684.         if(value && datsiz)
  3685.           memcpy(node, value, MIN(datsiz,16));
  3686.         node->key[0] = ((unsigned long*)key)[0];
  3687.         node->key[1] = ((unsigned long*)key)[1];
  3688.  
  3689.         while(level >= 0)
  3690.         {
  3691.             node->fptr[level] = update[level]->fptr[level];
  3692.             update[level]->fptr[level] = node;
  3693.             level--;
  3694.         }
  3695.         TBL->lastptr = node;
  3696.         return node;
  3697.      }
  3698.     }
  3699.     return 0;
  3700. }
  3701. static int
  3702. StringFind(void *tbl, char *string, void *result)
  3703. {
  3704. unsigned long key[2];
  3705. struct {
  3706.     char *symname;
  3707. } *valp;
  3708.  
  3709.     key[0] = 0;
  3710.     key[1] = 0;
  3711.     sym_hash(key, string);
  3712.  
  3713.     if(SymFind(tbl, key, &valp) == 1)
  3714.     {
  3715.     unsigned long *key1;
  3716.         do {
  3717.             if(!strcmp(string, valp->symname))
  3718.             {
  3719.                 if(result)
  3720.                     *((void**)result) = valp;
  3721.                 return 1;
  3722.             }
  3723.             /* Check duplicates */
  3724.             if(!SymNext(tbl))
  3725.                 break;
  3726.             SymKey(tbl, &key1);
  3727.             SymValue(tbl, &valp);
  3728.         } while(KEYEQ(key, key1));
  3729.     }
  3730.     return 0;
  3731. }
  3732. static int
  3733. StringInsert(void *tbl, char *string, void *result)
  3734. {
  3735. unsigned long key[2];
  3736. struct {
  3737.     char *symname;
  3738. } *valp;
  3739.  
  3740.     key[0] = 0;
  3741.     key[1] = 0;
  3742.     sym_hash(key, string);
  3743.     if(SymFind(tbl, key, &valp))
  3744.     {/* hash keys match */
  3745.     unsigned long *key1;
  3746.         do {
  3747.             if(!strcmp(string, valp->symname))
  3748.             {
  3749.                 if(result)
  3750.                     *((void**)result) = valp;
  3751.                 return 1;
  3752.             }
  3753.             /* Check duplicates */
  3754.             if(!SymNext(tbl))
  3755.                 break;
  3756.             SymKey(tbl, &key1);
  3757.             SymValue(tbl, &valp);
  3758.         } while(KEYEQ(key, key1));
  3759.     }
  3760.     /* NOMATCH */
  3761.     valp = SymInsert(tbl, key, &string, 4);
  3762.     if(result)
  3763.         *((void**)result) = valp;
  3764.     return 0;
  3765. }
  3766. static void
  3767. SymDelete(void *tbl, void *key)
  3768. {
  3769. NodePS node;
  3770.  
  3771.     if(tbl && key)
  3772.     {
  3773.       if(TBL->nbins)
  3774.       {/* hashed dictionary */
  3775.       KEY cat;
  3776.       NodePS *binp;
  3777.       NodePS prev = 0;
  3778.  
  3779.         hash(key, &cat);
  3780.         binp = &TBL->bins[cat.hv % TBL->nbins];
  3781.         if((node = *binp))
  3782.         {
  3783.             do {
  3784.                 if(        node->key[0] == cat.k[0]
  3785.                     &&    node->key[0] == cat.k[1])
  3786.                 {
  3787.                     if(prev)
  3788.                         prev->fptr[0] = node->fptr[0];
  3789.                     else
  3790.                         *binp = node->fptr[0];
  3791.  
  3792.                     free_Snode(tbl, node);
  3793.                     if(TBL->lastptr == node)
  3794.                     {
  3795.                         TBL->lastptr = 0;
  3796.                         TBL->lastbin = TBL->nbins;
  3797.                     }
  3798.                     return;
  3799.                 }
  3800.                 prev = node;
  3801.              } while((node = node->fptr[0]));
  3802.         }
  3803.       }
  3804.       else
  3805.       {/* sorted dictionary */
  3806.       int level;
  3807.       NodePS update[SYM_MAXLEVEL+1];
  3808.  
  3809.         node = TBL->header;
  3810.         for(level = TBL->level; level >= 0; level--)
  3811.         {
  3812.           while ( KEYLT(node->fptr[level]->key, ((unsigned long*)key)) )
  3813.             node = node->fptr[level];
  3814.           update[level] = node;
  3815.         }
  3816.         node = node->fptr[0];
  3817.  
  3818.         if( KEYEQ(node->key, ((unsigned long*)key)) )
  3819.         {
  3820.             for(level = 0; level <= TBL->level; level++)
  3821.             {
  3822.                 if (update[level]->fptr[level] == node)
  3823.                      update[level]->fptr[level] = node->fptr[level];
  3824.                 else break;
  3825.             }
  3826.  
  3827.             while((TBL->level > 0) && (TBL->header->fptr[TBL->level] == _NNIL))
  3828.                 TBL->level--;
  3829.  
  3830.             if(TBL->lastptr == node)
  3831.                 TBL->lastptr = 0;
  3832.             free_Snode(tbl, node);
  3833.         }
  3834.       }
  3835.     }
  3836. }
  3837. static int
  3838. SymHead(void *tbl)
  3839. {/* Set up for sequential access */
  3840. int nbins;
  3841.  
  3842.     if(tbl)
  3843.     {
  3844.       if((nbins = TBL->nbins))
  3845.       {/* hashed dictionary */
  3846.       NodePS node;
  3847.       int i;
  3848.         TBL->lastptr = 0;
  3849.         for(i = 0; i < nbins; ++i)
  3850.         {
  3851.             if( (node = TBL->bins[i]) != 0)
  3852.             {
  3853.                 TBL->lastbin = i;
  3854.                 return 1;
  3855.             }
  3856.         }
  3857.         TBL->lastbin = nbins;
  3858.         return 0; /* empty */
  3859.       }
  3860.       else
  3861.       {/* sorted dictionary */
  3862.         TBL->lastptr = TBL->header;
  3863.         return (TBL->lastptr->fptr[0] == _NNIL) ? 0 : 1;
  3864.       }
  3865.     }
  3866.     return 0;
  3867. }
  3868. static int
  3869. SymNext(void *tbl)
  3870. {/* Move to next sequential entry */
  3871. int nbins;
  3872.  
  3873.     if(tbl)
  3874.     {
  3875.       if((nbins = TBL->nbins))
  3876.       {/* hashed dictionary */
  3877.         if(TBL->lastptr && ((TBL->lastptr = TBL->lastptr->fptr[0])))
  3878.             return 1;
  3879.         else
  3880.         {
  3881.         int i;
  3882.             for(i = TBL->lastbin; i < nbins; ++i)
  3883.             {
  3884.                 if((TBL->lastptr = TBL->bins[i]) != 0)
  3885.                 {
  3886.                     TBL->lastbin = i+1;
  3887.                     return 1;
  3888.                 }
  3889.             }
  3890.             return 0;
  3891.         }
  3892.       }
  3893.       else
  3894.       {/* sorted dictionary */
  3895.         if(TBL->lastptr)
  3896.         {
  3897.             if(TBL->lastptr != _NNIL)
  3898.                 TBL->lastptr = TBL->lastptr->fptr[0];
  3899.             return (TBL->lastptr == _NNIL) ? 0 : 1;
  3900.         }
  3901.       }
  3902.     }
  3903.     return 0;
  3904. }
  3905. static void
  3906. SymGetMark(void *tbl, void *markptr)
  3907. {
  3908.     if(tbl && markptr)
  3909.     {
  3910.         ((long*)markptr)[0] = TBL->lastbin;
  3911.         ((long*)markptr)[1] = (long)TBL->lastptr;
  3912.     }
  3913. }
  3914. static int
  3915. SymMarkNext(void *tbl, void *mark)
  3916. {/* Mark current position, and move to next sequential entry */
  3917.     SymGetMark(tbl, mark);
  3918.     return SymNext(tbl);
  3919. }
  3920. static void
  3921. SymSetMark(void *tbl, void *markptr)
  3922. {
  3923.     if(tbl && markptr)
  3924.     {
  3925.         TBL->lastbin = ((long*)markptr)[0];
  3926.         TBL->lastptr = (NodePS)((long*)markptr)[1];
  3927.     }
  3928. }
  3929. static void
  3930. SymKey(void *tbl, void *keyptr)
  3931. {/* Retrieve key info pointer for current spot */
  3932.  
  3933.     if(tbl && keyptr && TBL->lastptr)
  3934.         *((unsigned long**)keyptr) = &TBL->lastptr->key[0];
  3935. }
  3936. static void
  3937. SymValue(void *tbl, void *datptr)
  3938. {/* Retrieve value pointer for current spot */
  3939.  
  3940.     if(tbl && datptr && TBL->lastptr)
  3941.         *((unsigned long**)datptr) = &TBL->lastptr->value[0];
  3942. }
  3943.  
  3944. /* ==================== END SYMBOL TABLE HANDLERS ========================== */
  3945.  
  3946. /* ========================== OPTIMIZATION ================================= */
  3947. static int
  3948. forward(unsigned char *p)
  3949. {
  3950. unsigned char *next;
  3951.  
  3952.     do {
  3953.         next = (void*)((Pop)p)->next;
  3954.         while(        *next == 0
  3955.                 ||    *next == lineop
  3956.                 ||    *next == labelop)
  3957.             next = (void*)((Pop)next)->next;
  3958.  
  3959.         if(*next == endop)
  3960.         {
  3961.             if(*p == *(next+8))
  3962.             {
  3963.                 *p = 0;
  3964.                 *next = 0;
  3965.                 return 1;
  3966.             }
  3967.             return 0;
  3968.         }
  3969.     } while(forward(next));
  3970.  
  3971.     return 0;
  3972. }
  3973. static void
  3974. eliminate_extraneous_infops(Piv iv, int level)
  3975. {
  3976. Pafile pf;
  3977. unsigned char *p;
  3978. int i;
  3979.     for(i = 0; i < iv->numfiles; ++i)
  3980.     {
  3981.         iv->filenum = i;
  3982.         pf = iv->files[i];
  3983.         if(!(p = pf->prog_p))
  3984.             continue;
  3985.         if(pf->header_p->hdr.opt_level >= level)
  3986.             continue;
  3987.         pf->header_p->hdr.opt_level = level;
  3988.         while(*p != endfileop)
  3989.         {
  3990.             switch(*p)
  3991.             {
  3992.                 case    unopop:
  3993.                 case    arrayelemop:
  3994.                 case    ptrelemop:
  3995.                 case    strelemop:
  3996.                 case    ptrdimsop:
  3997.                 case    arraydimsop:
  3998.                     forward(p);
  3999.                     break;
  4000.             }
  4001.             p = POP->next;
  4002.         }
  4003.     }
  4004. }
  4005. static void
  4006. clean_temps(Piv iv)
  4007. {
  4008. long *key;
  4009. long *val;
  4010. long hitemp = iv->first_temp & 0xffff0000;
  4011.  
  4012.     if(iv->temps_written == 0)
  4013.         return;
  4014.     if(SymHead(iv->tmptbl))
  4015.     {
  4016.         while(SymNext(iv->tmptbl))
  4017.         {
  4018.             SymKey(iv->tmptbl, &key);
  4019.  
  4020.             if((key[0] & 0xffff0000) == hitemp)
  4021.             {
  4022.             char *ptr;
  4023.             long saveit;
  4024.  
  4025.                 SymValue(iv->tmptbl, &val);
  4026.                 saveit = val[1];
  4027.                 ptr = (void*)val[0];
  4028.  
  4029.                 val[0] = 0;    /* allow reuse of this slot */
  4030.                 val[1] = 0;
  4031.  
  4032.                 while(ptr)
  4033.                 {
  4034.                 void *nptr = (void*)((PopT)ptr)->tmpnum;
  4035.                     ((PopT)ptr)->tmpnum = key[0];
  4036.  
  4037.                     if(!saveit)
  4038.                     {
  4039.                     unsigned char *p = ptr-8;                    
  4040.                     unsigned char op = *p;
  4041.  
  4042.                         *p = 0;                        
  4043.                         ++iv->killop;
  4044.                         if(op == duptmpop)
  4045.                         {/* special test for post increment */
  4046.                             p = POP->next;
  4047.                             p = POP->next;
  4048.                             if(*p == grabop)
  4049.                                 *p = 0;
  4050.                         }
  4051.                     }
  4052.                     ptr = nptr;
  4053.                 }
  4054.             }
  4055.         }
  4056.         if(!hitemp)
  4057.             iv->temps_written = 0;
  4058.     }
  4059. }
  4060.  
  4061. static void
  4062. read_temp(Piv iv, PopT ptr, unsigned long last)
  4063. {
  4064. unsigned long key[2];
  4065. long *result;
  4066.  
  4067.     if(last == ptr->tmpnum)
  4068.         return;
  4069.  
  4070.     key[0] = ptr->tmpnum;
  4071.     key[1] = 0;
  4072.  
  4073.     if(SymFind(iv->tmptbl, key, &result) == 1)
  4074.     {
  4075.         result[1] = 1;
  4076.     }
  4077.     else PERROR(pName ":Syserr: read temp %d not found\n", key[0]);
  4078. }
  4079. static int 
  4080. reading_self(unsigned char *p, long tmpnum)
  4081. {
  4082.     if((p[2]&0xe0) == OPTEMP || (p[2]&0xe0) == OPRET)
  4083.     {
  4084.           return 1;
  4085.     }
  4086.     if((p[3]&0xe0) == OPTEMP || (p[3]&0xe0) == OPRET)
  4087.     {
  4088.         return 1;
  4089.     }
  4090.     return 0;
  4091. }
  4092. static long
  4093. write_temp(Piv iv, PopT ptr, unsigned char opcode)
  4094. {
  4095. long key[2];
  4096. long val[2];
  4097. long *result;
  4098. long hitemp = ptr->tmpnum & 0xffff0000;
  4099.  
  4100.     if(ptr->atype & A_MEMADDR && opcode < duptmpop)
  4101.     {/* actually reading from this destination slot */
  4102.         read_temp(iv, ptr, 0);
  4103.         return 0;
  4104.     }
  4105.  
  4106.     if(hitemp > (iv->first_temp & 0xffff0000))
  4107.     {/* Inner block, CompoundExp or NestedFunc */
  4108.         iv->first_temp = hitemp + 1;
  4109.     }
  4110.     else if(hitemp < (iv->first_temp & 0xffff0000))
  4111.     {/* Exit inner block */
  4112.         if(!reading_self(((char*)ptr)-8, ptr->tmpnum))
  4113.         {
  4114.             while(hitemp < (iv->first_temp & 0xffff0000))
  4115.             {
  4116.                 clean_temps(iv);
  4117.                 iv->first_temp -= 0x00010000;
  4118.             }
  4119.         }
  4120.     }
  4121.     if(ptr->tmpnum == iv->first_temp)
  4122.     {
  4123.         if(!reading_self(((char*)ptr)-8, ptr->tmpnum))
  4124.             clean_temps(iv);
  4125.     }
  4126.     ++iv->temps_written;
  4127.     key[0] = ptr->tmpnum;
  4128.     key[1] = 0;
  4129.  
  4130.     if(SymFind(iv->tmptbl, key, &result) == 1)
  4131.     {
  4132.     PopT optr = (PopT)result[0];
  4133.         result[0] = (long)ptr;
  4134.         ptr->tmpnum = (long)optr;
  4135.     }
  4136.     else
  4137.     {
  4138.         val[0] = (long)ptr;
  4139.         val[1] = 0;
  4140.  
  4141.         SymInsert(iv->tmptbl, key, val, 8);
  4142.         ptr->tmpnum = 0;
  4143.     }
  4144.     return key[0];
  4145. }
  4146. static void
  4147. eliminate_unused_temps(Piv iv, int level)
  4148. {
  4149. Pafile pf;
  4150. unsigned char *p;
  4151. int i;
  4152. long last_write;
  4153.  
  4154.     iv->tmptbl = NewSymTable(iv->category, 111);
  4155.     for(i = 0; i < iv->numfiles; ++i)
  4156.     {
  4157.         iv->filenum = i;
  4158.         pf = iv->files[i];
  4159.         if(pf->header_p->hdr.opt_level >= level)
  4160.             continue;
  4161.         pf->header_p->hdr.opt_level = level;
  4162. rekill:
  4163.         if(!(p = pf->prog_p))
  4164.             continue;
  4165.         iv->first_temp = 1;
  4166.         iv->temps_written = 0;
  4167.         iv->killop = 0;
  4168.         while(*p != endfileop)
  4169.         {
  4170.             while(*p < labelop)
  4171.             {
  4172.                 if(*p == truthop)
  4173.                 {/* truthops of single chars are unnecessary */
  4174.                   if((p[2]&0xe0) == OPTEMP)
  4175.                   {
  4176.                     if(((PopT)(p+20))->dsize == 1)
  4177.                     {
  4178.                         if(((PopT)(p+8))->tmpnum == ((PopT)(p+20))->tmpnum)
  4179.                         {
  4180.                             *p = 0;
  4181.                             break;
  4182.                         }
  4183.                         else
  4184.                         {/* may be needed for code generation */
  4185.                             *p = aliastmpop;
  4186.                         }
  4187.                     }
  4188.                   }
  4189.                 }
  4190.                 if(*p)
  4191.                 {
  4192.                     if(*p == jmptrueop || *p == jmpfalseop)
  4193.                         read_temp(iv,(PopT)(p+4), 0);
  4194.                     if(*p == retdataop)
  4195.                         read_temp(iv, (PopT)p, 0);
  4196.                     else
  4197.                     {
  4198.                         last_write = 0;
  4199.                         if((p[1]&0xe0) == OPTEMP)
  4200.                             last_write = write_temp(iv, (PopT)(p+8), *p);
  4201.                         if((p[2]&0xe0) == OPTEMP || (p[2]&0xe0) == OPRET)
  4202.                             read_temp(iv, (PopT)((p+8+(p[1]&0x1f))), last_write);
  4203.                         if((p[3]&0xe0) == OPTEMP || (p[3]&0xe0) == OPRET)
  4204.                             read_temp(iv, (PopT)((p+8+(p[1]&0x1f))+(p[2]&0x1f)), last_write);
  4205.                     }
  4206.                 }
  4207.                 break;
  4208.             }
  4209.             p = POP->next;
  4210.         }
  4211.         do {
  4212.             clean_temps(iv);
  4213.             iv->first_temp -= 0x00010000;
  4214.         } while(iv->first_temp > 0);
  4215.         if(iv->killop)
  4216.         {
  4217.             goto rekill;
  4218.         }
  4219.     }
  4220. }
  4221. static void
  4222. retarget_jmps(Piv iv, int level)
  4223. {
  4224. Pafile pf;
  4225. unsigned char *p;
  4226. int i;
  4227.     for(i = 0; i < iv->numfiles; ++i)
  4228.     {
  4229.         iv->filenum = i;
  4230.         pf = iv->files[i];
  4231.         if(!(p = pf->prog_p))
  4232.             continue;
  4233.         if(pf->header_p->hdr.opt_level >= level)
  4234.             continue;
  4235.     }
  4236. }
  4237.  
  4238.  
  4239. static void
  4240. optimize(Piv iv)
  4241. {
  4242.     eliminate_extraneous_infops(iv, 50);
  4243.     eliminate_unused_temps(iv, 51);
  4244.     retarget_jmps(iv, 52);
  4245. }
  4246. /* ========================== END OPTIMIZATION ============================= */
  4247. /* ====================== BASIC INPUT FILE PROCESSING ====================== */
  4248. static long
  4249. label_insert(Piv iv, long label, int filenum, unsigned char *p)
  4250. {
  4251. long *result;
  4252. struct {
  4253.     long k1;
  4254.     long k2;
  4255. } key;
  4256.  
  4257. struct {
  4258.     long newlabel;
  4259. } val;
  4260.  
  4261.     key.k1 = label;
  4262.     key.k2 = filenum;
  4263.  
  4264.     /* check for duplicate label -- they happen */
  4265.     if(SymFind(iv->labeltbl, &key, &result) == 1)
  4266.     {
  4267.         if(*p == labelop)
  4268.             *p = 0; /* kill the instruction */
  4269.         return 0;
  4270.     }
  4271.  
  4272.     val.newlabel = ++iv->lastlabel;
  4273.     SymInsert(iv->labeltbl, &key, &val, 4);
  4274.  
  4275. #if REALLY_NEED_OFFSETS
  4276.     key.k1 = val.newlabel;
  4277.     val.newlabel = -1;
  4278.     SymInsert(iv->newlabeltbl, &key, &val, 4);
  4279. #endif
  4280.  
  4281.     return iv->lastlabel;
  4282. }
  4283. static long
  4284. label_find(Piv iv, long label, int filenum)
  4285. {
  4286. struct {
  4287.     long k1;
  4288.     long k2;
  4289. } key;
  4290.  
  4291. long *result;
  4292.  
  4293.     key.k1 = label;
  4294.     key.k2 = filenum;
  4295.  
  4296.     if(SymFind(iv->labeltbl, &key, &result) == 1)
  4297.         return *result;
  4298.     else
  4299.         return 0;
  4300. }
  4301. #if REALLY_NEED_OFFSETS
  4302. static void
  4303. newlabel_insert(Piv iv, long label)
  4304. {
  4305. struct {
  4306.     long k1;
  4307.     long k2;
  4308. } key;
  4309.  
  4310. long *result;
  4311.  
  4312.     key.k1 = label;
  4313.     key.k2 = iv->filenum;
  4314.     if(SymFind(iv->newlabeltbl, &key, &result) == 1)
  4315.     {
  4316.         *result = ++iv->labelnum;
  4317.     }
  4318.     else PERROR(pName ":Syserr: Label %d not found\n", label);
  4319. }
  4320. static long
  4321. newlabel_fix(Piv iv, long label)
  4322. {
  4323.     if(label)
  4324.     {
  4325.     struct {
  4326.         long k1;
  4327.         long k2;
  4328.     } key ;
  4329.  
  4330.     long *val;
  4331.  
  4332.         key.k1 = label;
  4333.         key.k2 = iv->filenum;
  4334.         if(SymFind(iv->newlabeltbl, &key, &val) == 1)
  4335.         {
  4336.             return val[0];
  4337.         }
  4338.     }
  4339.     return label;
  4340. }
  4341. #endif /* REALLY_NEED_OFFSETS */
  4342.  
  4343. static void
  4344. extern_insert(Piv iv, unsigned char *p, int filenum)
  4345. {
  4346. struct {
  4347.     short k1;
  4348.     short k2;
  4349.     long k3;
  4350. } key;
  4351. struct {
  4352.     unsigned char *p;
  4353. } val;
  4354.  
  4355.     key.k1 = GS(POPI->s.symnum);
  4356.     key.k2 = filenum;
  4357.     key.k3 = 0;
  4358.  
  4359.     val.p = p;
  4360.     SymInsert(iv->extrntbl, &key, &val, 4);
  4361. }
  4362. static void
  4363. reloc_insert(Piv iv, int fileno, unsigned char *p)
  4364. {
  4365. struct _rkey key;
  4366. struct _rval val;
  4367.  
  4368.     key.spot = GL(POPI->reloc.spot);    /* reloc target offset */
  4369.     key.fileno = fileno;            /* fileno */
  4370.     val.opcode = *p;                    /* opcode */
  4371.     val.rsize = GL(POPI->reloc.rsize);    /* reloc size */
  4372.     val.p = p;                            /* pointer to input buffer */
  4373.     val.base = GL(POPI->reloc.base);        /* base of data object pointed to */
  4374.     val.offset = GL(POPI->reloc.offset);    /* offset to be added to base */
  4375.     val.rsym = GS(POPI->reloc.rsym);        /* symbol number if external */
  4376.  
  4377.     SymInsert(iv->reloctbl, &key, &val, 18);
  4378. }
  4379. static void
  4380. data_insert(void *tbl, unsigned long offset,
  4381.             unsigned long size, void *p, void *prevp)
  4382. {
  4383. static long locid = 1;
  4384. struct _dkey key;
  4385. struct _dval val;
  4386.  
  4387. unsigned char opcode, prevopcode = 0;
  4388.  
  4389.     key.offset = offset;
  4390.     key.pad = 0;
  4391.  
  4392.     val.size = size;
  4393.     val.p = p;
  4394.     val.prevp = prevp;
  4395.     val.locid = 0;
  4396.     opcode = *((unsigned char *)p);
  4397.     if(prevp)
  4398.     {
  4399.         prevopcode = *((unsigned char*)prevp);
  4400.         if(        prevopcode != glodatop
  4401.             &&    prevopcode != glofuncop
  4402.             &&    prevopcode != extfuncop
  4403.             &&    prevopcode != globssop)
  4404.         {
  4405.             val.locid = locid++;
  4406.         }    
  4407.     }
  4408.     SymInsert(tbl, &key, &val, sizeof(val));
  4409. }
  4410.  
  4411. static void
  4412. global_insert(Piv iv, Pafile pf, unsigned char *p)
  4413. {
  4414. unsigned long key[2];
  4415. struct _gloval val;
  4416. PopI pp;
  4417. unsigned char opcode = *p;
  4418.  
  4419.     if(opcode == extvarop)
  4420.         pp = POPI;
  4421.     else
  4422.         pp = (PopI)(POP->next+8);
  4423.  
  4424.     key[0] = 0;
  4425.     key[1] = 0;
  4426.  
  4427.     val.symnum = GS(pp->s.symnum);
  4428.     val.symname = pf->symaddr[val.symnum];
  4429.     val.p = p;
  4430.     val.pf = pf;
  4431.     if(val.symnum < 0 || val.symnum >= pf->numsyms)
  4432.     {
  4433.         PERROR(pName ":Syserr: BAD SYMNUM=%d opcode=%d\n", val.symnum, opcode);
  4434.     }
  4435.     sym_hash(key, val.symname);
  4436.  
  4437.     /* Duplicate entries are allowed */
  4438.     SymInsert(iv->gbltbl, key, &val, sizeof(val));
  4439. }
  4440.  
  4441. static int
  4442. setup_nodelinks(Piv iv, char *infile_name, void *inbuf, int insize)
  4443. {
  4444. unsigned char *p = inbuf;
  4445. unsigned char *endbuf = inbuf+insize;
  4446. Pafile pf=0;
  4447. int lastline = 0;
  4448. unsigned char *funcp;
  4449. unsigned char *nfuncp;
  4450.  
  4451.     while(p < endbuf && *p != endallop)
  4452.     {
  4453.     unsigned char *q = p;
  4454.         if(iv->debug >= '3')
  4455.         {
  4456.             cfeprintf("OP(%d '%s' p=%p line=%d)\n", *p, oxgenops[*p], p, lastline);
  4457.         }
  4458.         switch(*p)
  4459.         {
  4460.             case headerop:
  4461.                 if(iv->numfiles >= 1024) {
  4462.                     PERROR(pName ": Sorry, too many files\n");
  4463.                 }
  4464.                 pf = iv->files[iv->numfiles] = 
  4465.                     Ccalloc(iv->category, 1, sizeof(struct _afile));
  4466.                 pf->filenum = iv->numfiles++;
  4467.                 pf->file_p = p;
  4468.                 pf->header_p = POPI;
  4469.                 if(iv->strip)
  4470.                 {/* Gonna strip declarations and line numbers */
  4471.                     pf->header_p->hdr.target_debugger = 0;
  4472.                 }
  4473.                 break;
  4474.  
  4475.             case dataop:
  4476.                 pf->size_p = POPI;
  4477.                 pf->thunk_offset = GL(POPI->dat.thunk_offset);
  4478.                 pf->bss_offset = GL(POPI->dat.bss_offset);
  4479.                 break;
  4480.             case gfuncdefop:
  4481.             case sfuncdefop:
  4482.                 if(pf->prog_p == 0)
  4483.                     pf->prog_p = p;
  4484.                 funcp = p;
  4485.                 break;
  4486.             case funcexitop:
  4487.                 PS(((PopI)(funcp+8))->funcdef.tempmax) = GL(POPI->funcexit.tempmax);
  4488.                 break;
  4489.             case nestedfuncdefop:
  4490.                 nfuncp = p;
  4491.                 break;
  4492.             case nestedfuncexitop:
  4493.                 PS(((PopI)(nfuncp+8))->funcdef.tempmax) = GL(POPI->funcexit.tempmax);
  4494.                 break;
  4495.             case segdefop:
  4496.                 if(pf->seg_p == 0)
  4497.                     pf->seg_p = p;
  4498.                 pf->numsegs += 1;
  4499.                 iv->numsegs += 1;
  4500.                 break;
  4501.             case lineop:
  4502.                 lastline = GL( POPI->line.line );
  4503.                 if(iv->strip)
  4504.                     *p = 0;        /* strip line numbers */
  4505.                 break;
  4506.             case declop:
  4507.                 if(iv->strip)
  4508.                 {/* strip declarations */
  4509.                     do {
  4510.                         *p = 0;
  4511.                         q += (long)GL(POP->next);
  4512.                         POP->next = q;
  4513.                         p = q;
  4514.                     } while(*p != endop);                    
  4515.                     *p = 0;
  4516.                 }
  4517.                 else
  4518.                 {
  4519.                     if(pf->decl_p == 0)
  4520.                         pf->decl_p = p;
  4521.                     pf->numdecls += 1;
  4522.                     iv->numdecls += 1;
  4523.                 }
  4524.                 break;
  4525.             case switchidop:
  4526.                 if(pf->switch_p == 0)
  4527.                     pf->switch_p = p;
  4528.                 break;
  4529.             case labelop:
  4530.                 PL( POP->data ) = 
  4531.                         label_insert(iv, GL( POP->data ), pf->filenum, p);
  4532.                 break;            
  4533.             case symbop:
  4534.                 pf->numsyms = GL(POP->data);
  4535.                 iv->numsyms += pf->numsyms;
  4536.                 break;
  4537.             case symblockop:
  4538.                 pf->symtext_p = p + 12;
  4539.                 goto blka;
  4540.             case stringblockop:
  4541.             case datablockop:
  4542.             case mallocblockop:
  4543.             case thunkblockop:
  4544.             {
  4545.             long size;
  4546.                 if(pf->data_p == 0)
  4547.                     pf->data_p = p;
  4548. blka:
  4549.                 size = GL(POP->data);
  4550.                 q += size+((4-(size&3))&3);
  4551.                 break;
  4552.             }
  4553.             case glofuncop:
  4554.             case extfuncop:
  4555.             case glodatop:
  4556.             case globssop:
  4557.             case extvarop:
  4558.             case bssblockop:
  4559.                 if(pf->data_p == 0)
  4560.                     pf->data_p = p;
  4561.                 break;
  4562.             case maxtempop:
  4563.                 pf->maxtemp = GL(POP->data);
  4564.                 pf->maxtempclass = GL(POP->data1);
  4565.                 pf->maxtemp_p = p;
  4566.                 break;
  4567.         }
  4568.         q += (long)GL(POP->next);
  4569.         POP->next = q;
  4570.         p = q;
  4571.     }
  4572.     if(*p != endallop)
  4573.     {
  4574.         PERROR(pName ": Malformed input file: %s\n", infile_name);
  4575.     }
  4576.     return 0;
  4577. }
  4578. static void
  4579. setup_syms_decls(Piv iv)
  4580. {
  4581. int i;
  4582.  
  4583.     for(i = 0; i < iv->numfiles; ++i)
  4584.     {
  4585.     int symnum = 0;
  4586.     Pafile pf = iv->files[i];
  4587.     unsigned char *p = pf->file_p;
  4588.     unsigned char *prevp = 0;
  4589.  
  4590.         pf->symaddr = Ccalloc(iv->category, sizeof(void*), pf->numsyms);
  4591.         pf->decladdr = Ccalloc(iv->category, sizeof(void*), pf->numdecls);
  4592.  
  4593.         while(*p != endfileop)
  4594.         {
  4595.             switch(*p)
  4596.             {
  4597.                 case    symoffsetop:
  4598.                   pf->symaddr[symnum] = pf->symtext_p + GL(POP->data);
  4599.                   ++symnum;
  4600.                   break;
  4601.  
  4602.                 case    declop:
  4603.                   pf->decladdr[GS(POPI->dcl.declnum)] = p;
  4604.                   break;
  4605.  
  4606.                 case    relocop:
  4607.                 case    extlocop:
  4608.                   ++pf->numrelocs;
  4609.                   reloc_insert(iv, i, p);
  4610.                   break;
  4611.  
  4612.                 case    glodatop:
  4613.                 case    globssop:
  4614.                 case    glofuncop:
  4615.                 case    extfuncop:
  4616.                   global_insert(iv, pf, p);
  4617.                   break;
  4618.  
  4619.                 case    extvarop:
  4620.                   extern_insert(iv, p, i);
  4621.                   global_insert(iv, pf, p);
  4622.                   break;
  4623.  
  4624.                 case    stringblockop:
  4625.                 case    datablockop:
  4626.                 case    mallocblockop:
  4627.                 case    thunkblockop:
  4628.                 case    bssblockop:
  4629.                   if(!pf->datatbl)
  4630.                     pf->datatbl = NewSymTable(iv->category, 0);  /* sorted */
  4631.  
  4632.                   data_insert(pf->datatbl,GL(DATI.offset),GL(DATI.size),
  4633.                               p, prevp);
  4634.                   if(*p == thunkblockop) {
  4635.                     PL(POP->data5) = label_find(iv, GL(POP->data5), i);
  4636.                   }
  4637.                   break;
  4638.  
  4639.                 case    jmploopop:
  4640.                 case    jmpcontinueop:
  4641.                 case    jmpbreakop:
  4642.                 case    jmpgotoop:
  4643.                 case    jmptrueop:
  4644.                 case    jmpfalseop:
  4645.                 case    funcstartop:
  4646.                 case    funcstopop:
  4647.                 case    casevalop:
  4648.                 case    switchop:
  4649.                   PL(POP->data) = label_find(iv, GL(POP->data), i);
  4650.                   break;
  4651.             }
  4652.             prevp = p;
  4653.             p = POP->next;
  4654.         }
  4655.     }
  4656. }
  4657. static int
  4658. sym_insert(Piv iv, char *symname, int symnum)
  4659. {/* Used only for combining symbols in link phase */
  4660. struct {
  4661.     char *symname;
  4662.     int symnum;
  4663. } *valp;
  4664.  
  4665.     if(StringInsert(iv->symtbl, symname, &valp))
  4666.         return -valp->symnum;    /* MATCH */
  4667.     valp->symnum = symnum;
  4668.     return symnum;
  4669. }
  4670. static void
  4671. combine_syms_decls(Piv iv)
  4672. {
  4673. int i,j;
  4674. Pafile pf;
  4675. int numsyms;
  4676. int numdecls;
  4677.  
  4678.     /* COMBINE SYMBOLS */
  4679.     pf = iv->files[0];
  4680.     numsyms = pf->numsyms;
  4681.     pf->symtran = Ccalloc(iv->category, sizeof(short), pf->numsyms);
  4682.     memcpy(iv->symaddr, pf->symaddr, sizeof(void*) * numsyms);
  4683.  
  4684.  
  4685.     for(i = 0; i < numsyms; ++i)
  4686.     {/* file 0 */
  4687.         sym_insert(iv, pf->symaddr[i], i);
  4688.         pf->symtran[i] = i;
  4689.     }
  4690.     for(i = 1; i < iv->numfiles; ++i)
  4691.     {
  4692.     int start;
  4693.  
  4694.         pf = iv->files[i];
  4695.         pf->symtran = Ccalloc(iv->category, sizeof(short), pf->numsyms);
  4696.         if(pf->header_p->hdr.target_debugger)
  4697.             start = 1;
  4698.         else
  4699.             start = 3;
  4700.         for(j = start; j < pf->numsyms; ++j)
  4701.         {
  4702.         int k;
  4703.           if((k = sym_insert(iv, pf->symaddr[j], numsyms)) > 0)
  4704.           { /* new entry */
  4705.             iv->symaddr[numsyms++] = pf->symaddr[j];
  4706.             pf->symtran[j] = k;
  4707.           }
  4708.           else pf->symtran[j] = -k;
  4709.         }
  4710.     }
  4711.     iv->numsyms = numsyms;
  4712.  
  4713.     /* COMBINE DECLARATIONS */
  4714.     pf = iv->files[0];
  4715.     numdecls = pf->numdecls;
  4716.     pf->decltran = Ccalloc(iv->category, sizeof(short), pf->numdecls);
  4717.     memcpy(iv->decladdr, pf->decladdr, sizeof(void*) * numdecls);
  4718.  
  4719.     for(i = 0; i < numdecls; ++i)
  4720.     {/* file 0 */
  4721.         pf->decltran[i] = i;
  4722.     }
  4723.     for(i = 1; i < iv->numfiles; ++i)
  4724.     {
  4725.         pf = iv->files[i];
  4726.         pf->decltran = Ccalloc(iv->category, sizeof(short), pf->numdecls);
  4727.         if(pf->numdecls < 21)
  4728.             continue;
  4729.         for(j = 1; j <= 21; ++j)
  4730.             pf->decltran[j] = j;
  4731.         for(j = 22; j < pf->numdecls; ++j) {
  4732.             iv->decladdr[numdecls] = pf->decladdr[j];
  4733.             pf->decltran[j] = numdecls++;
  4734.         }
  4735.     }
  4736.     iv->numdecls = numdecls;
  4737. }
  4738.  
  4739. static void
  4740. link_dups(Piv iv, int dupcnt, struct _gloval *valp[])
  4741. {
  4742. int i;
  4743. int vars[5] = {0,0,0,0,0};
  4744. unsigned long cdsize = 0;
  4745. unsigned long cdoffset = 0;
  4746. short cdfile = 0;
  4747. int cdnum = 0;
  4748. short segid = 0;
  4749.  
  4750. #define GDAT vars[0]
  4751. #define GBSS vars[1]
  4752. #define GFUNC vars[2]
  4753. #define EVAR vars[3]
  4754. #define EFUNC vars[4]
  4755.  
  4756.     /* Count the types of matches */
  4757.     for(i = 0; i <= dupcnt; ++i)
  4758.         vars[*(valp[i]->p) - glodatop] += 1;
  4759.  
  4760.     /* Check for errors */
  4761.     if(        GDAT > 1 
  4762.         ||    GFUNC > 1
  4763.         ||    (GFUNC && (GDAT || GBSS || EVAR))
  4764.         ||    (EFUNC && (GDAT || GBSS || EVAR)))
  4765.     {
  4766.         ++iv->errors;
  4767.         for(i = 0; i < dupcnt; ++i)
  4768.         {
  4769.             PWARN(pName ": Symbol `%s' multiply defined or mistyped.\n",
  4770.                   valp[i]->symname);
  4771.             PWARN(pName":  In file: `%s'\n", valp[i]->pf->symaddr[INFILE_SYMNUM]);
  4772.         }
  4773.         return;
  4774.     }
  4775.     if(EFUNC && GFUNC)
  4776.     {/* match up functions */
  4777.     Pop dp;
  4778.         for(i = 0; i <= dupcnt; ++i)
  4779.           if(*(valp[i]->p) == glofuncop)
  4780.             break;
  4781.         dp = (Pop)((Pop)valp[i]->p)->next;    /* points to thunkblockop */
  4782.  
  4783.         cdoffset = GL(dp->data1);            /* save this offset */
  4784.         cdfile = valp[i]->pf->filenum;        /* save this file */
  4785.         for(i = 0; i <= dupcnt; ++i)
  4786.         {
  4787.           if(*(valp[i]->p) == extfuncop)
  4788.           {
  4789.             *(valp[i]->p) = 0;                    /* convert to nilop */
  4790.             dp = (Pop)((Pop)valp[i]->p)->next;    /* points to thunkblockop */
  4791.  
  4792.             /* Kill the thunkblock */
  4793.             *((char*)dp) = 0;
  4794.             PL(dp->data4) = cdoffset;            /* use this offset for access */
  4795.             PS(((short*)dp)[1]) = cdfile;        /* fileno to unused slots */
  4796.           }
  4797.         }
  4798.     }
  4799.     else if(EFUNC)
  4800.     {/* multiple references to external function */
  4801.     Pop    dp = (Pop)((Pop)valp[0]->p)->next;    /* points to first thunkblockop */
  4802.  
  4803.         cdoffset = GL(dp->data1);            /* save first offset */
  4804.         cdfile = valp[0]->pf->filenum;        /* save first file */
  4805.         for(i = 1; i <= dupcnt; ++i)
  4806.         {/* Kill all thunkblocks except the first */
  4807.             *(valp[i]->p) = 0;                    /* convert to nilop */
  4808.             dp = (Pop)((Pop)valp[i]->p)->next;    /* points to thunkblockop */
  4809.             *((char*)dp) = 0;
  4810.             PL(dp->data4) = cdoffset;            /* use this offset for access */
  4811.             PS(((short*)dp)[1]) = cdfile;        /* fileno to unused slots */
  4812.         }
  4813.     }
  4814.     else if(GBSS)
  4815.     {/* comdefs */
  4816.     int multsize = 0;
  4817.  
  4818.         /* PICK THE BIGGEST GLOBAL BSS (comdef) */
  4819.         for(i = 0; i <= dupcnt; ++i)
  4820.         {
  4821.         Pop dp = (Pop)((Pop)valp[i]->p)->next;    /* points to bssblockop */
  4822.           if((short)dp->data4 && segid == 0)
  4823.           {
  4824.             segid = (short)dp->data4;
  4825.           }
  4826.           else if((short)dp->data4 && (short)dp->data4 != segid)
  4827.           {
  4828.             ++iv->errors;
  4829.             PWARN(pName ": Variable `%s' defined in multiple segments.\n",
  4830.                 valp[i]->symname);
  4831.             PWARN(pName ":  In file: `%s'\n", valp[i]->pf->symaddr[INFILE_SYMNUM]);
  4832.           }
  4833.           if(*(valp[i]->p) == globssop)
  4834.           {
  4835.           long size = GL(dp->data);
  4836.             if(cdsize && size != cdsize)
  4837.                 multsize = 1;
  4838.             if(size > cdsize) {
  4839.                 cdsize = size;
  4840.                 cdoffset = GL(dp->data1);
  4841.                 cdfile = valp[i]->pf->filenum;
  4842.                 cdnum = i;
  4843.             }
  4844.           }
  4845.         }
  4846.         if(GDAT)
  4847.         {
  4848.           /* INITIALIZED DATA WILL ALWAYS OVERRIDE BSS */
  4849.           for(i = 0; i <= dupcnt; ++i)
  4850.           {
  4851.             if(*(valp[i]->p) == glodatop)
  4852.             {
  4853.             Pop dp = (Pop)((Pop)valp[i]->p)->next;    /* points to datablockop */
  4854.             long size = GL(dp->data);
  4855.               if(cdsize && size != cdsize)
  4856.                   multsize = 1;
  4857.               if(size < cdsize)
  4858.               {
  4859.             ++iv->errors;
  4860.             PWARN(pName ": Initialized variable `%s' of size (%d)\n",
  4861.               valp[i]->symname, size);
  4862.             PWARN(pName ":  In file: `%s'\n",
  4863.               valp[i]->pf->symaddr[INFILE_SYMNUM]);
  4864.             PWARN(pName ":  Is incommensurate with common size (%d).\n",
  4865.               cdsize);
  4866.               }
  4867.               else
  4868.               {
  4869.                   cdsize = size;
  4870.                   cdoffset = GL(dp->data1);
  4871.                   cdfile = valp[i]->pf->filenum;
  4872.                   cdnum = i;
  4873.               }
  4874.             }
  4875.           }
  4876.         }
  4877.         if(multsize)
  4878.         {
  4879.           PWARN(pName ":warning: Common Variable `%s' has multiple sizes.\n",
  4880.               valp[0]->symname);
  4881.           for(i = 0; i <= dupcnt; ++i)
  4882.           {
  4883.           unsigned char opcode = *(valp[i]->p);
  4884.             if(opcode == globssop || opcode == glodatop)
  4885.             {
  4886.                 PWARN(pName ":warning:Size=%d in file: `%s'\n",
  4887.                   GL(((Pop)((Pop)valp[i]->p)->next)->data),
  4888.                   valp[i]->pf->symaddr[INFILE_SYMNUM]);
  4889.             }
  4890.           }
  4891.         }
  4892.         /* FINALLY, LINK COMMONS TO THE CHOSEN ONE */
  4893.         for(i = 0; i <= dupcnt; ++i)
  4894.         {
  4895.           if(i != cdnum && *(valp[i]->p) == globssop)
  4896.           {
  4897.           Pop dp = (Pop)((Pop)valp[i]->p)->next;    /* points to bssblockop */
  4898.  
  4899.             *(valp[i]->p) = 0;            /* globssop becomes nilop */
  4900.             *((char*)dp) = 0;            /* bssblockop becomes nilop */
  4901.             PL(dp->data4) = cdoffset;    /* use this new offset for access */
  4902.             PS(((short*)dp)[1]) = cdfile;    /* put fileno in unused slots */
  4903.           }
  4904.         }
  4905.     }
  4906.     else if(GDAT)
  4907.     {
  4908.         for(i = 0; i <= dupcnt; ++i)
  4909.         {
  4910.         Pop dp = (Pop)((Pop)valp[i]->p)->next;    /* points to datablockop */
  4911.           if((short)dp->data4 && segid == 0)
  4912.           {
  4913.             segid = (short)dp->data4;
  4914.           }
  4915.           else if((short)dp->data4 && (short)dp->data4 != segid)
  4916.           {
  4917.             ++iv->errors;
  4918.             PWARN(pName ": Variable `%s' defined in multiple segments.\n",
  4919.                 valp[i]->symname);
  4920.             PWARN(pName ": In file: `%s'\n", valp[i]->pf->symaddr[INFILE_SYMNUM]);
  4921.           }
  4922.           if(*(valp[i]->p) == glodatop)
  4923.           {
  4924.             cdsize = GL(dp->data);
  4925.             cdoffset = GL(dp->data1);
  4926.             cdfile = valp[i]->pf->filenum;
  4927.             cdnum = i;
  4928.             break;
  4929.           }
  4930.         }
  4931.     }
  4932.     if(EVAR && (GDAT || GBSS))
  4933.     {/* match up variables */
  4934.         /* LINK EXTERNS TO THE CHOSEN ONE */
  4935.         for(i = 0; i <= dupcnt; ++i)
  4936.         {
  4937.           if(*(valp[i]->p) == extvarop)
  4938.           {
  4939.           Pop dp = (Pop)valp[i]->p;
  4940.  
  4941.             *((char*)dp) = 0;            /* extvarop becomes nilop */
  4942.             PL(dp->data1) = cdoffset;    /* use this new offset for access */
  4943.             PS(((short*)dp)[1]) = cdfile;    /* put fileno in unused slots */
  4944.             PS(dp->data4) = segid;
  4945.             break;
  4946.           }
  4947.         }
  4948.     }
  4949. #undef GDAT
  4950. #undef GBSS
  4951. #undef GFUNC
  4952. #undef EVAR
  4953. #undef EFUNC
  4954.  
  4955. }
  4956. static void
  4957. link_globals(Piv iv)
  4958. {
  4959.     if(SymHead(iv->gbltbl))
  4960.     {
  4961.     struct _gloval *valp[1024];    /* pointers to symtable value structs */
  4962.  
  4963.       /* Pass over the sorted symbol table and process duplicate entries */
  4964.       while(SymNext(iv->gbltbl))
  4965.       {
  4966.       unsigned long *key;
  4967.       long mark[2];                            /* Table position saver */
  4968.       int dupcnt = 0;
  4969.         SymKey(iv->gbltbl, &key);            /* Pointer to first key */
  4970.         SymValue(iv->gbltbl, &valp[0]);        /* Pointer to first value */
  4971.  
  4972.         while(SymMarkNext(iv->gbltbl, mark))
  4973.         {/* Look forward for duplicates */
  4974.         unsigned long *key1;
  4975.           SymKey(iv->gbltbl, &key1);                /* Pointer to next key */
  4976.           if(KEYEQ(key, key1))
  4977.           {/* Hashed keys match, check the strings */
  4978.             SymValue(iv->gbltbl, &valp[dupcnt+1]);    /* Pointer to next value */
  4979.             if(!strcmp(valp[dupcnt]->symname, valp[dupcnt+1]->symname))
  4980.             {/* Duplicate entry found */
  4981.                 ++dupcnt;
  4982.                 continue;
  4983.             }
  4984.           }
  4985.           break;
  4986.         }
  4987.         if(dupcnt > 0)
  4988.         {/* Process a collection of duplicate symbol names */
  4989.           link_dups(iv, dupcnt, valp);
  4990.         }
  4991.         SymSetMark(iv->gbltbl, mark);
  4992.  
  4993.       }/* END: while(SymNext) */
  4994.     }/* END: if(SymHead) */
  4995. }
  4996. static void
  4997. realloc_data(Piv iv)
  4998. {
  4999. int i;
  5000. Pafile pf;
  5001. unsigned char *p, *prevp;
  5002. unsigned long offset = 0;
  5003.  
  5004.     iv->datatbl = NewSymTable(iv->category, 0);     /* sorted table */
  5005.  
  5006.     for(i = 0; i < iv->numfiles; ++i)
  5007.     {
  5008.         pf = iv->files[i];
  5009.         p = pf->data_p;
  5010.         prevp = 0;
  5011.         while(*p != endfileop)
  5012.         {
  5013.             if(        *p == datablockop
  5014.                 ||    *p == mallocblockop
  5015.                 ||    *p == stringblockop)
  5016.             {
  5017.                 PL(POP->data1) = offset;                
  5018.                 data_insert(iv->datatbl, offset, GL(POP->data), p, prevp);
  5019.                 offset += GL(POP->data);
  5020.                 ROUNDUP(offset, 4);
  5021.             }
  5022.             prevp = p;
  5023.             p = POP->next;
  5024.         }
  5025.     }
  5026.     iv->thunk_offset = offset;
  5027.  
  5028.     for(i = 0; i < iv->numfiles; ++i)
  5029.     {
  5030.         pf = iv->files[i];
  5031.         p = pf->data_p;
  5032.         prevp = 0;
  5033.         while(*p != endfileop)
  5034.         {
  5035.             if(*p == thunkblockop)
  5036.             {
  5037.                 PL(POP->data1) = offset;
  5038.                 data_insert(iv->datatbl, offset, GL(POP->data), p, prevp);
  5039.                 offset += GL(POP->data);
  5040.                 ROUNDUP(offset, 4);
  5041.             }
  5042.             prevp = p;
  5043.             p = POP->next;
  5044.         }
  5045.     }
  5046.     iv->bss_offset = offset;
  5047.  
  5048.     for(i = 0; i < iv->numfiles; ++i)
  5049.     {
  5050.         pf = iv->files[i];
  5051.         p = pf->data_p;
  5052.         prevp = 0;
  5053.         while(*p != endfileop)
  5054.         {
  5055.             if(*p == bssblockop)
  5056.             {
  5057.                 PL(POP->data1) = offset;
  5058.                 data_insert(iv->datatbl, offset, GL(POP->data), p, prevp);
  5059.                 offset += GL(POP->data);
  5060.                 ROUNDUP(offset, 4);
  5061.             }
  5062.             prevp = p;
  5063.             p = POP->next;
  5064.         }
  5065.     }
  5066.     iv->total_size = offset;
  5067. }
  5068. static void
  5069. reset_data_relocs(Piv iv)
  5070. {/* Pass over initialized data and set new offsets in each relocatable slot */
  5071. struct _data {/* datatbl node */
  5072. /* value area 20 bytes */
  5073.     unsigned long size;
  5074.     unsigned char *p;
  5075.     unsigned char unused[12];
  5076. /* key area 8 bytes */
  5077.     unsigned long offset;
  5078.     long unused1;
  5079. };
  5080.     /* PASS OVER ALL THE ENTRIES IN `reloctbl' */
  5081.     if(SymHead(iv->reloctbl))
  5082.     {
  5083.         while(SymNext(iv->reloctbl))
  5084.         {
  5085.         struct _rkey *kp;
  5086.         struct _rval *vp;
  5087.         struct _data *dp, *ndp;
  5088.         unsigned char *p;
  5089.         Pafile pf, npf;
  5090.         unsigned long object_base;
  5091.         int noset = 0;
  5092.  
  5093.           SymKey(iv->reloctbl, &kp);
  5094.           SymValue(iv->reloctbl, &vp);
  5095.           npf = pf = iv->files[kp->fileno];    /* pointer to file struct */
  5096.           p = vp->p;        /* pointer to relocop in input buffer */
  5097.  
  5098.           if(vp->opcode == extlocop)
  5099.           {/* External variable */
  5100.           short key[4];
  5101.           struct {
  5102.           unsigned char *p;    /* pointer to extvarop in input buffer */
  5103.           } *ep;
  5104.             key[0] = vp->rsym;         /* external symbol number */
  5105.             key[1] = pf->filenum;
  5106.             key[2] = 0;
  5107.             key[3] = 0;
  5108.  
  5109.             /* LOOK UP THE EXTERNAL SYMBOL */
  5110.             if(SymFind(iv->extrntbl, key, &ep) && *(ep->p) == 0)
  5111.             {/* symbol exists and the extvarop was filled in */
  5112.  
  5113.                 npf = iv->files[GS( ((short*)(ep->p))[1] )];
  5114.                 PL( POPI->reloc.base ) = GL( ((Pop)(ep->p))->data1 );
  5115.                 *p = relocop;    /* switch input file from `extlocop' */
  5116.             }
  5117.             else
  5118.             {/* Not found or not filled in, leave it alone */
  5119.                 noset = 1;
  5120.             }
  5121.           }
  5122.  
  5123.           /* RESET THE ENTRY IN THE INITIALIZED DATA SLOT */
  5124.           if(SymFindRange(pf->datatbl, &kp->spot, &dp))
  5125.           {/* This entry describes a block of data containg the reloc target */
  5126.           unsigned char *ip = dp->p;    /* points to input buffer */
  5127.           unsigned long extra = kp->spot - dp->offset; /* offset into data */
  5128.  
  5129.  
  5130.             /* Reset the relocop target in the input file */
  5131.  
  5132.             PL( POPI->reloc.spot ) = GL( ((PopI)(ip+8))->s.offset ) + extra;
  5133.  
  5134.             if(vp->rsize == 4)
  5135.             {/* 32 bit relocation */
  5136.             unsigned long *lp;
  5137.  
  5138.                 if(noset)
  5139.                     goto reset32;
  5140.  
  5141.                 lp = (unsigned long*)(ip+24+extra);    /* pointer to target */
  5142.                 object_base = GL( POPI->reloc.base );
  5143.  
  5144.                 /* Find the object that the target points to */
  5145. relink32:
  5146.                 if(SymFindRange(npf->datatbl, &object_base, &ndp))
  5147.                 {
  5148.                     if(*(ndp->p) == 0)
  5149.                     {/* The found object is a discarded thunkblock, relink */
  5150.                         npf = iv->files[GS( ((short*)(ndp->p))[1] )];
  5151.                         object_base = GL( ((Pop)(ndp->p))->data4 );
  5152.                         goto relink32;
  5153.                     }
  5154.                     else
  5155.                     {/* Use the new offset in the input file */
  5156.  
  5157.                         object_base = GL( ((Pop)(ndp->p))->data1 );
  5158.                     }
  5159.                     PL( POPI->reloc.base ) = object_base; /* the `relocop' */
  5160.                     PL(*lp) = object_base + GL( POPI->reloc.offset );/* data */
  5161.                     vp->base = (long)lp;
  5162. reset32:
  5163.                     {
  5164.                     struct _rkey key;
  5165.                     struct _rval val;
  5166.  
  5167.                         key.spot = GL(POPI->reloc.spot);
  5168.                         key.fileno = 0;
  5169.                         val.opcode = *p;
  5170.                         val.rsize = GL(POPI->reloc.rsize);
  5171.                         val.p = p;
  5172.                         val.base = GL(POPI->reloc.base);
  5173.                         val.offset = GL(POPI->reloc.offset);
  5174.                         val.rsym = GS(POPI->reloc.rsym);    
  5175.                         val.fileno = kp->fileno;
  5176.                         SymInsert(iv->newreloctbl, &key, &val, 18);
  5177.                     }
  5178.                 }
  5179.                 else
  5180.                 {
  5181.                     ++iv->errors;
  5182.                     PWARN(pName ":syserr: 32 bit object at offset %d not found\n",object_base);
  5183.                 }
  5184.             }
  5185.             else if(vp->rsize == 2)
  5186.             {/* 16 bit relocation (MORE WORK NEEDED) */
  5187.             unsigned short *sp;
  5188.  
  5189.                 if(noset)
  5190.                     goto reset16;
  5191.                 sp = (unsigned short*)(ip+24+extra);    /* pointer to target */
  5192.                 object_base = GL( POPI->reloc.base );
  5193. relink16:
  5194.                 if(SymFindRange(npf->datatbl, &object_base, &ndp))
  5195.                 {
  5196.                     if(*(ndp->p) == 0)
  5197.                     {/* The found object is a discarded thunkblock, relink */
  5198.                         npf = iv->files[GS( ((short*)(ndp->p))[1] )];
  5199.                         object_base = GL( ((Pop)(ndp->p))->data4 );
  5200.                         goto relink16;
  5201.                     }
  5202.                     else
  5203.                     {/* Use the new offset in the input file */
  5204.  
  5205.                         object_base = GL( ((Pop)(ndp->p))->data1 );
  5206.                     }
  5207.                     PL( POPI->reloc.base ) = object_base; /* the `relocop' */
  5208.                     PS(*sp) = object_base + GL( POPI->reloc.offset );/* data */
  5209. reset16:
  5210.                     {
  5211.                     struct _rkey key;
  5212.                     struct _rval val;
  5213.  
  5214.                         key.spot = GL(POPI->reloc.spot);
  5215.                         key.fileno = 0;
  5216.                         val.opcode = *p;
  5217.                         val.rsize = GL(POPI->reloc.rsize);
  5218.                         val.p = p;
  5219.                         val.base = GL(POPI->reloc.base);
  5220.                         val.offset = GL(POPI->reloc.offset);
  5221.                         val.rsym = GS(POPI->reloc.rsym);    
  5222.                         val.fileno = kp->fileno;
  5223.                         SymInsert(iv->newreloctbl, &key, &val, 18);
  5224.                     }
  5225.                 }
  5226.                 else
  5227.                 {
  5228.                     ++iv->errors;
  5229.                     PWARN(pName ":syserr: 16 bit object at offset %d not found\n", object_base);
  5230.                 }
  5231.  
  5232.             }
  5233.           }
  5234.           else /* !SymFindRange */
  5235.           {
  5236.             ++iv->errors;
  5237.             PWARN(pName ":syserr: reloc not found at %d in file %d\n", 
  5238.                     kp->spot, kp->fileno);
  5239.           }
  5240.         }/* END: While(SymNext) */
  5241.     }/* END: if(SymHead) */
  5242. }
  5243. static void
  5244. reset_offset(Piv iv, Pafile pf, PopA pa)
  5245. {/* All offsets are guaranteed to be inside objects */
  5246. struct _data {/* datatbl node */
  5247. /* value area 16 bytes */
  5248.     unsigned long size;
  5249.     unsigned char *p;
  5250.     unsigned long unused[2];
  5251. /* key area 8 bytes */
  5252.     unsigned long offset;
  5253.     long unused1;
  5254. };
  5255.  
  5256. unsigned long offset;
  5257. struct _data *dp;
  5258. unsigned long object_base;
  5259. long extra;
  5260. unsigned short atype;
  5261. short symnum;
  5262.  
  5263.     offset = GL( pa->offset );
  5264.     atype = GS( pa->atype );
  5265.     symnum = GS( pa->symnum );
  5266.  
  5267.     PS( pa->symnum ) = pf->symtran[symnum];
  5268.     PS( pa->declnum ) = pf->decltran[GS(pa->declnum)];
  5269.  
  5270.     if(atype & A_EXTERN)
  5271.     {
  5272.     short key[4];
  5273.     struct {
  5274.     unsigned char *p;    /* pointer to extvarop in input buffer */
  5275.     } *ep;
  5276.         key[0] = symnum;         /* external symbol number */
  5277.         key[1] = pf->filenum;
  5278.         key[2] = 0;
  5279.         key[3] = 0;
  5280.  
  5281.             /* LOOK UP THE EXTERNAL SYMBOL */
  5282.         if(SymFind(iv->extrntbl, key, &ep) && *(ep->p) == 0)
  5283.         {/* symbol exists and the extvarop was filled in */
  5284.  
  5285.             pf = iv->files[GS( ((short*)(ep->p))[1] )];
  5286.             offset += GL( ((Pop)(ep->p))->data1 );
  5287.         }
  5288.         else
  5289.         {/* Not found or not filled in, leave it alone */
  5290.  
  5291.             return;
  5292.         }
  5293.     }
  5294.     extra = 0;    /* first time through */
  5295.  
  5296.     /* Find the object that the offset points to */
  5297. relink:
  5298.     if(SymFindRange(pf->datatbl, &offset, &dp))
  5299.     {
  5300.         if(extra == 0)
  5301.             extra = offset - dp->offset;
  5302.         object_base = dp->offset;
  5303.  
  5304.         if(*(dp->p) == 0)
  5305.         {/* The found object is a discarded block, relink */
  5306.             pf = iv->files[GS( ((short*)(dp->p))[1] )];
  5307.             offset = GL( ((Pop)(dp->p))->data4 );
  5308.             goto relink;
  5309.         }
  5310.         else
  5311.         {/* Use the adjusted offset in the input buffer */
  5312.  
  5313.             object_base = GL( ((Pop)(dp->p))->data1 );
  5314.         }
  5315.         PL( pa->offset ) = object_base + extra;
  5316.         if(atype & A_EXTERN)
  5317.         {
  5318.             PS( pa->atype ) = atype & ~A_EXTERN;        
  5319.         }
  5320.     }
  5321.     else
  5322.     {
  5323.         ++iv->errors;
  5324.         PWARN(pName ":syserr: object `%s' at offset %d not found\n", 
  5325.             pf->symaddr[symnum], offset);
  5326.     }
  5327. }
  5328. static void
  5329. reset_text_relocs(Piv iv)
  5330. {/* Pass over text and set new offsets in instructions that reference data */
  5331. int i;
  5332.  
  5333.     for(i = 0; i < iv->numfiles; ++i)
  5334.     {
  5335.     Pafile pf;
  5336.     unsigned char *p;
  5337.  
  5338.         pf = iv->files[i];
  5339.         if(!(p = pf->prog_p))
  5340.             continue;
  5341.  
  5342.         while(*p != endfileop)
  5343.         {
  5344.             if(*p && *p <= (unsigned char)100)
  5345.             {/* instruction */
  5346.             int inc = 8;
  5347.                 if((p[1]&0xe0) == OPDATA)
  5348.                     reset_offset(iv, pf, POPA);
  5349.                 inc += (p[1]&0x1f);
  5350.                 if((p[2]&0xe0) == OPDATA)
  5351.                     reset_offset(iv, pf, POPA);
  5352.                 inc += (p[2]&0x1f);
  5353.                 if((p[3]&0xe0) == OPDATA)
  5354.                     reset_offset(iv, pf, POPA);
  5355.             }
  5356.             p = POP->next;                
  5357.         }
  5358.     }
  5359.  
  5360. }
  5361. static void *
  5362. seg_find(Piv iv, int id)
  5363. {
  5364. long key[2];
  5365. void **result;
  5366.  
  5367.     if(iv->segtbl)
  5368.     {
  5369.         key[0] = id;
  5370.         key[1] = 0;
  5371.         if(SymFind(iv->segtbl, key, &result) == 1)
  5372.             return *result;
  5373.     }
  5374.     return 0;    
  5375. }
  5376. static void
  5377. check_seg(Piv iv, unsigned char *p, Pafile pf)
  5378. {
  5379. PopI np, op;
  5380.     if(!(iv->segtbl))
  5381.     {
  5382.         iv->segtbl = NewSymTable(iv->category, 111);
  5383.     }
  5384.     if((op = seg_find(iv, GS(POPI->segdef.segid))))
  5385.     {
  5386.         np = POPI;
  5387.         if(        GL(np->segdef.v1) == GL(op->segdef.v1)
  5388.             &&    GL(np->segdef.v2) == GL(op->segdef.v2)
  5389.             &&    GL(np->segdef.v3) == GL(op->segdef.v3))
  5390.         {/* segments of same name have the same values */
  5391.             *p = 0;    /* kill the new definition */
  5392.             return;
  5393.         }
  5394.         else
  5395.         {/* segments of same name have different values */
  5396.             ++iv->errors;
  5397.             PWARN(pName ":Segment `%s' defined differently.\n",
  5398.                 iv->symaddr[GS(POPI->segdef.segid)]);
  5399.             PWARN(pName ":  In file: `%s'\n", pf->symaddr[INFILE_SYMNUM]);
  5400.             return;
  5401.         }
  5402.     }
  5403.     else
  5404.     {
  5405.     long key[2];
  5406.     PopI pp = POPI;
  5407.         key[0] = GS(POPI->segdef.segid);
  5408.         key[1] = 0;
  5409.         SymInsert(iv->segtbl, key, &pp, 4);
  5410.     }
  5411. }
  5412. static void
  5413. reset_syms_decls(Piv iv)
  5414. {
  5415. int i;
  5416.     for(i = 0; i < iv->numfiles; ++i)
  5417.     {
  5418.     Pafile pf;
  5419.     unsigned char *p;
  5420.  
  5421.         pf = iv->files[i];
  5422.         p = pf->file_p;
  5423.  
  5424.         while(*p != endfileop)
  5425.         {
  5426.           if(*p == segdefop)
  5427.           {
  5428.             PS(POPI->segdef.segid) = pf->symtran[GS(POPI->segdef.segid)];
  5429.             check_seg(iv, p, pf);
  5430.           }
  5431.           else if(i > 0)
  5432.           {
  5433.             switch(*p)
  5434.             {
  5435.                 case    declop:
  5436.                     if(GS(POPI->dcl.declnum) < 22)
  5437.                     {/* kill the base declarations */
  5438.                         *p = 0;
  5439.                         p = POP->next;                
  5440.                         *p = 0;
  5441.                     }
  5442.                     else
  5443.                      PS(POPI->dcl.declnum)=pf->decltran[GS(POPI->dcl.declnum)];
  5444.                     break;
  5445.                 case    extlocop:
  5446.                     PS(POPI->reloc.rsym) = pf->symtran[GS(POPI->reloc.rsym)];
  5447.                     break;
  5448.                 case    gfuncdefop:
  5449.                 case    sfuncdefop:
  5450.                     if(pf->numsegs)
  5451.                     PS(POPI->funcdef.segid) = pf->symtran[GS(POPI->funcdef.segid)];
  5452.                 case    nestedfuncdefop:
  5453.                     PL(POPI->funcdef.symnum)=pf->symtran[GL(POPI->funcdef.symnum)];
  5454.                     break;
  5455.                 case    bssblockop:
  5456.                 case    datablockop:
  5457.                     if(pf->numsegs)
  5458.                     PS( POPI->s.segid ) = pf->symtran[GS(POPI->s.segid)];
  5459.                 case    stringblockop:
  5460.                 case    mallocblockop:
  5461.                 case    thunkblockop:
  5462.                 case    extvarop:
  5463.                     PS( POPI->s.symnum ) = pf->symtran[GS(POPI->s.symnum)];
  5464.                     PS( POPI->s.declnum ) = pf->decltran[GS(POPI->s.declnum)];
  5465.                     break;
  5466.                 case    memberinfop:
  5467.                 case    bfieldinfop:
  5468.                     PS(POPI->memb.symnum) = pf->symtran[GS(POPI->memb.symnum)];
  5469.                     PS(POPI->memb.declnum) = pf->decltran[GS(POPI->memb.declnum)];
  5470.                     PS(POPI->memb.cdeclnum) = pf->decltran[GS(POPI->memb.cdeclnum)];
  5471.                     break;
  5472.                 case    structinfop:
  5473.                     PS(POPI->suinf.symnum) = pf->symtran[GS(POPI->suinf.symnum)];
  5474.                     break;
  5475.                 case    funcptrinfop:
  5476.                 case    ptrinfop:
  5477.                     PS(POPI->ptrinf.declnum) = pf->decltran[GS(POPI->ptrinf.declnum)];
  5478.                     break;
  5479.                 case    funcinfop:
  5480.                     PS(POPI->funcd.declnum) = pf->decltran[GS(POPI->funcd.declnum)];
  5481.                     PS(POPI->funcd.symnum) = pf->symtran[GS(POPI->funcd.symnum)];
  5482.                     break;
  5483.                 case    arrayinfop:
  5484.                     PS(POPI->ary.declnum) = pf->decltran[GS(POPI->ary.declnum)];
  5485.                     break;
  5486.                 case    lineop:
  5487.                     PL(POPI->line.filenamenum) = pf->symtran[GL(POPI->line.filenamenum)];
  5488.                     break;
  5489.             }/* END: switch(*p) */
  5490.           }/* END: i > 0 */
  5491.           p = POP->next;                
  5492.         }
  5493.     }
  5494. }
  5495. static int
  5496. link_files(Piv iv)
  5497. {
  5498.     iv->extrntbl = NewSymTable(iv->category, 4092);    /* hashed table */
  5499.     iv->reloctbl = NewSymTable(iv->category, 4092); /* hashed table */
  5500.     iv->newreloctbl = NewSymTable(iv->category, 4092); /* hashed table */
  5501.     iv->gbltbl = NewSymTable(iv->category, 0);    /* sorted table */
  5502.  
  5503.     setup_syms_decls(iv);
  5504.  
  5505.     if(iv->numfiles > 1)
  5506.     {
  5507.         iv->symaddr = Ccalloc(iv->category, sizeof(void*), iv->numsyms);
  5508.         iv->decladdr = Ccalloc(iv->category, sizeof(void*), iv->numdecls);
  5509.         iv->symtbl = NewSymTable(iv->category, 0); /* sorted table */
  5510.         combine_syms_decls(iv);
  5511.  
  5512.         link_globals(iv);
  5513.         realloc_data(iv);
  5514.         reset_data_relocs(iv);
  5515.         reset_text_relocs(iv);
  5516.  
  5517.         reset_syms_decls(iv);
  5518.     }
  5519.     else
  5520.     {
  5521.         iv->symaddr = iv->files[0]->symaddr;
  5522.         iv->decladdr = iv->files[0]->decladdr;
  5523.         iv->symtbl = NewSymTable(iv->category, 0); /* sorted table */
  5524.         combine_syms_decls(iv);
  5525.  
  5526.         realloc_data(iv);
  5527.         reset_data_relocs(iv);
  5528.         reset_text_relocs(iv);
  5529.     }
  5530.     return iv->errors;
  5531. }
  5532.  
  5533. /* ======================== GLOBAL ROUTINES ========================== */
  5534. int
  5535. Global(readfile) (Piv iv, char *infile_name)
  5536. {
  5537. FILE *infile;
  5538. long infile_size;
  5539. char *inbuf;
  5540.  
  5541.     iv->infile_name = infile_name;
  5542.     if(!(infile = fopen(infile_name, "rb")))
  5543.     {
  5544.         PERROR(pName ": Can't open input file: %s\n", infile_name);
  5545.     }
  5546.     fseek(infile, 0, SEEK_END);
  5547.     infile_size = ftell(infile);    
  5548.     fseek(infile, 0, SEEK_SET);
  5549.  
  5550.     if(infile_size == 0)
  5551.     {
  5552.         PERROR(pName ": Empty input file: %s\n", infile_name);
  5553.     }
  5554.     inbuf = Cmalloc(iv->category, infile_size);
  5555.  
  5556.     if(fread(inbuf, 1, infile_size, infile) != infile_size)
  5557.     {
  5558.         fclose(infile);
  5559.         PERROR(pName ": Error reading input file: %s\n", infile_name);
  5560.     }
  5561.     fclose(infile);
  5562.  
  5563.     if(setup_nodelinks(iv, infile_name, inbuf, infile_size))
  5564.         return 4;
  5565.     return 0;
  5566. }
  5567. int
  5568. Global(proc_files) (Piv iv, void *name)
  5569. {
  5570. int ret;
  5571.  
  5572.     if(!(ret = link_files(iv)))
  5573.     {
  5574.         optimize(iv);
  5575.         if(name)
  5576.           iv->symaddr[2] = name;    /* symbol 2 is the output filename */
  5577.         ret = gen_output(iv, iv->symaddr[2]);
  5578.     }
  5579.     return ret;
  5580. }
  5581. void *
  5582. Global(open_instance) (void)
  5583. {
  5584. Piv iv;
  5585. int category;
  5586. #if USING_FRAMEWORK
  5587.     if(num_instance <= 0)
  5588.     {
  5589.         oxlink_clear_bss(pName ".o");    /* reset global storage */
  5590.         local_category = NewMallocCategory();
  5591.     }
  5592.     ++num_instance;
  5593. #endif
  5594.     category = Cnewcat();
  5595.     iv = Ccalloc(category, 1, sizeof(struct _iv));
  5596.     iv->category = category;
  5597.     return iv;
  5598. }
  5599. void
  5600. Global(close_instance) (Piv iv)
  5601. {
  5602.     if(iv->outfile)
  5603.       fclose(iv->outfile);
  5604.     if(iv->remove_infile)
  5605.     {
  5606.     int i;
  5607.       for(i = 1; i < iv->argc; ++i)
  5608.         unlink(propernameof(iv, iv->argv[i]));
  5609.     }
  5610.     Cfreecat(iv->category);
  5611. #if USING_FRAMEWORK
  5612.     if(--num_instance == 0)
  5613.         freecat(local_category);
  5614. #endif
  5615. }
  5616.  
  5617. /* =========================== THE MAIN PROGRAM ======================= */
  5618.  
  5619. static char *
  5620. filenameof(char *path)
  5621. {
  5622. char *ret = path;
  5623. int i;
  5624.     for(i = 0; path[i]; ++i)
  5625.       if(path[i] == '/')
  5626.         ret = &path[i+1];
  5627.     return ret;
  5628. }
  5629.  
  5630. static char *
  5631. propernameof(Piv iv, char *path)
  5632. {
  5633. char *name = filenameof(path);
  5634. int namlen = strlen(name);
  5635. int i;
  5636.     for(i = namlen-1; i >= 0; --i)
  5637.     {
  5638.       if(name[i] == '/' || name[i] == '\\')
  5639.           break;
  5640.       else if(name[i] == '.')
  5641.         return path;
  5642.     }
  5643.     name = Cmalloc(iv->category, strlen(path)+8);
  5644.     strcpy(name, path);
  5645.     strcat(name, ".anf");
  5646.     return name;
  5647. }
  5648. static void
  5649. Usage()
  5650. {
  5651. fputs(
  5652. "Usage: " pName " [-odsLDR?] [infile...]\n"
  5653. "   -o outfile == name of output file\n"
  5654. "   -d == print debug output\n"
  5655. "   -D == only print debug output\n"
  5656. "   -s == strip declarations and line numbers\n"
  5657. "   -L == generate listing only (to .lst)\n"
  5658. "   -R == remove the input file\n"
  5659. "   -? == print this message\n"
  5660. "   Default input file is `code.anf'.\n"
  5661. "   Default output file is specified by the input.\n"
  5662. ,stderr);
  5663. }
  5664.  
  5665. #if USING_FRAMEWORK
  5666. int
  5667. PROG (int argc, char **argv)
  5668. #else
  5669. int
  5670. main (int argc, char **argv)
  5671. #endif
  5672. {
  5673. int i,j;
  5674. char *outfilename = 0;
  5675. volatile Piv iv;
  5676. char debug, only_debug, strip, listing_wanted, remove_infile;
  5677. int ret;
  5678.  
  5679.     remove_infile = listing_wanted = strip = debug = only_debug = 0;
  5680.  
  5681.     /* Get options */
  5682.     for(i = 1; i < argc; ++i)
  5683.     {
  5684.     int trimsize = 1;
  5685.         if(argv[i][0] == '-')
  5686.         {
  5687.             for (j=1; argv[i][j]; j++)
  5688.             {
  5689.                 switch(argv[i][j])
  5690.                 {    
  5691.                     case    'D':
  5692.                         only_debug = 1;
  5693.                         /* FALL THROUGH */
  5694.                     case    'd':
  5695.                         debug = argv[i][++j];
  5696.                         break;
  5697.                     case    's':
  5698.                         strip = 1;
  5699.                         break;
  5700.                     case    'o':
  5701.                         if(argv[i][j+1]) {
  5702.                             outfilename = &argv[i][j+1];
  5703.                         }
  5704.                         else if(i < argc-1) {
  5705.                             outfilename = argv[i+1];
  5706.                             trimsize = 2;
  5707.                         } else {
  5708.                             PWARN(pName ": no output filename\n");
  5709.                             Usage();
  5710.                             return 0;
  5711.                         }
  5712.                         goto trim;
  5713.                         break;
  5714.                     case    'L':
  5715.                         listing_wanted = 1;
  5716.                         break;
  5717.                     case    'R':
  5718.                         remove_infile = 1;
  5719.                         break;
  5720.                     case '?':
  5721.                         Usage();
  5722.                         return 0;
  5723.                     default:
  5724.                         PWARN(pName ": Invalid switch: %c\n", argv[i][j]);
  5725.                         Usage();
  5726.                         return 0;
  5727.                 }
  5728.             }/* END: for(j) */
  5729. trim:
  5730.             /* Trim switch */
  5731.             for(j = i; j < argc-trimsize; ++j)
  5732.                 argv[j] = argv[j+trimsize];
  5733.             argc -= trimsize;
  5734.             --i;
  5735.         }/* END: if('-') */
  5736.     }/* END: for(argc) */
  5737.  
  5738.     iv = Global(open_instance) ();
  5739.     if((ret = setjmp(run_env))) {
  5740.         Global(close_instance) (iv);
  5741. #if USING_FRAMEWORK
  5742.         return ret;
  5743. #else
  5744.         exit(ret);
  5745. #endif
  5746.     }
  5747.     iv->debug = debug;
  5748.     iv->only_debug = only_debug;
  5749.     iv->labeltbl = NewSymTable(iv->category, 4092);
  5750. #if REALLY_NEED_OFFSETS
  5751.     iv->newlabeltbl = NewSymTable(iv->category, 4092);
  5752. #endif
  5753.     iv->strip = strip;
  5754.     iv->listing_wanted = listing_wanted;
  5755.     iv->remove_infile = remove_infile;
  5756.     iv->argc = argc;
  5757.     iv->argv = argv;
  5758.  
  5759.     if(argc < 2)
  5760.     {/* Default input filename is 'code.anf' */
  5761.         ret = Global(readfile) (iv, "code.anf");
  5762.     }
  5763.     else
  5764.     {/* READ EACH INPUT FILE */
  5765.     
  5766.         for(i = 1; i < argc; ++i)
  5767.           if((ret = Global(readfile) (iv, propernameof(iv,argv[i]))))
  5768.             break;
  5769.     }
  5770.     if(!ret && !iv->only_debug)
  5771.     {
  5772.         ret = Global(proc_files) (iv, outfilename);
  5773.     }
  5774.     Global(close_instance) (iv);
  5775. #if USING_FRAMEWORK
  5776.     return ret;
  5777. #else
  5778.     exit(ret);
  5779. #endif
  5780. }
  5781.  
  5782.