xref: /openbsd/sys/dev/microcode/aic7xxx/aicasm.c (revision 898184e3)
1 /* $OpenBSD: aicasm.c,v 1.15 2012/12/05 23:20:19 deraadt Exp $ */
2 /*
3  * Aic7xxx SCSI host adapter firmware asssembler
4  *
5  * Copyright (c) 1997, 1998, 2000, 2001 Justin T. Gibbs.
6  * Copyright (c) 2001, 2002 Adaptec Inc.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  * 3. Neither the names of the above-listed copyright holders nor the names
21  *    of any contributors may be used to endorse or promote products derived
22  *    from this software without specific prior written permission.
23  *
24  * Alternatively, this software may be distributed under the terms of the
25  * GNU General Public License ("GPL") version 2 as published by the Free
26  * Software Foundation.
27  *
28  * NO WARRANTY
29  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
32  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
38  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39  * POSSIBILITY OF SUCH DAMAGES.
40  *
41  * $Id: aicasm.c,v 1.15 2012/12/05 23:20:19 deraadt Exp $
42  *
43  * $FreeBSD: src/sys/dev/aic7xxx/aicasm/aicasm.c,v 1.37 2004/03/12 21:45:25 trhodes Exp $
44  */
45 #include <sys/types.h>
46 #include <sys/mman.h>
47 
48 #include <ctype.h>
49 #include <inttypes.h>
50 #include <regex.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <sysexits.h>
55 #include <unistd.h>
56 
57 #if linux
58 #include <endian.h>
59 #else
60 #include <machine/endian.h>
61 #endif
62 
63 #include "aicasm.h"
64 #include "aicasm_symbol.h"
65 #include "aicasm_insformat.h"
66 
67 typedef struct patch {
68 	TAILQ_ENTRY(patch) links;
69 	int		patch_func;
70 	u_int		begin;
71 	u_int		skip_instr;
72 	u_int		skip_patch;
73 } patch_t;
74 
75 TAILQ_HEAD(patch_list, patch) patches;
76 
77 static void usage(void);
78 static void back_patch(void);
79 static void output_code(void);
80 static void output_listing(char *ifilename);
81 static void dump_scope(scope_t *scope);
82 static void emit_patch(scope_t *scope, int patch);
83 static int check_patch(patch_t **start_patch, int start_instr,
84 		       int *skip_addr, int *func_vals);
85 
86 struct path_list search_path;
87 int includes_search_curdir;
88 char *appname;
89 char *stock_include_file;
90 FILE *ofile;
91 char *ofilename;
92 char *regfilename;
93 FILE *regfile;
94 char *listfilename;
95 FILE *listfile;
96 char *regdiagfilename;
97 FILE *regdiagfile;
98 int   src_mode;
99 int   dst_mode;
100 
101 static TAILQ_HEAD(,instruction) seq_program;
102 struct cs_tailq cs_tailq;
103 struct scope_list scope_stack;
104 symlist_t patch_functions;
105 
106 #if DEBUG
107 extern int yy_flex_debug;
108 extern int mm_flex_debug;
109 extern int yydebug;
110 extern int mmdebug;
111 #endif
112 extern FILE *yyin;
113 extern int yyparse(void);
114 
115 int main(int argc, char *argv[]);
116 
117 int
118 main(int argc, char *argv[])
119 {
120 	extern char *optarg;
121 	extern int optind;
122 	int  ch;
123 	int  retval;
124 	char *inputfilename;
125 	scope_t *sentinal;
126 
127 	TAILQ_INIT(&patches);
128 	SLIST_INIT(&search_path);
129 	TAILQ_INIT(&seq_program);
130 	TAILQ_INIT(&cs_tailq);
131 	SLIST_INIT(&scope_stack);
132 
133 	/* Set Sentinal scope node */
134 	sentinal = scope_alloc();
135 	sentinal->type = SCOPE_ROOT;
136 
137 	includes_search_curdir = 1;
138 	appname = *argv;
139 	regfile = NULL;
140 	listfile = NULL;
141 #if DEBUG
142 	yy_flex_debug = 0;
143 	mm_flex_debug = 0;
144 	yydebug = 0;
145 	mmdebug = 0;
146 #endif
147 	while ((ch = getopt(argc, argv, "d:i:l:n:o:p:r:I:X")) != -1) {
148 		switch(ch) {
149 		case 'd':
150 #if DEBUG
151 			if (strcmp(optarg, "s") == 0) {
152 				yy_flex_debug = 1;
153 				mm_flex_debug = 1;
154 			} else if (strcmp(optarg, "p") == 0) {
155 				yydebug = 1;
156 				mmdebug = 1;
157 			} else {
158 				fprintf(stderr, "%s: -d Requires either an "
159 					"'s' or 'p' argument\n", appname);
160 				usage();
161 			}
162 #else
163 			stop("-d: Assembler not built with debugging "
164 			     "information", EX_SOFTWARE);
165 #endif
166 			break;
167 		case 'i':
168 			stock_include_file = optarg;
169 			break;
170 		case 'l':
171 			/* Create a program listing */
172 			if ((listfile = fopen(optarg, "w")) == NULL) {
173 				perror(optarg);
174 				stop(NULL, EX_CANTCREAT);
175 			}
176 			listfilename = optarg;
177 			break;
178 		case 'n':
179 			/* Don't complain about the -nostdinc directrive */
180 			if (strcmp(optarg, "ostdinc")) {
181 				fprintf(stderr, "%s: Unknown option -%c%s\n",
182 					appname, ch, optarg);
183 				usage();
184 				/* NOTREACHED */
185 			}
186 			break;
187 		case 'o':
188 			if ((ofile = fopen(optarg, "w")) == NULL) {
189 				perror(optarg);
190 				stop(NULL, EX_CANTCREAT);
191 			}
192 			ofilename = optarg;
193 			break;
194 		case 'p':
195 			/* Create Register Diagnostic "printing" Functions */
196 			if ((regdiagfile = fopen(optarg, "w")) == NULL) {
197 				perror(optarg);
198 				stop(NULL, EX_CANTCREAT);
199 			}
200 			regdiagfilename = optarg;
201 			break;
202 		case 'r':
203 			if ((regfile = fopen(optarg, "w")) == NULL) {
204 				perror(optarg);
205 				stop(NULL, EX_CANTCREAT);
206 			}
207 			regfilename = optarg;
208 			break;
209 		case 'I':
210 		{
211 			path_entry_t include_dir;
212 
213 			if (strcmp(optarg, "-") == 0) {
214 				if (includes_search_curdir == 0) {
215 					fprintf(stderr, "%s: Warning - '-I-' "
216 							"specified multiple "
217 							"times\n", appname);
218 				}
219 				includes_search_curdir = 0;
220 				for (include_dir = SLIST_FIRST(&search_path);
221 				     include_dir != NULL;
222 				     include_dir = SLIST_NEXT(include_dir,
223 							      links))
224 					/*
225 					 * All entries before a '-I-' only
226 					 * apply to includes specified with
227 					 * quotes instead of "<>".
228 					 */
229 					include_dir->quoted_includes_only = 1;
230 			} else {
231 				include_dir =
232 				    (path_entry_t)malloc(sizeof(*include_dir));
233 				if (include_dir == NULL) {
234 					perror(optarg);
235 					stop(NULL, EX_OSERR);
236 				}
237 				include_dir->directory = strdup(optarg);
238 				if (include_dir->directory == NULL) {
239 					perror(optarg);
240 					stop(NULL, EX_OSERR);
241 				}
242 				include_dir->quoted_includes_only = 0;
243 				SLIST_INSERT_HEAD(&search_path, include_dir,
244 						  links);
245 			}
246 			break;
247 		}
248 		case 'X':
249 			/* icc version of -nostdinc */
250 			break;
251 		case '?':
252 		default:
253 			usage();
254 			/* NOTREACHED */
255 		}
256 	}
257 	argc -= optind;
258 	argv += optind;
259 
260 	if (argc != 1) {
261 		fprintf(stderr, "%s: No input file specifiled\n", appname);
262 		usage();
263 		/* NOTREACHED */
264 	}
265 
266 	if (regdiagfile != NULL
267 	 && (regfile == NULL || stock_include_file == NULL)) {
268 		fprintf(stderr,
269 			"%s: The -p option requires the -r and -i options.\n",
270 			appname);
271 		usage();
272 		/* NOTREACHED */
273 	}
274 	symtable_open();
275 	inputfilename = *argv;
276 	include_file(*argv, SOURCE_FILE);
277 	retval = yyparse();
278 	if (retval == 0) {
279 		if (SLIST_FIRST(&scope_stack) == NULL
280 		 || SLIST_FIRST(&scope_stack)->type != SCOPE_ROOT) {
281 			stop("Unterminated conditional expression", EX_DATAERR);
282 			/* NOTREACHED */
283 		}
284 
285 		/* Process outmost scope */
286 		process_scope(SLIST_FIRST(&scope_stack));
287 		/*
288 		 * Decend the tree of scopes and insert/emit
289 		 * patches as appropriate.  We perform a depth first
290 		 * tranversal, recursively handling each scope.
291 		 */
292 		/* start at the root scope */
293 		dump_scope(SLIST_FIRST(&scope_stack));
294 
295 		/* Patch up forward jump addresses */
296 		back_patch();
297 
298 		if (ofile != NULL)
299 			output_code();
300 		if (regfile != NULL)
301 			symtable_dump(regfile, regdiagfile);
302 		if (listfile != NULL)
303 			output_listing(inputfilename);
304 	}
305 
306 	stop(NULL, 0);
307 	/* NOTREACHED */
308 	return (0);
309 }
310 
311 static void
312 usage()
313 {
314 
315 	(void)fprintf(stderr,
316 "usage: %-16s [-nostdinc|-X] [-I-] [-I directory] [-o output_file]\n"
317 "	[-r register_output_file [-p register_diag_file -i includefile]]\n"
318 "	[-l program_list_file]\n"
319 "	input_file\n", appname);
320 	exit(EX_USAGE);
321 }
322 
323 static void
324 back_patch()
325 {
326 	struct instruction *cur_instr;
327 
328 	for (cur_instr = TAILQ_FIRST(&seq_program);
329 	     cur_instr != NULL;
330 	     cur_instr = TAILQ_NEXT(cur_instr, links)) {
331 		if (cur_instr->patch_label != NULL) {
332 			struct ins_format3 *f3_instr;
333 			u_int address;
334 
335 			if (cur_instr->patch_label->type != LABEL) {
336 				char buf[255];
337 
338 				snprintf(buf, sizeof(buf),
339 					 "Undefined label %s",
340 					 cur_instr->patch_label->name);
341 				stop(buf, EX_DATAERR);
342 				/* NOTREACHED */
343 			}
344 			f3_instr = &cur_instr->format.format3;
345 			address = f3_instr->address;
346 			address += cur_instr->patch_label->info.linfo->address;
347 			f3_instr->address = address;
348 		}
349 	}
350 }
351 
352 static void
353 output_code()
354 {
355 	struct instruction *cur_instr;
356 	patch_t *cur_patch;
357 	critical_section_t *cs;
358 	symbol_node_t *cur_node;
359 	int instrcount;
360 
361 	instrcount = 0;
362 	fprintf(ofile,
363 "/*\n"
364 " * DO NOT EDIT - This file is automatically generated\n"
365 " *		 from the following source files:\n"
366 " *\n"
367 "%s */\n", versions);
368 
369 	fprintf(ofile, "static const uint8_t seqprog[] = {\n");
370 	for (cur_instr = TAILQ_FIRST(&seq_program);
371 	     cur_instr != NULL;
372 	     cur_instr = TAILQ_NEXT(cur_instr, links)) {
373 
374 		fprintf(ofile, "%s\t0x%02x, 0x%02x, 0x%02x, 0x%02x",
375 			cur_instr == TAILQ_FIRST(&seq_program) ? "" : ",\n",
376 #if BYTE_ORDER == LITTLE_ENDIAN
377 			cur_instr->format.bytes[0],
378 			cur_instr->format.bytes[1],
379 			cur_instr->format.bytes[2],
380 			cur_instr->format.bytes[3]);
381 #else
382 			cur_instr->format.bytes[3],
383 			cur_instr->format.bytes[2],
384 			cur_instr->format.bytes[1],
385 			cur_instr->format.bytes[0]);
386 #endif
387 		instrcount++;
388 	}
389 	fprintf(ofile, "\n};\n\n");
390 
391 	if (patch_arg_list == NULL)
392 		stop("Patch argument list not defined",
393 		     EX_DATAERR);
394 
395 	/*
396 	 *  Output patch information.  Patch functions first.
397 	 */
398 	fprintf(ofile,
399 "typedef int %spatch_func_t (%s);\n", prefix, patch_arg_list);
400 
401 	for (cur_node = SLIST_FIRST(&patch_functions);
402 	     cur_node != NULL;
403 	     cur_node = SLIST_NEXT(cur_node,links)) {
404 		fprintf(ofile,
405 "static %spatch_func_t %spatch%d_func;\n"
406 "\n"
407 "static int\n"
408 "%spatch%d_func(%s)\n"
409 "{\n"
410 "	return (%s);\n"
411 "}\n\n",
412 			prefix,
413 			prefix,
414 			cur_node->symbol->info.condinfo->func_num,
415 			prefix,
416 			cur_node->symbol->info.condinfo->func_num,
417 			patch_arg_list,
418 			cur_node->symbol->name);
419 	}
420 
421 	fprintf(ofile,
422 "static const struct patch {\n"
423 "	%spatch_func_t		*patch_func;\n"
424 "	uint32_t		 begin		:10,\n"
425 "				 skip_instr	:10,\n"
426 "				 skip_patch	:12;\n"
427 "} patches[] = {\n", prefix);
428 
429 	for (cur_patch = TAILQ_FIRST(&patches);
430 	     cur_patch != NULL;
431 	     cur_patch = TAILQ_NEXT(cur_patch,links)) {
432 		fprintf(ofile, "%s\t{ %spatch%d_func, %d, %d, %d }",
433 			cur_patch == TAILQ_FIRST(&patches) ? "" : ",\n",
434 			prefix,
435 			cur_patch->patch_func, cur_patch->begin,
436 			cur_patch->skip_instr, cur_patch->skip_patch);
437 	}
438 
439 	fprintf(ofile, "\n};\n\n");
440 
441 	fprintf(ofile,
442 "static const struct cs {\n"
443 "	uint16_t	begin;\n"
444 "	uint16_t	end;\n"
445 "} critical_sections[] = {\n");
446 
447 	for (cs = TAILQ_FIRST(&cs_tailq);
448 	     cs != NULL;
449 	     cs = TAILQ_NEXT(cs, links)) {
450 		fprintf(ofile, "%s\t{ %d, %d }",
451 			cs == TAILQ_FIRST(&cs_tailq) ? "" : ",\n",
452 			cs->begin_addr, cs->end_addr);
453 	}
454 
455 	fprintf(ofile, "\n};\n\n");
456 
457 	fprintf(ofile,
458 "#define NUM_CRITICAL_SECTIONS (sizeof(critical_sections) / sizeof(*critical_sections))\n");
459 
460 	fprintf(stderr, "%s: %d instructions used\n", appname, instrcount);
461 }
462 
463 static void
464 dump_scope(scope_t *scope)
465 {
466 	scope_t *cur_scope;
467 
468 	/*
469 	 * Emit the first patch for this scope
470 	 */
471 	emit_patch(scope, 0);
472 
473 	/*
474 	 * Dump each scope within this one.
475 	 */
476 	cur_scope = TAILQ_FIRST(&scope->inner_scope);
477 
478 	while (cur_scope != NULL) {
479 
480 		dump_scope(cur_scope);
481 
482 		cur_scope = TAILQ_NEXT(cur_scope, scope_links);
483 	}
484 
485 	/*
486 	 * Emit the second, closing, patch for this scope
487 	 */
488 	emit_patch(scope, 1);
489 }
490 
491 void
492 emit_patch(scope_t *scope, int patch)
493 {
494 	patch_info_t *pinfo;
495 	patch_t *new_patch;
496 
497 	pinfo = &scope->patches[patch];
498 
499 	if (pinfo->skip_instr == 0)
500 		/* No-Op patch */
501 		return;
502 
503 	new_patch = (patch_t *)malloc(sizeof(*new_patch));
504 
505 	if (new_patch == NULL)
506 		stop("Could not malloc patch structure", EX_OSERR);
507 
508 	memset(new_patch, 0, sizeof(*new_patch));
509 
510 	if (patch == 0) {
511 		new_patch->patch_func = scope->func_num;
512 		new_patch->begin = scope->begin_addr;
513 	} else {
514 		new_patch->patch_func = 0;
515 		new_patch->begin = scope->end_addr;
516 	}
517 	new_patch->skip_instr = pinfo->skip_instr;
518 	new_patch->skip_patch = pinfo->skip_patch;
519 	TAILQ_INSERT_TAIL(&patches, new_patch, links);
520 }
521 
522 void
523 output_listing(char *ifilename)
524 {
525 	char buf[1024];
526 	FILE *ifile;
527 	struct instruction *cur_instr;
528 	patch_t *cur_patch;
529 	symbol_node_t *cur_func;
530 	int *func_values;
531 	int instrcount;
532 	int instrptr;
533 	int line;
534 	int func_count;
535 	int skip_addr;
536 
537 	instrcount = 0;
538 	instrptr = 0;
539 	line = 1;
540 	skip_addr = 0;
541 	if ((ifile = fopen(ifilename, "r")) == NULL) {
542 		perror(ifilename);
543 		stop(NULL, EX_DATAERR);
544 	}
545 
546 	/*
547 	 * Determine which options to apply to this listing.
548 	 */
549 	for (func_count = 0, cur_func = SLIST_FIRST(&patch_functions);
550 	    cur_func != NULL;
551 	    cur_func = SLIST_NEXT(cur_func, links))
552 		func_count++;
553 
554 	func_values = NULL;
555 	if (func_count != 0) {
556 		func_values = (int *)malloc(func_count * sizeof(int));
557 
558 		if (func_values == NULL)
559 			stop("Could not malloc", EX_OSERR);
560 
561 		func_values[0] = 0; /* FALSE func */
562 		func_count--;
563 
564 		/*
565 		 * Ask the user to fill in the return values for
566 		 * the rest of the functions.
567 		 */
568 
569 
570 		for (cur_func = SLIST_FIRST(&patch_functions);
571 		     cur_func != NULL && SLIST_NEXT(cur_func, links) != NULL;
572 		     cur_func = SLIST_NEXT(cur_func, links), func_count--) {
573 			int input;
574 
575 			fprintf(stdout, "\n(%s)\n", cur_func->symbol->name);
576 			fprintf(stdout,
577 				"Enter the return value for "
578 				"this expression[T/F]:");
579 
580 			while (1) {
581 
582 				input = getchar();
583 				input = toupper(input);
584 
585 				if (input == 'T') {
586 					func_values[func_count] = 1;
587 					break;
588 				} else if (input == 'F') {
589 					func_values[func_count] = 0;
590 					break;
591 				}
592 			}
593 			if (isatty(fileno(stdin)) == 0)
594 				putchar(input);
595 		}
596 		fprintf(stdout, "\nThanks!\n");
597 	}
598 
599 	/* Now output the listing */
600 	cur_patch = TAILQ_FIRST(&patches);
601 	for (cur_instr = TAILQ_FIRST(&seq_program);
602 	     cur_instr != NULL;
603 	     cur_instr = TAILQ_NEXT(cur_instr, links), instrcount++) {
604 
605 		if (check_patch(&cur_patch, instrcount,
606 				&skip_addr, func_values) == 0) {
607 			/* Don't count this instruction as it is in a patch
608 			 * that was removed.
609 			 */
610                         continue;
611 		}
612 
613 		while (line < cur_instr->srcline) {
614 			fgets(buf, sizeof(buf), ifile);
615 				fprintf(listfile, "             \t%s", buf);
616 				line++;
617 		}
618 		fprintf(listfile, "%04x %02x%02x%02x%02x", instrptr,
619 #if BYTE_ORDER == LITTLE_ENDIAN
620 			cur_instr->format.bytes[0],
621 			cur_instr->format.bytes[1],
622 			cur_instr->format.bytes[2],
623 			cur_instr->format.bytes[3]);
624 #else
625 			cur_instr->format.bytes[3],
626 			cur_instr->format.bytes[2],
627 			cur_instr->format.bytes[1],
628 			cur_instr->format.bytes[0]);
629 #endif
630 		/*
631 		 * Macro expansions can cause several instructions
632 		 * to be output for a single source line.  Only
633 		 * advance the line once in these cases.
634 		 */
635 		if (line == cur_instr->srcline) {
636 			fgets(buf, sizeof(buf), ifile);
637 			fprintf(listfile, "\t%s", buf);
638 			line++;
639 		} else {
640 			fprintf(listfile, "\n");
641 		}
642 		instrptr++;
643 	}
644 	/* Dump the remainder of the file */
645 	while(fgets(buf, sizeof(buf), ifile) != NULL)
646 		fprintf(listfile, "             %s", buf);
647 
648 	fclose(ifile);
649 }
650 
651 static int
652 check_patch(patch_t **start_patch, int start_instr,
653 	    int *skip_addr, int *func_vals)
654 {
655 	patch_t *cur_patch;
656 
657 	cur_patch = *start_patch;
658 
659 	while (cur_patch != NULL && start_instr == cur_patch->begin) {
660 		if (func_vals[cur_patch->patch_func] == 0) {
661 			int skip;
662 
663 			/* Start rejecting code */
664 			*skip_addr = start_instr + cur_patch->skip_instr;
665 			for (skip = cur_patch->skip_patch;
666 			     skip > 0 && cur_patch != NULL;
667 			     skip--)
668 				cur_patch = TAILQ_NEXT(cur_patch, links);
669 		} else {
670 			/* Accepted this patch.  Advance to the next
671 			 * one and wait for our intruction pointer to
672 			 * hit this point.
673 			 */
674 			cur_patch = TAILQ_NEXT(cur_patch, links);
675 		}
676 	}
677 
678 	*start_patch = cur_patch;
679 	if (start_instr < *skip_addr)
680 		/* Still skipping */
681 		return (0);
682 
683 	return (1);
684 }
685 
686 /*
687  * Print out error information if appropriate, and clean up before
688  * terminating the program.
689  */
690 void
691 stop(const char *string, int err_code)
692 {
693 	if (string != NULL) {
694 		fprintf(stderr, "%s: ", appname);
695 		if (yyfilename != NULL) {
696 			fprintf(stderr, "Stopped at file %s, line %d - ",
697 				yyfilename, yylineno);
698 		}
699 		fprintf(stderr, "%s\n", string);
700 	}
701 
702 	if (ofile != NULL) {
703 		fclose(ofile);
704 		if (err_code != 0) {
705 			fprintf(stderr, "%s: Removing %s due to error\n",
706 				appname, ofilename);
707 			unlink(ofilename);
708 		}
709 	}
710 
711 	if (regfile != NULL) {
712 		fclose(regfile);
713 		if (err_code != 0) {
714 			fprintf(stderr, "%s: Removing %s due to error\n",
715 				appname, regfilename);
716 			unlink(regfilename);
717 		}
718 	}
719 
720 	if (listfile != NULL) {
721 		fclose(listfile);
722 		if (err_code != 0) {
723 			fprintf(stderr, "%s: Removing %s due to error\n",
724 				appname, listfilename);
725 			unlink(listfilename);
726 		}
727 	}
728 
729 	symlist_free(&patch_functions);
730 	symtable_close();
731 
732 	exit(err_code);
733 }
734 
735 struct instruction *
736 seq_alloc()
737 {
738 	struct instruction *new_instr;
739 
740 	new_instr = (struct instruction *)malloc(sizeof(struct instruction));
741 	if (new_instr == NULL)
742 		stop("Unable to malloc instruction object", EX_SOFTWARE);
743 	memset(new_instr, 0, sizeof(*new_instr));
744 	TAILQ_INSERT_TAIL(&seq_program, new_instr, links);
745 	new_instr->srcline = yylineno;
746 	return new_instr;
747 }
748 
749 critical_section_t *
750 cs_alloc()
751 {
752 	critical_section_t *new_cs;
753 
754 	new_cs= (critical_section_t *)malloc(sizeof(critical_section_t));
755 	if (new_cs == NULL)
756 		stop("Unable to malloc critical_section object", EX_SOFTWARE);
757 	memset(new_cs, 0, sizeof(*new_cs));
758 
759 	TAILQ_INSERT_TAIL(&cs_tailq, new_cs, links);
760 	return new_cs;
761 }
762 
763 scope_t *
764 scope_alloc()
765 {
766 	scope_t *new_scope;
767 
768 	new_scope = (scope_t *)malloc(sizeof(scope_t));
769 	if (new_scope == NULL)
770 		stop("Unable to malloc scope object", EX_SOFTWARE);
771 	memset(new_scope, 0, sizeof(*new_scope));
772 	TAILQ_INIT(&new_scope->inner_scope);
773 
774 	if (SLIST_FIRST(&scope_stack) != NULL) {
775 		TAILQ_INSERT_TAIL(&SLIST_FIRST(&scope_stack)->inner_scope,
776 				  new_scope, scope_links);
777 	}
778 	/* This patch is now the current scope */
779 	SLIST_INSERT_HEAD(&scope_stack, new_scope, scope_stack_links);
780 	return new_scope;
781 }
782 
783 void
784 process_scope(scope_t *scope)
785 {
786 	/*
787 	 * We are "leaving" this scope.  We should now have
788 	 * enough information to process the lists of scopes
789 	 * we encapsulate.
790 	 */
791 	scope_t *cur_scope;
792 	u_int skip_patch_count;
793 	u_int skip_instr_count;
794 
795 	cur_scope = TAILQ_LAST(&scope->inner_scope, scope_tailq);
796 	skip_patch_count = 0;
797 	skip_instr_count = 0;
798 	while (cur_scope != NULL) {
799 		u_int patch0_patch_skip;
800 
801 		patch0_patch_skip = 0;
802 		switch (cur_scope->type) {
803 		case SCOPE_IF:
804 		case SCOPE_ELSE_IF:
805 			if (skip_instr_count != 0) {
806 				/* Create a tail patch */
807 				patch0_patch_skip++;
808 				cur_scope->patches[1].skip_patch =
809 				    skip_patch_count + 1;
810 				cur_scope->patches[1].skip_instr =
811 				    skip_instr_count;
812 			}
813 
814 			/* Count Head patch */
815 			patch0_patch_skip++;
816 
817 			/* Count any patches contained in our inner scope */
818 			patch0_patch_skip += cur_scope->inner_scope_patches;
819 
820 			cur_scope->patches[0].skip_patch = patch0_patch_skip;
821 			cur_scope->patches[0].skip_instr =
822 			    cur_scope->end_addr - cur_scope->begin_addr;
823 
824 			skip_instr_count += cur_scope->patches[0].skip_instr;
825 
826 			skip_patch_count += patch0_patch_skip;
827 			if (cur_scope->type == SCOPE_IF) {
828 				scope->inner_scope_patches += skip_patch_count;
829 				skip_patch_count = 0;
830 			        skip_instr_count = 0;
831 			}
832 			break;
833 		case SCOPE_ELSE:
834 			/* Count any patches contained in our innter scope */
835 			skip_patch_count += cur_scope->inner_scope_patches;
836 
837 			skip_instr_count += cur_scope->end_addr
838 					  - cur_scope->begin_addr;
839 			break;
840 		case SCOPE_ROOT:
841 			stop("Unexpected scope type encountered", EX_SOFTWARE);
842 			/* NOTREACHED */
843 		}
844 
845 		cur_scope = TAILQ_PREV(cur_scope, scope_tailq, scope_links);
846 	}
847 }
848