]> Shamusworld >> Repos - rmac/blob - object.c
Added new optimisation option "+op" which enforces PC relative mode (#123)
[rmac] / object.c
1 //
2 // RMAC - Reboot's Macro Assembler for all Atari computers
3 // OBJECT.C - Writing Object Files
4 // Copyright (C) 199x Landon Dyer, 2011-2020 Reboot and Friends
5 // RMAC derived from MADMAC v1.07 Written by Landon Dyer, 1986
6 // Source utilised with the kind permission of Landon Dyer
7 //
8
9 #include "object.h"
10 #include "6502.h"
11 #include "direct.h"
12 #include "dsp56k.h"
13 #include "error.h"
14 #include "mark.h"
15 #include "riscasm.h"
16 #include "sect.h"
17 #include "symbol.h"
18 #include "version.h"
19
20 //#define DEBUG_ELF
21
22 uint32_t symsize = 0;                   // Size of BSD/ELF symbol table
23 uint32_t strindx = 0x00000004;  // BSD/ELF string table index
24 uint8_t * strtable;                             // Pointer to the symbol string table
25 uint8_t * objImage;                             // Global object image pointer
26 int elfHdrNum[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
27 uint32_t extraSyms;
28
29 static uint16_t tdb_tab[] = {
30         0,                              // absolute
31         AL_TEXT,                // TEXT segment based
32         AL_DATA, 0,             // DATA segment based
33         AL_BSS                  // BSS segment based
34 };
35
36 uint32_t PRGFLAGS;      /* PRGFLAGS as defined in Atari Compendium Chapter 2
37 Definition              Bit(s)  Meaning
38 --------------- ------- --------------------------------------------------------
39 PF_FASTLOAD             0               If set, clear only the BSS area on program load,
40                                                 otherwise clear the entire heap.
41 PF_TTRAMLOAD    1               If set, the program may be loaded into alternative RAM,
42                                                 otherwise it must be loaded into standard RAM.
43 PF_TTRAMMEM             2               If set, the program's Malloc() requests may be satisfied
44                                                 from alternative RAM, otherwise they must be satisfied
45                                                 from standard RAM.
46 -                               3               Currently unused
47 See left.               4 & 5   If these bits are set to 0 (PF_PRIVATE), the processes'
48                                                 entire memory space will be considered private
49                                                 (when memory protection is enabled).If these bits are
50                                                 set to 1 (PF_GLOBAL), the processes' entire memory space
51                                                 will be readable and writable by any process (i.e.
52                                                 global). If these bits are set to 2 (PF_SUPERVISOR), the
53                                                 processes' entire memory space will only be readable and
54                                                 writable by itself and any other process in supervisor
55                                                 mode.If these bits are set to 3 (PF_READABLE), the
56                                                 processes' entire memory space will be readable by any
57                                                 application but only writable by itself.
58 -                               6-15    Currently unused
59 */
60
61 // Internal function prototypes
62 static void WriteLOD(void);
63 static void WriteP56(void);
64
65
66 //
67 // Add entry to symbol table (in ALCYON mode)
68 // If 'globflag' is 1, make the symbol global
69 // If in .PRG mode, adjust symbol values for fake link
70 //
71 uint8_t * AddSymEntry(register uint8_t * buf, SYM * sym, int globflag)
72 {
73         // Copy symbol name to buffer (first 8 chars or less)
74         register uint8_t * s = sym->sname;
75         register int i;
76         uint32_t extra = 0;
77
78         for(i=0; i<8 && *s; i++)
79                 *buf++ = *s++;
80
81         while (i++ < 8)
82                 *buf++ = '\0';
83
84         register uint16_t w1 = sym->sattr;
85         register uint16_t w = AL_DEFINED | tdb_tab[w1 & TDB];
86
87         if (prg_flag == 3)
88         {
89                 // Extended symbol - Check to see if symbol is larger than 8 characters
90                 // and write an extra 14 characters where the next symbol would be.
91                 // Modify the flag word for this
92                 if (*s)
93                 {
94                         //printf("%s '%i' - will write extended symbol\n", sym->sname,s[0]);
95                         uint8_t *buf2 = buf + 6;
96
97                         for(i=8; i<8+14 && *s; i++)
98                                 *buf2++ = *s++;
99
100                         while (i++ < 8 + 14)
101                                 *buf2++ = '\0';
102
103                         symsize += 14;
104                         w |= 0x48;
105                         extra = 14;
106                 }
107         }
108
109         //
110         // Construct and deposit flag word
111         //
112         // o  all symbols are AL_DEFINED
113         // o  install T/D/B/A base
114         //   o  install 'equated'
115         //   o  commons (COMMON) are AL_EXTERN, but not BSS
116         // o  exports (DEFINED) are AL_GLOBAL
117         // o  imports (~DEFINED) are AL_EXTERN
118         //
119         if (w1 & EQUATED)               // Equated
120                 w |= AL_EQUATED;
121
122         if (w1 & COMMON)
123         {
124                 w |= AL_EXTERN | AL_GLOBAL;     // Common symbol
125                 w &= ~AL_BSS;           // They're not BSS in Alcyon object files
126         }
127
128         if (w1 & DEFINED)
129         {
130                 if (globflag)           // Export the symbol
131                         w |= AL_GLOBAL;
132         }
133         else
134                 w |= AL_EXTERN;         // Imported symbol
135
136         SETBE16(buf, 0, w);
137         buf += 2;
138         register uint32_t z = (uint32_t)sym->svalue;
139
140         if (prg_flag)                   // Relocate value in .PRG segment
141         {
142                 w1 &= DATA | BSS;
143
144                 if (w1)
145                         z += sect[TEXT].sloc;
146
147                 if (w1 & BSS)
148                         z += sect[DATA].sloc;
149         }
150
151         SETBE32(buf, 0, z);             // Deposit symbol value
152         buf += 4;
153
154         symsize += 14;
155         buf += extra;
156
157         return buf;
158 }
159
160
161 //
162 // Add an entry to the BSD symbol table
163 //
164 uint8_t * AddBSDSymEntry(uint8_t * buf, SYM * sym, int globflag)
165 {
166         chptr = buf;                                            // Point to buffer for depositing longs
167         D_long(strindx);                                        // Deposit the symbol string index
168
169         uint16_t w1 = sym->sattr;                       // Obtain symbol attributes
170         uint32_t z = 0;                                         // Initialize resulting symbol flags
171
172         if (w1 & EQUATED)
173         {
174                 z = 0x02000000;                                 // Set equated flag
175         }
176         else
177         {
178                 switch (w1 & TDB)
179                 {
180                 case TEXT: z = 0x04000000; break;       // Set TEXT segment flag
181                 case DATA: z = 0x06000000; break;       // Set DATA segment flag
182                 case BSS : z = 0x08000000; break;       // Set BSS segment flag
183                 }
184         }
185
186         if (globflag)
187                 z |= 0x01000000;                                // Set global flag if requested
188
189         D_long(z);                                                      // Deposit symbol attribute
190         z = sym->svalue;                                        // Obtain symbol value
191
192         if (w1 & (DATA | BSS))
193                 z += sect[TEXT].sloc;                   // If DATA or BSS add TEXT segment size
194
195         if (w1 & BSS)
196                 z += sect[DATA].sloc;                   // If BSS add DATA segment size
197
198         D_long(z);                                                      // Deposit symbol value
199         strcpy(strtable + strindx, sym->sname);
200         strindx += strlen(sym->sname) + 1;      // Incr string index incl null terminate
201         buf += 12;                                                      // Increment buffer to next record
202         symsize += 12;                                          // Increment symbol table size
203
204         return buf;
205 }
206
207
208 //
209 // Add entry to ELF symbol table; if `globflag' is 1, make the symbol global
210 //
211 uint8_t * AddELFSymEntry(uint8_t * buf, SYM * sym, int globflag)
212 {
213         chptr = buf;
214         ch_size = 0;
215         D_long(strindx);                // st_name
216         D_long(sym->svalue);    // st_value
217         D_long(0);                              // st_size
218         uint8_t st_info = 0;
219
220         register WORD w1 = sym->sattr;
221
222         if (w1 & DEFINED)
223         {
224                 if (globflag)           // Export the symbol
225                         st_info |= 16;   //STB_GLOBAL (1<<4)
226         }
227         else if (w1 & (GLOBAL | REFERENCED))
228                 st_info |= 16;
229
230         D_byte(st_info);
231         D_byte(0);                              // st_other
232
233         uint16_t st_shndx = 0xFFF1;     // Assume absolute (equated) number
234
235         if (w1 & TEXT)
236                 st_shndx = elfHdrNum[ES_TEXT];
237         else if (w1 & DATA)
238                 st_shndx = elfHdrNum[ES_DATA];
239         else if (w1 & BSS)
240                 st_shndx = elfHdrNum[ES_BSS];
241         else if (globflag)
242                 st_shndx = 0;           // Global, not absolute
243
244         D_word(st_shndx);
245
246         strcpy(strtable + strindx, sym->sname);
247         strindx += strlen(sym->sname) + 1;      // Incr string index incl null terminate
248         symsize += 0x10;                                        // Increment symbol table size
249
250         return buf + 0x10;
251 }
252
253
254 //
255 // Helper function for ELF output
256 //
257 int DepositELFSectionHeader(uint8_t * ptr, uint32_t name, uint32_t type, uint32_t flags, uint32_t addr, uint32_t offset, uint32_t size, uint32_t link, uint32_t info, uint32_t addralign, uint32_t entsize)
258 {
259         chptr = ptr;
260         ch_size = 0;
261         D_long(name);
262         D_long(type);
263         D_long(flags);
264         D_long(addr);
265         D_long(offset);
266         D_long(size);
267         D_long(link);
268         D_long(info);
269         D_long(addralign);
270         D_long(entsize);
271         return 40;
272 }
273
274
275 //
276 // Deposit an entry in the Section Header string table
277 //
278 uint32_t DepositELFSHSTEntry(uint8_t ** pTable, const uint8_t * s)
279 {
280 #ifdef DEBUG_ELF
281 printf("DepositELFSHSTEntry: s = \"%s\"\n", s);
282 #endif
283         uint32_t strSize = strlen(s);
284         strcpy(*pTable, s);
285         *pTable += strSize + 1;
286         return strSize + 1;
287 }
288
289
290 //
291 // Deposit a symbol table entry in the ELF Symbol Table
292 //
293 uint32_t DepositELFSymbol(uint8_t * ptr, uint32_t name, uint32_t addr, uint32_t size, uint8_t info, uint8_t other, uint16_t shndx)
294 {
295         chptr = ptr;
296         ch_size = 0;
297         D_long(name);
298         D_long(addr);
299         D_long(size);
300         *chptr++ = info;
301         *chptr++ = other;
302         D_word(shndx);
303         return 16;
304 }
305
306
307 //
308 // Write an object file to the passed in file descriptor
309 // N.B.: Return value is ignored...
310 //
311 int WriteObject(int fd)
312 {
313         LONG tds;                               // TEXT & DATA segment size
314         int i;                                  // Temporary int
315         CHUNK * cp;                             // Chunk (for gather)
316         uint8_t * buf;                  // Scratch area
317         uint8_t * p;                    // Temporary ptr
318         LONG trsize, drsize;    // Size of relocations
319         uint32_t unused;                // For supressing 'write' warnings
320
321         if (verb_flag)
322         {
323                 printf("TEXT segment: %d bytes\n", sect[TEXT].sloc);
324                 printf("DATA segment: %d bytes\n", sect[DATA].sloc);
325                 printf("BSS  segment: %d bytes\n", sect[BSS].sloc);
326         }
327
328         // Write requested object file...
329         if ((obj_format == BSD) || ((obj_format == ALCYON) && (prg_flag == 0)))
330         {
331                 ch_size = 0;
332
333                 // Force BSD format (if it was ALCYON format)
334                 obj_format = BSD;
335
336                 if (verb_flag)
337                 {
338                         printf("Total       : %d bytes\n", sect[TEXT].sloc + sect[DATA].sloc + sect[BSS].sloc);
339                 }
340
341                 sy_assign(NULL, NULL);                                          // Assign index numbers to the symbols
342                 tds = sect[TEXT].sloc + sect[DATA].sloc;        // Get size of TEXT and DATA segment
343                 buf = malloc(0x800000);                                         // Allocate 8MB object file image memory
344
345                 if (buf == NULL)
346                 {
347                         error("cannot allocate object file memory (in BSD mode)");
348                         return ERROR;
349                 }
350
351                 memset(buf, 0, 0x800000);               // Clear allocated memory
352                 objImage = buf;                                 // Set global object image pointer
353                 strtable = malloc(0x200000);    // Allocate 2MB string table buffer
354
355                 if (strtable == NULL)
356                 {
357                         free(buf);
358                         error("cannot allocate string table memory (in BSD mode)");
359                         return ERROR;
360                 }
361
362                 memset(strtable, 0, 0x200000);  // Clear allocated memory
363
364                 // Build object file header
365                 chptr = buf;                                    // Base of header (for D_foo macros)
366                 ch_size = 0;
367                 challoc = 0x800000;
368                 D_long(0x00000107);                             // Magic number
369                 D_long(sect[TEXT].sloc);                // TEXT size
370                 D_long(sect[DATA].sloc);                // DATA size
371                 D_long(sect[BSS].sloc);                 // BSS size
372                 D_long(0x00000000);                             // Symbol size
373                 D_long(0x00000000);                             // First entry (0L)
374                 D_long(0x00000000);                             // TEXT relocation size
375                 D_long(0x00000000);                             // DATA relocation size
376
377                 // Construct TEXT and DATA segments (without relocation changes)
378                 p = buf + BSDHDRSIZE;
379
380                 for(i=TEXT; i<=DATA; i++)
381                 {
382                         for(cp=sect[i].sfcode; cp!=NULL; cp=cp->chnext)
383                         {
384                                 memcpy(p, cp->chptr, cp->ch_size);
385                                 p += cp->ch_size;
386                         }
387                 }
388
389                 // Do relocation tables (and make changes to segment data)
390                 p = buf + BSDHDRSIZE + tds;             // Move obj image ptr to reloc info
391                 trsize = MarkBSDImage(p, tds, sect[TEXT].sloc, TEXT);// Do TEXT relocation table
392                 chptr = buf + 0x18;                             // Point to relocation hdr entry
393                 D_long(trsize);                                 // Write the relocation table size
394
395                 // Move obj image ptr to reloc info
396                 p = buf + BSDHDRSIZE + tds + trsize;
397                 drsize = MarkBSDImage(p, tds, sect[TEXT].sloc, DATA);// Do DATA relocation table
398                 chptr = buf + 0x1C;                             // Point to relocation hdr entry
399                 D_long(drsize);                                 // Write the relocation table size
400
401                 // Point to start of symbol table
402                 p = buf + BSDHDRSIZE + tds + trsize + drsize;
403                 sy_assign(p, AddBSDSymEntry);   // Build symbol and string tables
404                 chptr = buf + 0x10;                             // Point to sym table size hdr entry
405                 D_long(symsize);                                // Write the symbol table size
406
407                 // Point to string table
408                 p = buf + BSDHDRSIZE + tds + trsize + drsize + symsize;
409                 memcpy(p, strtable, strindx);   // Copy string table to object image
410                 chptr = p;                                              // Point to string table size long
411                 D_long(strindx);                                // Write string table size
412
413                 // Write the BSD object file from the object image buffer
414                 unused = write(fd, buf, BSDHDRSIZE + tds + trsize + drsize + symsize + strindx + 4);
415
416                 if (verb_flag)
417                 {
418                         printf("TextRel size: %d bytes\n", trsize);
419                         printf("DataRel size: %d bytes\n", drsize);
420                 }
421
422                 if (buf)
423                 {
424                         free(strtable);                         // Free allocated memory
425                         free(buf);                                      // Free allocated memory
426                 }
427         }
428         else if (obj_format == ALCYON)
429         {
430                 ch_size = 0;
431
432                 if (verb_flag)
433                 {
434                         if (prg_flag)
435                                 printf("TOS header  : 28 bytes\n");
436
437                         printf("Total       : %d bytes\n", sect[TEXT].sloc + sect[DATA].sloc + sect[BSS].sloc + (prg_flag ? 28 : 0));
438                 }
439
440                 // Assign index numbers to the symbols, get # of symbols (we assume
441                 // that all symbols can potentially be extended, hence the x28)
442                 // (To clarify: 28 bytes is the size of an extended symbol)
443                 uint32_t symbolMaxSize = sy_assign(NULL, NULL) * 28;
444
445                 // Alloc memory for header + text + data, symbol and relocation
446                 // information construction.
447                 tds = sect[TEXT].sloc + sect[DATA].sloc;
448                 buf = malloc(HDRSIZE + tds + symbolMaxSize);
449
450                 // Build object file header just before the text+data image
451                 chptr = buf;                            // -> base of header
452                 ch_size = 0;
453                 challoc = HDRSIZE + tds + symbolMaxSize;
454                 D_word(0x601A);                         // 00 - magic number
455                 D_long(sect[TEXT].sloc);        // 02 - TEXT size
456                 D_long(sect[DATA].sloc);        // 06 - DATA size
457                 D_long(sect[BSS].sloc);         // 0A - BSS size
458                 D_long(0);                                      // 0E - symbol table size (filled later)
459                 D_long(0);                                      // 12 - stack size (unused)
460                 D_long(PRGFLAGS);                       // 16 - PRGFLAGS
461                 D_word(0);                                      // 1A - relocation information exists
462
463                 // Construct text and data segments; fixup relocatable longs in .PRG
464                 // mode; finally write the header + text + data
465                 p = buf + HDRSIZE;
466
467                 for(i=TEXT; i<=DATA; i++)
468                 {
469                         for(cp=sect[i].sfcode; cp!=NULL; cp=cp->chnext)
470                         {
471                                 memcpy(p, cp->chptr, cp->ch_size);
472                                 p += cp->ch_size;
473                         }
474                 }
475
476                 // Do a first pass on the Alcyon image, if in PRG mode
477                 if (prg_flag)
478                         MarkImage(buf + HDRSIZE, tds, sect[TEXT].sloc, 0);
479
480                 // Construct symbol table and update the header entry, if necessary
481                 if (prg_flag > 1)
482                 {
483                         // sy_assign with AddSymEntry updates symsize (stays 0 otherwise)
484                         sy_assign(buf + HDRSIZE + tds, AddSymEntry);
485                         chptr = buf + 0x0E;                     // Point to symbol table size entry
486                         D_long(symsize);
487
488                         if (verb_flag)
489                                 printf("Symbol table: %d bytes\n", symsize);
490                 }
491
492                 // Write out the header + text & data + symbol table (if any)
493                 unused = write(fd, buf, HDRSIZE + tds + symsize);
494
495                 // Construct and write relocation information; the size of it changes if
496                 // we're writing a RELMODed executable. N.B.: Destroys buffer!
497                 tds = MarkImage(buf, tds, sect[TEXT].sloc, 1);
498                 unused = write(fd, buf, tds);
499         }
500         else if (obj_format == ELF)
501         {
502                 // Allocate 6MB object file image memory
503                 buf = malloc(0x600000);
504
505                 if (buf == NULL)
506                 {
507                         error("cannot allocate object file memory (in ELF mode)");
508                         return ERROR;
509                 }
510
511                 memset(buf, 0, 0x600000);
512                 objImage = buf;                                 // Set global object image pointer
513                 strtable = malloc(0x200000);    // Allocate 2MB string table buffer
514
515                 if (strtable == NULL)
516                 {
517                         error("cannot allocate string table memory (in ELF mode)");
518                         return ERROR;
519                 }
520
521                 memset(strtable, 0, 0x200000);
522
523                 // This is pretty much a first pass at this shite, so there's room for
524                 // improvement. :-P
525                 uint8_t headers[4 * 10 * 10];   // (DWORD * 10) = 1 hdr, 10 entries
526                 int headerSize = 0;
527                 uint8_t shstrtab[128];                  // The section header string table proper
528                 uint32_t shstTab[9];                    // Index into shstrtab for strings
529                 uint8_t * shstPtr = shstrtab;   // Temp pointer
530                 uint32_t shstSize = 0;
531                 int numEntries = 4;                             // There are always at *least* 4 sections
532                 int shstIndex = 1;                              // The section where the shstrtab lives
533                 int elfSize = 0;                                // Size of the ELF object
534                 // Clear the header numbers
535                 memset(elfHdrNum, 0, 9 * sizeof(int));
536
537                 //
538                 // First step is to see what sections need to be made; we also
539                 // construct the section header string table here at the same time.
540                 //
541                 shstTab[ES_NULL] = shstSize;
542                 shstSize += DepositELFSHSTEntry(&shstPtr, "");
543                 shstTab[ES_SHSTRTAB] = shstSize;
544                 shstSize += DepositELFSHSTEntry(&shstPtr, ".shstrtab");
545                 shstTab[ES_SYMTAB] = shstSize;
546                 shstSize += DepositELFSHSTEntry(&shstPtr, ".symtab");
547                 shstTab[ES_STRTAB] = shstSize;
548                 shstSize += DepositELFSHSTEntry(&shstPtr, ".strtab");
549
550                 if (sect[TEXT].sloc > 0)
551                 {
552                         elfHdrNum[ES_TEXT] = shstIndex;
553                         shstTab[ES_TEXT] = shstSize;
554                         shstSize += DepositELFSHSTEntry(&shstPtr, ".text");
555                         shstIndex++;
556                         numEntries++;
557                 }
558
559                 if (sect[DATA].sloc > 0)
560                 {
561                         elfHdrNum[ES_DATA] = shstIndex;
562                         shstTab[ES_DATA] = shstSize;
563                         shstSize += DepositELFSHSTEntry(&shstPtr, ".data");
564                         shstIndex++;
565                         numEntries++;
566                 }
567
568                 if (sect[BSS].sloc > 0)
569                 {
570                         elfHdrNum[ES_BSS] = shstIndex;
571                         shstTab[ES_BSS] = shstSize;
572                         shstSize += DepositELFSHSTEntry(&shstPtr, ".bss");
573                         shstIndex++;
574                         numEntries++;
575                 }
576
577                 if (sect[TEXT].relocs > 0)
578                 {
579                         elfHdrNum[ES_RELATEXT] = shstIndex;
580                         shstTab[ES_RELATEXT] = shstSize;
581                         shstSize += DepositELFSHSTEntry(&shstPtr, ".relaTEXT");
582                         shstIndex++;
583                         numEntries++;
584                 }
585
586                 if (sect[DATA].relocs > 0)
587                 {
588                         elfHdrNum[ES_RELADATA] = shstIndex;
589                         shstTab[ES_RELADATA] = shstSize;
590                         shstSize += DepositELFSHSTEntry(&shstPtr, ".relaDATA");
591                         shstIndex++;
592                         numEntries++;
593                 }
594
595                 elfHdrNum[ES_SHSTRTAB] = shstIndex + 0;
596                 elfHdrNum[ES_SYMTAB]   = shstIndex + 1;
597                 elfHdrNum[ES_STRTAB]   = shstIndex + 2;
598
599 #ifdef DEBUG_ELF
600 printf("ELF shstrtab size: %i bytes. Entries:\n", shstSize);
601 for(int j=0; j<i; j++)
602         printf("\"%s\"\n", shstrtab + shstTab[j]);
603 #endif
604
605                 // Construct ELF header
606                 // If you want to make any sense out of this you'd better take a look
607                 // at Executable and Linkable Format on Wikipedia.
608                 chptr = buf;
609                 ch_size = 0;
610                 challoc = 0x600000;
611                 D_long(0x7F454C46); // 00 - "<7F>ELF" Magic Number
612                 D_byte(0x01); // 04 - 32 vs 64 (1 = 32, 2 = 64)
613                 D_byte(0x02); // 05 - Endianness (1 = LE, 2 = BE)
614                 D_byte(0x01); // 06 - Original version of ELF (set to 1)
615                 D_byte(0x00); // 07 - Target OS ABI (0 = System V)
616                 D_byte(0x00); // 08 - ABI Extra (unneeded)
617                 D_byte(0x00); // 09 - Pad bytes
618                 D_word(0x00);
619                 D_long(0x00);
620                 D_word(0x01); // 10 - ELF Type (1 = relocatable)
621                 D_word(0x04); // 12 - Architecture (EM_68K = 4, Motorola M68K family)
622                 D_long(0x01); // 14 - Version (1 = original ELF)
623                 D_long(0x00); // 18 - Entry point virtual address (unneeded)
624                 D_long(0x00); // 1C - Program header table offset (unneeded)
625                 D_long(0x00); // 20 - Section header table offset (to be determined)
626
627                 if (0)
628                 {
629                         // Specifically for 68000 CPU
630                         D_long(0x01000000) // 24 - Processor-specific flags - EF_M68K_M68000
631                 }
632                 else
633                 {
634                         // CPUs other than 68000 (68020...)
635                         D_long(0); // 24 - Processor-specific flags (ISA dependent)
636                 }
637
638                 D_word(0x0034); // 28 - ELF header size in bytes
639                 D_word(0); // 2A - Program header table entry size
640                 D_word(0); // 2C - Program header table entry count
641                 D_word(0x0028); // 2E - Section header entry size - 40 bytes for ELF32
642                 D_word(numEntries); // 30 - Section header table entry count
643                 D_word(shstIndex); // 32 - Section header string table index
644
645                 elfSize += 0x34;
646
647                 // Deposit section header 0 (NULL)
648                 headerSize += DepositELFSectionHeader(headers + headerSize, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
649
650                 int textLoc = elfSize;
651
652                 // Construct TEXT section, if any
653                 if (sect[TEXT].sloc > 0)
654                 {
655                         headerSize += DepositELFSectionHeader(headers + headerSize, shstTab[ES_TEXT], 1, 6, 0, elfSize, sect[TEXT].sloc, 0, 0, largestAlign[0], 0);
656
657                         for(CHUNK * cp=sect[TEXT].sfcode; cp!=NULL; cp=cp->chnext)
658                         {
659                                 memcpy(buf + elfSize, cp->chptr, cp->ch_size);
660                                 elfSize += cp->ch_size;
661                         }
662
663                         // Pad for next section (LONG boundary)
664                         elfSize = (elfSize + 3) & ~3;
665                 }
666
667                 int dataLoc = elfSize;
668
669                 // Construct DATA section, if any
670                 if (sect[DATA].sloc > 0)
671                 {
672                         headerSize += DepositELFSectionHeader(headers + headerSize, shstTab[ES_DATA], 1, 3, 0, elfSize, sect[DATA].sloc, 0, 0, largestAlign[1], 0);
673
674                         for(CHUNK * cp=sect[DATA].sfcode; cp!=NULL; cp=cp->chnext)
675                         {
676                                 memcpy(buf + elfSize, cp->chptr, cp->ch_size);
677                                 elfSize += cp->ch_size;
678                         }
679
680                         // Pad for next section (LONG boundary)
681                         elfSize = (elfSize + 3) & ~3;
682                 }
683
684                 // Construct BSS section, if any
685                 if (sect[BSS].sloc > 0)
686                 {
687                         headerSize += DepositELFSectionHeader(headers + headerSize, shstTab[ES_BSS], 8, 3, 0, elfSize, sect[BSS].sloc, 0, 0, largestAlign[2], 0);
688                 }
689
690                 int textrelLoc = headerSize;
691
692                 // Add headers for relocated sections, if any...
693                 if (sect[TEXT].relocs > 0)
694                         headerSize += DepositELFSectionHeader(headers + headerSize, shstTab[ES_RELATEXT], 4, 0x00, 0, 0, 0, elfHdrNum[ES_SYMTAB], elfHdrNum[ES_TEXT], 4, 0x0C);
695
696                 int datarelLoc = headerSize;
697
698                 if (sect[DATA].relocs > 0)
699                         headerSize += DepositELFSectionHeader(headers + headerSize, shstTab[ES_RELADATA], 4, 0x40, 0, 0, 0, elfHdrNum[ES_SYMTAB], elfHdrNum[ES_DATA], 4, 0x0C);
700
701                 // Add shstrtab
702                 headerSize += DepositELFSectionHeader(headers + headerSize, shstTab[ES_SHSTRTAB], 3, 0, 0, elfSize, shstSize, 0, 0, 1, 0);
703                 memcpy(buf + elfSize, shstrtab, shstSize);
704                 elfSize += shstSize;
705                 // Pad for next section (LONG boundary)
706                 elfSize = (elfSize + 3) & ~3;
707
708                 // Add section headers
709                 int headerLoc = elfSize;
710                 chptr = buf + 0x20;             // Set section header offset in ELF header
711                 D_long(headerLoc);
712                 elfSize += (4 * 10) * numEntries;
713
714                 // Add symbol table & string table
715                 int symtabLoc = elfSize;
716                 strindx = 0;    // Make sure we start at the beginning...
717                 elfSize += DepositELFSymbol(buf + elfSize, 0, 0, 0, 0, 0, 0);
718                 *strtable = 0;
719                 strindx++;
720                 extraSyms = 1;
721
722                 if (sect[TEXT].sloc > 0)
723                 {
724                         elfSize += DepositELFSymbol(buf + elfSize, 0, 0, 0, 3, 0, elfHdrNum[ES_TEXT]);
725                         extraSyms++;
726                 }
727
728                 if (sect[DATA].sloc > 0)
729                 {
730                         elfSize += DepositELFSymbol(buf + elfSize, 0, 0, 0, 3, 0, elfHdrNum[ES_DATA]);
731                         extraSyms++;
732                 }
733
734                 if (sect[BSS].sloc > 0)
735                 {
736                         elfSize += DepositELFSymbol(buf + elfSize, 0, 0, 0, 3, 0, elfHdrNum[ES_BSS]);
737                         extraSyms++;
738                 }
739
740                 int numSymbols = sy_assign_ELF(buf + elfSize, AddELFSymEntry);
741                 elfSize += numSymbols * 0x10;
742
743                 // String table
744                 int strtabLoc = elfSize;
745                 memcpy(buf + elfSize, strtable, strindx);
746                 elfSize += strindx;
747                 // Pad for next section (LONG boundary)
748                 elfSize = (elfSize + 3) & ~3;
749
750                 headerSize += DepositELFSectionHeader(headers + headerSize, shstTab[ES_SYMTAB], 2, 0, 0, symtabLoc, (numSymbols + extraSyms) * 0x10, shstIndex + 2, firstglobal + extraSyms, 4, 0x10);
751                 headerSize += DepositELFSectionHeader(headers + headerSize, shstTab[ES_STRTAB], 3, 0, 0, strtabLoc, strindx, 0, 0, 1, 0);
752
753                 // Add relocation tables, if any (no need to align after these, they're
754                 // already on DWORD boundaries)
755                 if (sect[TEXT].relocs > 0)
756                 {
757                         uint32_t textrelSize = CreateELFRelocationRecord(buf + elfSize, buf + textLoc, TEXT);
758                         // Deposit offset & size, now that we know them
759                         chptr = headers + textrelLoc + 0x10;
760                         D_long(elfSize);
761                         D_long(textrelSize);
762                         elfSize += textrelSize;
763                 }
764
765                 if (sect[DATA].relocs > 0)
766                 {
767                         uint32_t datarelSize = CreateELFRelocationRecord(buf + elfSize, buf + dataLoc, DATA);
768                         // Deposit offset & size, now that we know them
769                         chptr = headers + datarelLoc + 0x10;
770                         D_long(elfSize);
771                         D_long(datarelSize);
772                         elfSize += datarelSize;
773                 }
774
775                 // Copy headers into the object
776                 memcpy(buf + headerLoc, headers, headerSize);
777
778                 // Finally, write out the object
779                 unused = write(fd, buf, elfSize);
780
781                 // Free allocated memory
782                 if (buf)
783                 {
784                         free(buf);
785                         free(strtable);
786                 }
787         }
788         else if (obj_format == XEX)
789         {
790                 // Just write the object file
791                 m6502obj(fd);
792         }
793         else if (obj_format == P56 || obj_format == LOD)
794         {
795                 // Allocate 6MB object file image memory
796                 uint8_t * buf = malloc(0x600000);
797
798                 if (buf == NULL)
799                         return error("cannot allocate object file memory (in P56/LOD mode)");
800
801 //              objImage = buf;                                 // Set global object image pointer
802
803                 memset(buf, 0, 0x600000);               // Clear allocated memory
804
805                 // Iterate through DSP ram buffers
806                 chptr = buf;                                    // -> base of header
807                 ch_size = 0;
808                 challoc = 0x600000;
809
810                 if (obj_format == LOD)
811                         WriteLOD();
812                 else
813                         WriteP56();
814
815                 // Write all the things \o/
816                 unused = write(fd, buf, chptr - buf);
817
818                 if (buf)
819                         free(buf);
820         }
821         else if (obj_format == RAW)
822         {
823                 if (!org68k_active)
824                 {
825                         return error("cannot output absolute binary without a starting address (.org or command line)");
826                 }
827
828                 // Alloc memory for text + data construction.
829                 tds = sect[TEXT].sloc + sect[DATA].sloc;
830                 buf = malloc(tds);
831                 chptr = buf;
832
833                 // Construct text and data segments; fixup relocatable longs;
834                 // finally write the text + data
835
836                 p = buf;
837                 objImage = buf;                                 // Set global object image pointer
838
839                 for (i = TEXT; i <= DATA; i++)
840                 {
841                         for (cp = sect[i].sfcode; cp != NULL; cp = cp->chnext)
842                         {
843                                 memcpy(p, cp->chptr, cp->ch_size);
844                                 p += cp->ch_size;
845                         }
846                 }
847
848                 if (MarkABSImage(buf, tds, sect[TEXT].sloc, TEXT) != OK)  // Do TEXT relocation table
849                 {
850                         return ERROR;
851                 }
852                 if (MarkABSImage(buf, tds, sect[TEXT].sloc, DATA) != OK) // Do DATA relocation table
853                 {
854                         return ERROR;
855                 }
856
857                 // Write out the header + text & data + symbol table (if any)
858                 unused = write(fd, buf, tds);
859
860         }
861         return 0;
862 }
863
864
865 static void WriteLOD(void)
866 {
867         D_printf("_START %s 0000 0000 0000 RMAC %01i.%01i.%01i\n\n", firstfname, MAJOR, MINOR, PATCH);
868
869         for(DSP_ORG * l=&dsp_orgmap[0]; l<dsp_currentorg; l++)
870         {
871                 if (l->end != l->start)
872                 {
873                         switch (l->memtype)
874                         {
875                         case ORG_P: D_printf("_DATA P %.4X\n", l->orgadr); break;
876                         case ORG_X: D_printf("_DATA X %.4X\n", l->orgadr); break;
877                         case ORG_Y: D_printf("_DATA Y %.4X\n", l->orgadr); break;
878                         case ORG_L: D_printf("_DATA L %.4X\n", l->orgadr); break;
879                         default:
880                                 error("Internal error: unknown DSP56001 org'd section");
881                                 return;
882                         }
883
884                         CHUNK * cp = l->chunk;
885                         uint8_t * p_chunk = l->start;
886                         uint8_t * p_chunk_end = p_chunk;
887                         uint32_t j = 0;
888
889                         while (p_chunk_end != l->end)
890                         {
891                                 if (l->end < (cp->chptr + cp->ch_size) && l->end > cp->chptr)
892                                 {
893                                         // If the end of the section is inside the current chunk, just dump everything and stop
894                                         p_chunk_end = l->end;
895                                 }
896                                 else
897                                 {
898                                         // If the end of the section is not inside the current chunk, just dump everything from the current chunk and move on to the next
899                                         p_chunk_end = cp->chptr + cp->ch_size;
900                                 }
901
902                                 uint32_t count = (uint32_t)(p_chunk_end - p_chunk);
903
904                                 for(uint32_t i=0; i<count; i+=3)
905                                 {
906                                         if ((j & 7) != 7)
907                                         {
908                                                 D_printf("%.6X ", (((p_chunk[0] << 8) | p_chunk[1]) << 8) | p_chunk[2]);
909                                         }
910                                         else
911                                         {
912                                                 D_printf("%.6X\n", (((p_chunk[0] << 8) | p_chunk[1]) << 8) | p_chunk[2]);
913                                         }
914
915                                         p_chunk += 3;
916                                         j++;
917                                 }
918
919                                 cp = cp->chnext;        // Advance chunk
920
921                                 if (cp != NULL)
922                                         p_chunk = cp->chptr;    // Set dump pointer to start of this chunk
923                         }
924
925                         if ((j & 7) != 0)
926                                 D_printf("\n");
927                 }
928         }
929
930         // Dump the symbol table into the buf
931         DumpLODSymbols();
932
933         D_printf("\n_END %.4X\n", dsp_orgmap[0].orgadr);
934 }
935
936
937 static void WriteP56(void)
938 {
939         for(DSP_ORG * l=&dsp_orgmap[0]; l<dsp_currentorg; l++)
940         {
941                 if (l->end == l->start)
942                         continue;
943
944                 if ((l->memtype < ORG_P) || (l->memtype > ORG_L))
945                 {
946                         error("Internal error: unknown DSP56001 org'd section");
947                         return;
948                 }
949
950                 CHUNK * cp = l->chunk;
951                 uint8_t * p_chunk = l->start;
952                 uint8_t * p_chunk_end = p_chunk;
953
954                 // Memory type (P, X, Y or L)
955                 D_dsp(l->memtype);
956
957                 // Chunk start address (in DSP words)
958                 D_dsp(l->orgadr);
959
960                 // Chunk length (in DSP words)
961                 // We'll fill this field after we write the chunk so we can calculate
962                 // how long it is (so if the chunk is split into different CHUNKs we
963                 // can deal with this during copy)
964                 uint8_t * p_buf_len = chptr;
965                 chptr += 3;
966
967                 // The chunk itself
968                 uint32_t chunk_size = 0;
969
970                 while (p_chunk_end != l->end)
971                 {
972                         if (l->end < (cp->chptr + cp->ch_size) && l->end > cp->chptr)
973                         {
974                                 // If the end of the section is inside the current chunk, just
975                                 // dump everything and stop
976                                 p_chunk_end = l->end;
977                         }
978                         else
979                         {
980                                 // If the end of the section is not inside the current chunk,
981                                 // just dump everything from the current chunk and move on to
982                                 // the next
983                                 p_chunk_end = cp->chptr + cp->ch_size;
984                         }
985
986                         uint32_t current_chunk_size = p_chunk_end - p_chunk;
987                         chunk_size += current_chunk_size;
988                         memcpy(chptr, p_chunk, current_chunk_size);
989                         chptr += current_chunk_size;
990
991                         cp = cp->chnext;        // Advance chunk
992
993                         if (cp != NULL)
994                                 p_chunk = cp->chptr;    // Set dump pointer to start of this chunk
995                 }
996
997                 // Now we can mark the chunk's length (DSP word size is 24-bits, so
998                 // the byte count needs to be divided by 3)
999                 SETBE24(p_buf_len, chunk_size / 3);
1000         }
1001 }
1002