DccFrontend.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. #include <QtCore/QFileInfo>
  2. #include <QtCore/QDebug>
  3. #include <cstdio>
  4. #include "dcc.h"
  5. #include "DccFrontend.h"
  6. #include "project.h"
  7. #include "disassem.h"
  8. #include "CallGraph.h"
  9. class Loader
  10. {
  11. bool loadIntoProject(IProject *);
  12. };
  13. struct PSP { /* PSP structure */
  14. uint16_t int20h; /* interrupt 20h */
  15. uint16_t eof; /* segment, end of allocation block */
  16. uint8_t res1; /* reserved */
  17. uint8_t dosDisp[5]; /* far call to DOS function dispatcher */
  18. uint8_t int22h[4]; /* vector for terminate routine */
  19. uint8_t int23h[4]; /* vector for ctrl+break routine */
  20. uint8_t int24h[4]; /* vector for error routine */
  21. uint8_t res2[22]; /* reserved */
  22. uint16_t segEnv; /* segment address of environment block */
  23. uint8_t res3[34]; /* reserved */
  24. uint8_t int21h[6]; /* opcode for int21h and far return */
  25. uint8_t res4[6]; /* reserved */
  26. uint8_t fcb1[16]; /* default file control block 1 */
  27. uint8_t fcb2[16]; /* default file control block 2 */
  28. uint8_t res5[4]; /* reserved */
  29. uint8_t cmdTail[0x80]; /* command tail and disk transfer area */
  30. };
  31. static struct MZHeader { /* EXE file header */
  32. uint8_t sigLo; /* .EXE signature: 0x4D 0x5A */
  33. uint8_t sigHi;
  34. uint16_t lastPageSize; /* Size of the last page */
  35. uint16_t numPages; /* Number of pages in the file */
  36. uint16_t numReloc; /* Number of relocation items */
  37. uint16_t numParaHeader; /* # of paragraphs in the header */
  38. uint16_t minAlloc; /* Minimum number of paragraphs */
  39. uint16_t maxAlloc; /* Maximum number of paragraphs */
  40. uint16_t initSS; /* Segment displacement of stack */
  41. uint16_t initSP; /* Contents of SP at entry */
  42. uint16_t checkSum; /* Complemented checksum */
  43. uint16_t initIP; /* Contents of IP at entry */
  44. uint16_t initCS; /* Segment displacement of code */
  45. uint16_t relocTabOffset; /* Relocation table offset */
  46. uint16_t overlayNum; /* Overlay number */
  47. } header;
  48. #define EXE_RELOCATION 0x10 /* EXE images rellocated to above PSP */
  49. //static void LoadImage(char *filename);
  50. static void displayMemMap(void);
  51. /****************************************************************************
  52. * displayLoadInfo - Displays low level loader type info.
  53. ***************************************************************************/
  54. void PROG::displayLoadInfo(void)
  55. {
  56. int i;
  57. printf("File type is %s\n", (fCOM)?"COM":"EXE");
  58. if (! fCOM) {
  59. printf("Signature = %02X%02X\n", header.sigLo, header.sigHi);
  60. printf("File size %% 512 = %04X\n", LH(&header.lastPageSize));
  61. printf("File size / 512 = %04X pages\n", LH(&header.numPages));
  62. printf("# relocation items = %04X\n", LH(&header.numReloc));
  63. printf("Offset to load image = %04X paras\n", LH(&header.numParaHeader));
  64. printf("Minimum allocation = %04X paras\n", LH(&header.minAlloc));
  65. printf("Maximum allocation = %04X paras\n", LH(&header.maxAlloc));
  66. }
  67. printf("Load image size = %04" PRIiPTR "\n", cbImage - sizeof(PSP));
  68. printf("Initial SS:SP = %04X:%04X\n", initSS, initSP);
  69. printf("Initial CS:IP = %04X:%04X\n", initCS, initIP);
  70. if (option.VeryVerbose && cReloc)
  71. {
  72. printf("\nRelocation Table\n");
  73. for (i = 0; i < cReloc; i++)
  74. {
  75. printf("%06X -> [%04X]\n", relocTable[i],LH(image() + relocTable[i]));
  76. }
  77. }
  78. printf("\n");
  79. }
  80. /*****************************************************************************
  81. * fill - Fills line for displayMemMap()
  82. ****************************************************************************/
  83. static void fill(int ip, char *bf)
  84. {
  85. PROG &prog(Project::get()->prog);
  86. static uint8_t type[4] = {'.', 'd', 'c', 'x'};
  87. uint8_t i;
  88. for (i = 0; i < 16; i++, ip++)
  89. {
  90. *bf++ = ' ';
  91. *bf++ = (ip < prog.cbImage)? type[(prog.map[ip >> 2] >> ((ip & 3) * 2)) & 3]: ' ';
  92. }
  93. *bf = '\0';
  94. }
  95. /*****************************************************************************
  96. * displayMemMap - Displays the memory bitmap
  97. ****************************************************************************/
  98. static void displayMemMap(void)
  99. {
  100. PROG &prog(Project::get()->prog);
  101. char c, b1[33], b2[33], b3[33];
  102. uint8_t i;
  103. int ip = 0;
  104. printf("\nMemory Map\n");
  105. while (ip < prog.cbImage)
  106. {
  107. fill(ip, b1);
  108. printf("%06X %s\n", ip, b1);
  109. ip += 16;
  110. for (i = 3, c = b1[1]; i < 32 && c == b1[i]; i += 2)
  111. ; /* Check if all same */
  112. if (i > 32)
  113. {
  114. fill(ip, b2); /* Skip until next two are not same */
  115. fill(ip+16, b3);
  116. if (! (strcmp(b1, b2) || strcmp(b1, b3)))
  117. {
  118. printf(" :\n");
  119. do
  120. {
  121. ip += 16;
  122. fill(ip+16, b1);
  123. } while (! strcmp(b1, b2));
  124. }
  125. }
  126. }
  127. printf("\n");
  128. }
  129. DccFrontend::DccFrontend(QObject *parent) :
  130. QObject(parent)
  131. {
  132. }
  133. /*****************************************************************************
  134. * FrontEnd - invokes the loader, parser, disassembler (if asm1), icode
  135. * rewritter, and displays any useful information.
  136. ****************************************************************************/
  137. bool DccFrontend::FrontEnd ()
  138. {
  139. /* Do depth first flow analysis building call graph and procedure list,
  140. * and attaching the I-code to each procedure */
  141. parse (*Project::get());
  142. if (option.asm1)
  143. {
  144. std::cout << "dcc: writing assembler file "<<asm1_name.toStdString()<<'\n';
  145. }
  146. /* Search through code looking for impure references and flag them */
  147. Disassembler ds(1);
  148. for(Function &f : Project::get()->pProcList)
  149. {
  150. f.markImpure();
  151. if (option.asm1)
  152. {
  153. ds.disassem(&f);
  154. }
  155. }
  156. if (option.Interact)
  157. {
  158. interactDis(&Project::get()->pProcList.front(), 0); /* Interactive disassembler */
  159. }
  160. /* Converts jump target addresses to icode offsets */
  161. for(Function &f : Project::get()->pProcList)
  162. {
  163. f.bindIcodeOff();
  164. }
  165. /* Print memory bitmap */
  166. if (option.Map)
  167. displayMemMap();
  168. return(true); // we no longer own proj !
  169. }
  170. struct DosLoader {
  171. protected:
  172. void prepareImage(PROG &prog,size_t sz,QFile &fp) {
  173. /* Allocate a block of memory for the program. */
  174. prog.cbImage = sz + sizeof(PSP);
  175. prog.Imagez = new uint8_t [prog.cbImage];
  176. prog.Imagez[0] = 0xCD; /* Fill in PSP int 20h location */
  177. prog.Imagez[1] = 0x20; /* for termination checking */
  178. /* Read in the image past where a PSP would go */
  179. if (sz != fp.read((char *)prog.Imagez + sizeof(PSP),sz))
  180. fatalError(CANNOT_READ, fp.fileName().toLocal8Bit().data());
  181. }
  182. };
  183. struct ComLoader : public DosLoader {
  184. bool canLoad(QFile &fp) {
  185. fp.seek(0);
  186. char sig[2];
  187. if(2==fp.read(sig,2)) {
  188. return not (sig[0] == 0x4D && sig[1] == 0x5A);
  189. }
  190. return false;
  191. }
  192. bool load(PROG &prog,QFile &fp) {
  193. /* COM file
  194. * In this case the load module size is just the file length
  195. */
  196. auto cb = fp.size();
  197. /* COM programs start off with an ORG 100H (to leave room for a PSP)
  198. * This is also the implied start address so if we load the image
  199. * at offset 100H addresses should all line up properly again.
  200. */
  201. prog.initCS = 0;
  202. prog.initIP = 0x100;
  203. prog.initSS = 0;
  204. prog.initSP = 0xFFFE;
  205. prog.cReloc = 0;
  206. prepareImage(prog,cb,fp);
  207. /* Set up memory map */
  208. cb = (prog.cbImage + 3) / 4;
  209. prog.map = (uint8_t *)malloc(cb);
  210. memset(prog.map, BM_UNKNOWN, (size_t)cb);
  211. return true;
  212. }
  213. };
  214. struct ExeLoader : public DosLoader {
  215. bool canLoad(QFile &fp) {
  216. if(fp.size()<sizeof(header))
  217. return false;
  218. MZHeader tmp_header;
  219. fp.seek(0);
  220. fp.read((char *)&tmp_header, sizeof(header));
  221. if(not (tmp_header.sigLo == 0x4D && tmp_header.sigHi == 0x5A))
  222. return false;
  223. /* This is a typical DOS kludge! */
  224. if (LH(&header.relocTabOffset) == 0x40)
  225. {
  226. qDebug() << "Don't understand new EXE format";
  227. return false;
  228. }
  229. return true;
  230. }
  231. bool load(PROG &prog,QFile &fp) {
  232. /* Read rest of header */
  233. fp.seek(0);
  234. if (fp.read((char *)&header, sizeof(header)) != sizeof(header))
  235. return false;
  236. /* Calculate the load module size.
  237. * This is the number of pages in the file
  238. * less the length of the header and reloc table
  239. * less the number of bytes unused on last page
  240. */
  241. uint32_t cb = (uint32_t)LH(&header.numPages) * 512 - (uint32_t)LH(&header.numParaHeader) * 16;
  242. if (header.lastPageSize)
  243. {
  244. cb -= 512 - LH(&header.lastPageSize);
  245. }
  246. /* We quietly ignore minAlloc and maxAlloc since for our
  247. * purposes it doesn't really matter where in real memory
  248. * the program would end up. EXE programs can't really rely on
  249. * their load location so setting the PSP segment to 0 is fine.
  250. * Certainly programs that prod around in DOS or BIOS are going
  251. * to have to load DS from a constant so it'll be pretty
  252. * obvious.
  253. */
  254. prog.initCS = (int16_t)LH(&header.initCS) + EXE_RELOCATION;
  255. prog.initIP = (int16_t)LH(&header.initIP);
  256. prog.initSS = (int16_t)LH(&header.initSS) + EXE_RELOCATION;
  257. prog.initSP = (int16_t)LH(&header.initSP);
  258. prog.cReloc = (int16_t)LH(&header.numReloc);
  259. /* Allocate the relocation table */
  260. if (prog.cReloc)
  261. {
  262. prog.relocTable.resize(prog.cReloc);
  263. fp.seek(LH(&header.relocTabOffset));
  264. /* Read in seg:offset pairs and convert to Image ptrs */
  265. uint8_t buf[4];
  266. for (int i = 0; i < prog.cReloc; i++)
  267. {
  268. fp.read((char *)buf,4);
  269. prog.relocTable[i] = LH(buf) + (((int)LH(buf+2) + EXE_RELOCATION)<<4);
  270. }
  271. }
  272. /* Seek to start of image */
  273. uint32_t start_of_image= LH(&header.numParaHeader) * 16;
  274. fp.seek(start_of_image);
  275. /* Allocate a block of memory for the program. */
  276. prepareImage(prog,cb,fp);
  277. /* Set up memory map */
  278. cb = (prog.cbImage + 3) / 4;
  279. prog.map = (uint8_t *)malloc(cb);
  280. memset(prog.map, BM_UNKNOWN, (size_t)cb);
  281. /* Relocate segment constants */
  282. for(uint32_t v : prog.relocTable) {
  283. uint8_t *p = &prog.Imagez[v];
  284. uint16_t w = (uint16_t)LH(p) + EXE_RELOCATION;
  285. *p++ = (uint8_t)(w & 0x00FF);
  286. *p = (uint8_t)((w & 0xFF00) >> 8);
  287. }
  288. return true;
  289. }
  290. };
  291. /*****************************************************************************
  292. * LoadImage
  293. ****************************************************************************/
  294. bool Project::load()
  295. {
  296. // addTask(loaderSelection,PreCond(BinaryImage))
  297. // addTask(applyLoader,PreCond(Loader))
  298. const char *fname = binary_path().toLocal8Bit().data();
  299. QFile finfo(binary_path());
  300. /* Open the input file */
  301. if(!finfo.open(QFile::ReadOnly)) {
  302. fatalError(CANNOT_OPEN, fname);
  303. }
  304. /* Read in first 2 bytes to check EXE signature */
  305. if (finfo.size()<=2)
  306. {
  307. fatalError(CANNOT_READ, fname);
  308. }
  309. ComLoader com_loader;
  310. ExeLoader exe_loader;
  311. if(exe_loader.canLoad(finfo)) {
  312. prog.fCOM = false;
  313. return exe_loader.load(prog,finfo);
  314. }
  315. if(com_loader.canLoad(finfo)) {
  316. prog.fCOM = true;
  317. return com_loader.load(prog,finfo);
  318. }
  319. return false;
  320. }
  321. uint32_t SynthLab;
  322. /* Parses the program, builds the call graph, and returns the list of
  323. * procedures found */
  324. void DccFrontend::parse(Project &proj)
  325. {
  326. PROG &prog(proj.prog);
  327. STATE state;
  328. /* Set initial state */
  329. state.setState(rES, 0); /* PSP segment */
  330. state.setState(rDS, 0);
  331. state.setState(rCS, prog.initCS);
  332. state.setState(rSS, prog.initSS);
  333. state.setState(rSP, prog.initSP);
  334. state.IP = ((uint32_t)prog.initCS << 4) + prog.initIP;
  335. SynthLab = SYNTHESIZED_MIN;
  336. /* Check for special settings of initial state, based on idioms of the
  337. startup code */
  338. state.checkStartup();
  339. Function *start_proc;
  340. /* Make a struct for the initial procedure */
  341. if (prog.offMain != -1)
  342. {
  343. start_proc = proj.createFunction(0,"main");
  344. start_proc->retVal.loc = REG_FRAME;
  345. start_proc->retVal.type = TYPE_WORD_SIGN;
  346. start_proc->retVal.id.regi = rAX;
  347. /* We know where main() is. Start the flow of control from there */
  348. start_proc->procEntry = prog.offMain;
  349. /* In medium and large models, the segment of main may (will?) not be
  350. the same as the initial CS segment (of the startup code) */
  351. state.setState(rCS, prog.segMain);
  352. state.IP = prog.offMain;
  353. }
  354. else
  355. {
  356. start_proc = proj.createFunction(0,"start");
  357. /* Create initial procedure at program start address */
  358. start_proc->procEntry = (uint32_t)state.IP;
  359. }
  360. /* The state info is for the first procedure */
  361. start_proc->state = state;
  362. /* Set up call graph initial node */
  363. proj.callGraph = new CALL_GRAPH;
  364. proj.callGraph->proc = start_proc;
  365. /* This proc needs to be called to set things up for LibCheck(), which
  366. checks a proc to see if it is a know C (etc) library */
  367. SetupLibCheck();
  368. //BUG: proj and g_proj are 'live' at this point !
  369. /* Recursively build entire procedure list */
  370. start_proc->FollowCtrl(proj.callGraph, &state);
  371. /* This proc needs to be called to clean things up from SetupLibCheck() */
  372. CleanupLibCheck();
  373. }