outbin.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701
  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. * outbin.c output routines for the Netwide Assembler to produce
  35. * flat-form binary files
  36. */
  37. /* This is the extended version of NASM's original binary output
  38. * format. It is backward compatible with the original BIN format,
  39. * and contains support for multiple sections and advanced section
  40. * ordering.
  41. *
  42. * Feature summary:
  43. *
  44. * - Users can create an arbitrary number of sections; they are not
  45. * limited to just ".text", ".data", and ".bss".
  46. *
  47. * - Sections can be either progbits or nobits type.
  48. *
  49. * - You can specify that they be aligned at a certian boundary
  50. * following the previous section ("align="), or positioned at an
  51. * arbitrary byte-granular location ("start=").
  52. *
  53. * - You can specify a "virtual" start address for a section, which
  54. * will be used for the calculation for all address references
  55. * with respect to that section ("vstart=").
  56. *
  57. * - The ORG directive, as well as the section/segment directive
  58. * arguments ("align=", "start=", "vstart="), can take a critical
  59. * expression as their value. For example: "align=(1 << 12)".
  60. *
  61. * - You can generate map files using the 'map' directive.
  62. *
  63. */
  64. /* Uncomment the following define if you want sections to adapt
  65. * their progbits/nobits state depending on what type of
  66. * instructions are issued, rather than defaulting to progbits.
  67. * Note that this behavior violates the specification.
  68. #define ABIN_SMART_ADAPT
  69. */
  70. #include "compiler.h"
  71. #include <stdio.h>
  72. #include <stdlib.h>
  73. #include <string.h>
  74. #include <ctype.h>
  75. #include "nasm.h"
  76. #include "nasmlib.h"
  77. #include "error.h"
  78. #include "saa.h"
  79. #include "stdscan.h"
  80. #include "labels.h"
  81. #include "eval.h"
  82. #include "outform.h"
  83. #include "outlib.h"
  84. #ifdef OF_BIN
  85. static FILE *rf = NULL;
  86. static void (*do_output)(void);
  87. /* Section flags keep track of which attributes the user has defined. */
  88. #define START_DEFINED 0x001
  89. #define ALIGN_DEFINED 0x002
  90. #define FOLLOWS_DEFINED 0x004
  91. #define VSTART_DEFINED 0x008
  92. #define VALIGN_DEFINED 0x010
  93. #define VFOLLOWS_DEFINED 0x020
  94. #define TYPE_DEFINED 0x040
  95. #define TYPE_PROGBITS 0x080
  96. #define TYPE_NOBITS 0x100
  97. /* This struct is used to keep track of symbols for map-file generation. */
  98. static struct bin_label {
  99. char *name;
  100. struct bin_label *next;
  101. } *no_seg_labels, **nsl_tail;
  102. static struct Section {
  103. char *name;
  104. struct SAA *contents;
  105. int64_t length; /* section length in bytes */
  106. /* Section attributes */
  107. int flags; /* see flag definitions above */
  108. uint64_t align; /* section alignment */
  109. uint64_t valign; /* notional section alignment */
  110. uint64_t start; /* section start address */
  111. uint64_t vstart; /* section virtual start address */
  112. char *follows; /* the section that this one will follow */
  113. char *vfollows; /* the section that this one will notionally follow */
  114. int32_t start_index; /* NASM section id for non-relocated version */
  115. int32_t vstart_index; /* the NASM section id */
  116. struct bin_label *labels; /* linked-list of label handles for map output. */
  117. struct bin_label **labels_end; /* Holds address of end of labels list. */
  118. struct Section *prev; /* Points to previous section (implicit follows). */
  119. struct Section *next; /* This links sections with a defined start address. */
  120. /* The extended bin format allows for sections to have a "virtual"
  121. * start address. This is accomplished by creating two sections:
  122. * one beginning at the Load Memory Address and the other beginning
  123. * at the Virtual Memory Address. The LMA section is only used to
  124. * define the section.<section_name>.start label, but there isn't
  125. * any other good way for us to handle that label.
  126. */
  127. } *sections, *last_section;
  128. static struct Reloc {
  129. struct Reloc *next;
  130. int32_t posn;
  131. int32_t bytes;
  132. int32_t secref;
  133. int32_t secrel;
  134. struct Section *target;
  135. } *relocs, **reloctail;
  136. static uint64_t origin;
  137. static int origin_defined;
  138. /* Stuff we need for map-file generation. */
  139. #define MAP_ORIGIN 1
  140. #define MAP_SUMMARY 2
  141. #define MAP_SECTIONS 4
  142. #define MAP_SYMBOLS 8
  143. static int map_control = 0;
  144. extern macros_t bin_stdmac[];
  145. static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
  146. int32_t secrel)
  147. {
  148. struct Reloc *r;
  149. r = *reloctail = nasm_malloc(sizeof(struct Reloc));
  150. reloctail = &r->next;
  151. r->next = NULL;
  152. r->posn = s->length;
  153. r->bytes = bytes;
  154. r->secref = secref;
  155. r->secrel = secrel;
  156. r->target = s;
  157. }
  158. static struct Section *find_section_by_name(const char *name)
  159. {
  160. struct Section *s;
  161. list_for_each(s, sections)
  162. if (!strcmp(s->name, name))
  163. break;
  164. return s;
  165. }
  166. static struct Section *find_section_by_index(int32_t index)
  167. {
  168. struct Section *s;
  169. list_for_each(s, sections)
  170. if ((index == s->vstart_index) || (index == s->start_index))
  171. break;
  172. return s;
  173. }
  174. static struct Section *create_section(char *name)
  175. {
  176. struct Section *s = nasm_zalloc(sizeof(*s));
  177. s->prev = last_section;
  178. s->name = nasm_strdup(name);
  179. s->labels_end = &(s->labels);
  180. s->contents = saa_init(1L);
  181. /* Register our sections with NASM. */
  182. s->vstart_index = seg_alloc();
  183. s->start_index = seg_alloc();
  184. /* FIXME: Append to a tail, we need some helper */
  185. last_section->next = s;
  186. last_section = s;
  187. return last_section;
  188. }
  189. static void bin_cleanup(void)
  190. {
  191. struct Section *g, **gp;
  192. struct Section *gs = NULL, **gsp;
  193. struct Section *s, **sp;
  194. struct Section *nobits = NULL, **nt;
  195. struct Section *last_progbits;
  196. struct bin_label *l;
  197. struct Reloc *r;
  198. uint64_t pend;
  199. int h;
  200. #ifdef DEBUG
  201. nasm_error(ERR_DEBUG,
  202. "bin_cleanup: Sections were initially referenced in this order:\n");
  203. for (h = 0, s = sections; s; h++, s = s->next)
  204. fprintf(stdout, "%i. %s\n", h, s->name);
  205. #endif
  206. /* Assembly has completed, so now we need to generate the output file.
  207. * Step 1: Separate progbits and nobits sections into separate lists.
  208. * Step 2: Sort the progbits sections into their output order.
  209. * Step 3: Compute start addresses for all progbits sections.
  210. * Step 4: Compute vstart addresses for all sections.
  211. * Step 5: Apply relocations.
  212. * Step 6: Write the sections' data to the output file.
  213. * Step 7: Generate the map file.
  214. * Step 8: Release all allocated memory.
  215. */
  216. /* To do: Smart section-type adaptation could leave some empty sections
  217. * without a defined type (progbits/nobits). Won't fix now since this
  218. * feature will be disabled. */
  219. /* Step 1: Split progbits and nobits sections into separate lists. */
  220. nt = &nobits;
  221. /* Move nobits sections into a separate list. Also pre-process nobits
  222. * sections' attributes. */
  223. for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
  224. if (s->flags & TYPE_PROGBITS) {
  225. sp = &s->next;
  226. continue;
  227. }
  228. /* Do some special pre-processing on nobits sections' attributes. */
  229. if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
  230. if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
  231. VFOLLOWS_DEFINED))
  232. nasm_fatal(ERR_NOFILE,
  233. "cannot mix real and virtual attributes"
  234. " in nobits section (%s)", s->name);
  235. /* Real and virtual attributes mean the same thing for nobits sections. */
  236. if (s->flags & START_DEFINED) {
  237. s->vstart = s->start;
  238. s->flags |= VSTART_DEFINED;
  239. }
  240. if (s->flags & ALIGN_DEFINED) {
  241. s->valign = s->align;
  242. s->flags |= VALIGN_DEFINED;
  243. }
  244. if (s->flags & FOLLOWS_DEFINED) {
  245. s->vfollows = s->follows;
  246. s->flags |= VFOLLOWS_DEFINED;
  247. s->flags &= ~FOLLOWS_DEFINED;
  248. }
  249. }
  250. /* Every section must have a start address. */
  251. if (s->flags & VSTART_DEFINED) {
  252. s->start = s->vstart;
  253. s->flags |= START_DEFINED;
  254. }
  255. /* Move the section into the nobits list. */
  256. *sp = s->next;
  257. s->next = NULL;
  258. *nt = s;
  259. nt = &s->next;
  260. }
  261. /* Step 2: Sort the progbits sections into their output order. */
  262. /* In Step 2 we move around sections in groups. A group
  263. * begins with a section (group leader) that has a user-
  264. * defined start address or follows section. The remainder
  265. * of the group is made up of the sections that implicitly
  266. * follow the group leader (i.e., they were defined after
  267. * the group leader and were not given an explicit start
  268. * address or follows section by the user). */
  269. /* For anyone attempting to read this code:
  270. * g (group) points to a group of sections, the first one of which has
  271. * a user-defined start address or follows section.
  272. * gp (g previous) holds the location of the pointer to g.
  273. * gs (g scan) is a temp variable that we use to scan to the end of the group.
  274. * gsp (gs previous) holds the location of the pointer to gs.
  275. * nt (nobits tail) points to the nobits section-list tail.
  276. */
  277. /* Link all 'follows' groups to their proper position. To do
  278. * this we need to know three things: the start of the group
  279. * to relocate (g), the section it is following (s), and the
  280. * end of the group we're relocating (gs). */
  281. for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
  282. if (!(g->flags & FOLLOWS_DEFINED)) {
  283. while (g->next) {
  284. if ((g->next->flags & FOLLOWS_DEFINED) &&
  285. strcmp(g->name, g->next->follows))
  286. break;
  287. g = g->next;
  288. }
  289. if (!g->next)
  290. break;
  291. gp = &g->next;
  292. g = g->next;
  293. }
  294. /* Find the section that this group follows (s). */
  295. for (sp = &sections, s = sections;
  296. s && strcmp(s->name, g->follows);
  297. sp = &s->next, s = s->next) ;
  298. if (!s)
  299. nasm_fatal(ERR_NOFILE, "section %s follows an invalid or"
  300. " unknown section (%s)", g->name, g->follows);
  301. if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
  302. !strcmp(s->name, s->next->follows))
  303. nasm_fatal(ERR_NOFILE, "sections %s and %s can't both follow"
  304. " section %s", g->name, s->next->name, s->name);
  305. /* Find the end of the current follows group (gs). */
  306. for (gsp = &g->next, gs = g->next;
  307. gs && (gs != s) && !(gs->flags & START_DEFINED);
  308. gsp = &gs->next, gs = gs->next) {
  309. if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
  310. strcmp(gs->name, gs->next->follows)) {
  311. gsp = &gs->next;
  312. gs = gs->next;
  313. break;
  314. }
  315. }
  316. /* Re-link the group after its follows section. */
  317. *gsp = s->next;
  318. s->next = g;
  319. *gp = gs;
  320. }
  321. /* Link all 'start' groups to their proper position. Once
  322. * again we need to know g, s, and gs (see above). The main
  323. * difference is we already know g since we sort by moving
  324. * groups from the 'unsorted' list into a 'sorted' list (g
  325. * will always be the first section in the unsorted list). */
  326. for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
  327. for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
  328. if ((s->flags & START_DEFINED) && (g->start < s->start))
  329. break;
  330. /* Find the end of the group (gs). */
  331. for (gs = g->next, gsp = &g->next;
  332. gs && !(gs->flags & START_DEFINED);
  333. gsp = &gs->next, gs = gs->next) ;
  334. /* Re-link the group before the target section. */
  335. *sp = g;
  336. *gsp = s;
  337. }
  338. /* Step 3: Compute start addresses for all progbits sections. */
  339. /* Make sure we have an origin and a start address for the first section. */
  340. if (origin_defined) {
  341. if (sections->flags & START_DEFINED) {
  342. /* Make sure this section doesn't begin before the origin. */
  343. if (sections->start < origin)
  344. nasm_fatal(ERR_NOFILE, "section %s begins"
  345. " before program origin", sections->name);
  346. } else if (sections->flags & ALIGN_DEFINED) {
  347. sections->start = ALIGN(origin, sections->align);
  348. } else {
  349. sections->start = origin;
  350. }
  351. } else {
  352. if (!(sections->flags & START_DEFINED))
  353. sections->start = 0;
  354. origin = sections->start;
  355. }
  356. sections->flags |= START_DEFINED;
  357. /* Make sure each section has an explicit start address. If it
  358. * doesn't, then compute one based its alignment and the end of
  359. * the previous section. */
  360. for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
  361. * (has a defined start address, and is not zero length). */
  362. if (g == s)
  363. for (s = g->next;
  364. s && ((s->length == 0) || !(s->flags & START_DEFINED));
  365. s = s->next) ;
  366. /* Compute the start address of this section, if necessary. */
  367. if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
  368. if (!(g->flags & ALIGN_DEFINED)) {
  369. g->align = 4;
  370. g->flags |= ALIGN_DEFINED;
  371. }
  372. /* Set the section start address. */
  373. g->start = ALIGN(pend, g->align);
  374. g->flags |= START_DEFINED;
  375. }
  376. /* Ugly special case for progbits sections' virtual attributes:
  377. * If there is a defined valign, but no vstart and no vfollows, then
  378. * we valign after the previous progbits section. This case doesn't
  379. * really make much sense for progbits sections with a defined start
  380. * address, but it is possible and we must do *something*.
  381. * Not-so-ugly special case:
  382. * If a progbits section has no virtual attributes, we set the
  383. * vstart equal to the start address. */
  384. if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
  385. if (g->flags & VALIGN_DEFINED)
  386. g->vstart = ALIGN(pend, g->valign);
  387. else
  388. g->vstart = g->start;
  389. g->flags |= VSTART_DEFINED;
  390. }
  391. /* Ignore zero-length sections. */
  392. if (g->start < pend)
  393. continue;
  394. /* Compute the span of this section. */
  395. pend = g->start + g->length;
  396. /* Check for section overlap. */
  397. if (s) {
  398. if (s->start < origin)
  399. nasm_fatal(ERR_NOFILE, "section %s beings before program origin",
  400. s->name);
  401. if (g->start > s->start)
  402. nasm_fatal(ERR_NOFILE, "sections %s ~ %s and %s overlap!",
  403. gs->name, g->name, s->name);
  404. if (pend > s->start)
  405. nasm_fatal(ERR_NOFILE, "sections %s and %s overlap!",
  406. g->name, s->name);
  407. }
  408. /* Remember this section as the latest >0 length section. */
  409. gs = g;
  410. }
  411. /* Step 4: Compute vstart addresses for all sections. */
  412. /* Attach the nobits sections to the end of the progbits sections. */
  413. for (s = sections; s->next; s = s->next) ;
  414. s->next = nobits;
  415. last_progbits = s;
  416. /*
  417. * Scan for sections that don't have a vstart address. If we find
  418. * one we'll attempt to compute its vstart. If we can't compute
  419. * the vstart, we leave it alone and come back to it in a
  420. * subsequent scan. We continue scanning and re-scanning until
  421. * we've gone one full cycle without computing any vstarts.
  422. */
  423. do { /* Do one full scan of the sections list. */
  424. for (h = 0, g = sections; g; g = g->next) {
  425. if (g->flags & VSTART_DEFINED)
  426. continue;
  427. /* Find the section that this one virtually follows. */
  428. if (g->flags & VFOLLOWS_DEFINED) {
  429. for (s = sections; s && strcmp(g->vfollows, s->name);
  430. s = s->next) ;
  431. if (!s)
  432. nasm_fatal(ERR_NOFILE,
  433. "section %s vfollows unknown section (%s)",
  434. g->name, g->vfollows);
  435. } else if (g->prev != NULL)
  436. for (s = sections; s && (s != g->prev); s = s->next) ;
  437. /* The .bss section is the only one with prev = NULL.
  438. In this case we implicitly follow the last progbits
  439. section. */
  440. else
  441. s = last_progbits;
  442. /* If the section we're following has a vstart, we can proceed. */
  443. if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
  444. if (!(g->flags & VALIGN_DEFINED)) {
  445. g->valign = 4;
  446. g->flags |= VALIGN_DEFINED;
  447. }
  448. /* Compute the vstart address. */
  449. g->vstart = ALIGN(s->vstart + s->length, g->valign);
  450. g->flags |= VSTART_DEFINED;
  451. h++;
  452. /* Start and vstart mean the same thing for nobits sections. */
  453. if (g->flags & TYPE_NOBITS)
  454. g->start = g->vstart;
  455. }
  456. }
  457. } while (h);
  458. /* Now check for any circular vfollows references, which will manifest
  459. * themselves as sections without a defined vstart. */
  460. for (h = 0, s = sections; s; s = s->next) {
  461. if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
  462. * no-no, but we'll throw a fatal one eventually so it's ok. */
  463. nasm_error(ERR_NONFATAL, "cannot compute vstart for section %s",
  464. s->name);
  465. h++;
  466. }
  467. }
  468. if (h)
  469. nasm_fatal(ERR_NOFILE, "circular vfollows path detected");
  470. #ifdef DEBUG
  471. nasm_error(ERR_DEBUG,
  472. "bin_cleanup: Confirm final section order for output file:\n");
  473. for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
  474. h++, s = s->next)
  475. fprintf(stdout, "%i. %s\n", h, s->name);
  476. #endif
  477. /* Step 5: Apply relocations. */
  478. /* Prepare the sections for relocating. */
  479. list_for_each(s, sections)
  480. saa_rewind(s->contents);
  481. /* Apply relocations. */
  482. list_for_each(r, relocs) {
  483. uint8_t *p, mydata[8];
  484. int64_t l;
  485. int b;
  486. nasm_assert(r->bytes <= 8);
  487. memset(mydata, 0, sizeof(mydata));
  488. saa_fread(r->target->contents, r->posn, mydata, r->bytes);
  489. p = mydata;
  490. l = 0;
  491. for (b = r->bytes - 1; b >= 0; b--)
  492. l = (l << 8) + mydata[b];
  493. s = find_section_by_index(r->secref);
  494. if (s) {
  495. if (r->secref == s->start_index)
  496. l += s->start;
  497. else
  498. l += s->vstart;
  499. }
  500. s = find_section_by_index(r->secrel);
  501. if (s) {
  502. if (r->secrel == s->start_index)
  503. l -= s->start;
  504. else
  505. l -= s->vstart;
  506. }
  507. WRITEADDR(p, l, r->bytes);
  508. saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
  509. }
  510. /* Step 6: Write the section data to the output file. */
  511. do_output();
  512. /* Step 7: Generate the map file. */
  513. if (map_control) {
  514. static const char not_defined[] = "not defined";
  515. /* Display input and output file names. */
  516. fprintf(rf, "\n- NASM Map file ");
  517. for (h = 63; h; h--)
  518. fputc('-', rf);
  519. fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
  520. inname, outname);
  521. if (map_control & MAP_ORIGIN) { /* Display program origin. */
  522. fprintf(rf, "-- Program origin ");
  523. for (h = 61; h; h--)
  524. fputc('-', rf);
  525. fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
  526. }
  527. /* Display sections summary. */
  528. if (map_control & MAP_SUMMARY) {
  529. fprintf(rf, "-- Sections (summary) ");
  530. for (h = 57; h; h--)
  531. fputc('-', rf);
  532. fprintf(rf, "\n\nVstart Start Stop "
  533. "Length Class Name\n");
  534. list_for_each(s, sections) {
  535. fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
  536. s->vstart, s->start, s->start + s->length,
  537. s->length);
  538. if (s->flags & TYPE_PROGBITS)
  539. fprintf(rf, "progbits ");
  540. else
  541. fprintf(rf, "nobits ");
  542. fprintf(rf, "%s\n", s->name);
  543. }
  544. fprintf(rf, "\n");
  545. }
  546. /* Display detailed section information. */
  547. if (map_control & MAP_SECTIONS) {
  548. fprintf(rf, "-- Sections (detailed) ");
  549. for (h = 56; h; h--)
  550. fputc('-', rf);
  551. fprintf(rf, "\n\n");
  552. list_for_each(s, sections) {
  553. fprintf(rf, "---- Section %s ", s->name);
  554. for (h = 65 - strlen(s->name); h; h--)
  555. fputc('-', rf);
  556. fprintf(rf, "\n\nclass: ");
  557. if (s->flags & TYPE_PROGBITS)
  558. fprintf(rf, "progbits");
  559. else
  560. fprintf(rf, "nobits");
  561. fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
  562. "\nalign: ", s->length, s->start);
  563. if (s->flags & ALIGN_DEFINED)
  564. fprintf(rf, "%16"PRIX64"", s->align);
  565. else
  566. fputs(not_defined, rf);
  567. fprintf(rf, "\nfollows: ");
  568. if (s->flags & FOLLOWS_DEFINED)
  569. fprintf(rf, "%s", s->follows);
  570. else
  571. fputs(not_defined, rf);
  572. fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
  573. if (s->flags & VALIGN_DEFINED)
  574. fprintf(rf, "%16"PRIX64"", s->valign);
  575. else
  576. fputs(not_defined, rf);
  577. fprintf(rf, "\nvfollows: ");
  578. if (s->flags & VFOLLOWS_DEFINED)
  579. fprintf(rf, "%s", s->vfollows);
  580. else
  581. fputs(not_defined, rf);
  582. fprintf(rf, "\n\n");
  583. }
  584. }
  585. /* Display symbols information. */
  586. if (map_control & MAP_SYMBOLS) {
  587. int32_t segment;
  588. int64_t offset;
  589. bool found_label;
  590. fprintf(rf, "-- Symbols ");
  591. for (h = 68; h; h--)
  592. fputc('-', rf);
  593. fprintf(rf, "\n\n");
  594. if (no_seg_labels) {
  595. fprintf(rf, "---- No Section ");
  596. for (h = 63; h; h--)
  597. fputc('-', rf);
  598. fprintf(rf, "\n\nValue Name\n");
  599. list_for_each(l, no_seg_labels) {
  600. found_label = lookup_label(l->name, &segment, &offset);
  601. nasm_assert(found_label);
  602. fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
  603. }
  604. fprintf(rf, "\n\n");
  605. }
  606. list_for_each(s, sections) {
  607. if (s->labels) {
  608. fprintf(rf, "---- Section %s ", s->name);
  609. for (h = 65 - strlen(s->name); h; h--)
  610. fputc('-', rf);
  611. fprintf(rf, "\n\nReal Virtual Name\n");
  612. list_for_each(l, s->labels) {
  613. found_label = lookup_label(l->name, &segment, &offset);
  614. nasm_assert(found_label);
  615. fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
  616. s->start + offset, s->vstart + offset,
  617. l->name);
  618. }
  619. fprintf(rf, "\n");
  620. }
  621. }
  622. }
  623. }
  624. /* Close the report file. */
  625. if (map_control && (rf != stdout) && (rf != stderr))
  626. fclose(rf);
  627. /* Step 8: Release all allocated memory. */
  628. /* Free sections, label pointer structs, etc.. */
  629. while (sections) {
  630. s = sections;
  631. sections = s->next;
  632. saa_free(s->contents);
  633. nasm_free(s->name);
  634. if (s->flags & FOLLOWS_DEFINED)
  635. nasm_free(s->follows);
  636. if (s->flags & VFOLLOWS_DEFINED)
  637. nasm_free(s->vfollows);
  638. while (s->labels) {
  639. l = s->labels;
  640. s->labels = l->next;
  641. nasm_free(l);
  642. }
  643. nasm_free(s);
  644. }
  645. /* Free no-section labels. */
  646. while (no_seg_labels) {
  647. l = no_seg_labels;
  648. no_seg_labels = l->next;
  649. nasm_free(l);
  650. }
  651. /* Free relocation structures. */
  652. while (relocs) {
  653. r = relocs->next;
  654. nasm_free(relocs);
  655. relocs = r;
  656. }
  657. }
  658. static void bin_out(int32_t segto, const void *data,
  659. enum out_type type, uint64_t size,
  660. int32_t segment, int32_t wrt)
  661. {
  662. uint8_t *p, mydata[8];
  663. struct Section *s;
  664. if (wrt != NO_SEG) {
  665. wrt = NO_SEG; /* continue to do _something_ */
  666. nasm_error(ERR_NONFATAL, "WRT not supported by binary output format");
  667. }
  668. /* Handle absolute-assembly (structure definitions). */
  669. if (segto == NO_SEG) {
  670. if (type != OUT_RESERVE)
  671. nasm_error(ERR_NONFATAL, "attempt to assemble code in"
  672. " [ABSOLUTE] space");
  673. return;
  674. }
  675. /* Find the segment we are targeting. */
  676. s = find_section_by_index(segto);
  677. if (!s)
  678. nasm_panic(0, "code directed to nonexistent segment?");
  679. /* "Smart" section-type adaptation code. */
  680. if (!(s->flags & TYPE_DEFINED)) {
  681. if (type == OUT_RESERVE)
  682. s->flags |= TYPE_DEFINED | TYPE_NOBITS;
  683. else
  684. s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
  685. }
  686. if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
  687. nasm_error(ERR_WARNING, "attempt to initialize memory in a"
  688. " nobits section: ignored");
  689. switch (type) {
  690. case OUT_ADDRESS:
  691. {
  692. int asize = abs((int)size);
  693. if (segment != NO_SEG && !find_section_by_index(segment)) {
  694. if (segment % 2)
  695. nasm_error(ERR_NONFATAL, "binary output format does not support"
  696. " segment base references");
  697. else
  698. nasm_error(ERR_NONFATAL, "binary output format does not support"
  699. " external references");
  700. segment = NO_SEG;
  701. }
  702. if (s->flags & TYPE_PROGBITS) {
  703. if (segment != NO_SEG)
  704. add_reloc(s, asize, segment, -1L);
  705. p = mydata;
  706. WRITEADDR(p, *(int64_t *)data, asize);
  707. saa_wbytes(s->contents, mydata, asize);
  708. }
  709. /*
  710. * Reassign size with sign dropped, we will need it
  711. * for section length calculation.
  712. */
  713. size = asize;
  714. break;
  715. }
  716. case OUT_RAWDATA:
  717. if (s->flags & TYPE_PROGBITS)
  718. saa_wbytes(s->contents, data, size);
  719. break;
  720. case OUT_RESERVE:
  721. if (s->flags & TYPE_PROGBITS) {
  722. nasm_error(ERR_WARNING, "uninitialized space declared in"
  723. " %s section: zeroing", s->name);
  724. saa_wbytes(s->contents, NULL, size);
  725. }
  726. break;
  727. case OUT_REL1ADR:
  728. case OUT_REL2ADR:
  729. case OUT_REL4ADR:
  730. case OUT_REL8ADR:
  731. {
  732. int64_t addr = *(int64_t *)data - size;
  733. size = realsize(type, size);
  734. if (segment != NO_SEG && !find_section_by_index(segment)) {
  735. if (segment % 2)
  736. nasm_error(ERR_NONFATAL, "binary output format does not support"
  737. " segment base references");
  738. else
  739. nasm_error(ERR_NONFATAL, "binary output format does not support"
  740. " external references");
  741. segment = NO_SEG;
  742. }
  743. if (s->flags & TYPE_PROGBITS) {
  744. add_reloc(s, size, segment, segto);
  745. p = mydata;
  746. WRITEADDR(p, addr - s->length, size);
  747. saa_wbytes(s->contents, mydata, size);
  748. }
  749. break;
  750. }
  751. default:
  752. nasm_error(ERR_NONFATAL, "unsupported relocation type %d\n", type);
  753. break;
  754. }
  755. s->length += size;
  756. }
  757. static void bin_deflabel(char *name, int32_t segment, int64_t offset,
  758. int is_global, char *special)
  759. {
  760. (void)segment; /* Don't warn that this parameter is unused */
  761. (void)offset; /* Don't warn that this parameter is unused */
  762. if (special)
  763. nasm_error(ERR_NONFATAL, "binary format does not support any"
  764. " special symbol types");
  765. else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
  766. nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
  767. else if (is_global == 2)
  768. nasm_error(ERR_NONFATAL, "binary output format does not support common"
  769. " variables");
  770. else {
  771. struct Section *s;
  772. struct bin_label ***ltp;
  773. /* Remember label definition so we can look it up later when
  774. * creating the map file. */
  775. s = find_section_by_index(segment);
  776. if (s)
  777. ltp = &(s->labels_end);
  778. else
  779. ltp = &nsl_tail;
  780. (**ltp) = nasm_malloc(sizeof(struct bin_label));
  781. (**ltp)->name = name;
  782. (**ltp)->next = NULL;
  783. *ltp = &((**ltp)->next);
  784. }
  785. }
  786. /* These constants and the following function are used
  787. * by bin_secname() to parse attribute assignments. */
  788. enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
  789. ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
  790. ATTRIB_NOBITS, ATTRIB_PROGBITS
  791. };
  792. static int bin_read_attribute(char **line, int *attribute,
  793. uint64_t *value)
  794. {
  795. expr *e;
  796. int attrib_name_size;
  797. struct tokenval tokval;
  798. char *exp;
  799. /* Skip whitespace. */
  800. while (**line && nasm_isspace(**line))
  801. (*line)++;
  802. if (!**line)
  803. return 0;
  804. /* Figure out what attribute we're reading. */
  805. if (!nasm_strnicmp(*line, "align=", 6)) {
  806. *attribute = ATTRIB_ALIGN;
  807. attrib_name_size = 6;
  808. } else {
  809. if (!nasm_strnicmp(*line, "start=", 6)) {
  810. *attribute = ATTRIB_START;
  811. attrib_name_size = 6;
  812. } else if (!nasm_strnicmp(*line, "follows=", 8)) {
  813. *attribute = ATTRIB_FOLLOWS;
  814. *line += 8;
  815. return 1;
  816. } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
  817. *attribute = ATTRIB_VSTART;
  818. attrib_name_size = 7;
  819. } else if (!nasm_strnicmp(*line, "valign=", 7)) {
  820. *attribute = ATTRIB_VALIGN;
  821. attrib_name_size = 7;
  822. } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
  823. *attribute = ATTRIB_VFOLLOWS;
  824. *line += 9;
  825. return 1;
  826. } else if (!nasm_strnicmp(*line, "nobits", 6) &&
  827. (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
  828. *attribute = ATTRIB_NOBITS;
  829. *line += 6;
  830. return 1;
  831. } else if (!nasm_strnicmp(*line, "progbits", 8) &&
  832. (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
  833. *attribute = ATTRIB_PROGBITS;
  834. *line += 8;
  835. return 1;
  836. } else
  837. return 0;
  838. }
  839. /* Find the end of the expression. */
  840. if ((*line)[attrib_name_size] != '(') {
  841. /* Single term (no parenthesis). */
  842. exp = *line += attrib_name_size;
  843. while (**line && !nasm_isspace(**line))
  844. (*line)++;
  845. if (**line) {
  846. **line = '\0';
  847. (*line)++;
  848. }
  849. } else {
  850. char c;
  851. int pcount = 1;
  852. /* Full expression (delimited by parenthesis) */
  853. exp = *line += attrib_name_size + 1;
  854. while (1) {
  855. (*line) += strcspn(*line, "()'\"");
  856. if (**line == '(') {
  857. ++(*line);
  858. ++pcount;
  859. }
  860. if (**line == ')') {
  861. ++(*line);
  862. --pcount;
  863. if (!pcount)
  864. break;
  865. }
  866. if ((**line == '"') || (**line == '\'')) {
  867. c = **line;
  868. while (**line) {
  869. ++(*line);
  870. if (**line == c)
  871. break;
  872. }
  873. if (!**line) {
  874. nasm_error(ERR_NONFATAL,
  875. "invalid syntax in `section' directive");
  876. return -1;
  877. }
  878. ++(*line);
  879. }
  880. if (!**line) {
  881. nasm_error(ERR_NONFATAL, "expecting `)'");
  882. return -1;
  883. }
  884. }
  885. *(*line - 1) = '\0'; /* Terminate the expression. */
  886. }
  887. /* Check for no value given. */
  888. if (!*exp) {
  889. nasm_error(ERR_WARNING, "No value given to attribute in"
  890. " `section' directive");
  891. return -1;
  892. }
  893. /* Read and evaluate the expression. */
  894. stdscan_reset();
  895. stdscan_set(exp);
  896. tokval.t_type = TOKEN_INVALID;
  897. e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
  898. if (e) {
  899. if (!is_really_simple(e)) {
  900. nasm_error(ERR_NONFATAL, "section attribute value must be"
  901. " a critical expression");
  902. return -1;
  903. }
  904. } else {
  905. nasm_error(ERR_NONFATAL, "Invalid attribute value"
  906. " specified in `section' directive.");
  907. return -1;
  908. }
  909. *value = (uint64_t)reloc_value(e);
  910. return 1;
  911. }
  912. static void bin_sectalign(int32_t seg, unsigned int value)
  913. {
  914. struct Section *s = find_section_by_index(seg);
  915. if (!s || !is_power2(value))
  916. return;
  917. if (value > s->align)
  918. s->align = value;
  919. if (!(s->flags & ALIGN_DEFINED))
  920. s->flags |= ALIGN_DEFINED;
  921. }
  922. static void bin_assign_attributes(struct Section *sec, char *astring)
  923. {
  924. int attribute, check;
  925. uint64_t value;
  926. char *p;
  927. while (1) { /* Get the next attribute. */
  928. check = bin_read_attribute(&astring, &attribute, &value);
  929. /* Skip bad attribute. */
  930. if (check == -1)
  931. continue;
  932. /* Unknown section attribute, so skip it and warn the user. */
  933. if (!check) {
  934. if (!*astring)
  935. break; /* End of line. */
  936. else {
  937. p = astring;
  938. while (*astring && !nasm_isspace(*astring))
  939. astring++;
  940. if (*astring) {
  941. *astring = '\0';
  942. astring++;
  943. }
  944. nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
  945. " \"%s\"", p);
  946. }
  947. continue;
  948. }
  949. switch (attribute) { /* Handle nobits attribute. */
  950. case ATTRIB_NOBITS:
  951. if ((sec->flags & TYPE_DEFINED)
  952. && (sec->flags & TYPE_PROGBITS))
  953. nasm_error(ERR_NONFATAL,
  954. "attempt to change section type"
  955. " from progbits to nobits");
  956. else
  957. sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
  958. continue;
  959. /* Handle progbits attribute. */
  960. case ATTRIB_PROGBITS:
  961. if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
  962. nasm_error(ERR_NONFATAL, "attempt to change section type"
  963. " from nobits to progbits");
  964. else
  965. sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
  966. continue;
  967. /* Handle align attribute. */
  968. case ATTRIB_ALIGN:
  969. if (!value || ((value - 1) & value)) {
  970. nasm_error(ERR_NONFATAL,
  971. "argument to `align' is not a power of two");
  972. } else {
  973. /*
  974. * Alignment is already satisfied if
  975. * the previous align value is greater
  976. */
  977. if ((sec->flags & ALIGN_DEFINED) && (value < sec->align))
  978. value = sec->align;
  979. /* Don't allow a conflicting align value. */
  980. if ((sec->flags & START_DEFINED) && (sec->start & (value - 1))) {
  981. nasm_error(ERR_NONFATAL,
  982. "`align' value conflicts with section start address");
  983. } else {
  984. sec->align = value;
  985. sec->flags |= ALIGN_DEFINED;
  986. }
  987. }
  988. continue;
  989. /* Handle valign attribute. */
  990. case ATTRIB_VALIGN:
  991. if (!value || ((value - 1) & value))
  992. nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
  993. " power of two");
  994. else { /* Alignment is already satisfied if the previous
  995. * align value is greater. */
  996. if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
  997. value = sec->valign;
  998. /* Don't allow a conflicting valign value. */
  999. if ((sec->flags & VSTART_DEFINED)
  1000. && (sec->vstart & (value - 1)))
  1001. nasm_error(ERR_NONFATAL,
  1002. "`valign' value conflicts "
  1003. "with `vstart' address");
  1004. else {
  1005. sec->valign = value;
  1006. sec->flags |= VALIGN_DEFINED;
  1007. }
  1008. }
  1009. continue;
  1010. /* Handle start attribute. */
  1011. case ATTRIB_START:
  1012. if (sec->flags & FOLLOWS_DEFINED)
  1013. nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
  1014. " section attributes");
  1015. else if ((sec->flags & START_DEFINED) && (value != sec->start))
  1016. nasm_error(ERR_NONFATAL, "section start address redefined");
  1017. else {
  1018. sec->start = value;
  1019. sec->flags |= START_DEFINED;
  1020. if (sec->flags & ALIGN_DEFINED) {
  1021. if (sec->start & (sec->align - 1))
  1022. nasm_error(ERR_NONFATAL, "`start' address conflicts"
  1023. " with section alignment");
  1024. sec->flags ^= ALIGN_DEFINED;
  1025. }
  1026. }
  1027. continue;
  1028. /* Handle vstart attribute. */
  1029. case ATTRIB_VSTART:
  1030. if (sec->flags & VFOLLOWS_DEFINED)
  1031. nasm_error(ERR_NONFATAL,
  1032. "cannot combine `vstart' and `vfollows'"
  1033. " section attributes");
  1034. else if ((sec->flags & VSTART_DEFINED)
  1035. && (value != sec->vstart))
  1036. nasm_error(ERR_NONFATAL,
  1037. "section virtual start address"
  1038. " (vstart) redefined");
  1039. else {
  1040. sec->vstart = value;
  1041. sec->flags |= VSTART_DEFINED;
  1042. if (sec->flags & VALIGN_DEFINED) {
  1043. if (sec->vstart & (sec->valign - 1))
  1044. nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
  1045. " with `valign' value");
  1046. sec->flags ^= VALIGN_DEFINED;
  1047. }
  1048. }
  1049. continue;
  1050. /* Handle follows attribute. */
  1051. case ATTRIB_FOLLOWS:
  1052. p = astring;
  1053. astring += strcspn(astring, " \t");
  1054. if (astring == p)
  1055. nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
  1056. " attribute");
  1057. else {
  1058. *(astring++) = '\0';
  1059. if (sec->flags & START_DEFINED)
  1060. nasm_error(ERR_NONFATAL,
  1061. "cannot combine `start' and `follows'"
  1062. " section attributes");
  1063. sec->follows = nasm_strdup(p);
  1064. sec->flags |= FOLLOWS_DEFINED;
  1065. }
  1066. continue;
  1067. /* Handle vfollows attribute. */
  1068. case ATTRIB_VFOLLOWS:
  1069. if (sec->flags & VSTART_DEFINED)
  1070. nasm_error(ERR_NONFATAL,
  1071. "cannot combine `vstart' and `vfollows'"
  1072. " section attributes");
  1073. else {
  1074. p = astring;
  1075. astring += strcspn(astring, " \t");
  1076. if (astring == p)
  1077. nasm_error(ERR_NONFATAL,
  1078. "expecting section name for `vfollows'"
  1079. " attribute");
  1080. else {
  1081. *(astring++) = '\0';
  1082. sec->vfollows = nasm_strdup(p);
  1083. sec->flags |= VFOLLOWS_DEFINED;
  1084. }
  1085. }
  1086. continue;
  1087. }
  1088. }
  1089. }
  1090. static void bin_define_section_labels(void)
  1091. {
  1092. static int labels_defined = 0;
  1093. struct Section *sec;
  1094. char *label_name;
  1095. size_t base_len;
  1096. if (labels_defined)
  1097. return;
  1098. list_for_each(sec, sections) {
  1099. base_len = strlen(sec->name) + 8;
  1100. label_name = nasm_malloc(base_len + 8);
  1101. strcpy(label_name, "section.");
  1102. strcpy(label_name + 8, sec->name);
  1103. /* section.<name>.start */
  1104. strcpy(label_name + base_len, ".start");
  1105. define_label(label_name, sec->start_index, 0L, false);
  1106. /* section.<name>.vstart */
  1107. strcpy(label_name + base_len, ".vstart");
  1108. define_label(label_name, sec->vstart_index, 0L, false);
  1109. nasm_free(label_name);
  1110. }
  1111. labels_defined = 1;
  1112. }
  1113. static int32_t bin_secname(char *name, int pass, int *bits)
  1114. {
  1115. char *p;
  1116. struct Section *sec;
  1117. /* bin_secname is called with *name = NULL at the start of each
  1118. * pass. Use this opportunity to establish the default section
  1119. * (default is BITS-16 ".text" segment).
  1120. */
  1121. if (!name) { /* Reset ORG and section attributes at the start of each pass. */
  1122. origin_defined = 0;
  1123. list_for_each(sec, sections)
  1124. sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
  1125. ALIGN_DEFINED | VALIGN_DEFINED);
  1126. /* Define section start and vstart labels. */
  1127. if (pass != 1)
  1128. bin_define_section_labels();
  1129. /* Establish the default (.text) section. */
  1130. *bits = 16;
  1131. sec = find_section_by_name(".text");
  1132. sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
  1133. return sec->vstart_index;
  1134. }
  1135. /* Attempt to find the requested section. If it does not
  1136. * exist, create it. */
  1137. p = name;
  1138. while (*p && !nasm_isspace(*p))
  1139. p++;
  1140. if (*p)
  1141. *p++ = '\0';
  1142. sec = find_section_by_name(name);
  1143. if (!sec) {
  1144. sec = create_section(name);
  1145. if (!strcmp(name, ".data"))
  1146. sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
  1147. else if (!strcmp(name, ".bss")) {
  1148. sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
  1149. sec->prev = NULL;
  1150. }
  1151. }
  1152. /* Handle attribute assignments. */
  1153. if (pass != 1)
  1154. bin_assign_attributes(sec, p);
  1155. #ifndef ABIN_SMART_ADAPT
  1156. /* The following line disables smart adaptation of
  1157. * PROGBITS/NOBITS section types (it forces sections to
  1158. * default to PROGBITS). */
  1159. if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
  1160. sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
  1161. #endif
  1162. return sec->vstart_index;
  1163. }
  1164. static enum directive_result
  1165. bin_directive(enum directive directive, char *args, int pass)
  1166. {
  1167. switch (directive) {
  1168. case D_ORG:
  1169. {
  1170. struct tokenval tokval;
  1171. uint64_t value;
  1172. expr *e;
  1173. stdscan_reset();
  1174. stdscan_set(args);
  1175. tokval.t_type = TOKEN_INVALID;
  1176. e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
  1177. if (e) {
  1178. if (!is_really_simple(e))
  1179. nasm_error(ERR_NONFATAL, "org value must be a critical"
  1180. " expression");
  1181. else {
  1182. value = reloc_value(e);
  1183. /* Check for ORG redefinition. */
  1184. if (origin_defined && (value != origin))
  1185. nasm_error(ERR_NONFATAL, "program origin redefined");
  1186. else {
  1187. origin = value;
  1188. origin_defined = 1;
  1189. }
  1190. }
  1191. } else
  1192. nasm_error(ERR_NONFATAL, "No or invalid offset specified"
  1193. " in ORG directive.");
  1194. return DIRR_OK;
  1195. }
  1196. case D_MAP:
  1197. {
  1198. /* The 'map' directive allows the user to generate section
  1199. * and symbol information to stdout, stderr, or to a file. */
  1200. char *p;
  1201. if (pass != 1)
  1202. return DIRR_OK;
  1203. args += strspn(args, " \t");
  1204. while (*args) {
  1205. p = args;
  1206. args += strcspn(args, " \t");
  1207. if (*args != '\0')
  1208. *(args++) = '\0';
  1209. if (!nasm_stricmp(p, "all"))
  1210. map_control |=
  1211. MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
  1212. else if (!nasm_stricmp(p, "brief"))
  1213. map_control |= MAP_ORIGIN | MAP_SUMMARY;
  1214. else if (!nasm_stricmp(p, "sections"))
  1215. map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
  1216. else if (!nasm_stricmp(p, "segments"))
  1217. map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
  1218. else if (!nasm_stricmp(p, "symbols"))
  1219. map_control |= MAP_SYMBOLS;
  1220. else if (!rf) {
  1221. if (!nasm_stricmp(p, "stdout"))
  1222. rf = stdout;
  1223. else if (!nasm_stricmp(p, "stderr"))
  1224. rf = stderr;
  1225. else { /* Must be a filename. */
  1226. rf = nasm_open_write(p, NF_TEXT);
  1227. if (!rf) {
  1228. nasm_error(ERR_WARNING, "unable to open map file `%s'",
  1229. p);
  1230. map_control = 0;
  1231. return DIRR_OK;
  1232. }
  1233. }
  1234. } else
  1235. nasm_error(ERR_WARNING, "map file already specified");
  1236. }
  1237. if (map_control == 0)
  1238. map_control |= MAP_ORIGIN | MAP_SUMMARY;
  1239. if (!rf)
  1240. rf = stdout;
  1241. return DIRR_OK;
  1242. }
  1243. default:
  1244. return DIRR_UNKNOWN;
  1245. }
  1246. }
  1247. static int32_t bin_segbase(int32_t segment)
  1248. {
  1249. return segment;
  1250. }
  1251. const struct ofmt of_bin, of_ith, of_srec;
  1252. static void binfmt_init(void);
  1253. static void do_output_bin(void);
  1254. static void do_output_ith(void);
  1255. static void do_output_srec(void);
  1256. static void bin_init(void)
  1257. {
  1258. do_output = do_output_bin;
  1259. binfmt_init();
  1260. }
  1261. static void ith_init(void)
  1262. {
  1263. do_output = do_output_ith;
  1264. binfmt_init();
  1265. }
  1266. static void srec_init(void)
  1267. {
  1268. do_output = do_output_srec;
  1269. binfmt_init();
  1270. }
  1271. static void binfmt_init(void)
  1272. {
  1273. relocs = NULL;
  1274. reloctail = &relocs;
  1275. origin_defined = 0;
  1276. no_seg_labels = NULL;
  1277. nsl_tail = &no_seg_labels;
  1278. /* Create default section (.text). */
  1279. sections = last_section = nasm_zalloc(sizeof(struct Section));
  1280. last_section->name = nasm_strdup(".text");
  1281. last_section->contents = saa_init(1L);
  1282. last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
  1283. last_section->labels_end = &(last_section->labels);
  1284. last_section->start_index = seg_alloc();
  1285. last_section->vstart_index = seg_alloc();
  1286. }
  1287. /* Generate binary file output */
  1288. static void do_output_bin(void)
  1289. {
  1290. struct Section *s;
  1291. uint64_t addr = origin;
  1292. /* Write the progbits sections to the output file. */
  1293. list_for_each(s, sections) {
  1294. /* Skip non-progbits sections */
  1295. if (!(s->flags & TYPE_PROGBITS))
  1296. continue;
  1297. /* Skip zero-length sections */
  1298. if (s->length == 0)
  1299. continue;
  1300. /* Pad the space between sections. */
  1301. nasm_assert(addr <= s->start);
  1302. fwritezero(s->start - addr, ofile);
  1303. /* Write the section to the output file. */
  1304. saa_fpwrite(s->contents, ofile);
  1305. /* Keep track of the current file position */
  1306. addr = s->start + s->length;
  1307. }
  1308. }
  1309. /* Generate Intel hex file output */
  1310. static void write_ith_record(unsigned int len, uint16_t addr,
  1311. uint8_t type, void *data)
  1312. {
  1313. char buf[1+2+4+2+255*2+2+2];
  1314. char *p = buf;
  1315. uint8_t csum, *dptr = data;
  1316. unsigned int i;
  1317. nasm_assert(len <= 255);
  1318. csum = len + addr + (addr >> 8) + type;
  1319. for (i = 0; i < len; i++)
  1320. csum += dptr[i];
  1321. csum = -csum;
  1322. p += sprintf(p, ":%02X%04X%02X", len, addr, type);
  1323. for (i = 0; i < len; i++)
  1324. p += sprintf(p, "%02X", dptr[i]);
  1325. p += sprintf(p, "%02X\n", csum);
  1326. nasm_write(buf, p-buf, ofile);
  1327. }
  1328. static void do_output_ith(void)
  1329. {
  1330. uint8_t buf[32];
  1331. struct Section *s;
  1332. uint64_t addr, hiaddr, hilba;
  1333. uint64_t length;
  1334. unsigned int chunk;
  1335. /* Write the progbits sections to the output file. */
  1336. hilba = 0;
  1337. list_for_each(s, sections) {
  1338. /* Skip non-progbits sections */
  1339. if (!(s->flags & TYPE_PROGBITS))
  1340. continue;
  1341. /* Skip zero-length sections */
  1342. if (s->length == 0)
  1343. continue;
  1344. addr = s->start;
  1345. length = s->length;
  1346. saa_rewind(s->contents);
  1347. while (length) {
  1348. hiaddr = addr >> 16;
  1349. if (hiaddr != hilba) {
  1350. buf[0] = hiaddr >> 8;
  1351. buf[1] = hiaddr;
  1352. write_ith_record(2, 0, 4, buf);
  1353. hilba = hiaddr;
  1354. }
  1355. chunk = 32 - (addr & 31);
  1356. if (length < chunk)
  1357. chunk = length;
  1358. saa_rnbytes(s->contents, buf, chunk);
  1359. write_ith_record(chunk, (uint16_t)addr, 0, buf);
  1360. addr += chunk;
  1361. length -= chunk;
  1362. }
  1363. }
  1364. /* Write closing record */
  1365. write_ith_record(0, 0, 1, NULL);
  1366. }
  1367. /* Generate Motorola S-records */
  1368. static void write_srecord(unsigned int len, unsigned int alen,
  1369. uint32_t addr, uint8_t type, void *data)
  1370. {
  1371. char buf[2+2+8+255*2+2+2];
  1372. char *p = buf;
  1373. uint8_t csum, *dptr = data;
  1374. unsigned int i;
  1375. nasm_assert(len <= 255);
  1376. switch (alen) {
  1377. case 2:
  1378. addr &= 0xffff;
  1379. break;
  1380. case 3:
  1381. addr &= 0xffffff;
  1382. break;
  1383. case 4:
  1384. break;
  1385. default:
  1386. nasm_assert(0);
  1387. break;
  1388. }
  1389. csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
  1390. for (i = 0; i < len; i++)
  1391. csum += dptr[i];
  1392. csum = 0xff-csum;
  1393. p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
  1394. for (i = 0; i < len; i++)
  1395. p += sprintf(p, "%02X", dptr[i]);
  1396. p += sprintf(p, "%02X\n", csum);
  1397. nasm_write(buf, p-buf, ofile);
  1398. }
  1399. static void do_output_srec(void)
  1400. {
  1401. uint8_t buf[32];
  1402. struct Section *s;
  1403. uint64_t addr, maxaddr;
  1404. uint64_t length;
  1405. int alen;
  1406. unsigned int chunk;
  1407. char dtype, etype;
  1408. maxaddr = 0;
  1409. list_for_each(s, sections) {
  1410. /* Skip non-progbits sections */
  1411. if (!(s->flags & TYPE_PROGBITS))
  1412. continue;
  1413. /* Skip zero-length sections */
  1414. if (s->length == 0)
  1415. continue;
  1416. addr = s->start + s->length - 1;
  1417. if (addr > maxaddr)
  1418. maxaddr = addr;
  1419. }
  1420. if (maxaddr <= 0xffff) {
  1421. alen = 2;
  1422. dtype = '1'; /* S1 = 16-bit data */
  1423. etype = '9'; /* S9 = 16-bit end */
  1424. } else if (maxaddr <= 0xffffff) {
  1425. alen = 3;
  1426. dtype = '2'; /* S2 = 24-bit data */
  1427. etype = '8'; /* S8 = 24-bit end */
  1428. } else {
  1429. alen = 4;
  1430. dtype = '3'; /* S3 = 32-bit data */
  1431. etype = '7'; /* S7 = 32-bit end */
  1432. }
  1433. /* Write head record */
  1434. write_srecord(0, 2, 0, '0', NULL);
  1435. /* Write the progbits sections to the output file. */
  1436. list_for_each(s, sections) {
  1437. /* Skip non-progbits sections */
  1438. if (!(s->flags & TYPE_PROGBITS))
  1439. continue;
  1440. /* Skip zero-length sections */
  1441. if (s->length == 0)
  1442. continue;
  1443. addr = s->start;
  1444. length = s->length;
  1445. saa_rewind(s->contents);
  1446. while (length) {
  1447. chunk = 32 - (addr & 31);
  1448. if (length < chunk)
  1449. chunk = length;
  1450. saa_rnbytes(s->contents, buf, chunk);
  1451. write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
  1452. addr += chunk;
  1453. length -= chunk;
  1454. }
  1455. }
  1456. /* Write closing record */
  1457. write_srecord(0, alen, 0, etype, NULL);
  1458. }
  1459. const struct ofmt of_bin = {
  1460. "flat-form binary files (e.g. DOS .COM, .SYS)",
  1461. "bin",
  1462. "",
  1463. 0,
  1464. 64,
  1465. null_debug_arr,
  1466. &null_debug_form,
  1467. bin_stdmac,
  1468. bin_init,
  1469. null_reset,
  1470. nasm_do_legacy_output,
  1471. bin_out,
  1472. bin_deflabel,
  1473. bin_secname,
  1474. NULL,
  1475. bin_sectalign,
  1476. bin_segbase,
  1477. bin_directive,
  1478. bin_cleanup,
  1479. NULL /* pragma list */
  1480. };
  1481. const struct ofmt of_ith = {
  1482. "Intel hex",
  1483. "ith",
  1484. ".ith", /* really should have been ".hex"... */
  1485. OFMT_TEXT,
  1486. 64,
  1487. null_debug_arr,
  1488. &null_debug_form,
  1489. bin_stdmac,
  1490. ith_init,
  1491. null_reset,
  1492. nasm_do_legacy_output,
  1493. bin_out,
  1494. bin_deflabel,
  1495. bin_secname,
  1496. NULL,
  1497. bin_sectalign,
  1498. bin_segbase,
  1499. bin_directive,
  1500. bin_cleanup,
  1501. NULL /* pragma list */
  1502. };
  1503. const struct ofmt of_srec = {
  1504. "Motorola S-records",
  1505. "srec",
  1506. ".srec",
  1507. OFMT_TEXT,
  1508. 64,
  1509. null_debug_arr,
  1510. &null_debug_form,
  1511. bin_stdmac,
  1512. srec_init,
  1513. null_reset,
  1514. nasm_do_legacy_output,
  1515. bin_out,
  1516. bin_deflabel,
  1517. bin_secname,
  1518. NULL,
  1519. bin_sectalign,
  1520. bin_segbase,
  1521. bin_directive,
  1522. bin_cleanup,
  1523. NULL /* pragma list */
  1524. };
  1525. #endif /* #ifdef OF_BIN */