Debian Codegraph @

src/output.c

raw symbols SCIP
1 // ACME - a crossassembler for producing 6502/65c02/65816/65ce02 code.
2 // Copyright (C) 1998-2024 Marco Baye
3 // Have a look at "acme.c" for further info
4 //
5 // Output stuff
6 // 24 Nov 2007 Added possibility to suppress segment overlap warnings
7 // 25 Sep 2011 Fixed bug in !to (colons in filename could be interpreted as EOS)
8 // 5 Mar 2014 Fixed bug where setting *>0xffff resulted in hangups.
9 // 19 Nov 2014 Merged Johann Klasek's report listing generator patch
10 // 22 Sep 2015 Added big-endian output functions
11 // 20 Apr 2019 Prepared for "make segment overlap warnings into errors" later on
12 #include "output.h"
13 #include <stdlib.h> // for free()
14 #include <string.h> // for memset()
15 #include "cpu.h"
16 #include "global.h"
17
18
19 // wrapper fn for segment problems -> either warning or error
20 static void throwsegmentproblem(const char msg[])
21 {
22 if (config.strict_segments)
23 countorthrow_value_error(msg);
24 else
25 throw_finalpass_warning(msg);
26 }
27
28
29 // segment list stuff:
30
31
32 // structure for linked list of segment data
33 struct segment {
34 struct segment *next,
35 *prev;
36 intval_t start,
37 length;
38 };
39
40 // init head element of segment list
41 static void segmentlist_headinit(struct segment *list_head)
42 {
43 list_head->next = list_head;
44 list_head->prev = list_head;
45 }
46
47 // clear segment list
48 static void segmentlist_release(struct segment *list_head)
49 {
50 struct segment *next,
51 *tmp;
52
53 next = list_head->next;
54 while (next != list_head) {
55 tmp = next;
56 next = next->next;
57 free(tmp);
58 }
59 // re-init head element
60 segmentlist_headinit(list_head);
61 }
62
63 // link segment data into segment list
64 // segments are sorted first by start address and then by length, example:
65 // start $0400, length $0100
66 // start $0401, length $0100
67 // start $0401, length $0101
68 static void segmentlist_add(struct segment *list_head, intval_t start, intval_t length)
69 {
70 struct segment *new_segment,
71 *test_segment = list_head->next;
72
73 // init new segment
74 new_segment = safe_malloc(sizeof(*new_segment));
75 new_segment->start = start;
76 new_segment->length = length;
77 // use ring head as sentinel
78 list_head->start = start;
79 list_head->length = length + 1; // +1 to make sure sentinel exits loop
80 // walk ring to find correct spot
81 while ((test_segment->start < new_segment->start)
82 || ((test_segment->start == new_segment->start) && (test_segment->length < new_segment->length)))
83 test_segment = test_segment->next;
84 // link into ring
85 new_segment->next = test_segment;
86 new_segment->prev = test_segment->prev;
87 new_segment->next->prev = new_segment;
88 new_segment->prev->next = new_segment;
89 }
90
91 // check whether given address is inside one of the segments
92 static void segmentlist_check(struct segment *list_head, intval_t new_pc)
93 {
94 struct segment *test_segment = list_head->next;
95
96 // use list head as sentinel
97 list_head->start = new_pc + 1; // +1 to make sure sentinel exits loop
98 list_head->length = 1;
99 // search ring for matching entry
100 while (test_segment->start <= new_pc) {
101 if ((test_segment->start + test_segment->length) > new_pc) {
102 // TODO - include overlap size in error message!
103 throwsegmentproblem("Segment starts inside another one, overwriting it.");
104 return; // we found one problem, no need to go on looking for more
105 }
106 test_segment = test_segment->next;
107 }
108 }
109
110 // return new segment limit value according to the given address.
111 // just find the next segment start.
112 static intval_t segmentlist_findlimit(struct segment *list_head, intval_t new_pc)
113 {
114 struct segment *test_segment = list_head->next;
115
116 // search for smallest segment start address that
117 // is larger than given address
118 // use list head as sentinel
119 list_head->start = new_pc + 1;
120 while (test_segment->start <= new_pc)
121 test_segment = test_segment->next;
122 if (test_segment == list_head)
123 return OUTBUF_MAXSIZE;
124 else
125 return test_segment->start; // next segment limits this one
126 }
127
128
129 // general output stuff:
130
131
132 // structure for all output stuff:
133 struct output {
134 // output buffer stuff
135 char *buffer; // holds assembled code (size is needed_bufsize)
136 intval_t write_idx; // index of next write
137 intval_t lowest_written; // smallest address used
138 intval_t highest_written; // largest address used
139 intval_t forced_start_idx; // first index to go into output file
140 intval_t forced_limit_idx; // first index to not go into output file
141 struct {
142 intval_t start; // start of current segment (or NO_VALUE_GIVEN if none)
143 intval_t limit; // first address segment may NOT use
144 bits flags; // segment flags ("overlay" and "invisible", see header file)
145 struct segment list_head; // head element of doubly-linked ring list
146 } segm;
147 char xor; // output modifier
148 intval_t needed_bufsize; // calculated at end of each pass
149 };
150
151 // for offset assembly:
152 // struct to describe a pseudopc context (each label gets a pointer to this)
153 struct pseudopc {
154 struct pseudopc *outer; // next layer (to be able to "unpseudopc" labels by more than one level)
155 intval_t offset; // inner minus outer pc
156 };
157 static struct pseudopc outermost_pseudopc_context; // dummy struct when "!pseudopc" not in use
158 static struct pseudopc *pseudopc_current_context = &outermost_pseudopc_context; // current struct
159
160
161 // variables
162 static struct output default_output;
163 static struct output *out = &default_output; // FIXME - never changes! is the ptr a preparation for "assembling several different parts in one go"?
164 static intval_t program_counter; // current program counter (pseudopc value)
165 static int statement_size; // added to program counter after each statement
166 // "program_counter" differs substantially from "out->write_idx":
167 // - "write_idx" changes after each byte, "program_counter" only changes between statements
168 // (when "statement_size" gets added)
169 // - of course the values can be wildly different because of offset assembly
170 // - because "!pseudopc" can be nested and we need all offsets separately for
171 // the '&' operator anyway, we do not keep a total offset.
172
173 // report binary output
174 static void report_binary(char value)
175 {
176 if (report->bin_used == 0)
177 report->bin_address = out->write_idx; // remember address at start of line
178 if (report->bin_used < REPORT_BINBUFSIZE)
179 report->bin_buf[report->bin_used++] = value;
180 }
181
182
183 // complain about reaching another segment
184 static void breached_limit(int offending_offset)
185 {
186 // FIXME - find a way to make this a normal error instead of a serious one,
187 // so it can be suppressed until we are sure the program won't shrink any
188 // further:
189 if (offending_offset >= OUTBUF_MAXSIZE)
190 throw_serious_error("Reached memory limit.");
191 throwsegmentproblem("Segment reached another one, overwriting it."); // FIXME - add segment name to msg!
192 // now that we breached the current limit, find the next one
193 out->segm.limit = segmentlist_findlimit(&out->segm.list_head, offending_offset);
194 }
195
196
197 // function ptr to write byte into output buffer (points to real_output or no_output)
198 void (*output_byte)(intval_t byte);
199
200 // test for "has user set program counter yet?"
201 #define PC_NOT_SET (program_counter == NO_VALUE_GIVEN)
202
203 // send low byte to output buffer and remember to later increase program counter
204 static void real_output(intval_t byte)
205 {
206 // TODO - add additional check for current segment's "limit" value
207 // did we reach next segment?
208 if (out->write_idx >= out->segm.limit)
209 breached_limit(out->write_idx);
210 // new minimum address?
211 if (out->write_idx < out->lowest_written)
212 out->lowest_written = out->write_idx;
213 // new maximum address?
214 if (out->write_idx > out->highest_written)
215 out->highest_written = out->write_idx;
216 // tell report listing about byte
217 if (report->fd)
218 report_binary(byte & 0xff); // file for reporting
219 // write byte to output buffer
220 if (out->buffer) {
221 if (out->write_idx >= out->needed_bufsize) {
222 //fprintf(stderr, "write idx=0x%x, needed bufsize=0x%x\n", out->write_idx, out->needed_bufsize);
223 throw_serious_error("Output buffer overrun.");
224 // FIXME - change this to BUG and add code to make sure it does not happen!
225 // or maybe at least enlarge the buffer by 16 bytes and place a canary in
226 // it so we can do a sanity check at the end!
227 // (but that only helps for sequential writes without holes...)
228 }
229 out->buffer[out->write_idx] = (byte & 0xff) ^ out->xor;
230 }
231 // advance pointer
232 out->write_idx++;
233 ++statement_size; // count this byte
234 }
235
236 // throw "program counter not defined" error and then use a fake pc so this does
237 // not happen again
238 static void complain_and_use_dummy_pc(void)
239 {
240 throw_error(exception_pc_undefined);
241 programcounter_set(cpu_current_type->dummy_pc, 0); // 0 = no flags
242 }
243
244 // throw error (pc undefined) and use fake pc from now on
245 static void no_output(intval_t byte)
246 {
247 complain_and_use_dummy_pc(); // this lets output_byte point to the real_output
248 output_byte(byte); // try again
249 }
250
251
252 // skip over some bytes in output buffer without starting a new segment
253 // (used by "!skip")
254 void output_skip(int size)
255 {
256 if (size < 1) {
257 // ok for zero, but why is there no error message
258 // output for negative values?
259 // ...because caller should have caught those!
260 // FIXME - add BUG() for those!
261 return;
262 }
263
264 // check whether ptr undefined
265 if (PC_NOT_SET)
266 complain_and_use_dummy_pc();
267
268 // removed all address checks because "skip" does not actually write!
269 // if a source code starts/ends with "!skip 20", older versions included that
270 // part in the output file, which is stupid and contradicts the fact that empty
271 // segments at the start/end are not included either!
272
273 // advance ptrs
274 out->write_idx += size;
275 statement_size += size; // count bytes so PC will be adjusted correctly after this
276 }
277
278
279 // remember current outbuf index as start/limit of output file
280 void outbuf_set_outfile_start(void)
281 {
282 // check whether ptr undefined
283 if (PC_NOT_SET)
284 complain_and_use_dummy_pc();
285 out->forced_start_idx = out->write_idx;
286 }
287 void outbuf_set_outfile_limit(void)
288 {
289 // check whether ptr undefined
290 if (PC_NOT_SET)
291 complain_and_use_dummy_pc();
292 out->forced_limit_idx = out->write_idx;
293 }
294
295
296 // called once on startup, inits structs
297 void output_init(void)
298 {
299 // init ring list of segments
300 segmentlist_headinit(&out->segm.list_head);
301 // init the one field not initialized by output_passinit:
302 out->needed_bufsize = NO_VALUE_GIVEN;
303 }
304
305 // called before each pass, clears segment list and disables output
306 void output_passinit(void)
307 {
308 // init output struct:
309 if (pass.flags.generate_output) {
310 // we are supposed to actually generate correct output, so
311 // allocate and init output buffer:
312 if (out->needed_bufsize == NO_VALUE_GIVEN) {
313 // this is not an error. it happens when the source code
314 // does not create a single output byte, for example if
315 // someone uses ACME simply for "!info 3456 / 78"
316 out->needed_bufsize = 16; // actually 1 would suffice...
317 }
318 if (out->needed_bufsize > OUTBUF_MAXSIZE) {
319 throw_serious_error("Output buffer size exceeds maximum.");
320 }
321 //fprintf(stderr, "Allocating outbuf of size 0x%06x.\n", out->needed_bufsize);
322 out->buffer = safe_malloc(out->needed_bufsize);
323 // fill output buffer with initial byte value
324 if (config.mem_init_value == NO_VALUE_GIVEN) {
325 memset(out->buffer, 0, out->needed_bufsize); // default is zero
326 } else {
327 memset(out->buffer, config.mem_init_value & 0xff, out->needed_bufsize);
328 }
329 } else {
330 out->buffer = NULL;
331 }
332 // program counter has not been set yet, so the write index is also unknown:
333 out->write_idx = NO_VALUE_GIVEN; // must be same value as pc on pass init!
334 // invalidate start and end (first byte actually written will fix them)
335 out->lowest_written = OUTBUF_MAXSIZE; // FIXME - add code so OUTBUF_MAXSIZE-1 is a hard limit!
336 out->highest_written = -1;
337 // no overrides for start and end yet:
338 out->forced_start_idx = NO_VALUE_GIVEN;
339 out->forced_limit_idx = NO_VALUE_GIVEN;
340 // not in a segment
341 out->segm.start = NO_VALUE_GIVEN; // TODO - "no active segment" could be made a segment flag!
342 out->segm.limit = OUTBUF_MAXSIZE;
343 out->segm.flags = 0;
344 // clear list of segments, otherwise most segments would collide with
345 // their older selves from earlier passes:
346 segmentlist_release(&out->segm.list_head);
347 // no "encryption":
348 out->xor = 0;
349 // needed size of buffer will be calculated at end of pass, so
350 //out->needed_bufsize = do not overwrite result of previous pass
351
352 // deactivate output - any byte written will trigger error:
353 output_byte = no_output;
354
355 // program counter stuff:
356 program_counter = NO_VALUE_GIVEN; // must be same value as write_idx on pass init!
357 statement_size = 0; // increase PC by this at end of statement
358
359 // pseudopc stuff:
360 // init dummy pseudopc struct
361 outermost_pseudopc_context.outer = NULL;
362 outermost_pseudopc_context.offset = 0;
363 // and use it:
364 pseudopc_current_context = &outermost_pseudopc_context;
365 }
366
367
368 // show start and end of current segment
369 // called whenever a new segment begins, and at end of pass.
370 static void end_segment(void)
371 {
372 intval_t amount;
373
374 // if there is no segment, there is nothing to do
375 if (out->segm.start == NO_VALUE_GIVEN)
376 return;
377
378 // ignore "invisible" segments
379 if (out->segm.flags & SEGMENT_FLAG_INVISIBLE)
380 return;
381
382 // ignore empty segments
383 amount = out->write_idx - out->segm.start;
384 if (amount == 0)
385 return;
386
387 // link to segment list
388 segmentlist_add(&out->segm.list_head, out->segm.start, amount);
389 // announce
390 if (pass.flags.is_final_pass && (config.process_verbosity >= 2)) {
391 // TODO - change output to start, limit, size, name:
392 printf("Segment size is %d (0x%04x) bytes (0x%04x - 0x%04x exclusive).\n",
393 amount, amount, out->segm.start, out->write_idx);
394 }
395 }
396
397
398 // called after each pass, closes last code segment and calculates outbuffer size
399 void output_endofpass(void)
400 {
401 intval_t bufsize;
402
403 // properly finalize previous segment (link to list, announce)
404 end_segment();
405
406 // calculate size of output buffer
407 if (out->highest_written >= out->lowest_written) {
408 bufsize = out->highest_written + 1;
409 } else {
410 bufsize = NO_VALUE_GIVEN;
411 }
412 // changing the size counts as a symbol change
413 if (out->needed_bufsize != bufsize)
414 ++pass.counters.symbolchanges;
415 out->needed_bufsize = bufsize;
416 //fprintf(stderr, "Need outbuf size of 0x%04x bytes.\n", out->needed_bufsize);
417 }
418
419
420 // change output pointer and enable output
421 static void start_segment(intval_t address_change, bits segment_flags)
422 {
423 // properly finalize previous segment (link to list, announce)
424 end_segment();
425
426 // calculate start of new segment
427 out->write_idx = out->write_idx + address_change;
428 if (out->write_idx < 0) {
429 throw_serious_error("Tried to write to negative address.");
430 } else if (out->write_idx >= OUTBUF_MAXSIZE) {
431 throw_serious_error("Reached memory limit.");
432 }
433 out->segm.start = out->write_idx;
434 out->segm.flags = segment_flags;
435 // allow "writing to buffer" (even though buffer does not really exist until final pass)
436 output_byte = real_output;
437 // check for other segments and maybe count/throw warning or error
438 if (!(segment_flags & SEGMENT_FLAG_OVERLAY))
439 segmentlist_check(&out->segm.list_head, out->segm.start);
440 out->segm.limit = segmentlist_findlimit(&out->segm.list_head, out->segm.start);
441 }
442
443
444 // get/set "encryption" byte
445 char output_get_xor(void)
446 {
447 return out->xor;
448 }
449 void output_set_xor(char xor)
450 {
451 out->xor = xor;
452 }
453
454
455 // set program counter to defined value -> start a new segment.
456 // this will in turn set the outbuf index according to the current pseudopc offset.
457 // if start address was given on command line, this will be called at the start of each pass.
458 // in addition to that, it will be called on each "*= VALUE".
459 void programcounter_set(intval_t new_pc, bits segment_flags)
460 {
461 intval_t pc_change;
462
463 pc_change = new_pc - program_counter;
464 program_counter = new_pc;
465 // now tell output buffer to start a new segment
466 start_segment(pc_change, segment_flags);
467 }
468
469
470 // get program counter value
471 void programcounter_read_pc(struct number *target)
472 {
473 // check whether ptr undefined
474 if (PC_NOT_SET) {
475 target->ntype = NUMTYPE_UNDEFINED;
476 } else {
477 target->ntype = NUMTYPE_INT;
478 }
479 target->flags = 0;
480 target->val.intval = program_counter;
481 target->addr_refs = 1; // program counter is an address
482 }
483 // get program counter and check if defined
484 void programcounter_read_asterisk(struct number *target)
485 {
486 programcounter_read_pc(target);
487
488 // defined?
489 if (target->ntype != NUMTYPE_UNDEFINED)
490 return;
491
492 // either complain or count
493 if (pass.flags.complain_about_undefined)
494 throw_error("Symbol not defined (*).");
495 else
496 ++pass.counters.undefineds;
497 // counting is not needed when called by expression parser, because that
498 // will count undefined _results_ on its own.
499 // but if this was called by implicit label definition, we want to count
500 // undefined pc to make sure "label" throws the same error as "label=*"
501 }
502
503
504 // get size of current statement (until now) - needed for "!bin" verbose output
505 int output_get_statement_size(void)
506 {
507 return statement_size;
508 }
509
510
511 // adjust program counter (called at end of each statement)
512 void output_end_statement(void)
513 {
514 program_counter += statement_size;
515 statement_size = 0; // reset
516 // we could check if we overran cpu's address space here and maybe throw
517 // an error, but then the user would have to add "!pseudopc" blocks even
518 // if they just wanted to re-cut some existing cartridge file using
519 // "!binary", without using any assembler mnemonics.
520 }
521
522
523 // return start and size of memory block to write to output file,
524 // along with load address for cbm/apple headers.
525 void output_get_result(const char **ptr, intval_t *size, intval_t *loadaddr)
526 {
527 intval_t start,
528 limit, // end+1
529 amount;
530
531 if (out->buffer == NULL)
532 BUG("noOutBuf", 0);
533
534 start = out->lowest_written;
535 limit = out->highest_written + 1;
536 // if pseudo opcodes were used, they override the actual values:
537 if (out->forced_start_idx != NO_VALUE_GIVEN)
538 start = out->forced_start_idx;
539 if (out->forced_limit_idx != NO_VALUE_GIVEN)
540 limit = out->forced_limit_idx;
541 // if cli args were given, they override even harder:
542 if (config.outfile_start != NO_VALUE_GIVEN)
543 start = config.outfile_start;
544 if (config.outfile_limit != NO_VALUE_GIVEN)
545 limit = config.outfile_limit;
546
547 if (limit <= start) {
548 // nothing written
549 start = 0; // I could try to use some segment start, but what for?
550 amount = 0;
551 // FIXME - how about not writing anything in this case?
552 // a CBM file would consist of a bogus load address and nothing else!
553 } else {
554 amount = limit - start;
555 }
556
557 *ptr = out->buffer + start;
558 *size = amount;
559 *loadaddr = start;
560 }
561
562
563 // pseudopc stuff:
564
565 // start offset assembly
566 void pseudopc_start(struct number *new_pc)
567 {
568 struct pseudopc *new_context;
569
570 // check whether ptr undefined
571 if (PC_NOT_SET)
572 complain_and_use_dummy_pc();
573
574 new_context = safe_malloc(sizeof(*new_context)); // create new struct (this must never be freed, as it gets linked to labels!)
575 new_context->outer = pseudopc_current_context; // let it point to previous one
576 new_context->offset = new_pc->val.intval - program_counter; // remember offset
577 pseudopc_current_context = new_context; // make new struct the current one
578 program_counter = new_pc->val.intval; // set new pc
579 }
580 // end offset assembly
581 void pseudopc_end(void)
582 {
583 program_counter = program_counter - pseudopc_current_context->offset; // remove offset
584 pseudopc_current_context = pseudopc_current_context->outer; // go back to outer block
585 if (pseudopc_current_context == NULL)
586 BUG("PseudoPCContext", 0);
587 }
588 // un-pseudopc a value by given number of levels
589 void pseudopc_unpseudo(struct number *target, struct pseudopc *context, unsigned int levels)
590 {
591 switch (target->ntype) {
592 case NUMTYPE_UNDEFINED:
593 return; // this might be an unresolved forward ref,
594 // which would have no context ptr.
595 // so we do nothing now and let later passes handle it.
596 case NUMTYPE_INT:
597 break; // this is what we expect
598 case NUMTYPE_FLOAT:
599 throw_error("Un-pseudopc operator '&' does not work on floats.");
600 return;
601 default:
602 BUG("IllegalNumberType8", target->ntype);
603 }
604 if (context == NULL) {
605 throw_error("Un-pseudopc operator '&' only works on addresses.");
606 return;
607 }
608 while (levels--) {
609 if (context == &outermost_pseudopc_context) {
610 throw_error("Un-pseudopc operator '&' has no !pseudopc context.");
611 return;
612 }
613 target->val.intval = target->val.intval - context->offset; // remove offset
614 context = context->outer;
615 }
616 }
617 // return pointer to current "pseudopc" struct
618 // this gets called when parsing label definitions
619 struct pseudopc *pseudopc_get_context(void)
620 {
621 return pseudopc_current_context;
622 }
623 // returns nonzero if "!pseudopc" is in effect, zero otherwise
624 int pseudopc_isactive(void)
625 {
626 return pseudopc_current_context != &outermost_pseudopc_context;
627 }