outcoff.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. /* ----------------------------------------------------------------------- *
  2. *
  3. * Copyright 1996-2017 The NASM Authors - All Rights Reserved
  4. * See the file AUTHORS included with the NASM distribution for
  5. * the specific copyright holders.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following
  9. * conditions are met:
  10. *
  11. * * Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. * * Redistributions in binary form must reproduce the above
  14. * copyright notice, this list of conditions and the following
  15. * disclaimer in the documentation and/or other materials provided
  16. * with the distribution.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  19. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  20. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  21. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  23. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  25. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  26. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  27. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  29. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  30. * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. * ----------------------------------------------------------------------- */
  33. /*
  34. * outcoff.c output routines for the Netwide Assembler to produce
  35. * COFF object files (for DJGPP and Win32)
  36. */
  37. #include "compiler.h"
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. #include <string.h>
  41. #include <ctype.h>
  42. #include <time.h>
  43. #include "nasm.h"
  44. #include "nasmlib.h"
  45. #include "ilog2.h"
  46. #include "error.h"
  47. #include "saa.h"
  48. #include "raa.h"
  49. #include "eval.h"
  50. #include "outform.h"
  51. #include "outlib.h"
  52. #include "pecoff.h"
  53. #if defined(OF_COFF) || defined(OF_WIN32) || defined(OF_WIN64)
  54. /*
  55. * Notes on COFF:
  56. *
  57. * (0) When I say `standard COFF' below, I mean `COFF as output and
  58. * used by DJGPP'. I assume DJGPP gets it right.
  59. *
  60. * (1) Win32 appears to interpret the term `relative relocation'
  61. * differently from standard COFF. Standard COFF understands a
  62. * relative relocation to mean that during relocation you add the
  63. * address of the symbol you're referencing, and subtract the base
  64. * address of the section you're in. Win32 COFF, by contrast, seems
  65. * to add the address of the symbol and then subtract the address
  66. * of THE BYTE AFTER THE RELOCATED DWORD. Hence the two formats are
  67. * subtly incompatible.
  68. *
  69. * (2) Win32 doesn't bother putting any flags in the header flags
  70. * field (at offset 0x12 into the file).
  71. *
  72. * (3) Win32 uses some extra flags into the section header table:
  73. * it defines flags 0x80000000 (writable), 0x40000000 (readable)
  74. * and 0x20000000 (executable), and uses them in the expected
  75. * combinations. It also defines 0x00100000 through 0x00700000 for
  76. * section alignments of 1 through 64 bytes.
  77. *
  78. * (4) Both standard COFF and Win32 COFF seem to use the DWORD
  79. * field directly after the section name in the section header
  80. * table for something strange: they store what the address of the
  81. * section start point _would_ be, if you laid all the sections end
  82. * to end starting at zero. Dunno why. Microsoft's documentation
  83. * lists this field as "Virtual Size of Section", which doesn't
  84. * seem to fit at all. In fact, Win32 even includes non-linked
  85. * sections such as .drectve in this calculation.
  86. *
  87. * Newer versions of MASM seem to have changed this to be zero, and
  88. * that apparently matches the COFF spec, so go with that.
  89. *
  90. * (5) Standard COFF does something very strange to common
  91. * variables: the relocation point for a common variable is as far
  92. * _before_ the variable as its size stretches out _after_ it. So
  93. * we must fix up common variable references. Win32 seems to be
  94. * sensible on this one.
  95. */
  96. /* Flag which version of COFF we are currently outputting. */
  97. bool win32, win64;
  98. static int32_t imagebase_sect;
  99. #define WRT_IMAGEBASE "..imagebase"
  100. /*
  101. * Some common section flags by default
  102. */
  103. #define TEXT_FLAGS_WIN \
  104. (IMAGE_SCN_CNT_CODE | \
  105. IMAGE_SCN_ALIGN_16BYTES | \
  106. IMAGE_SCN_MEM_EXECUTE | \
  107. IMAGE_SCN_MEM_READ)
  108. #define TEXT_FLAGS_DOS \
  109. (IMAGE_SCN_CNT_CODE)
  110. #define DATA_FLAGS_WIN \
  111. (IMAGE_SCN_CNT_INITIALIZED_DATA | \
  112. IMAGE_SCN_ALIGN_4BYTES | \
  113. IMAGE_SCN_MEM_READ | \
  114. IMAGE_SCN_MEM_WRITE)
  115. #define DATA_FLAGS_DOS \
  116. (IMAGE_SCN_CNT_INITIALIZED_DATA)
  117. #define BSS_FLAGS_WIN \
  118. (IMAGE_SCN_CNT_UNINITIALIZED_DATA | \
  119. IMAGE_SCN_ALIGN_4BYTES | \
  120. IMAGE_SCN_MEM_READ | \
  121. IMAGE_SCN_MEM_WRITE)
  122. #define BSS_FLAGS_DOS \
  123. (IMAGE_SCN_CNT_UNINITIALIZED_DATA)
  124. #define RDATA_FLAGS_WIN \
  125. (IMAGE_SCN_CNT_INITIALIZED_DATA | \
  126. IMAGE_SCN_ALIGN_8BYTES | \
  127. IMAGE_SCN_MEM_READ)
  128. #define RDATA_FLAGS_DOS \
  129. (IMAGE_SCN_CNT_INITIALIZED_DATA)
  130. #define PDATA_FLAGS \
  131. (IMAGE_SCN_CNT_INITIALIZED_DATA | \
  132. IMAGE_SCN_ALIGN_4BYTES | \
  133. IMAGE_SCN_MEM_READ)
  134. #define XDATA_FLAGS \
  135. (IMAGE_SCN_CNT_INITIALIZED_DATA | \
  136. IMAGE_SCN_ALIGN_8BYTES | \
  137. IMAGE_SCN_MEM_READ)
  138. #define INFO_FLAGS \
  139. (IMAGE_SCN_ALIGN_1BYTES | \
  140. IMAGE_SCN_LNK_INFO | \
  141. IMAGE_SCN_LNK_REMOVE)
  142. #define TEXT_FLAGS ((win32 | win64) ? TEXT_FLAGS_WIN : TEXT_FLAGS_DOS)
  143. #define DATA_FLAGS ((win32 | win64) ? DATA_FLAGS_WIN : DATA_FLAGS_DOS)
  144. #define BSS_FLAGS ((win32 | win64) ? BSS_FLAGS_WIN : BSS_FLAGS_DOS)
  145. #define RDATA_FLAGS ((win32 | win64) ? RDATA_FLAGS_WIN : RDATA_FLAGS_DOS)
  146. #define SECT_DELTA 32
  147. struct coff_Section **coff_sects;
  148. static int sectlen;
  149. int coff_nsects;
  150. struct SAA *coff_syms;
  151. uint32_t coff_nsyms;
  152. static int32_t def_seg;
  153. static int initsym;
  154. static struct RAA *bsym, *symval;
  155. struct SAA *coff_strs;
  156. static uint32_t strslen;
  157. static void coff_gen_init(void);
  158. static void coff_sect_write(struct coff_Section *, const uint8_t *, uint32_t);
  159. static void coff_write(void);
  160. static void coff_section_header(char *, int32_t, int32_t, int32_t, int32_t, int32_t, int, int32_t);
  161. static void coff_write_relocs(struct coff_Section *);
  162. static void coff_write_symbols(void);
  163. static void coff_win32_init(void)
  164. {
  165. win32 = true;
  166. win64 = false;
  167. coff_gen_init();
  168. }
  169. static void coff_win64_init(void)
  170. {
  171. win32 = false;
  172. win64 = true;
  173. coff_gen_init();
  174. imagebase_sect = seg_alloc()+1;
  175. backend_label(WRT_IMAGEBASE, imagebase_sect, 0);
  176. }
  177. static void coff_std_init(void)
  178. {
  179. win32 = win64 = false;
  180. coff_gen_init();
  181. }
  182. static void coff_gen_init(void)
  183. {
  184. coff_sects = NULL;
  185. coff_nsects = sectlen = 0;
  186. coff_syms = saa_init(sizeof(struct coff_Symbol));
  187. coff_nsyms = 0;
  188. bsym = raa_init();
  189. symval = raa_init();
  190. coff_strs = saa_init(1);
  191. strslen = 0;
  192. def_seg = seg_alloc();
  193. }
  194. static void coff_cleanup(void)
  195. {
  196. struct coff_Reloc *r;
  197. int i;
  198. dfmt->cleanup();
  199. coff_write();
  200. for (i = 0; i < coff_nsects; i++) {
  201. if (coff_sects[i]->data)
  202. saa_free(coff_sects[i]->data);
  203. while (coff_sects[i]->head) {
  204. r = coff_sects[i]->head;
  205. coff_sects[i]->head = coff_sects[i]->head->next;
  206. nasm_free(r);
  207. }
  208. nasm_free(coff_sects[i]->name);
  209. nasm_free(coff_sects[i]);
  210. }
  211. nasm_free(coff_sects);
  212. saa_free(coff_syms);
  213. raa_free(bsym);
  214. raa_free(symval);
  215. saa_free(coff_strs);
  216. }
  217. int coff_make_section(char *name, uint32_t flags)
  218. {
  219. struct coff_Section *s;
  220. size_t namelen;
  221. s = nasm_zalloc(sizeof(*s));
  222. if (flags != BSS_FLAGS)
  223. s->data = saa_init(1);
  224. s->tail = &s->head;
  225. if (!strcmp(name, ".text"))
  226. s->index = def_seg;
  227. else
  228. s->index = seg_alloc();
  229. s->namepos = -1;
  230. namelen = strlen(name);
  231. if (namelen > 8) {
  232. if (win32 || win64) {
  233. s->namepos = strslen + 4;
  234. saa_wbytes(coff_strs, name, namelen + 1);
  235. strslen += namelen + 1;
  236. } else {
  237. namelen = 8;
  238. }
  239. }
  240. s->name = nasm_malloc(namelen + 1);
  241. strncpy(s->name, name, namelen);
  242. s->name[namelen] = '\0';
  243. s->flags = flags;
  244. if (coff_nsects >= sectlen) {
  245. sectlen += SECT_DELTA;
  246. coff_sects = nasm_realloc(coff_sects, sectlen * sizeof(*coff_sects));
  247. }
  248. coff_sects[coff_nsects++] = s;
  249. return coff_nsects - 1;
  250. }
  251. static inline int32_t coff_sectalign_flags(unsigned int align)
  252. {
  253. return (ilog2_32(align) + 1) << 20;
  254. }
  255. static int32_t coff_section_names(char *name, int pass, int *bits)
  256. {
  257. char *p;
  258. uint32_t flags, align_and = ~0L, align_or = 0L;
  259. int i;
  260. /*
  261. * Set default bits.
  262. */
  263. if (!name) {
  264. if(win64)
  265. *bits = 64;
  266. else
  267. *bits = 32;
  268. return def_seg;
  269. }
  270. p = name;
  271. while (*p && !nasm_isspace(*p))
  272. p++;
  273. if (*p)
  274. *p++ = '\0';
  275. if (strlen(name) > 8) {
  276. if (!win32 && !win64) {
  277. nasm_error(ERR_WARNING,
  278. "COFF section names limited to 8 characters: truncating");
  279. name[8] = '\0';
  280. }
  281. }
  282. flags = 0;
  283. while (*p && nasm_isspace(*p))
  284. p++;
  285. while (*p) {
  286. char *q = p;
  287. while (*p && !nasm_isspace(*p))
  288. p++;
  289. if (*p)
  290. *p++ = '\0';
  291. while (*p && nasm_isspace(*p))
  292. p++;
  293. if (!nasm_stricmp(q, "code") || !nasm_stricmp(q, "text")) {
  294. flags = TEXT_FLAGS;
  295. } else if (!nasm_stricmp(q, "data")) {
  296. flags = DATA_FLAGS;
  297. } else if (!nasm_stricmp(q, "rdata")) {
  298. if (win32 | win64)
  299. flags = RDATA_FLAGS;
  300. else {
  301. flags = DATA_FLAGS; /* gotta do something */
  302. nasm_error(ERR_NONFATAL, "standard COFF does not support"
  303. " read-only data sections");
  304. }
  305. } else if (!nasm_stricmp(q, "bss")) {
  306. flags = BSS_FLAGS;
  307. } else if (!nasm_stricmp(q, "info")) {
  308. if (win32 | win64)
  309. flags = INFO_FLAGS;
  310. else {
  311. flags = DATA_FLAGS; /* gotta do something */
  312. nasm_error(ERR_NONFATAL, "standard COFF does not support"
  313. " informational sections");
  314. }
  315. } else if (!nasm_strnicmp(q, "align=", 6)) {
  316. if (!(win32 | win64))
  317. nasm_error(ERR_NONFATAL, "standard COFF does not support"
  318. " section alignment specification");
  319. else {
  320. if (q[6 + strspn(q + 6, "0123456789")])
  321. nasm_error(ERR_NONFATAL,
  322. "argument to `align' is not numeric");
  323. else {
  324. unsigned int align = atoi(q + 6);
  325. if (!align || ((align - 1) & align))
  326. nasm_error(ERR_NONFATAL, "argument to `align' is not a"
  327. " power of two");
  328. else if (align > 64)
  329. nasm_error(ERR_NONFATAL, "Win32 cannot align sections"
  330. " to better than 64-byte boundaries");
  331. else {
  332. align_and = ~0x00F00000L;
  333. align_or = coff_sectalign_flags(align);
  334. }
  335. }
  336. }
  337. }
  338. }
  339. for (i = 0; i < coff_nsects; i++)
  340. if (!strcmp(name, coff_sects[i]->name))
  341. break;
  342. if (i == coff_nsects) {
  343. if (!flags) {
  344. if (!strcmp(name, ".data"))
  345. flags = DATA_FLAGS;
  346. else if (!strcmp(name, ".rdata"))
  347. flags = RDATA_FLAGS;
  348. else if (!strcmp(name, ".bss"))
  349. flags = BSS_FLAGS;
  350. else if (win64 && !strcmp(name, ".pdata"))
  351. flags = PDATA_FLAGS;
  352. else if (win64 && !strcmp(name, ".xdata"))
  353. flags = XDATA_FLAGS;
  354. else
  355. flags = TEXT_FLAGS;
  356. }
  357. i = coff_make_section(name, flags);
  358. if (flags)
  359. coff_sects[i]->flags = flags;
  360. coff_sects[i]->flags &= align_and;
  361. coff_sects[i]->flags |= align_or;
  362. } else if (pass == 1) {
  363. /* Check if any flags are specified */
  364. if (flags) {
  365. unsigned int align_flags = flags & IMAGE_SCN_ALIGN_MASK;
  366. /* Warn if non-alignment flags differ */
  367. if ((flags ^ coff_sects[i]->flags) & ~IMAGE_SCN_ALIGN_MASK) {
  368. nasm_error(ERR_WARNING, "section attributes ignored on"
  369. " redeclaration of section `%s'", name);
  370. }
  371. /* Check if alignment might be needed */
  372. if (align_flags > IMAGE_SCN_ALIGN_1BYTES) {
  373. unsigned int sect_align_flags = coff_sects[i]->flags & IMAGE_SCN_ALIGN_MASK;
  374. /* Compute the actual alignment */
  375. unsigned int align = 1u << ((align_flags - IMAGE_SCN_ALIGN_1BYTES) >> 20);
  376. /* Update section header as needed */
  377. if (align_flags > sect_align_flags) {
  378. coff_sects[i]->flags = (coff_sects[i]->flags & ~IMAGE_SCN_ALIGN_MASK) | align_flags;
  379. }
  380. /* Check if not already aligned */
  381. if (coff_sects[i]->len % align) {
  382. unsigned int padding = (align - coff_sects[i]->len) % align;
  383. /* We need to write at most 8095 bytes */
  384. char buffer[8095];
  385. if (coff_sects[i]->flags & IMAGE_SCN_CNT_CODE) {
  386. /* Fill with INT 3 instructions */
  387. memset(buffer, 0xCC, padding);
  388. } else {
  389. memset(buffer, 0x00, padding);
  390. }
  391. saa_wbytes(coff_sects[i]->data, buffer, padding);
  392. coff_sects[i]->len += padding;
  393. }
  394. }
  395. }
  396. }
  397. return coff_sects[i]->index;
  398. }
  399. static void coff_deflabel(char *name, int32_t segment, int64_t offset,
  400. int is_global, char *special)
  401. {
  402. int pos = strslen + 4;
  403. struct coff_Symbol *sym;
  404. if (special)
  405. nasm_error(ERR_NONFATAL, "COFF format does not support any"
  406. " special symbol types");
  407. if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
  408. if (strcmp(name,WRT_IMAGEBASE))
  409. nasm_error(ERR_NONFATAL, "unrecognized special symbol `%s'", name);
  410. return;
  411. }
  412. if (strlen(name) > 8) {
  413. size_t nlen = strlen(name)+1;
  414. saa_wbytes(coff_strs, name, nlen);
  415. strslen += nlen;
  416. } else
  417. pos = -1;
  418. sym = saa_wstruct(coff_syms);
  419. sym->strpos = pos;
  420. sym->namlen = strlen(name);
  421. if (pos == -1)
  422. strcpy(sym->name, name);
  423. sym->is_global = !!is_global;
  424. sym->type = 0; /* Default to T_NULL (no type) */
  425. if (segment == NO_SEG)
  426. sym->section = -1; /* absolute symbol */
  427. else {
  428. int i;
  429. sym->section = 0;
  430. for (i = 0; i < coff_nsects; i++)
  431. if (segment == coff_sects[i]->index) {
  432. sym->section = i + 1;
  433. break;
  434. }
  435. if (!sym->section)
  436. sym->is_global = true;
  437. }
  438. if (is_global == 2)
  439. sym->value = offset;
  440. else
  441. sym->value = (sym->section == 0 ? 0 : offset);
  442. /*
  443. * define the references from external-symbol segment numbers
  444. * to these symbol records.
  445. */
  446. if (sym->section == 0)
  447. bsym = raa_write(bsym, segment, coff_nsyms);
  448. if (segment != NO_SEG)
  449. symval = raa_write(symval, segment, sym->section ? 0 : sym->value);
  450. coff_nsyms++;
  451. }
  452. static int32_t coff_add_reloc(struct coff_Section *sect, int32_t segment,
  453. int16_t type)
  454. {
  455. struct coff_Reloc *r;
  456. r = *sect->tail = nasm_malloc(sizeof(struct coff_Reloc));
  457. sect->tail = &r->next;
  458. r->next = NULL;
  459. r->address = sect->len;
  460. if (segment == NO_SEG) {
  461. r->symbol = 0, r->symbase = ABS_SYMBOL;
  462. } else {
  463. int i;
  464. r->symbase = REAL_SYMBOLS;
  465. for (i = 0; i < coff_nsects; i++) {
  466. if (segment == coff_sects[i]->index) {
  467. r->symbol = i * 2;
  468. r->symbase = SECT_SYMBOLS;
  469. break;
  470. }
  471. }
  472. if (r->symbase == REAL_SYMBOLS)
  473. r->symbol = raa_read(bsym, segment);
  474. }
  475. r->type = type;
  476. sect->nrelocs++;
  477. /*
  478. * Return the fixup for standard COFF common variables.
  479. */
  480. if (r->symbase == REAL_SYMBOLS && !(win32 | win64))
  481. return raa_read(symval, segment);
  482. return 0;
  483. }
  484. static void coff_out(int32_t segto, const void *data,
  485. enum out_type type, uint64_t size,
  486. int32_t segment, int32_t wrt)
  487. {
  488. struct coff_Section *s;
  489. uint8_t mydata[8], *p;
  490. int i;
  491. if (wrt != NO_SEG && !win64) {
  492. wrt = NO_SEG; /* continue to do _something_ */
  493. nasm_error(ERR_NONFATAL, "WRT not supported by COFF output formats");
  494. }
  495. /*
  496. * handle absolute-assembly (structure definitions)
  497. */
  498. if (segto == NO_SEG) {
  499. if (type != OUT_RESERVE)
  500. nasm_error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
  501. " space");
  502. return;
  503. }
  504. s = NULL;
  505. for (i = 0; i < coff_nsects; i++) {
  506. if (segto == coff_sects[i]->index) {
  507. s = coff_sects[i];
  508. break;
  509. }
  510. }
  511. if (!s) {
  512. int tempint; /* ignored */
  513. if (segto != coff_section_names(".text", 2, &tempint))
  514. nasm_panic(0, "strange segment conditions in COFF driver");
  515. else
  516. s = coff_sects[coff_nsects - 1];
  517. }
  518. /* magically default to 'wrt ..imagebase' in .pdata and .xdata */
  519. if (win64 && wrt == NO_SEG) {
  520. if (!strcmp(s->name,".pdata") || !strcmp(s->name,".xdata"))
  521. wrt = imagebase_sect;
  522. }
  523. if (!s->data && type != OUT_RESERVE) {
  524. nasm_error(ERR_WARNING, "attempt to initialize memory in"
  525. " BSS section `%s': ignored", s->name);
  526. s->len += realsize(type, size);
  527. return;
  528. }
  529. memset(mydata, 0, sizeof(mydata));
  530. if (dfmt && dfmt->debug_output) {
  531. struct coff_DebugInfo dinfo;
  532. dinfo.segto = segto;
  533. dinfo.seg = segment;
  534. dinfo.section = s;
  535. if (type == OUT_ADDRESS)
  536. dinfo.size = abs((int)size);
  537. else
  538. dinfo.size = realsize(type, size);
  539. dfmt->debug_output(type, &dinfo);
  540. }
  541. if (type == OUT_RESERVE) {
  542. if (s->data) {
  543. nasm_error(ERR_WARNING, "uninitialised space declared in"
  544. " non-BSS section `%s': zeroing", s->name);
  545. coff_sect_write(s, NULL, size);
  546. } else
  547. s->len += size;
  548. } else if (type == OUT_RAWDATA) {
  549. if (segment != NO_SEG)
  550. nasm_panic(0, "OUT_RAWDATA with other than NO_SEG");
  551. coff_sect_write(s, data, size);
  552. } else if (type == OUT_ADDRESS) {
  553. int asize = abs((int)size);
  554. if (!win64) {
  555. if (asize != 4 && (segment != NO_SEG || wrt != NO_SEG)) {
  556. nasm_error(ERR_NONFATAL, "COFF format does not support non-32-bit"
  557. " relocations");
  558. } else {
  559. int32_t fix = 0;
  560. if (segment != NO_SEG || wrt != NO_SEG) {
  561. if (wrt != NO_SEG) {
  562. nasm_error(ERR_NONFATAL, "COFF format does not support"
  563. " WRT types");
  564. } else if (segment % 2) {
  565. nasm_error(ERR_NONFATAL, "COFF format does not support"
  566. " segment base references");
  567. } else
  568. fix = coff_add_reloc(s, segment, IMAGE_REL_I386_DIR32);
  569. }
  570. p = mydata;
  571. WRITELONG(p, *(int64_t *)data + fix);
  572. coff_sect_write(s, mydata, asize);
  573. }
  574. } else {
  575. int32_t fix = 0;
  576. p = mydata;
  577. if (asize == 8) {
  578. if (wrt == imagebase_sect) {
  579. nasm_error(ERR_NONFATAL, "operand size mismatch: 'wrt "
  580. WRT_IMAGEBASE "' is a 32-bit operand");
  581. }
  582. fix = coff_add_reloc(s, segment, IMAGE_REL_AMD64_ADDR64);
  583. WRITEDLONG(p, *(int64_t *)data + fix);
  584. coff_sect_write(s, mydata, asize);
  585. } else {
  586. fix = coff_add_reloc(s, segment,
  587. wrt == imagebase_sect ? IMAGE_REL_AMD64_ADDR32NB:
  588. IMAGE_REL_AMD64_ADDR32);
  589. WRITELONG(p, *(int64_t *)data + fix);
  590. coff_sect_write(s, mydata, asize);
  591. }
  592. }
  593. } else if (type == OUT_REL2ADR) {
  594. nasm_error(ERR_NONFATAL, "COFF format does not support 16-bit"
  595. " relocations");
  596. } else if (type == OUT_REL4ADR) {
  597. if (segment == segto && !(win64)) /* Acceptable for RIP-relative */
  598. nasm_panic(0, "intra-segment OUT_REL4ADR");
  599. else if (segment == NO_SEG && win32)
  600. nasm_error(ERR_NONFATAL, "Win32 COFF does not correctly support"
  601. " relative references to absolute addresses");
  602. else {
  603. int32_t fix = 0;
  604. if (segment != NO_SEG && segment % 2) {
  605. nasm_error(ERR_NONFATAL, "COFF format does not support"
  606. " segment base references");
  607. } else
  608. fix = coff_add_reloc(s, segment,
  609. win64 ? IMAGE_REL_AMD64_REL32 : IMAGE_REL_I386_REL32);
  610. p = mydata;
  611. if (win32 | win64) {
  612. WRITELONG(p, *(int64_t *)data + 4 - size + fix);
  613. } else {
  614. WRITELONG(p, *(int64_t *)data - (size + s->len) + fix);
  615. }
  616. coff_sect_write(s, mydata, 4L);
  617. }
  618. }
  619. }
  620. static void coff_sect_write(struct coff_Section *sect,
  621. const uint8_t *data, uint32_t len)
  622. {
  623. saa_wbytes(sect->data, data, len);
  624. sect->len += len;
  625. }
  626. typedef struct tagString {
  627. struct tagString *next;
  628. int len;
  629. char *String;
  630. } STRING;
  631. #define EXPORT_SECTION_NAME ".drectve"
  632. #define EXPORT_SECTION_FLAGS INFO_FLAGS
  633. /*
  634. * #define EXPORT_SECTION_NAME ".text"
  635. * #define EXPORT_SECTION_FLAGS TEXT_FLAGS
  636. */
  637. static STRING *Exports = NULL;
  638. static struct coff_Section *directive_sec;
  639. static void AddExport(char *name)
  640. {
  641. STRING *rvp = Exports, *newS;
  642. newS = (STRING *) nasm_malloc(sizeof(STRING));
  643. newS->len = strlen(name);
  644. newS->next = NULL;
  645. newS->String = (char *)nasm_malloc(newS->len + 1);
  646. strcpy(newS->String, name);
  647. if (rvp == NULL) {
  648. int i;
  649. for (i = 0; i < coff_nsects; i++) {
  650. if (!strcmp(EXPORT_SECTION_NAME, coff_sects[i]->name))
  651. break;
  652. }
  653. if (i == coff_nsects)
  654. i = coff_make_section(EXPORT_SECTION_NAME, EXPORT_SECTION_FLAGS);
  655. directive_sec = coff_sects[i];
  656. Exports = newS;
  657. } else {
  658. while (rvp->next) {
  659. if (!strcmp(rvp->String, name))
  660. return;
  661. rvp = rvp->next;
  662. }
  663. rvp->next = newS;
  664. }
  665. }
  666. static void BuildExportTable(STRING **rvp)
  667. {
  668. STRING *p, *t;
  669. if (!rvp || !*rvp)
  670. return;
  671. list_for_each_safe(p, t, *rvp) {
  672. coff_sect_write(directive_sec, (uint8_t *)"-export:", 8);
  673. coff_sect_write(directive_sec, (uint8_t *)p->String, p->len);
  674. coff_sect_write(directive_sec, (uint8_t *)" ", 1);
  675. nasm_free(p->String);
  676. nasm_free(p);
  677. }
  678. *rvp = NULL;
  679. }
  680. static enum directive_result
  681. coff_directives(enum directive directive, char *value, int pass)
  682. {
  683. switch (directive) {
  684. case D_EXPORT:
  685. {
  686. char *q, *name;
  687. if (pass == 2)
  688. return DIRR_OK; /* ignore in pass two */
  689. name = q = value;
  690. while (*q && !nasm_isspace(*q))
  691. q++;
  692. if (nasm_isspace(*q)) {
  693. *q++ = '\0';
  694. while (*q && nasm_isspace(*q))
  695. q++;
  696. }
  697. if (!*name) {
  698. nasm_error(ERR_NONFATAL, "`export' directive requires export name");
  699. return DIRR_ERROR;
  700. }
  701. if (*q) {
  702. nasm_error(ERR_NONFATAL, "unrecognized export qualifier `%s'", q);
  703. return DIRR_ERROR;
  704. }
  705. AddExport(name);
  706. return DIRR_OK;
  707. }
  708. case D_SAFESEH:
  709. {
  710. static int sxseg=-1;
  711. int i;
  712. if (!win32) /* Only applicable for -f win32 */
  713. return 0;
  714. if (sxseg == -1) {
  715. for (i = 0; i < coff_nsects; i++)
  716. if (!strcmp(".sxdata",coff_sects[i]->name))
  717. break;
  718. if (i == coff_nsects)
  719. sxseg = coff_make_section(".sxdata", IMAGE_SCN_LNK_INFO);
  720. else
  721. sxseg = i;
  722. }
  723. /*
  724. * pass0 == 2 is the only time when the full set of symbols are
  725. * guaranteed to be present; it is the final output pass.
  726. */
  727. if (pass0 == 2) {
  728. uint32_t n;
  729. saa_rewind(coff_syms);
  730. for (n = 0; n < coff_nsyms; n++) {
  731. struct coff_Symbol *sym = saa_rstruct(coff_syms);
  732. bool equals;
  733. /*
  734. * sym->strpos is biased by 4, because symbol
  735. * table is prefixed with table length
  736. */
  737. if (sym->strpos >=4) {
  738. char *name = nasm_malloc(sym->namlen+1);
  739. saa_fread(coff_strs, sym->strpos-4, name, sym->namlen);
  740. name[sym->namlen] = '\0';
  741. equals = !strcmp(value,name);
  742. nasm_free(name);
  743. } else {
  744. equals = !strcmp(value,sym->name);
  745. }
  746. if (equals) {
  747. /*
  748. * this value arithmetics effectively reflects
  749. * initsym in coff_write(): 2 for file, 1 for
  750. * .absolute and two per each section
  751. */
  752. unsigned char value[4],*p=value;
  753. WRITELONG(p,n + 2 + 1 + coff_nsects*2);
  754. coff_sect_write(coff_sects[sxseg],value,4);
  755. sym->type = 0x20;
  756. break;
  757. }
  758. }
  759. if (n == coff_nsyms) {
  760. nasm_error(ERR_NONFATAL,
  761. "`safeseh' directive requires valid symbol");
  762. return DIRR_ERROR;
  763. }
  764. }
  765. return DIRR_OK;
  766. }
  767. default:
  768. return DIRR_UNKNOWN;
  769. }
  770. }
  771. /* handle relocations storm, valid for win32/64 only */
  772. static inline void coff_adjust_relocs(struct coff_Section *s)
  773. {
  774. if (s->nrelocs < IMAGE_SCN_MAX_RELOC)
  775. return;
  776. #ifdef OF_COFF
  777. else
  778. {
  779. if (ofmt == &of_coff)
  780. nasm_fatal(0,
  781. "Too many relocations (%d) for section `%s'",
  782. s->nrelocs, s->name);
  783. }
  784. #endif
  785. s->flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
  786. s->nrelocs++;
  787. }
  788. static void coff_write(void)
  789. {
  790. int32_t pos, sympos, vsize;
  791. int i;
  792. /* fill in the .drectve section with -export's */
  793. BuildExportTable(&Exports);
  794. if (win32) {
  795. /* add default value for @feat.00, this allows to 'link /safeseh' */
  796. uint32_t n;
  797. saa_rewind(coff_syms);
  798. for (n = 0; n < coff_nsyms; n++) {
  799. struct coff_Symbol *sym = saa_rstruct(coff_syms);
  800. if (sym->strpos == -1 && !strcmp("@feat.00",sym->name))
  801. break;
  802. }
  803. if (n == coff_nsyms)
  804. coff_deflabel("@feat.00", NO_SEG, 1, 0, NULL);
  805. }
  806. /*
  807. * Work out how big the file will get.
  808. * Calculate the start of the `real' symbols at the same time.
  809. * Check for massive relocations.
  810. */
  811. pos = 0x14 + 0x28 * coff_nsects;
  812. initsym = 3; /* two for the file, one absolute */
  813. for (i = 0; i < coff_nsects; i++) {
  814. if (coff_sects[i]->data) {
  815. coff_adjust_relocs(coff_sects[i]);
  816. coff_sects[i]->pos = pos;
  817. pos += coff_sects[i]->len;
  818. coff_sects[i]->relpos = pos;
  819. pos += 10 * coff_sects[i]->nrelocs;
  820. } else
  821. coff_sects[i]->pos = coff_sects[i]->relpos = 0L;
  822. initsym += 2; /* two for each section */
  823. }
  824. sympos = pos;
  825. /*
  826. * Output the COFF header.
  827. */
  828. if (win64)
  829. i = IMAGE_FILE_MACHINE_AMD64;
  830. else
  831. i = IMAGE_FILE_MACHINE_I386;
  832. fwriteint16_t(i, ofile); /* machine type */
  833. fwriteint16_t(coff_nsects, ofile); /* number of sections */
  834. fwriteint32_t(time(NULL), ofile); /* time stamp */
  835. fwriteint32_t(sympos, ofile);
  836. fwriteint32_t(coff_nsyms + initsym, ofile);
  837. fwriteint16_t(0, ofile); /* no optional header */
  838. /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
  839. fwriteint16_t((win32 | win64) ? 0 : 0x104, ofile);
  840. /*
  841. * Output the section headers.
  842. */
  843. vsize = 0L;
  844. for (i = 0; i < coff_nsects; i++) {
  845. coff_section_header(coff_sects[i]->name, coff_sects[i]->namepos, vsize, coff_sects[i]->len,
  846. coff_sects[i]->pos, coff_sects[i]->relpos,
  847. coff_sects[i]->nrelocs, coff_sects[i]->flags);
  848. vsize += coff_sects[i]->len;
  849. }
  850. /*
  851. * Output the sections and their relocations.
  852. */
  853. for (i = 0; i < coff_nsects; i++)
  854. if (coff_sects[i]->data) {
  855. saa_fpwrite(coff_sects[i]->data, ofile);
  856. coff_write_relocs(coff_sects[i]);
  857. }
  858. /*
  859. * Output the symbol and string tables.
  860. */
  861. coff_write_symbols();
  862. fwriteint32_t(strslen + 4, ofile); /* length includes length count */
  863. saa_fpwrite(coff_strs, ofile);
  864. }
  865. static void coff_section_header(char *name, int32_t namepos, int32_t vsize,
  866. int32_t datalen, int32_t datapos,
  867. int32_t relpos, int nrelocs, int32_t flags)
  868. {
  869. char padname[8];
  870. (void)vsize;
  871. if (namepos == -1) {
  872. strncpy(padname, name, 8);
  873. nasm_write(padname, 8, ofile);
  874. } else {
  875. /*
  876. * If name is longer than 8 bytes, write '/' followed
  877. * by offset into the strings table represented as
  878. * decimal number.
  879. */
  880. namepos = namepos % 100000000;
  881. padname[0] = '/';
  882. padname[1] = '0' + (namepos / 1000000);
  883. namepos = namepos % 1000000;
  884. padname[2] = '0' + (namepos / 100000);
  885. namepos = namepos % 100000;
  886. padname[3] = '0' + (namepos / 10000);
  887. namepos = namepos % 10000;
  888. padname[4] = '0' + (namepos / 1000);
  889. namepos = namepos % 1000;
  890. padname[5] = '0' + (namepos / 100);
  891. namepos = namepos % 100;
  892. padname[6] = '0' + (namepos / 10);
  893. namepos = namepos % 10;
  894. padname[7] = '0' + (namepos);
  895. nasm_write(padname, 8, ofile);
  896. }
  897. fwriteint32_t(0, ofile); /* Virtual size field - set to 0 or vsize */
  898. fwriteint32_t(0L, ofile); /* RVA/offset - we ignore */
  899. fwriteint32_t(datalen, ofile);
  900. fwriteint32_t(datapos, ofile);
  901. fwriteint32_t(relpos, ofile);
  902. fwriteint32_t(0L, ofile); /* no line numbers - we don't do 'em */
  903. /*
  904. * a special case -- if there are too many relocs
  905. * we have to put IMAGE_SCN_MAX_RELOC here and write
  906. * the real relocs number into VirtualAddress of first
  907. * relocation
  908. */
  909. if (flags & IMAGE_SCN_LNK_NRELOC_OVFL)
  910. fwriteint16_t(IMAGE_SCN_MAX_RELOC, ofile);
  911. else
  912. fwriteint16_t(nrelocs, ofile);
  913. fwriteint16_t(0, ofile); /* again, no line numbers */
  914. fwriteint32_t(flags, ofile);
  915. }
  916. static void coff_write_relocs(struct coff_Section *s)
  917. {
  918. struct coff_Reloc *r;
  919. /* a real number of relocations if needed */
  920. if (s->flags & IMAGE_SCN_LNK_NRELOC_OVFL) {
  921. fwriteint32_t(s->nrelocs, ofile);
  922. fwriteint32_t(0, ofile);
  923. fwriteint16_t(0, ofile);
  924. }
  925. for (r = s->head; r; r = r->next) {
  926. fwriteint32_t(r->address, ofile);
  927. fwriteint32_t(r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
  928. r->symbase == ABS_SYMBOL ? initsym - 1 :
  929. r->symbase == SECT_SYMBOLS ? 2 : 0),
  930. ofile);
  931. fwriteint16_t(r->type, ofile);
  932. }
  933. }
  934. static void coff_symbol(char *name, int32_t strpos, int32_t value,
  935. int section, int type, int storageclass, int aux)
  936. {
  937. char padname[8];
  938. if (name) {
  939. strncpy(padname, name, 8);
  940. nasm_write(padname, 8, ofile);
  941. } else {
  942. fwriteint32_t(0, ofile);
  943. fwriteint32_t(strpos, ofile);
  944. }
  945. fwriteint32_t(value, ofile);
  946. fwriteint16_t(section, ofile);
  947. fwriteint16_t(type, ofile);
  948. fputc(storageclass, ofile);
  949. fputc(aux, ofile);
  950. }
  951. static void coff_write_symbols(void)
  952. {
  953. char filename[18];
  954. uint32_t i;
  955. /*
  956. * The `.file' record, and the file name auxiliary record.
  957. */
  958. coff_symbol(".file", 0L, 0L, -2, 0, 0x67, 1);
  959. strncpy(filename, inname, 18);
  960. nasm_write(filename, 18, ofile);
  961. /*
  962. * The section records, with their auxiliaries.
  963. */
  964. memset(filename, 0, 18); /* useful zeroed buffer */
  965. for (i = 0; i < (uint32_t) coff_nsects; i++) {
  966. coff_symbol(coff_sects[i]->name, 0L, 0L, i + 1, 0, 3, 1);
  967. fwriteint32_t(coff_sects[i]->len, ofile);
  968. fwriteint16_t(coff_sects[i]->nrelocs,ofile);
  969. nasm_write(filename, 12, ofile);
  970. }
  971. /*
  972. * The absolute symbol, for relative-to-absolute relocations.
  973. */
  974. coff_symbol(".absolut", 0L, 0L, -1, 0, 3, 0);
  975. /*
  976. * The real symbols.
  977. */
  978. saa_rewind(coff_syms);
  979. for (i = 0; i < coff_nsyms; i++) {
  980. struct coff_Symbol *sym = saa_rstruct(coff_syms);
  981. coff_symbol(sym->strpos == -1 ? sym->name : NULL,
  982. sym->strpos, sym->value, sym->section,
  983. sym->type, sym->is_global ? 2 : 3, 0);
  984. }
  985. }
  986. static void coff_sectalign(int32_t seg, unsigned int value)
  987. {
  988. struct coff_Section *s = NULL;
  989. uint32_t align;
  990. int i;
  991. for (i = 0; i < coff_nsects; i++) {
  992. if (coff_sects[i]->index == seg) {
  993. s = coff_sects[i];
  994. break;
  995. }
  996. }
  997. if (!s || !is_power2(value))
  998. return;
  999. /* DOS has limitation on 64 bytes */
  1000. if (!(win32 | win64) && value > 64)
  1001. return;
  1002. align = (s->flags & IMAGE_SCN_ALIGN_MASK);
  1003. value = coff_sectalign_flags(value);
  1004. if (value > align)
  1005. s->flags = (s->flags & ~IMAGE_SCN_ALIGN_MASK) | value;
  1006. }
  1007. static int32_t coff_segbase(int32_t segment)
  1008. {
  1009. return segment;
  1010. }
  1011. extern macros_t coff_stdmac[];
  1012. #endif /* defined(OF_COFF) || defined(OF_WIN32) */
  1013. #ifdef OF_COFF
  1014. const struct ofmt of_coff = {
  1015. "COFF (i386) object files (e.g. DJGPP for DOS)",
  1016. "coff",
  1017. ".o",
  1018. 0,
  1019. 32,
  1020. null_debug_arr,
  1021. &null_debug_form,
  1022. coff_stdmac,
  1023. coff_std_init,
  1024. null_reset,
  1025. nasm_do_legacy_output,
  1026. coff_out,
  1027. coff_deflabel,
  1028. coff_section_names,
  1029. NULL,
  1030. coff_sectalign,
  1031. coff_segbase,
  1032. coff_directives,
  1033. coff_cleanup,
  1034. NULL /* pragma list */
  1035. };
  1036. #endif
  1037. extern const struct dfmt df_cv8;
  1038. #ifdef OF_WIN32
  1039. static const struct dfmt * const win32_debug_arr[2] = { &df_cv8, NULL };
  1040. const struct ofmt of_win32 = {
  1041. "Microsoft Win32 (i386) object files",
  1042. "win32",
  1043. ".obj",
  1044. 0,
  1045. 32,
  1046. win32_debug_arr,
  1047. &df_cv8,
  1048. coff_stdmac,
  1049. coff_win32_init,
  1050. null_reset,
  1051. nasm_do_legacy_output,
  1052. coff_out,
  1053. coff_deflabel,
  1054. coff_section_names,
  1055. NULL,
  1056. coff_sectalign,
  1057. coff_segbase,
  1058. coff_directives,
  1059. coff_cleanup,
  1060. NULL /* pragma list */
  1061. };
  1062. #endif
  1063. #ifdef OF_WIN64
  1064. static const struct dfmt * const win64_debug_arr[2] = { &df_cv8, NULL };
  1065. const struct ofmt of_win64 = {
  1066. "Microsoft Win64 (x86-64) object files",
  1067. "win64",
  1068. ".obj",
  1069. 0,
  1070. 64,
  1071. win64_debug_arr,
  1072. &df_cv8,
  1073. coff_stdmac,
  1074. coff_win64_init,
  1075. null_reset,
  1076. nasm_do_legacy_output,
  1077. coff_out,
  1078. coff_deflabel,
  1079. coff_section_names,
  1080. NULL,
  1081. coff_sectalign,
  1082. coff_segbase,
  1083. coff_directives,
  1084. coff_cleanup,
  1085. NULL /* pragma list */
  1086. };
  1087. #endif