parse_asm.c (38286B)
1 #include "../config.h" 2 3 #include "parse_asm.h" 4 #include <assert.h> 5 #include <ctype.h> 6 #include <stdint.h> 7 #include <stdlib.h> /* strtoul */ 8 #include <string.h> 9 #include <strings.h> 10 11 #if __STDC_NO_VLA__ 12 #include <alloca.h> 13 #endif 14 15 #include "ir_asm.h" 16 #include "table.h" 17 #include "tcutil.h" 18 19 #include "arch.h" 20 21 #if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE 22 const char kSegText[] = "__TEXT"; 23 const char kSecText[] = "__text"; 24 const char kSegRodata[] = "__DATA"; 25 const char kSecRodata[] = "__const"; 26 const char kSegData[] = "__DATA"; 27 const char kSecData[] = "__data"; 28 const char kSegBss[] = "__DATA"; 29 const char kSecBss[] = "__bss"; 30 #else 31 const char kSecText[] = ".text"; 32 const char kSecRodata[] = ".rodata"; 33 const char kSecData[] = ".data"; 34 const char kSecBss[] = ".bss"; 35 #endif 36 37 #if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE 38 #define WEAK "weak_definition" 39 #else 40 #define WEAK "weak" 41 #endif 42 43 static const char *kDirectiveTable[] = { 44 "ascii", 45 "string", 46 "section", 47 "text", 48 "data", 49 "bss", 50 "align", 51 "p2align", 52 "balign", 53 "type", 54 "byte", 55 "short", 56 "long", 57 "quad", 58 "comm", 59 "zero", 60 "globl", 61 "local", 62 WEAK, 63 "extern", 64 "int", 65 "word", 66 "2byte", 67 "4byte", 68 "8byte", 69 "fill", 70 "space", 71 "skip", 72 "set", 73 "equ", 74 "file", 75 "loc", 76 "ident", 77 "previous", 78 #ifndef __NO_FLONUM 79 "float", 80 "double", 81 #endif 82 #if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE 83 "subsections_via_symbols", 84 #endif 85 "size", 86 }; 87 88 struct SectionInfo * 89 get_section_info(struct ParseInfo *info, const char *name, const char *segname, int flag) 90 { 91 const struct Name *key = alloc_name(name, NULL, 1); 92 struct SectionInfo *section; 93 if (!table_try_get(info->section_infos, key, (void **)§ion)) { 94 section = calloc_or_die(sizeof(*section)); 95 section->name = key; 96 section->segname = segname; 97 section->irs = new_vector(); 98 section->flag = flag; 99 section->index = 0; 100 section->start_address = 0; 101 section->ds = NULL; 102 section->align = 1; 103 section->bss_size = 0; 104 section->rela_count = 0; 105 section->rela_buf = NULL; 106 if (!(flag & SF_BSS)) { 107 struct DataStorage *ds = calloc_or_die(sizeof(*ds)); 108 data_init(ds); 109 section->ds = ds; 110 } 111 table_put(info->section_infos, key, section); 112 } 113 return section; 114 } 115 116 struct SectionInfo * 117 set_current_section(struct ParseInfo *info, const char *name, const char *segname, int flag) 118 { 119 struct SectionInfo *section = get_section_info(info, name, segname, flag); 120 info->current_section = section; 121 return section; 122 } 123 124 static struct LabelInfo * 125 new_label(struct SectionInfo *section) 126 { 127 struct LabelInfo *info = calloc_or_die(sizeof(*info)); 128 info->section = section; 129 info->flag = 0; 130 info->address = 0; 131 info->kind = LK_NONE; 132 info->size = 0; 133 info->align = 0; 134 return info; 135 } 136 137 struct LabelInfo * 138 add_label_table( 139 struct Table *label_table, 140 const struct Name *label, 141 struct SectionInfo *section, 142 int define, 143 int global 144 ) 145 { 146 struct LabelInfo *info = table_get(label_table, label); 147 if (info != NULL) { 148 if (define) { 149 if ((info->flag & LF_DEFINED) != 0) { 150 fprintf(stderr, "`%.*s' already defined\n", NAMES(label)); 151 return NULL; 152 } 153 info->address = 1; 154 info->section = section; 155 } 156 } else { 157 info = new_label(section); 158 table_put(label_table, label, info); 159 } 160 if (define) 161 info->flag |= LF_DEFINED; 162 if (global) 163 info->flag |= LF_GLOBAL; 164 return info; 165 } 166 167 int 168 parse_error(struct ParseInfo *info, const char *message) 169 { 170 fprintf(stderr, "%s(%d): %s\n", info->filename, info->lineno, message); 171 fprintf(stderr, "%s\n", info->rawline); 172 ++info->error_count; 173 return 0; 174 } 175 176 static enum DirectiveType 177 find_directive(const char *p, size_t n) 178 { 179 const char **table = kDirectiveTable; 180 size_t i; 181 182 for (i = 0; i < ARRAY_SIZE(kDirectiveTable); ++i) { 183 const char *name = table[i]; 184 if (strncasecmp(p, name, n) == 0 && name[n] == '\0') { 185 return i + 1; 186 } 187 } 188 /* cfi directives are a family, tolerate them all */ 189 if (n >= 4 && strncasecmp(p, "cfi_", 4) == 0) 190 return DT_CFI; 191 return NODIRECTIVE; 192 } 193 194 int 195 immediate(const char **pp, int64_t *value) 196 { 197 const char *p = *pp; 198 int negative = 0; 199 if (*p == '-') { 200 negative = 1; 201 ++p; 202 } 203 204 int base = 10; 205 if (*p == '0') { 206 char c = tolower(p[1]); 207 if (c == 'x') { 208 base = 16; 209 p += 2; 210 c = tolower(*p); 211 if (!isxdigit(c)) 212 return 0; 213 } else if (isdigit(c)) { 214 if (c >= '8') 215 return 0; 216 base = 8; 217 } 218 } 219 const char *q = p; 220 unsigned long val = strtoul(p, (char **)&p, base); 221 if (p == q) 222 return 0; 223 224 *value = negative ? -val : val; 225 *pp = p; 226 return 1; 227 } 228 229 int 230 is_label_first_chr(char c) 231 { 232 return isalpha(c) || c == '_' || c == '.'; 233 } 234 235 int 236 is_label_chr(char c) 237 { 238 return is_label_first_chr(c) || isdigit(c); 239 } 240 241 static const char * 242 get_label_end(struct ParseInfo *info) 243 { 244 const char *start = info->p; 245 const char *p = start; 246 if (*p == '"') { 247 ++p; 248 for (;;) { 249 char c = *p; 250 if (c == '\0') { 251 parse_error(info, "string not closed"); 252 break; 253 } 254 255 ++p; 256 if (c == '"') 257 break; 258 if (c == '\\') 259 ++p; 260 } 261 /* a properly closed quoted string is valid even when empty (""); 262 * the p <= start check below exists for the bare-identifier 263 * branch, where reaching it unmoved means no label was found at 264 * all, so it does not apply here */ 265 return p; 266 } else { 267 const unsigned char *q = (const unsigned char *)p; 268 int ucc = 0; 269 for (;;) { 270 int uc = *++q; 271 if (ucc > 0) { 272 if (!isutf8follow(uc)) { 273 parse_error(info, "illegal byte sequence"); 274 return NULL; 275 } 276 --ucc; 277 continue; 278 } 279 if ((ucc = isutf8first(uc) - 1) > 0) 280 continue; 281 if (!is_label_chr(uc)) 282 break; 283 } 284 p = (const char *)q; 285 } 286 if (p <= start) 287 parse_error(info, "empty label"); 288 return p; 289 } 290 291 const struct Name * 292 unquote_label(const char *p, const char *q) 293 { 294 if (*p != '"') 295 return alloc_name(p, q, 0); 296 if (q[-1] != '"' || q == p + 2) 297 return NULL; 298 /* TODO: unescape */ 299 return alloc_name(p + 1, q - 1, 0); 300 } 301 302 static const struct Name * 303 parse_label(struct ParseInfo *info) 304 { 305 const char *start = info->p; 306 const char *p = get_label_end(info); 307 if (p == start) 308 return NULL; 309 310 info->p = p; 311 return unquote_label(start, p); 312 } 313 314 static const struct Name * 315 parse_section_name(struct ParseInfo *info) 316 { 317 const char *p = info->p; 318 const char *start = p; 319 320 if (!is_label_first_chr(*p)) 321 return NULL; 322 323 do { 324 ++p; 325 } while (isalnum_(*p) || *p == '.' || *p == '-' || *p == '_'); 326 info->p = p; 327 return alloc_name(start, p, 0); 328 } 329 330 enum TokenKind { 331 TK_EOF, 332 TK_UNKNOWN, 333 TK_LABEL, 334 TK_FIXNUM, 335 TK_ADD, 336 TK_SUB, 337 TK_MUL, 338 TK_DIV, 339 TK_FLONUM, 340 }; 341 342 struct Token { 343 enum TokenKind kind; 344 union { 345 struct { 346 const struct Name *name; 347 } label; 348 int64_t fixnum; 349 #ifndef __NO_FLONUM 350 Flonum flonum; 351 #endif 352 } u; 353 }; 354 355 static struct Token * 356 new_token(enum TokenKind kind) 357 { 358 struct Token *token = calloc_or_die(sizeof(*token)); 359 token->kind = kind; 360 return token; 361 } 362 363 #ifndef __NO_FLONUM 364 static struct Token * 365 read_flonum(struct ParseInfo *info, int base) 366 { 367 const char *start = info->p; 368 char *next; 369 #ifdef __TC 370 /* long double in the toolchain compiler is same as double, and if the target platform uses 371 */ 372 /* system library, it makes discrepancy */ 373 Flonum val = strtod(start, &next); 374 #else 375 Flonum val = strtold(start, &next); 376 #endif 377 struct Token *tok = new_token(TK_FLONUM); 378 tok->u.flonum = val; 379 info->p = next; 380 381 if (base == 16) { 382 /* check exponent part exists */ 383 const char *q; 384 for (q = start; q < next; ++q) { 385 if (tolower(*q) == 'p') 386 break; 387 } 388 if (q >= next) { 389 parse_error(info, "hex float literal must have exponent part"); 390 } 391 } 392 393 return tok; 394 } 395 #endif 396 397 static const struct Token * 398 fetch_token(struct ParseInfo *info) 399 { 400 static const struct Token kTokEOF = {.kind = TK_EOF}; 401 const char *start = skip_whitespaces(info->p); 402 const char *p = start; 403 char c = *p; 404 switch (c) { 405 case '\0': 406 return &kTokEOF; 407 case '0': 408 case '1': 409 case '2': 410 case '3': 411 case '4': 412 case '5': 413 case '6': 414 case '7': 415 case '8': 416 case '9': { 417 int base = 10; 418 if (c == '0' && tolower(p[1]) == 'x') { 419 #ifndef __NO_FLONUM 420 if (c == '.') /* hex float literal */ 421 return read_flonum(info, 16); 422 #endif 423 if (isxdigit(p[2])) { 424 p += 2; 425 base = 16; 426 } 427 } 428 char *q; 429 unsigned long long v = strtoull(p, &q, base); 430 #ifndef __NO_FLONUM 431 if (*q == '.' || tolower(*q) == 'e') { 432 info->p = p; 433 return read_flonum(info, 10); 434 } 435 #endif 436 struct Token *token = new_token(TK_FIXNUM); 437 token->u.fixnum = v; 438 info->p = q; 439 return token; 440 } 441 case '"': { 442 info->p = p; 443 const struct Name *label = parse_label(info); 444 if (label != NULL) { 445 struct Token *token = new_token(TK_LABEL); 446 token->u.label.name = label; 447 return token; 448 } 449 } break; 450 case '+': 451 case '-': 452 case '*': 453 case '/': { 454 enum TokenKind kind; 455 switch (c) { 456 default: 457 assert(0); /* to suppress warning */ 458 case '+': 459 kind = TK_ADD; 460 break; 461 case '-': 462 kind = TK_SUB; 463 break; 464 case '*': 465 kind = TK_MUL; 466 break; 467 case '/': 468 kind = TK_DIV; 469 break; 470 } 471 info->p = p + 1; 472 return new_token(kind); 473 } 474 #ifndef __NO_FLONUM 475 case '.': 476 if (isdigit(p[1])) { 477 info->p = p; 478 return read_flonum(info, 10); 479 } 480 break; 481 #endif 482 default: 483 break; 484 } 485 486 if (is_label_first_chr(c)) { 487 const char *label = p; 488 while (c = *++p, is_label_chr(c)) 489 ; 490 struct Token *token = new_token(TK_LABEL); 491 token->u.label.name = alloc_name(label, p, 0); 492 info->p = p; 493 return token; 494 } 495 496 static const struct Token kTokUnknown = {.kind = TK_UNKNOWN}; 497 return &kTokUnknown; 498 } 499 500 static const struct Token * 501 match(struct ParseInfo *info, enum TokenKind kind) 502 { 503 const struct Token *token = info->prefetched; 504 if (token == NULL) 505 token = fetch_token(info); 506 507 if (token->kind != kind) { 508 info->prefetched = token; 509 return NULL; 510 } 511 info->prefetched = NULL; 512 return token; 513 } 514 515 struct Expr * 516 new_expr(enum ExprKind kind) 517 { 518 struct Expr *expr = calloc_or_die(sizeof(*expr)); 519 expr->kind = kind; 520 return expr; 521 } 522 523 static struct Expr * 524 prim(struct ParseInfo *info) 525 { 526 struct Expr *expr = NULL; 527 const struct Token *tok; 528 if ((tok = match(info, TK_LABEL)) != NULL) { 529 expr = new_expr(EX_LABEL); 530 expr->u.label.name = tok->u.label.name; 531 } else if ((tok = match(info, TK_FIXNUM)) != NULL) { 532 expr = new_expr(EX_FIXNUM); 533 expr->u.fixnum = tok->u.fixnum; 534 #ifndef __NO_FLONUM 535 } else if ((tok = match(info, TK_FLONUM)) != NULL) { 536 expr = new_expr(EX_FLONUM); 537 expr->u.flonum = tok->u.flonum; 538 #endif 539 } 540 return expr; 541 } 542 543 static struct Expr * 544 unary(struct ParseInfo *info) 545 { 546 const struct Token *tok; 547 if ((tok = match(info, TK_ADD)) != NULL) { 548 struct Expr *expr = unary(info); 549 if (expr == NULL) 550 return NULL; 551 switch (expr->kind) { 552 case EX_FIXNUM: 553 case EX_FLONUM: 554 return expr; 555 default: { 556 struct Expr *op = new_expr(EX_POS); 557 op->u.unary.sub = expr; 558 return op; 559 } 560 } 561 } 562 563 if ((tok = match(info, TK_SUB)) != NULL) { 564 struct Expr *expr = unary(info); 565 if (expr == NULL) 566 return NULL; 567 switch (expr->kind) { 568 case EX_FIXNUM: 569 expr->u.fixnum = -expr->u.fixnum; 570 return expr; 571 #ifndef __NO_FLONUM 572 case EX_FLONUM: 573 expr->u.flonum = -expr->u.flonum; 574 return expr; 575 #endif 576 default: { 577 struct Expr *op = new_expr(EX_NEG); 578 op->u.unary.sub = expr; 579 return op; 580 } 581 } 582 } 583 584 return prim(info); 585 } 586 587 static struct Expr * 588 parse_mul(struct ParseInfo *info) 589 { 590 struct Expr *expr = unary(info); 591 if (expr == NULL) 592 return expr; 593 594 const struct Token *tok; 595 while ((tok = match(info, TK_MUL)) != NULL || (tok = match(info, TK_DIV)) != NULL) { 596 struct Expr *rhs = unary(info); 597 if (rhs == NULL) { 598 parse_error(info, "expression error"); 599 break; 600 } 601 602 struct Expr *lhs = expr; 603 if (lhs->kind == EX_FIXNUM && rhs->kind == EX_FIXNUM) { 604 switch (tok->kind) { 605 case TK_MUL: 606 lhs->u.fixnum *= rhs->u.fixnum; 607 break; 608 case TK_DIV: 609 lhs->u.fixnum /= rhs->u.fixnum; 610 break; 611 default: 612 assert(0); 613 break; 614 } 615 } else { 616 expr = new_expr((enum ExprKind)(tok->kind + (EX_MUL - TK_MUL))); /* assume exprkind is same 617 * order with tokenkind */ 618 expr->u.bop.lhs = lhs; 619 expr->u.bop.rhs = rhs; 620 } 621 } 622 return expr; 623 } 624 625 static struct Expr * 626 parse_add(struct ParseInfo *info) 627 { 628 struct Expr *expr = parse_mul(info); 629 if (expr == NULL) 630 return expr; 631 632 const struct Token *tok; 633 while ((tok = match(info, TK_ADD)) != NULL || (tok = match(info, TK_SUB)) != NULL) { 634 struct Expr *rhs = parse_mul(info); 635 if (rhs == NULL) { 636 parse_error(info, "expression error"); 637 break; 638 } 639 640 struct Expr *lhs = expr; 641 if (lhs->kind == EX_FIXNUM && rhs->kind == EX_FIXNUM) { 642 switch (tok->kind) { 643 case TK_ADD: 644 lhs->u.fixnum += rhs->u.fixnum; 645 break; 646 case TK_SUB: 647 lhs->u.fixnum -= rhs->u.fixnum; 648 break; 649 default: 650 assert(0); 651 break; 652 } 653 } else { 654 /* assume exprkind is same order with tokenkind */ 655 expr = new_expr((enum ExprKind)(tok->kind + (EX_ADD - TK_ADD))); 656 expr->u.bop.lhs = lhs; 657 expr->u.bop.rhs = rhs; 658 } 659 } 660 return expr; 661 } 662 663 struct Expr * 664 parse_expr(struct ParseInfo *info) 665 { 666 info->prefetched = NULL; 667 return parse_add(info); 668 } 669 670 #define R_NOOP 0 671 672 static /* enum rawopcode */ int 673 find_raw_opcode(struct ParseInfo *info) 674 { 675 const char *p = info->p; 676 const char *start = p; 677 678 while (isalnum(*p) || *p == '.') 679 ++p; 680 if (*p == '\0' || isspace(*p)) { 681 size_t n = p - start; 682 for (int i = 0;; ++i) { 683 const char *name = arch.raw_op_table[i]; 684 if (name == NULL) 685 break; 686 size_t len = strlen(name); 687 if (n == len && strncasecmp(start, name, n) == 0) { 688 info->p = skip_whitespaces(p); 689 return i + 1; 690 } 691 } 692 } 693 return R_NOOP; 694 } 695 696 static int 697 parse_inst(struct ParseInfo *info, struct Line *line) 698 { 699 struct Inst inst; 700 inst.op = NOOP; 701 inst.prefix = 0; 702 for (int i = 0; i < (int)ARRAY_SIZE(inst.opr); ++i) 703 inst.opr[i].type = NOOPERAND; 704 705 /* scan for arch-specific instruction prefixes (lock, rep, etc) */ 706 if (arch.scan_prefix) { 707 unsigned char pfx; 708 while ((pfx = arch.scan_prefix(info)) != 0) 709 inst.prefix |= pfx; 710 } 711 712 /* enum rawopcode */ int op = find_raw_opcode(info); 713 if (op != R_NOOP) { 714 const struct ParseInstTable *pt = &arch.parse_inst_table[op]; 715 int n = pt->count; 716 #if __STDC_NO_VLA__ 717 const struct ParseOpArray **candidates = alloca(n * sizeof(*candidates)); 718 assert(candidates != NULL); 719 #else 720 const struct ParseOpArray *candidates[n]; 721 #endif 722 memcpy(candidates, pt->array, n * sizeof(*candidates)); 723 for (int i = 0; i < (int)ARRAY_SIZE(inst.opr); ++i) { 724 unsigned int opr_flags = 0; 725 for (int j = 0; j < n; ++j) 726 opr_flags |= candidates[j]->opr_flags[i]; 727 if (opr_flags == 0) 728 break; 729 730 if (i > 0) { 731 if (*info->p != ',') { 732 if (candidates[0]->opr_flags[i] == 0) 733 break; 734 parse_error(info, "comma expected"); 735 return 0; /* error */ 736 } 737 info->p = skip_whitespaces(info->p + 1); 738 } 739 740 struct Operand *opr = &inst.opr[i]; 741 unsigned int result = arch.parse_operand(info, opr_flags, opr); 742 if (result == 0) { 743 parse_error(info, "illegal operand"); 744 info->p = NULL; 745 return 0; /* error */ 746 } 747 748 for (int j = 0; j < n; ++j) { 749 if ((candidates[j]->opr_flags[i] & result) == 0) { 750 memmove(&candidates[j], &candidates[j + 1], (n - j - 1) * sizeof(*candidates)); 751 --n; 752 --j; 753 } 754 } 755 756 info->p = skip_whitespaces(info->p); 757 } 758 759 if (n > 0) { 760 inst.op = candidates[0]->op; 761 } else { 762 return parse_error(info, "illegal operand"); 763 } 764 if (*info->p != '\0') 765 return parse_error(info, "instruction text after operands"); 766 } else { 767 return parse_error(info, "unknown instruction"); 768 } 769 770 if (inst.op != NOOP) { 771 struct Inst *cloned = calloc_or_die(sizeof(inst)); 772 *cloned = inst; 773 line->inst = cloned; 774 } 775 return 1; 776 } 777 778 void 779 parse_set_p(struct ParseInfo *info, const char *p) 780 { 781 info->p = p; 782 info->prefetched = NULL; 783 } 784 785 static char 786 unescape_char(struct ParseInfo *info) 787 { 788 const char *p = info->p; 789 char c = *p++; 790 switch (c) { 791 case '0': 792 case '1': 793 case '2': 794 case '3': 795 case '4': 796 case '5': 797 case '6': 798 case '7': 799 case '8': 800 case '9': { 801 /* octal, but accepts '8' and '9' */ 802 int x = 0; 803 --p; 804 for (int i = 0; i < 3; ++i, ++p) { /* "the numeric code is 3 octal digits." */ 805 char cc = *p; 806 if (!isdigit(cc)) 807 break; 808 x = (x << 3) | (cc - '0'); 809 } 810 info->p = p - 1; 811 return x; 812 } 813 case 'x': { 814 int x = 0; 815 for (;; ++p) { /* "all trailing hex digits are combined." */ 816 int v = xvalue(*p); 817 if (v < 0) 818 break; /* TODO: error */ 819 x = (x << 4) | v; 820 } 821 info->p = p - 1; 822 return x; 823 } 824 case 'a': 825 return '\a'; 826 case 'b': 827 return '\b'; 828 case 'f': 829 return '\f'; 830 case 'n': 831 return '\n'; 832 case 'r': 833 return '\r'; 834 case 't': 835 return '\t'; 836 case 'v': 837 return '\v'; 838 839 default: 840 parse_error(info, "illegal escape"); 841 /* fallthrough */ 842 case '\'': 843 case '"': 844 case '\\': 845 return c; 846 } 847 } 848 849 static size_t 850 unescape_string(struct ParseInfo *info, char *dst) 851 { 852 size_t len = 0; 853 for (; *info->p != '"'; ++info->p, ++len) { 854 char c = *info->p; 855 if (c == '\0') 856 parse_error(info, "string not closed"); 857 if (c == '\\') { 858 ++info->p; 859 c = unescape_char(info); 860 } 861 if (dst != NULL) 862 *dst++ = c; 863 } 864 ++info->p; 865 return len; 866 } 867 868 #if TC_TARGET_PLATFORM != TC_PLATFORM_APPLE 869 static char * 870 parse_string(struct ParseInfo *info) 871 { 872 const char *start = skip_whitespaces(info->p); 873 if (*start != '"') 874 return NULL; 875 876 info->p = start; 877 const char *p = get_label_end(info); 878 if (p == start) 879 return NULL; 880 881 info->p = p; 882 883 const char *s = start + 1, *e = p - 1; 884 return strndup(s, e - s); 885 } 886 887 static uint32_t 888 parse_section_flag(struct ParseInfo *info) 889 { 890 uint32_t flag = 0; 891 char *flag_str = parse_string(info); 892 if (flag_str == NULL) { 893 parse_error(info, ".section: flag string expected"); 894 } else { 895 for (char *p = flag_str; *p != '\0'; ++p) { 896 switch (*p) { 897 case 'a': /* ignore */ 898 break; 899 case 'w': 900 flag |= SF_WRITABLE; 901 break; 902 case 'x': 903 flag |= SF_EXECUTABLE; 904 break; 905 case 'T': 906 flag |= SF_TLS; 907 break; 908 default: 909 parse_error(info, ".section: illegal flag character"); 910 break; 911 } 912 } 913 } 914 return flag; 915 } 916 #endif 917 918 static int 919 dir_string(struct ParseInfo *info, enum DirectiveType dir) 920 { 921 if (*info->p != '"') 922 return parse_error(info, "`\"' expected"); 923 ++info->p; 924 const char *p = info->p; 925 size_t len = unescape_string(info, NULL); 926 if (dir == DT_STRING) 927 ++len; 928 char *str = calloc_or_die(len); 929 info->p = p; /* again */ 930 unescape_string(info, str); 931 932 struct SectionInfo *section = info->current_section; 933 struct Vector *irs = section->irs; 934 vec_push(irs, new_ir_data(str, len)); 935 return 1; 936 } 937 938 static int 939 dir_comm(struct ParseInfo *info, enum DirectiveType dir) 940 { 941 UNUSED(dir); 942 const struct Name *name = parse_label(info); 943 if (name == NULL) 944 return parse_error(info, ".comm: label expected"); 945 info->p = skip_whitespaces(info->p); 946 if (*info->p != ',') 947 return parse_error(info, ".comm: `,' expected"); 948 info->p = skip_whitespaces(info->p + 1); 949 int64_t size; 950 if (!immediate(&info->p, &size) || size <= 0) 951 return parse_error(info, ".comm: size expected"); 952 953 int64_t align = 0; 954 if (*info->p == ',') { 955 info->p = skip_whitespaces(info->p + 1); 956 if ( 957 !immediate(&info->p, &align) || 958 #if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE 959 align < 0 960 #else 961 align < 1 962 #endif 963 ) { 964 return parse_error(info, ".comm: optional alignment expected"); 965 } 966 #if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE 967 /* p2align on macos */ 968 align = 1 << align; 969 #endif 970 } 971 972 struct SectionInfo *section = get_section_info(info, kSecBss, kSegBss, SF_BSS | SF_WRITABLE); 973 struct Vector *irs = section->irs; 974 if (align > 1) 975 vec_push(irs, new_ir_align(align)); 976 vec_push(irs, new_ir_label(name)); 977 vec_push(irs, new_ir_bss(size)); 978 979 struct LabelInfo *label = add_label_table(info->label_table, name, section, 1, 0); 980 if (label == NULL) 981 return 0; 982 label->size = size; 983 label->align = align; 984 label->flag |= LF_COMM; 985 return 1; 986 } 987 988 static int 989 dir_zero(struct ParseInfo *info, enum DirectiveType dir) 990 { 991 UNUSED(dir); 992 int64_t num; 993 if (!immediate(&info->p, &num)) 994 return parse_error(info, ".zero: number expected"); 995 996 struct SectionInfo *section = info->current_section; 997 struct Vector *irs = section->irs; 998 vec_push(irs, new_ir_zero(num)); 999 return 1; 1000 } 1001 1002 static int 1003 dir_text(struct ParseInfo *info, enum DirectiveType dir) 1004 { 1005 UNUSED(dir); 1006 set_current_section(info, kSecText, kSegText, SF_EXECUTABLE); 1007 return 1; 1008 } 1009 1010 static int 1011 dir_data(struct ParseInfo *info, enum DirectiveType dir) 1012 { 1013 UNUSED(dir); 1014 set_current_section(info, kSecData, kSegData, SF_WRITABLE); 1015 return 1; 1016 } 1017 1018 static int 1019 dir_bss(struct ParseInfo *info, enum DirectiveType dir) 1020 { 1021 UNUSED(dir); 1022 set_current_section(info, kSecBss, kSegBss, SF_BSS | SF_WRITABLE); 1023 return 1; 1024 } 1025 1026 static int 1027 dir_align(struct ParseInfo *info, enum DirectiveType dir) 1028 { 1029 int64_t align; 1030 if (!immediate(&info->p, &align)) 1031 return parse_error(info, ".align: number expected"); 1032 if (dir == DT_P2ALIGN) 1033 align = 1 << align; 1034 1035 struct SectionInfo *section = info->current_section; 1036 struct Vector *irs = section->irs; 1037 vec_push(irs, new_ir_align(align)); 1038 return 1; 1039 } 1040 1041 static int 1042 dir_type(struct ParseInfo *info, enum DirectiveType dir) 1043 { 1044 UNUSED(dir); 1045 const struct Name *name = parse_label(info); 1046 if (name == NULL) 1047 return parse_error(info, ".type: label expected"); 1048 if (*info->p != ',') 1049 return parse_error(info, ".type: `,' expected"); 1050 info->p = skip_whitespaces(info->p + 1); 1051 enum LabelKind kind = LK_NONE; 1052 if (strcmp(info->p, "@function") == 0) { 1053 kind = LK_FUNC; 1054 info->p += 9; 1055 } else if (strcmp(info->p, "@object") == 0) { 1056 kind = LK_OBJECT; 1057 info->p += 7; 1058 } else { 1059 return parse_error(info, "illegal .type"); 1060 } 1061 1062 struct SectionInfo *section = info->current_section; 1063 struct LabelInfo *label = add_label_table(info->label_table, name, section, 0, 0); 1064 if (label != NULL) { 1065 label->kind = kind; 1066 } 1067 return 1; 1068 } 1069 1070 static int 1071 dir_bytes(struct ParseInfo *info, enum DirectiveType dir) 1072 { 1073 struct Expr *expr = parse_expr(info); 1074 if (expr == NULL) 1075 return parse_error(info, "expression expected"); 1076 1077 struct SectionInfo *section = info->current_section; 1078 struct Vector *irs = section->irs; 1079 1080 assert(expr->kind != EX_FLONUM); 1081 if (expr->kind == EX_FIXNUM) { 1082 /* TODO: target endian */ 1083 long value = expr->u.fixnum; 1084 int size = 1 << (dir - DT_BYTE); 1085 unsigned char *buf = malloc_or_die(size); 1086 for (int i = 0; i < size; ++i) 1087 buf[i] = value >> (8 * i); 1088 vec_push(irs, new_ir_data(buf, size)); 1089 } else { 1090 vec_push(irs, new_ir_expr((enum IrKind)(IR_EXPR_BYTE + (dir - DT_BYTE)), expr)); 1091 } 1092 return 1; 1093 } 1094 1095 /* .size is parsed but ignored, the linker computes sizes from section layout */ 1096 static int 1097 dir_size(struct ParseInfo *info, enum DirectiveType dir) 1098 { 1099 UNUSED(dir); 1100 /* consume the symbol name and comma */ 1101 parse_label(info); 1102 info->p = skip_whitespaces(info->p); 1103 if (*info->p == ',') { 1104 info->p = skip_whitespaces(info->p + 1); 1105 /* consume the rest of the line as an expression */ 1106 parse_expr(info); 1107 } 1108 return 1; 1109 } 1110 1111 #ifndef __NO_FLONUM 1112 static int 1113 dir_float(struct ParseInfo *info, enum DirectiveType dir) 1114 { 1115 struct Expr *expr = parse_expr(info); 1116 if (expr == NULL) 1117 return parse_error(info, "expression expected"); 1118 1119 Flonum value; 1120 switch (expr->kind) { 1121 case EX_FIXNUM: 1122 value = expr->u.fixnum; 1123 break; 1124 case EX_FLONUM: 1125 value = expr->u.flonum; 1126 break; 1127 default: 1128 assert(0); 1129 value = -1; 1130 break; 1131 } 1132 int size; 1133 switch (dir) { 1134 default: 1135 assert(0); /* fallthrough */ 1136 case DT_DOUBLE: 1137 size = sizeof(double); 1138 break; 1139 case DT_FLOAT: 1140 size = sizeof(float); 1141 break; 1142 } 1143 unsigned char *buf = malloc_or_die(size); 1144 if (dir == DT_FLOAT) { 1145 float fval = value; 1146 memcpy(buf, (void *)&fval, sizeof(fval)); /* TODO: endian */ 1147 } else { 1148 double dval = value; 1149 memcpy(buf, (void *)&dval, sizeof(dval)); /* TODO: endian */ 1150 } 1151 1152 struct SectionInfo *section = info->current_section; 1153 struct Vector *irs = section->irs; 1154 vec_push(irs, new_ir_data(buf, size)); 1155 return 1; 1156 } 1157 #endif 1158 1159 static int 1160 dir_label_attrib(struct ParseInfo *info, enum DirectiveType dir) 1161 { 1162 const struct Name *name = parse_label(info); 1163 if (name == NULL) { 1164 char buf[32]; 1165 snprintf(buf, sizeof(buf), "%s: label expected", dir == DT_GLOBL ? ".globl" : ".local"); 1166 return parse_error(info, buf); 1167 } 1168 1169 struct SectionInfo *section = info->current_section; 1170 struct LabelInfo *label = add_label_table(info->label_table, name, section, 0, dir == DT_GLOBL); 1171 if (label == NULL) { 1172 ++info->error_count; 1173 } else { 1174 if (dir == DT_WEAK) 1175 label->flag |= LF_WEAK; 1176 } 1177 return 1; 1178 } 1179 1180 static int 1181 dir_section(struct ParseInfo *info, enum DirectiveType dir) 1182 { 1183 UNUSED(dir); 1184 const struct Name *name = parse_section_name(info); 1185 if (name == NULL) 1186 return parse_error(info, ".section: section name expected"); 1187 #if TC_TARGET_PLATFORM != TC_PLATFORM_APPLE 1188 int flag = 0; 1189 const char *p = skip_whitespaces(info->p); 1190 if (*p == ',') { 1191 info->p = p + 1; 1192 flag = parse_section_flag(info); 1193 } 1194 1195 /* optional third field, elf section type (@progbits, @nobits, @note, 1196 * ...): this assembler infers the section type from the section 1197 * name/flags itself, so the field is accepted and only @note, which 1198 * the name .note* implies as well, changes anything */ 1199 if (name->bytes >= 5 && !strncmp(name->chars, ".note", 5)) 1200 flag |= SF_NOTE; 1201 p = skip_whitespaces(info->p); 1202 if (*p == ',') { 1203 const char *q = p + 1; 1204 q = skip_whitespaces(q); 1205 if (*q == '@') { 1206 ++q; 1207 if (!strncmp(q, "note", 4) && !isalnum((unsigned char)q[4])) 1208 flag |= SF_NOTE; 1209 while (isalpha((unsigned char)*q) || isdigit((unsigned char)*q)) 1210 ++q; 1211 info->p = q; 1212 } 1213 } 1214 1215 char *sectname = strndup(name->chars, name->bytes); 1216 set_current_section(info, sectname, kSegRodata, flag); 1217 #else 1218 const char *p = skip_whitespaces(info->p); 1219 if (*p != ',') 1220 return parse_error(info, "`,' expected"); 1221 info->p = skip_whitespaces(p + 1); 1222 const struct Name *name2 = parse_section_name(info); 1223 if (name2 == NULL) 1224 return parse_error(info, ".section: section name expected"); 1225 1226 int flag = 0; 1227 p = skip_whitespaces(info->p); 1228 if (*p == ',') { 1229 info->p = p + 1; 1230 const struct Name *modname = parse_section_name(info); 1231 if (modname != NULL) { 1232 if (equal_name(modname, alloc_cname("mod_init_funcs"))) { 1233 flag |= SF_INIT_FUNCS; 1234 } else if (equal_name(modname, alloc_cname("cstring_literals"))) { 1235 flag |= SF_CSTRLITERALS; 1236 } 1237 } 1238 if (flag == 0) 1239 return parse_error(info, ".section: section name expected"); 1240 } 1241 1242 char *segname = strndup(name->chars, name->bytes); 1243 char *sectname = strndup(name2->chars, name2->bytes); 1244 set_current_section(info, sectname, segname, flag); 1245 #endif 1246 return 1; 1247 } 1248 1249 #if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE 1250 static int 1251 dir_subsections_via_symbols(struct ParseInfo *info, enum DirectiveType dir) 1252 { 1253 /* TODO: handle this flag */ 1254 UNUSED(info); 1255 UNUSED(dir); 1256 return 1; 1257 } 1258 #endif 1259 1260 /* data directive aliases: .int/.word/.nbyte map to .long/.short/etc */ 1261 static int 1262 dir_bytes_alias(struct ParseInfo *info, enum DirectiveType dir) 1263 { 1264 switch (dir) { 1265 case DT_INT: 1266 dir = DT_LONG; 1267 break; /* .int = 4 bytes */ 1268 case DT_WORD: 1269 dir = DT_SHORT; 1270 break; /* .word = 2 bytes */ 1271 case DT_2BYTE: 1272 dir = DT_SHORT; 1273 break; 1274 case DT_4BYTE: 1275 dir = DT_LONG; 1276 break; 1277 case DT_8BYTE: 1278 dir = DT_QUAD; 1279 break; 1280 default: 1281 break; 1282 } 1283 return dir_bytes(info, dir); 1284 } 1285 1286 /* .fill repeat, size, value (gas manual) 1287 * repeat: number of data units, size: 1/2/4/8, value: fill pattern */ 1288 static int 1289 dir_fill(struct ParseInfo *info, enum DirectiveType dir) 1290 { 1291 UNUSED(dir); 1292 int64_t repeat = 1; 1293 int64_t size = 1; 1294 int64_t value = 0; 1295 struct SectionInfo *section; 1296 struct Vector *irs; 1297 int64_t i; 1298 1299 if (!immediate(&info->p, &repeat)) 1300 return parse_error(info, ".fill: repeat count expected"); 1301 1302 info->p = skip_whitespaces(info->p); 1303 if (*info->p == ',') { 1304 info->p = skip_whitespaces(info->p + 1); 1305 if (!immediate(&info->p, &size)) 1306 return parse_error(info, ".fill: size expected"); 1307 if (size != 1 && size != 2 && size != 4 && size != 8) 1308 return parse_error(info, ".fill: size must be 1, 2, 4, or 8"); 1309 1310 info->p = skip_whitespaces(info->p); 1311 if (*info->p == ',') { 1312 info->p = skip_whitespaces(info->p + 1); 1313 if (!immediate(&info->p, &value)) 1314 return parse_error(info, ".fill: value expected"); 1315 } 1316 } 1317 1318 section = info->current_section; 1319 irs = section->irs; 1320 if (value == 0) { 1321 /* a bss section has no data buffer to hold literal bytes; a 1322 zero fill is exactly what ir_zero already reserves */ 1323 vec_push(irs, new_ir_zero(repeat * size)); 1324 return 1; 1325 } 1326 for (i = 0; i < repeat; ++i) { 1327 unsigned char *buf = malloc_or_die(size); 1328 int j; 1329 for (j = 0; j < size; ++j) 1330 buf[j] = value >> (8 * j); 1331 vec_push(irs, new_ir_data(buf, size)); 1332 } 1333 return 1; 1334 } 1335 1336 /* .space size[, fill] and .skip alias 1337 * reserves size bytes filled with fill (default 0) */ 1338 static int 1339 dir_space(struct ParseInfo *info, enum DirectiveType dir) 1340 { 1341 UNUSED(dir); 1342 int64_t size; 1343 int64_t fill = 0; 1344 struct SectionInfo *section; 1345 struct Vector *irs; 1346 unsigned char *buf; 1347 int i; 1348 1349 if (!immediate(&info->p, &size)) 1350 return parse_error(info, ".space: size expected"); 1351 1352 info->p = skip_whitespaces(info->p); 1353 if (*info->p == ',') { 1354 info->p = skip_whitespaces(info->p + 1); 1355 if (!immediate(&info->p, &fill)) 1356 return parse_error(info, ".space: fill value expected"); 1357 } 1358 1359 section = info->current_section; 1360 irs = section->irs; 1361 if (fill == 0) { 1362 /* a bss section has no data buffer to hold literal bytes; a 1363 zero fill is exactly what ir_zero already reserves */ 1364 vec_push(irs, new_ir_zero(size)); 1365 return 1; 1366 } 1367 buf = malloc_or_die(size); 1368 for (i = 0; i < size; ++i) 1369 buf[i] = (unsigned char)fill; 1370 vec_push(irs, new_ir_data(buf, size)); 1371 return 1; 1372 } 1373 1374 /* .set/.equ: symbol assignment. tolerated for now, full evaluation 1375 * would require registering the symbol in the expression evaluator */ 1376 static int 1377 dir_set(struct ParseInfo *info, enum DirectiveType dir) 1378 { 1379 UNUSED(dir); 1380 parse_label(info); 1381 info->p = skip_whitespaces(info->p); 1382 if (*info->p == ',') { 1383 info->p = skip_whitespaces(info->p + 1); 1384 parse_expr(info); 1385 } 1386 return 1; 1387 } 1388 1389 /* tolerated directives: consume arguments and discard 1390 * used for .file, .loc, .ident, .extern, .previous, .cfi_* */ 1391 static int 1392 dir_ignore(struct ParseInfo *info, enum DirectiveType dir) 1393 { 1394 UNUSED(dir); 1395 UNUSED(info); 1396 return 1; 1397 } 1398 1399 static inline int 1400 handle_directive(struct ParseInfo *info, enum DirectiveType dir) 1401 { 1402 typedef int (*DirectiveFunc)(struct ParseInfo *info, enum DirectiveType dir); 1403 1404 static const DirectiveFunc kDirectiveFuncTable[] = { 1405 [NODIRECTIVE] = NULL, 1406 [DT_ASCII] = dir_string, 1407 [DT_STRING] = dir_string, 1408 [DT_SECTION] = dir_section, 1409 [DT_TEXT] = dir_text, 1410 [DT_DATA] = dir_data, 1411 [DT_BSS] = dir_bss, 1412 [DT_ALIGN] = dir_align, 1413 [DT_P2ALIGN] = dir_align, 1414 [DT_BALIGN] = dir_align, 1415 [DT_TYPE] = dir_type, 1416 [DT_BYTE] = dir_bytes, 1417 [DT_SHORT] = dir_bytes, 1418 [DT_LONG] = dir_bytes, 1419 [DT_QUAD] = dir_bytes, 1420 [DT_COMM] = dir_comm, 1421 [DT_ZERO] = dir_zero, 1422 [DT_GLOBL] = dir_label_attrib, 1423 [DT_LOCAL] = dir_label_attrib, 1424 [DT_WEAK] = dir_label_attrib, 1425 [DT_EXTERN] = dir_ignore, 1426 [DT_INT] = dir_bytes_alias, 1427 [DT_WORD] = dir_bytes_alias, 1428 [DT_2BYTE] = dir_bytes_alias, 1429 [DT_4BYTE] = dir_bytes_alias, 1430 [DT_8BYTE] = dir_bytes_alias, 1431 [DT_FILL] = dir_fill, 1432 [DT_SPACE] = dir_space, 1433 [DT_SKIP] = dir_space, 1434 [DT_SET] = dir_set, 1435 [DT_EQU] = dir_set, 1436 [DT_FILE] = dir_ignore, 1437 [DT_LOC] = dir_ignore, 1438 [DT_IDENT] = dir_ignore, 1439 [DT_PREVIOUS] = dir_ignore, 1440 #ifndef __NO_FLONUM 1441 [DT_FLOAT] = dir_float, 1442 [DT_DOUBLE] = dir_float, 1443 #endif 1444 #if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE 1445 [DT_SUBSECTIONS_VIA_SYMBOLS] = dir_subsections_via_symbols, 1446 #endif 1447 [DT_SIZE] = dir_size, 1448 [DT_CFI] = dir_ignore, 1449 }; 1450 1451 DirectiveFunc func = kDirectiveFuncTable[dir]; 1452 if (func == NULL) 1453 return 1; 1454 return (*func)(info, dir); 1455 } 1456 1457 int 1458 parse_line(struct Line *line, struct ParseInfo *info) 1459 { 1460 memset(line, 0, sizeof(*line)); 1461 line->label = NULL; 1462 line->inst = NULL; 1463 line->dir = NODIRECTIVE; 1464 1465 const char *p = skip_whitespaces(info->p); 1466 info->p = p; 1467 const char *q = get_label_end(info); 1468 const char *r = skip_whitespaces(q); 1469 if (*r == ':') { 1470 const struct Name *label = unquote_label(p, q); 1471 if (label == NULL) 1472 return parse_error(info, "illegal label"); 1473 line->label = label; 1474 info->p = p = skip_whitespaces(r + 1); 1475 } else if (*p == '.') { 1476 enum DirectiveType dir = find_directive(p + 1, q - p - 1); 1477 if (dir == NODIRECTIVE) { 1478 parse_error(info, "unknown directive"); 1479 return 0; 1480 } 1481 line->dir = dir; 1482 info->p = r; 1483 return handle_directive(info, dir); 1484 } 1485 1486 if (*p != '\0') { 1487 info->p = p; 1488 if (!parse_inst(info, line)) 1489 return 0; 1490 } 1491 return 1; 1492 } 1493 1494 struct Value 1495 calc_expr(struct Table *label_table, const struct Expr *expr) 1496 { 1497 assert(expr != NULL); 1498 switch (expr->kind) { 1499 case EX_LABEL: 1500 return (struct Value){.label = expr->u.label.name, .offset = 0}; 1501 case EX_FIXNUM: 1502 return (struct Value){.label = NULL, .offset = expr->u.fixnum}; 1503 case EX_ADD: 1504 case EX_SUB: 1505 case EX_MUL: 1506 case EX_DIV: { 1507 struct Value lhs = calc_expr(label_table, expr->u.bop.lhs); 1508 struct Value rhs = calc_expr(label_table, expr->u.bop.rhs); 1509 if (rhs.label != NULL) { 1510 if (expr->kind == EX_SUB && lhs.label != NULL) { 1511 struct LabelInfo *llabel, *rlabel; 1512 if (table_try_get(label_table, lhs.label, (void **)&llabel) 1513 && table_try_get(label_table, rhs.label, (void **)&rlabel)) { 1514 return (struct Value){.label = NULL, .offset = llabel->address - rlabel->address}; 1515 } else { 1516 error("Unresolved"); 1517 } 1518 } 1519 if (expr->kind != EX_ADD || lhs.label != NULL) { 1520 error("Illegal expression"); 1521 } 1522 /* offset + label */ 1523 return (struct Value){.label = rhs.label, .offset = lhs.offset + rhs.offset}; 1524 } 1525 if (lhs.label != NULL) { 1526 if (expr->kind != EX_ADD) { 1527 error("Illegal expression"); 1528 } 1529 /* label + offset */ 1530 return (struct Value){.label = lhs.label, .offset = lhs.offset + rhs.offset}; 1531 } 1532 1533 assert(lhs.label == NULL && rhs.label == NULL); 1534 switch (expr->kind) { 1535 case EX_ADD: 1536 lhs.offset += rhs.offset; 1537 break; 1538 case EX_SUB: 1539 lhs.offset -= rhs.offset; 1540 break; 1541 case EX_MUL: 1542 lhs.offset *= rhs.offset; 1543 break; 1544 case EX_DIV: 1545 lhs.offset /= rhs.offset; 1546 break; 1547 default: 1548 assert(0); 1549 break; 1550 } 1551 return lhs; 1552 } 1553 1554 case EX_POS: 1555 case EX_NEG: { 1556 struct Value value = calc_expr(label_table, expr->u.unary.sub); 1557 if (value.label != NULL) { 1558 error("Illegal expression"); 1559 } 1560 if (expr->kind == EX_NEG) 1561 value.offset = -value.offset; 1562 return value; 1563 } 1564 1565 default: 1566 assert(0); 1567 break; 1568 } 1569 return (struct Value){.label = NULL, .offset = 0}; 1570 }