2
0

dasm_x86.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /*
  2. ** DynASM x86 encoding engine.
  3. ** Copyright (C) 2005-2013 Mike Pall. All rights reserved.
  4. ** Released under the MIT license. See dynasm.lua for full copyright notice.
  5. */
  6. #include <stddef.h>
  7. #include <stdarg.h>
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #define DASM_ARCH "x86"
  11. #ifndef DASM_EXTERN
  12. #define DASM_EXTERN(a,b,c,d) 0
  13. #endif
  14. /* Action definitions. DASM_STOP must be 255. */
  15. enum {
  16. DASM_DISP = 233,
  17. DASM_IMM_S, DASM_IMM_B, DASM_IMM_W, DASM_IMM_D, DASM_IMM_WB, DASM_IMM_DB,
  18. DASM_VREG, DASM_SPACE, DASM_SETLABEL, DASM_REL_A, DASM_REL_LG, DASM_REL_PC,
  19. DASM_IMM_LG, DASM_IMM_PC, DASM_LABEL_LG, DASM_LABEL_PC, DASM_ALIGN,
  20. DASM_EXTERN, DASM_ESC, DASM_MARK, DASM_SECTION, DASM_STOP
  21. };
  22. /* Maximum number of section buffer positions for a single dasm_put() call. */
  23. #define DASM_MAXSECPOS 25
  24. /* DynASM encoder status codes. Action list offset or number are or'ed in. */
  25. #define DASM_S_OK 0x00000000
  26. #define DASM_S_NOMEM 0x01000000
  27. #define DASM_S_PHASE 0x02000000
  28. #define DASM_S_MATCH_SEC 0x03000000
  29. #define DASM_S_RANGE_I 0x11000000
  30. #define DASM_S_RANGE_SEC 0x12000000
  31. #define DASM_S_RANGE_LG 0x13000000
  32. #define DASM_S_RANGE_PC 0x14000000
  33. #define DASM_S_RANGE_VREG 0x15000000
  34. #define DASM_S_UNDEF_L 0x21000000
  35. #define DASM_S_UNDEF_PC 0x22000000
  36. /* Macros to convert positions (8 bit section + 24 bit index). */
  37. #define DASM_POS2IDX(pos) ((pos)&0x00ffffff)
  38. #define DASM_POS2BIAS(pos) ((pos)&0xff000000)
  39. #define DASM_SEC2POS(sec) ((sec)<<24)
  40. #define DASM_POS2SEC(pos) ((pos)>>24)
  41. #define DASM_POS2PTR(D, pos) (D->sections[DASM_POS2SEC(pos)].rbuf + (pos))
  42. /* Action list type. */
  43. typedef const unsigned char *dasm_ActList;
  44. /* Per-section structure. */
  45. typedef struct dasm_Section {
  46. int *rbuf; /* Biased buffer pointer (negative section bias). */
  47. int *buf; /* True buffer pointer. */
  48. size_t bsize; /* Buffer size in bytes. */
  49. int pos; /* Biased buffer position. */
  50. int epos; /* End of biased buffer position - max single put. */
  51. int ofs; /* Byte offset into section. */
  52. } dasm_Section;
  53. /* Core structure holding the DynASM encoding state. */
  54. struct dasm_State {
  55. size_t psize; /* Allocated size of this structure. */
  56. dasm_ActList actionlist; /* Current actionlist pointer. */
  57. int *lglabels; /* Local/global chain/pos ptrs. */
  58. size_t lgsize;
  59. int *pclabels; /* PC label chains/pos ptrs. */
  60. size_t pcsize;
  61. void **globals; /* Array of globals (bias -10). */
  62. dasm_Section *section; /* Pointer to active section. */
  63. size_t codesize; /* Total size of all code sections. */
  64. int maxsection; /* 0 <= sectionidx < maxsection. */
  65. int status; /* Status code. */
  66. dasm_Section sections[1]; /* All sections. Alloc-extended. */
  67. };
  68. /* The size of the core structure depends on the max. number of sections. */
  69. #define DASM_PSZ(ms) (sizeof(dasm_State)+(ms-1)*sizeof(dasm_Section))
  70. /* Initialize DynASM state. */
  71. void dasm_init(Dst_DECL, int maxsection)
  72. {
  73. dasm_State *D;
  74. size_t psz = 0;
  75. int i;
  76. Dst_REF = NULL;
  77. DASM_M_GROW(Dst, struct dasm_State, Dst_REF, psz, DASM_PSZ(maxsection));
  78. D = Dst_REF;
  79. D->psize = psz;
  80. D->lglabels = NULL;
  81. D->lgsize = 0;
  82. D->pclabels = NULL;
  83. D->pcsize = 0;
  84. D->globals = NULL;
  85. D->maxsection = maxsection;
  86. for (i = 0; i < maxsection; i++) {
  87. D->sections[i].buf = NULL; /* Need this for pass3. */
  88. D->sections[i].rbuf = D->sections[i].buf - DASM_SEC2POS(i);
  89. D->sections[i].bsize = 0;
  90. D->sections[i].epos = 0; /* Wrong, but is recalculated after resize. */
  91. }
  92. }
  93. /* Free DynASM state. */
  94. void dasm_free(Dst_DECL)
  95. {
  96. dasm_State *D = Dst_REF;
  97. int i;
  98. for (i = 0; i < D->maxsection; i++)
  99. if (D->sections[i].buf)
  100. DASM_M_FREE(Dst, D->sections[i].buf, D->sections[i].bsize);
  101. if (D->pclabels) DASM_M_FREE(Dst, D->pclabels, D->pcsize);
  102. if (D->lglabels) DASM_M_FREE(Dst, D->lglabels, D->lgsize);
  103. DASM_M_FREE(Dst, D, D->psize);
  104. }
  105. /* Setup global label array. Must be called before dasm_setup(). */
  106. void dasm_setupglobal(Dst_DECL, void **gl, unsigned int maxgl)
  107. {
  108. dasm_State *D = Dst_REF;
  109. D->globals = gl - 10; /* Negative bias to compensate for locals. */
  110. DASM_M_GROW(Dst, int, D->lglabels, D->lgsize, (10+maxgl)*sizeof(int));
  111. }
  112. /* Grow PC label array. Can be called after dasm_setup(), too. */
  113. void dasm_growpc(Dst_DECL, unsigned int maxpc)
  114. {
  115. dasm_State *D = Dst_REF;
  116. size_t osz = D->pcsize;
  117. DASM_M_GROW(Dst, int, D->pclabels, D->pcsize, maxpc*sizeof(int));
  118. memset((void *)(((unsigned char *)D->pclabels)+osz), 0, D->pcsize-osz);
  119. }
  120. /* Setup encoder. */
  121. void dasm_setup(Dst_DECL, const void *actionlist)
  122. {
  123. dasm_State *D = Dst_REF;
  124. int i;
  125. D->actionlist = (dasm_ActList)actionlist;
  126. D->status = DASM_S_OK;
  127. D->section = &D->sections[0];
  128. memset((void *)D->lglabels, 0, D->lgsize);
  129. if (D->pclabels) memset((void *)D->pclabels, 0, D->pcsize);
  130. for (i = 0; i < D->maxsection; i++) {
  131. D->sections[i].pos = DASM_SEC2POS(i);
  132. D->sections[i].ofs = 0;
  133. }
  134. }
  135. #ifdef DASM_CHECKS
  136. #define CK(x, st) \
  137. do { if (!(x)) { \
  138. D->status = DASM_S_##st|(int)(p-D->actionlist-1); return; } } while (0)
  139. #define CKPL(kind, st) \
  140. do { if ((size_t)((char *)pl-(char *)D->kind##labels) >= D->kind##size) { \
  141. D->status=DASM_S_RANGE_##st|(int)(p-D->actionlist-1); return; } } while (0)
  142. #else
  143. #define CK(x, st) ((void)0)
  144. #define CKPL(kind, st) ((void)0)
  145. #endif
  146. /* Pass 1: Store actions and args, link branches/labels, estimate offsets. */
  147. void dasm_put(Dst_DECL, int start, ...)
  148. {
  149. va_list ap;
  150. dasm_State *D = Dst_REF;
  151. dasm_ActList p = D->actionlist + start;
  152. dasm_Section *sec = D->section;
  153. int pos = sec->pos, ofs = sec->ofs, mrm = 4;
  154. int *b;
  155. if (pos >= sec->epos) {
  156. DASM_M_GROW(Dst, int, sec->buf, sec->bsize,
  157. sec->bsize + 2*DASM_MAXSECPOS*sizeof(int));
  158. sec->rbuf = sec->buf - DASM_POS2BIAS(pos);
  159. sec->epos = (int)sec->bsize/sizeof(int) - DASM_MAXSECPOS+DASM_POS2BIAS(pos);
  160. }
  161. b = sec->rbuf;
  162. b[pos++] = start;
  163. va_start(ap, start);
  164. while (1) {
  165. int action = *p++;
  166. if (action < DASM_DISP) {
  167. ofs++;
  168. } else if (action <= DASM_REL_A) {
  169. int n = va_arg(ap, int);
  170. b[pos++] = n;
  171. switch (action) {
  172. case DASM_DISP:
  173. if (n == 0) { if ((mrm&7) == 4) mrm = p[-2]; if ((mrm&7) != 5) break; }
  174. case DASM_IMM_DB: if (((n+128)&-256) == 0) goto ob;
  175. case DASM_REL_A: /* Assumes ptrdiff_t is int. !x64 */
  176. case DASM_IMM_D: ofs += 4; break;
  177. case DASM_IMM_S: CK(((n+128)&-256) == 0, RANGE_I); goto ob;
  178. case DASM_IMM_B: CK((n&-256) == 0, RANGE_I); ob: ofs++; break;
  179. case DASM_IMM_WB: if (((n+128)&-256) == 0) goto ob;
  180. case DASM_IMM_W: CK((n&-65536) == 0, RANGE_I); ofs += 2; break;
  181. case DASM_SPACE: p++; ofs += n; break;
  182. case DASM_SETLABEL: b[pos-2] = -0x40000000; break; /* Neg. label ofs. */
  183. case DASM_VREG: CK((n&-8) == 0 && (n != 4 || (*p&1) == 0), RANGE_VREG);
  184. if (*p++ == 1 && *p == DASM_DISP) mrm = n; continue;
  185. }
  186. mrm = 4;
  187. } else {
  188. int *pl, n;
  189. switch (action) {
  190. case DASM_REL_LG:
  191. case DASM_IMM_LG:
  192. n = *p++; pl = D->lglabels + n;
  193. if (n <= 246) { CKPL(lg, LG); goto putrel; } /* Bkwd rel or global. */
  194. pl -= 246; n = *pl;
  195. if (n < 0) n = 0; /* Start new chain for fwd rel if label exists. */
  196. goto linkrel;
  197. case DASM_REL_PC:
  198. case DASM_IMM_PC: pl = D->pclabels + va_arg(ap, int); CKPL(pc, PC);
  199. putrel:
  200. n = *pl;
  201. if (n < 0) { /* Label exists. Get label pos and store it. */
  202. b[pos] = -n;
  203. } else {
  204. linkrel:
  205. b[pos] = n; /* Else link to rel chain, anchored at label. */
  206. *pl = pos;
  207. }
  208. pos++;
  209. ofs += 4; /* Maximum offset needed. */
  210. if (action == DASM_REL_LG || action == DASM_REL_PC)
  211. b[pos++] = ofs; /* Store pass1 offset estimate. */
  212. break;
  213. case DASM_LABEL_LG: pl = D->lglabels + *p++; CKPL(lg, LG); goto putlabel;
  214. case DASM_LABEL_PC: pl = D->pclabels + va_arg(ap, int); CKPL(pc, PC);
  215. putlabel:
  216. n = *pl; /* n > 0: Collapse rel chain and replace with label pos. */
  217. while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = pos; }
  218. *pl = -pos; /* Label exists now. */
  219. b[pos++] = ofs; /* Store pass1 offset estimate. */
  220. break;
  221. case DASM_ALIGN:
  222. ofs += *p++; /* Maximum alignment needed (arg is 2**n-1). */
  223. b[pos++] = ofs; /* Store pass1 offset estimate. */
  224. break;
  225. case DASM_EXTERN: p += 2; ofs += 4; break;
  226. case DASM_ESC: p++; ofs++; break;
  227. case DASM_MARK: mrm = p[-2]; break;
  228. case DASM_SECTION:
  229. n = *p; CK(n < D->maxsection, RANGE_SEC); D->section = &D->sections[n];
  230. case DASM_STOP: goto stop;
  231. }
  232. }
  233. }
  234. stop:
  235. va_end(ap);
  236. sec->pos = pos;
  237. sec->ofs = ofs;
  238. }
  239. #undef CK
  240. /* Pass 2: Link sections, shrink branches/aligns, fix label offsets. */
  241. int dasm_link(Dst_DECL, size_t *szp)
  242. {
  243. dasm_State *D = Dst_REF;
  244. int secnum;
  245. int ofs = 0;
  246. #ifdef DASM_CHECKS
  247. *szp = 0;
  248. if (D->status != DASM_S_OK) return D->status;
  249. {
  250. int pc;
  251. for (pc = 0; pc*sizeof(int) < D->pcsize; pc++)
  252. if (D->pclabels[pc] > 0) return DASM_S_UNDEF_PC|pc;
  253. }
  254. #endif
  255. { /* Handle globals not defined in this translation unit. */
  256. int idx;
  257. for (idx = 10; idx*sizeof(int) < D->lgsize; idx++) {
  258. int n = D->lglabels[idx];
  259. /* Undefined label: Collapse rel chain and replace with marker (< 0). */
  260. while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = -idx; }
  261. }
  262. }
  263. /* Combine all code sections. No support for data sections (yet). */
  264. for (secnum = 0; secnum < D->maxsection; secnum++) {
  265. dasm_Section *sec = D->sections + secnum;
  266. int *b = sec->rbuf;
  267. int pos = DASM_SEC2POS(secnum);
  268. int lastpos = sec->pos;
  269. while (pos != lastpos) {
  270. dasm_ActList p = D->actionlist + b[pos++];
  271. while (1) {
  272. int op, action = *p++;
  273. switch (action) {
  274. case DASM_REL_LG: p++; op = p[-3]; goto rel_pc;
  275. case DASM_REL_PC: op = p[-2]; rel_pc: {
  276. int shrink = op == 0xe9 ? 3 : ((op&0xf0) == 0x80 ? 4 : 0);
  277. if (shrink) { /* Shrinkable branch opcode? */
  278. int lofs, lpos = b[pos];
  279. if (lpos < 0) goto noshrink; /* Ext global? */
  280. lofs = *DASM_POS2PTR(D, lpos);
  281. if (lpos > pos) { /* Fwd label: add cumulative section offsets. */
  282. int i;
  283. for (i = secnum; i < DASM_POS2SEC(lpos); i++)
  284. lofs += D->sections[i].ofs;
  285. } else {
  286. lofs -= ofs; /* Bkwd label: unfix offset. */
  287. }
  288. lofs -= b[pos+1]; /* Short branch ok? */
  289. if (lofs >= -128-shrink && lofs <= 127) ofs -= shrink; /* Yes. */
  290. else { noshrink: shrink = 0; } /* No, cannot shrink op. */
  291. }
  292. b[pos+1] = shrink;
  293. pos += 2;
  294. break;
  295. }
  296. case DASM_SPACE: case DASM_IMM_LG: case DASM_VREG: p++;
  297. case DASM_DISP: case DASM_IMM_S: case DASM_IMM_B: case DASM_IMM_W:
  298. case DASM_IMM_D: case DASM_IMM_WB: case DASM_IMM_DB:
  299. case DASM_SETLABEL: case DASM_REL_A: case DASM_IMM_PC: pos++; break;
  300. case DASM_LABEL_LG: p++;
  301. case DASM_LABEL_PC: b[pos++] += ofs; break; /* Fix label offset. */
  302. case DASM_ALIGN: ofs -= (b[pos++]+ofs)&*p++; break; /* Adjust ofs. */
  303. case DASM_EXTERN: p += 2; break;
  304. case DASM_ESC: p++; break;
  305. case DASM_MARK: break;
  306. case DASM_SECTION: case DASM_STOP: goto stop;
  307. }
  308. }
  309. stop: (void)0;
  310. }
  311. ofs += sec->ofs; /* Next section starts right after current section. */
  312. }
  313. D->codesize = ofs; /* Total size of all code sections */
  314. *szp = ofs;
  315. return DASM_S_OK;
  316. }
  317. #define dasmb(x) *cp++ = (unsigned char)(x)
  318. #ifndef DASM_ALIGNED_WRITES
  319. #define dasmw(x) \
  320. do { *((unsigned short *)cp) = (unsigned short)(x); cp+=2; } while (0)
  321. #define dasmd(x) \
  322. do { *((unsigned int *)cp) = (unsigned int)(x); cp+=4; } while (0)
  323. #else
  324. #define dasmw(x) do { dasmb(x); dasmb((x)>>8); } while (0)
  325. #define dasmd(x) do { dasmw(x); dasmw((x)>>16); } while (0)
  326. #endif
  327. /* Pass 3: Encode sections. */
  328. int dasm_encode(Dst_DECL, void *buffer)
  329. {
  330. dasm_State *D = Dst_REF;
  331. unsigned char *base = (unsigned char *)buffer;
  332. unsigned char *cp = base;
  333. int secnum;
  334. /* Encode all code sections. No support for data sections (yet). */
  335. for (secnum = 0; secnum < D->maxsection; secnum++) {
  336. dasm_Section *sec = D->sections + secnum;
  337. int *b = sec->buf;
  338. int *endb = sec->rbuf + sec->pos;
  339. while (b != endb) {
  340. dasm_ActList p = D->actionlist + *b++;
  341. unsigned char *mark = NULL;
  342. while (1) {
  343. int action = *p++;
  344. int n = (action >= DASM_DISP && action <= DASM_ALIGN) ? *b++ : 0;
  345. switch (action) {
  346. case DASM_DISP: if (!mark) mark = cp; {
  347. unsigned char *mm = mark;
  348. if (*p != DASM_IMM_DB && *p != DASM_IMM_WB) mark = NULL;
  349. if (n == 0) { int mrm = mm[-1]&7; if (mrm == 4) mrm = mm[0]&7;
  350. if (mrm != 5) { mm[-1] -= 0x80; break; } }
  351. if (((n+128) & -256) != 0) goto wd; else mm[-1] -= 0x40;
  352. }
  353. case DASM_IMM_S: case DASM_IMM_B: wb: dasmb(n); break;
  354. case DASM_IMM_DB: if (((n+128)&-256) == 0) {
  355. db: if (!mark) mark = cp; mark[-2] += 2; mark = NULL; goto wb;
  356. } else mark = NULL;
  357. case DASM_IMM_D: wd: dasmd(n); break;
  358. case DASM_IMM_WB: if (((n+128)&-256) == 0) goto db; else mark = NULL;
  359. case DASM_IMM_W: dasmw(n); break;
  360. case DASM_VREG: { int t = *p++; if (t >= 2) n<<=3; cp[-1] |= n; break; }
  361. case DASM_REL_LG: p++; if (n >= 0) goto rel_pc;
  362. b++; n = (int)(ptrdiff_t)D->globals[-n];
  363. case DASM_REL_A: rel_a: n -= (int)(ptrdiff_t)(cp+4); goto wd; /* !x64 */
  364. case DASM_REL_PC: rel_pc: {
  365. int shrink = *b++;
  366. int *pb = DASM_POS2PTR(D, n); if (*pb < 0) { n = pb[1]; goto rel_a; }
  367. n = *pb - ((int)(cp-base) + 4-shrink);
  368. if (shrink == 0) goto wd;
  369. if (shrink == 4) { cp--; cp[-1] = *cp-0x10; } else cp[-1] = 0xeb;
  370. goto wb;
  371. }
  372. case DASM_IMM_LG:
  373. p++; if (n < 0) { n = (int)(ptrdiff_t)D->globals[-n]; goto wd; }
  374. case DASM_IMM_PC: {
  375. int *pb = DASM_POS2PTR(D, n);
  376. n = *pb < 0 ? pb[1] : (*pb + (int)(ptrdiff_t)base);
  377. goto wd;
  378. }
  379. case DASM_LABEL_LG: {
  380. int idx = *p++;
  381. if (idx >= 10)
  382. D->globals[idx] = (void *)(base + (*p == DASM_SETLABEL ? *b : n));
  383. break;
  384. }
  385. case DASM_LABEL_PC: case DASM_SETLABEL: break;
  386. case DASM_SPACE: { int fill = *p++; while (n--) *cp++ = fill; break; }
  387. case DASM_ALIGN:
  388. n = *p++;
  389. while (((cp-base) & n)) *cp++ = 0x90; /* nop */
  390. break;
  391. case DASM_EXTERN: n = DASM_EXTERN(Dst, cp, p[1], *p); p += 2; goto wd;
  392. case DASM_MARK: mark = cp; break;
  393. case DASM_ESC: action = *p++;
  394. default: *cp++ = action; break;
  395. case DASM_SECTION: case DASM_STOP: goto stop;
  396. }
  397. }
  398. stop: (void)0;
  399. }
  400. }
  401. if (base + D->codesize != cp) /* Check for phase errors. */
  402. return DASM_S_PHASE;
  403. return DASM_S_OK;
  404. }
  405. /* Get PC label offset. */
  406. int dasm_getpclabel(Dst_DECL, unsigned int pc)
  407. {
  408. dasm_State *D = Dst_REF;
  409. if (pc*sizeof(int) < D->pcsize) {
  410. int pos = D->pclabels[pc];
  411. if (pos < 0) return *DASM_POS2PTR(D, -pos);
  412. if (pos > 0) return -1; /* Undefined. */
  413. }
  414. return -2; /* Unused or out of range. */
  415. }
  416. #ifdef DASM_CHECKS
  417. /* Optional sanity checker to call between isolated encoding steps. */
  418. int dasm_checkstep(Dst_DECL, int secmatch)
  419. {
  420. dasm_State *D = Dst_REF;
  421. if (D->status == DASM_S_OK) {
  422. int i;
  423. for (i = 1; i <= 9; i++) {
  424. if (D->lglabels[i] > 0) { D->status = DASM_S_UNDEF_L|i; break; }
  425. D->lglabels[i] = 0;
  426. }
  427. }
  428. if (D->status == DASM_S_OK && secmatch >= 0 &&
  429. D->section != &D->sections[secmatch])
  430. D->status = DASM_S_MATCH_SEC|(int)(D->section-D->sections);
  431. return D->status;
  432. }
  433. #endif