|
|
1.1 ! root 1: /* ! 2: Hatari - calculate.c ! 3: ! 4: Copyright (C) 1994, 2009-2010 by Eero Tamminen ! 5: ! 6: This file is distributed under the GNU Public License, version 2 or at ! 7: your option any later version. Read the file gpl.txt for details. ! 8: ! 9: calculate.c - parse numbers, number ranges and expressions. Supports ! 10: most unary and binary operations. Parenthesis are used for indirect ! 11: ST RAM value addressing. ! 12: ! 13: Originally based on code from my Clac calculator MiNT filter version. ! 14: */ ! 15: const char Eval_fileid[] = "Hatari calculate.c : " __DATE__ " " __TIME__; ! 16: ! 17: #include <ctype.h> ! 18: #include <limits.h> ! 19: #include <errno.h> ! 20: #include <stdio.h> ! 21: #include <stdlib.h> ! 22: #include <stdbool.h> ! 23: #include <SDL_types.h> ! 24: #include "breakcond.h" ! 25: #include "configuration.h" ! 26: #include "debugcpu.h" ! 27: #include "evaluate.h" ! 28: #include "main.h" ! 29: #include "m68000.h" ! 30: #include "nextMemory.h" ! 31: #include "symbols.h" ! 32: ! 33: /* define which character indicates which type of number on expression */ ! 34: #define PREFIX_BIN '%' /* binary decimal */ ! 35: #define PREFIX_DEC '#' /* normal decimal */ ! 36: #define PREFIX_HEX '$' /* hexadecimal */ ! 37: ! 38: /* define error codes */ ! 39: #define CLAC_EXP_ERR "No expression given" ! 40: #define CLAC_GEN_ERR "Syntax error" ! 41: #define CLAC_PAR_ERR "Mismatched parenthesis" ! 42: #define CLAC_DEF_ERR "Undefined result (1/0)" ! 43: #define CLAC_STK_ERR "Operation/value stack full" ! 44: #define CLAC_OVF_ERR "Overflow" ! 45: #define CLAC_OVR_ERR "Mode overflow" ! 46: #define CLAC_PRG_ERR "Internal program error" ! 47: ! 48: /* define internal allocation sizes (should be enough ;-) */ ! 49: #define PARDEPTH_MAX 16 /* max. parenth. nesting depth */ ! 50: #define OSTACK_MAX 64 /* size of the operator stack */ ! 51: #define VSTACK_MAX 64 /* size of the value stack */ ! 52: ! 53: /* operation with lowest precedence, used to finish calculations */ ! 54: #define LOWEST_PREDECENCE '|' ! 55: ! 56: /* globals + function identifier stack(s) */ ! 57: static struct { ! 58: const char *error; /* global error code */ ! 59: bool valid; /* value validation */ ! 60: } id = {0, 0}; ! 61: ! 62: /* parenthesis and function stacks */ ! 63: static struct { ! 64: int idx; /* parenthesis level */ ! 65: int max; /* maximum idx */ ! 66: int opx[PARDEPTH_MAX + 1]; /* current op index for par */ ! 67: int vax[PARDEPTH_MAX + 1]; /* current val index for par */ ! 68: } par = {0, PARDEPTH_MAX, {0}, {0}}; ! 69: ! 70: static struct { /* operator stack */ ! 71: int idx; ! 72: int max; ! 73: char buf[OSTACK_MAX + 1]; ! 74: } op = {0, OSTACK_MAX, ""}; ! 75: ! 76: static struct value_stk { /* value stack */ ! 77: int idx; ! 78: int max; ! 79: long long buf[VSTACK_MAX + 1]; ! 80: } val = {0, VSTACK_MAX, {0}}; ! 81: ! 82: /* -------------------------------------------------------------------- */ ! 83: /* macros */ ! 84: ! 85: /* increment stack index and put value on stack (ie. PUSH) */ ! 86: #define PUSH(stk,val) \ ! 87: if((stk).idx < (stk).max) { \ ! 88: (stk).idx += 1; \ ! 89: (stk).buf[(stk).idx] = (val); \ ! 90: } else { \ ! 91: id.error = CLAC_STK_ERR; \ ! 92: } ! 93: ! 94: /* -------------------------------------------------------------------- */ ! 95: /* declare subfunctions */ ! 96: ! 97: /* parse in-between operations */ ! 98: static void operation(long long value, char op); ! 99: /* parse unary operators */ ! 100: static void unary (char op); ! 101: /* apply a prefix to a value */ ! 102: static void apply_prefix(void); ! 103: /* juggle stacks, if possible */ ! 104: static void eval_stack(void); ! 105: /* operator -> operator level */ ! 106: static int get_level(int stk_offset); ! 107: /* evaluate operation */ ! 108: static long long apply_op(char op, long long x, long long y); ! 109: ! 110: /* increase parenthesis level */ ! 111: static void open_bracket(void); ! 112: /* decrease parenthesis level */ ! 113: static long long close_bracket(long long x); ! 114: ! 115: ! 116: /** ! 117: * Parse & set an (unsigned) number, assuming it's in the configured ! 118: * default number base unless it has a prefix: ! 119: * - '$' / '0x' / '0h' => hexadecimal ! 120: * - '#' / '0d' => normal decimal ! 121: * - '%' / '0b' => binary decimal ! 122: * - '0o' => octal decimal ! 123: * Return how many characters were parsed or zero for error. ! 124: */ ! 125: static int getNumber(const char *str, Uint32 *number, int *nbase) ! 126: { ! 127: char *end; ! 128: const char *start = str; ! 129: int base = ConfigureParams.Debugger.nNumberBase; ! 130: unsigned long int value; ! 131: ! 132: if (!str[0]) { ! 133: fprintf(stderr, "Value missing!\n"); ! 134: return 0; ! 135: } ! 136: ! 137: /* determine correct number base */ ! 138: if (str[0] == '0') { ! 139: ! 140: /* 0x & 0h = hex, 0d = dec, 0o = oct, 0b = bin ? */ ! 141: switch(str[1]) { ! 142: case 'b': ! 143: base = 2; ! 144: break; ! 145: case 'o': ! 146: base = 8; ! 147: break; ! 148: case 'd': ! 149: base = 10; ! 150: break; ! 151: case 'h': ! 152: case 'x': ! 153: base = 16; ! 154: break; ! 155: default: ! 156: str -= 2; ! 157: } ! 158: str += 2; ! 159: } ! 160: else if (!isxdigit(str[0])) { ! 161: ! 162: /* doesn't start with (hex) number -> is it prefix? */ ! 163: switch (*str++) { ! 164: case PREFIX_BIN: ! 165: base = 2; ! 166: break; ! 167: case PREFIX_DEC: ! 168: base = 10; ! 169: break; ! 170: case PREFIX_HEX: ! 171: base = 16; ! 172: break; ! 173: default: ! 174: fprintf(stderr, "Unrecognized number prefix in '%s'!\n", start); ! 175: return 0; ! 176: } ! 177: } ! 178: *nbase = base; ! 179: ! 180: /* parse number */ ! 181: errno = 0; ! 182: value = strtoul(str, &end, base); ! 183: if (errno == ERANGE && value == LONG_MAX) { ! 184: fprintf(stderr, "Overflow with value '%s'!\n", start); ! 185: return 0; ! 186: } ! 187: if ((errno != 0 && value == 0) || end == str) { ! 188: fprintf(stderr, "Invalid value '%s'!\n", start); ! 189: return 0; ! 190: } ! 191: *number = value; ! 192: return end - start; ! 193: } ! 194: ! 195: ! 196: /** ! 197: * Parse unsigned register/symbol/number value and set it to "number" ! 198: * and the number base used for parsing to "base". ! 199: * Return how many characters were parsed or zero for error. ! 200: */ ! 201: static int getValue(const char *str, Uint32 *number, int *base, bool bForDsp) ! 202: { ! 203: char name[64]; ! 204: const char *end; ! 205: Uint32 *addr; ! 206: int len; ! 207: ! 208: for (end = str; *end == '_' || isalnum(*end); end++); ! 209: ! 210: len = end-str; ! 211: if (len >= (int)sizeof(name)) { ! 212: fprintf(stderr, "ERROR: symbol name at '%s' too long (%d chars)\n", str, len); ! 213: return 0; ! 214: } ! 215: memcpy(name, str, len); ! 216: name[len] = '\0'; ! 217: ! 218: *base = 0; /* no base (e.g. variable) */ ! 219: ! 220: /* internal Hatari variable? */ ! 221: // if (BreakCond_GetHatariVariable(name, number)) { ! 222: // return len; ! 223: // } ! 224: ! 225: if (bForDsp) { ! 226: if (Symbols_GetDspAddress(SYMTYPE_ALL, name, number)) { ! 227: return len; ! 228: } ! 229: } else { ! 230: /* a special case CPU register? */ ! 231: if (strcasecmp(name, "PC") == 0) { ! 232: *number = M68000_GetPC(); ! 233: return len; ! 234: } ! 235: if (strcasecmp(name, "SR") == 0) { ! 236: *number = M68000_GetSR(); ! 237: return len; ! 238: } ! 239: /* a normal CPU register or symbol? */ ! 240: if (DebugCpu_GetRegisterAddress(name, &addr)) { ! 241: *number = *addr; ! 242: return len; ! 243: } ! 244: if (Symbols_GetCpuAddress(SYMTYPE_ALL, name, number)) { ! 245: return len; ! 246: } ! 247: } ! 248: ! 249: /* none of above, assume it's a number */ ! 250: return getNumber(str, number, base); ! 251: } ! 252: ! 253: ! 254: /* Check that number string is OK and isn't followed by unrecognized ! 255: * character (last char char is zero). If not, complain about it. ! 256: * Return true for success and false for failure. ! 257: */ ! 258: static bool isNumberOK(const char *str, int offset, int base) ! 259: { ! 260: const char *basestr; ! 261: ! 262: if (!offset) { ! 263: return false; ! 264: } ! 265: if (!str[offset]) { ! 266: /* no extra chars after the parsed part */ ! 267: return true; ! 268: } ! 269: switch (base) { ! 270: case 0: ! 271: fprintf(stderr, "Name '%s' contains non-alphanumeric characters!\n", str); ! 272: return false; ! 273: case 2: ! 274: basestr = "binary"; ! 275: break; ! 276: case 8: ! 277: basestr = "octal"; ! 278: break; ! 279: case 10: ! 280: basestr = "decimal"; ! 281: break; ! 282: case 16: ! 283: basestr = "hexadecimal"; ! 284: break; ! 285: default: ! 286: basestr = "unknown"; ! 287: } ! 288: fprintf(stderr, "Extra characters in %s based number '%s'!\n", basestr, str); ! 289: return false; ! 290: } ! 291: ! 292: /** ! 293: * Parse & set an (unsigned) number, assume it's in the configured ! 294: * default number base unless it has a suitable prefix. ! 295: * Return true for success and false for failure. ! 296: */ ! 297: bool Eval_Number(const char *str, Uint32 *number) ! 298: { ! 299: int offset, base; ! 300: /* TODO: add CPU/DSP flag and use getValue() instead of getNumber() ! 301: * like getRange() does, so that user can use variable names in ! 302: * addition to numbers. ! 303: */ ! 304: offset = getNumber(str, number, &base); ! 305: return isNumberOK(str, offset, base); ! 306: } ! 307: ! 308: ! 309: /** ! 310: * Parse an address range, eg. "$fa0000[-$fa0100]" or "pc[-a0]" and ! 311: * output appropriate warnings if range or values are invalid. ! 312: * Address can also be a register/variable/symbol name. ! 313: * returns: ! 314: * -1 if invalid address or range, ! 315: * 0 if single address, ! 316: * +1 if a range. ! 317: */ ! 318: int Eval_Range(char *str1, Uint32 *lower, Uint32 *upper, bool fordsp) ! 319: { ! 320: int offset, base, ret; ! 321: bool fDash = false; ! 322: char *str2 = str1; ! 323: ! 324: while (*str2) { ! 325: if (*str2 == '-') { ! 326: *str2++ = '\0'; ! 327: fDash = true; ! 328: break; ! 329: } ! 330: str2++; ! 331: } ! 332: ! 333: offset = getValue(str1, lower, &base, fordsp); ! 334: if (!isNumberOK(str1, offset, base)) { ! 335: /* first number not OK */ ! 336: fprintf(stderr,"Invalid address value '%s'!\n", str1); ! 337: ret = -1; ! 338: } else { ! 339: /* first number OK */ ! 340: ret = 0; ! 341: } ! 342: if (fDash) { ! 343: offset = getValue(str2, upper, &base, fordsp); ! 344: if (!isNumberOK(str2, offset, base)) { ! 345: /* second number not OK */ ! 346: fprintf(stderr, "Invalid address value '%s'!\n", str2); ! 347: ret = -1; ! 348: } else { ! 349: if (*lower > *upper) { ! 350: fprintf(stderr,"Invalid range ($%x > $%x)!\n", *lower, *upper); ! 351: /* not a range */ ! 352: ret = -1; ! 353: } else { ! 354: /* second number & range OK */ ! 355: ret = 1; ! 356: } ! 357: } ! 358: *--str2 = '-'; ! 359: } ! 360: return ret; ! 361: } ! 362: ! 363: ! 364: /** ! 365: * Evaluate expression. bForDsp determines which registers and symbols ! 366: * are interpreted. Sets given value and parsing offset. ! 367: * Return error string or NULL for success. ! 368: */ ! 369: const char* Eval_Expression(const char *in, Uint32 *out, int *erroff, bool bForDsp) ! 370: { ! 371: /* in : expression to evaluate */ ! 372: /* out : final parsed value */ ! 373: /* value : current parsed value */ ! 374: /* mark : current character in expression */ ! 375: /* valid : expression validation flag, set when number parsed */ ! 376: /* end : 'expression end' flag */ ! 377: /* offset: character offset in expression */ ! 378: ! 379: long long value; ! 380: int dummy, offset = 0; ! 381: char mark; ! 382: ! 383: /* Uses global variables: */ ! 384: ! 385: par.idx = 0; /* parenthesis stack pointer */ ! 386: par.opx[0] = par.vax[0] = 0; /* additional stack pointers */ ! 387: op.idx = val.idx = -1; ! 388: ! 389: id.error = NULL; ! 390: id.valid = false; /* value validation */ ! 391: value = 0; ! 392: ! 393: /* parsing loop, repeated until expression ends */ ! 394: do { ! 395: mark = in[offset]; ! 396: switch(mark) { ! 397: case '\0': ! 398: break; ! 399: case ' ': ! 400: case '\t': ! 401: offset ++; /* jump over white space */ ! 402: break; ! 403: case '~': /* prefixes */ ! 404: unary(mark); ! 405: offset ++; ! 406: break; ! 407: case '>': /* operators */ ! 408: case '<': ! 409: offset ++; ! 410: /* check that it's '>>' or '<<' */ ! 411: if (in[offset] != mark) ! 412: { ! 413: id.error = CLAC_GEN_ERR; ! 414: break; ! 415: } ! 416: operation (value, mark); ! 417: offset ++; ! 418: break; ! 419: case '|': ! 420: case '&': ! 421: case '^': ! 422: case '+': ! 423: case '-': ! 424: case '*': ! 425: case '/': ! 426: operation (value, mark); ! 427: offset ++; ! 428: break; ! 429: case '(': ! 430: open_bracket (); ! 431: offset ++; ! 432: break; ! 433: case ')': ! 434: value = close_bracket (value); ! 435: offset ++; ! 436: break; ! 437: default: ! 438: /* register/symbol/number value needed? */ ! 439: if (id.valid == false) { ! 440: Uint32 tmp; ! 441: int consumed; ! 442: consumed = getValue(&(in[offset]), &tmp, &dummy, bForDsp); ! 443: /* number parsed? */ ! 444: if (consumed) { ! 445: offset += consumed; ! 446: id.valid = true; ! 447: value = tmp; ! 448: break; ! 449: } ! 450: } ! 451: id.error = CLAC_GEN_ERR; ! 452: } ! 453: ! 454: /* until exit or error message */ ! 455: } while(mark && !id.error); ! 456: ! 457: /* result of evaluation */ ! 458: if (val.idx >= 0) ! 459: *out = val.buf[val.idx]; ! 460: ! 461: /* something to return? */ ! 462: if (!id.error) { ! 463: if (id.valid) { ! 464: ! 465: /* evaluate rest of the expression */ ! 466: operation (value, LOWEST_PREDECENCE); ! 467: if (par.idx) /* mismatched */ ! 468: id.error = CLAC_PAR_ERR; ! 469: else /* result out */ ! 470: *out = val.buf[val.idx]; ! 471: ! 472: } else { ! 473: if ((val.idx < 0) && (op.idx < 0)) { ! 474: id.error = CLAC_EXP_ERR; ! 475: } else /* trailing operators */ ! 476: id.error = CLAC_GEN_ERR; ! 477: } ! 478: } ! 479: ! 480: *erroff = offset; ! 481: if (id.error) { ! 482: *out = 0; ! 483: return id.error; ! 484: } ! 485: return NULL; ! 486: } ! 487: ! 488: ! 489: /* ==================================================================== */ ! 490: /* expression evaluation */ ! 491: /* ==================================================================== */ ! 492: ! 493: static void operation (long long value, char oper) ! 494: { ! 495: /* uses globals par[], id.error[], op[], val[] ! 496: * operation executed if the next one is on same or lower level ! 497: */ ! 498: /* something to calc? */ ! 499: if(id.valid == true) { ! 500: ! 501: /* add new items to stack */ ! 502: PUSH(op, oper); ! 503: PUSH(val, value); ! 504: ! 505: /* more than 1 operator */ ! 506: if(op.idx > par.opx[par.idx]) { ! 507: ! 508: /* but only one value */ ! 509: if(val.idx == par.vax[par.idx]) { ! 510: apply_prefix(); ! 511: } else { ! 512: /* evaluate all possible operations */ ! 513: eval_stack(); ! 514: } ! 515: } ! 516: /* next a number needed */ ! 517: id.valid = false; ! 518: } else { ! 519: /* pre- or post-operators instead of in-betweens? */ ! 520: unary(oper); ! 521: } ! 522: } ! 523: ! 524: /** ! 525: * handle unary operators ! 526: */ ! 527: static void unary (char oper) ! 528: { ! 529: /* check pre-value operators ! 530: * have to be parenthesised ! 531: */ ! 532: if(id.valid == false && op.idx < par.opx[par.idx]) ! 533: { ! 534: switch(oper) { ! 535: case '+': /* not needed */ ! 536: break; ! 537: case '-': ! 538: case '~': ! 539: PUSH(op, oper); ! 540: break; ! 541: default: ! 542: id.error = CLAC_GEN_ERR; ! 543: } ! 544: } ! 545: else ! 546: id.error = CLAC_GEN_ERR; ! 547: } ! 548: ! 549: /** ! 550: * apply a prefix to the current value ! 551: */ ! 552: static void apply_prefix(void) ! 553: { ! 554: long long value = val.buf[val.idx]; ! 555: ! 556: op.idx--; ! 557: switch(op.buf[op.idx]) { ! 558: case '-': ! 559: value = (-value); ! 560: break; ! 561: case '~': ! 562: value = (~value); ! 563: break; ! 564: default: ! 565: id.error = CLAC_PRG_ERR; ! 566: } ! 567: val.buf[val.idx] = value; ! 568: op.buf[op.idx] = op.buf[op.idx + 1]; ! 569: } ! 570: ! 571: /* -------------------------------------------------------------------- */ ! 572: /** ! 573: * evaluate operators if precedence allows it ! 574: */ ! 575: /* evaluate all possible (according to order of precedence) operators */ ! 576: static void eval_stack (void) ! 577: { ! 578: /* uses globals par[], op[], val[] */ ! 579: ! 580: /* # of operators >= 2 and prev. op-level >= current op-level ? */ ! 581: while ((op.idx > par.opx[par.idx]) && get_level (-1) >= get_level (0)) { ! 582: ! 583: /* shorten value stacks by one */ ! 584: /* + calculate resulting value */ ! 585: op.idx -= 1; ! 586: val.idx -= 1; ! 587: val.buf[val.idx] = apply_op(op.buf[op.idx], ! 588: val.buf[val.idx], val.buf[val.idx + 1]); ! 589: ! 590: /* pull the just used operator out of the stack */ ! 591: op.buf[op.idx] = op.buf[op.idx + 1]; ! 592: } ! 593: } ! 594: ! 595: /* -------------------------------------------------------------------- */ ! 596: /** ! 597: * return the precedence level of a given operator ! 598: */ ! 599: static int get_level (int offset) ! 600: { ! 601: /* used globals par[], op[] ! 602: * returns operator level of: operator[stack idx + offset] ! 603: */ ! 604: switch(op.buf[op.idx + offset]) { ! 605: case '|': /* binary operations */ ! 606: case '&': ! 607: case '^': ! 608: return 0; ! 609: ! 610: case '>': /* bit shifting */ ! 611: case '<': ! 612: return 1; ! 613: ! 614: case '+': ! 615: case '-': ! 616: return 2; ! 617: ! 618: case '*': ! 619: case '/': ! 620: return 3; ! 621: ! 622: default: ! 623: id.error = CLAC_PRG_ERR; ! 624: } ! 625: return 6; ! 626: } ! 627: ! 628: /* -------------------------------------------------------------------- */ ! 629: /** ! 630: * apply operator to given values, return the result ! 631: */ ! 632: static long long apply_op (char opcode, long long value1, long long value2) ! 633: { ! 634: /* uses global id.error[] */ ! 635: /* returns the result of operation */ ! 636: ! 637: switch (opcode) { ! 638: case '|': ! 639: value1 |= value2; ! 640: break; ! 641: case '&': ! 642: value1 &= value2; ! 643: break; ! 644: case '^': ! 645: value1 ^= value2; ! 646: break; ! 647: case '>': ! 648: value1 >>= value2; ! 649: case '<': ! 650: value1 <<= value2; ! 651: break; ! 652: case '+': ! 653: value1 += value2; ! 654: break; ! 655: case '-': ! 656: value1 -= value2; ! 657: break; ! 658: case '*': ! 659: value1 *= value2; ! 660: break; ! 661: case '/': ! 662: /* don't divide by zero */ ! 663: if (value2) ! 664: value1 /= value2; ! 665: else ! 666: id.error = CLAC_DEF_ERR; ! 667: break; ! 668: default: ! 669: id.error = CLAC_PRG_ERR; ! 670: } ! 671: return value1; /* return result */ ! 672: } ! 673: ! 674: ! 675: /* ==================================================================== */ ! 676: /* parenthesis and help */ ! 677: /* ==================================================================== */ ! 678: ! 679: /** ! 680: * open prenthesis, push values & operators to stack ! 681: */ ! 682: static void open_bracket (void) ! 683: { ! 684: if (id.valid == false) { /* preceded by operator */ ! 685: if (par.idx < PARDEPTH_MAX) { /* not nested too deep */ ! 686: par.idx ++; ! 687: par.opx[par.idx] = op.idx + 1; ! 688: par.vax[par.idx] = val.idx + 1; ! 689: } else ! 690: id.error = CLAC_STK_ERR; ! 691: } else ! 692: id.error = CLAC_GEN_ERR; ! 693: } ! 694: ! 695: /* -------------------------------------------------------------------- */ ! 696: /** ! 697: * close prenthesis, and evaluate / pop stacks ! 698: */ ! 699: /* last parsed value, last param. flag, trigonometric mode */ ! 700: static long long close_bracket (long long value) ! 701: { ! 702: /* returns the value of the parenthesised expression */ ! 703: ! 704: if (id.valid) { /* preceded by an operator */ ! 705: if (par.idx > 0) { /* prenthesis has a pair */ ! 706: Uint32 addr; ! 707: ! 708: /* calculate the value of parenthesised exp. */ ! 709: operation (value, LOWEST_PREDECENCE); ! 710: /* fetch the indirect ST RAM value */ ! 711: addr = val.buf[val.idx]; ! 712: value = DBGMemory_ReadLong(addr); ! 713: fprintf(stderr, " value in RAM at ($%x).l = $%"FMT_ll"x\n", addr, value); ! 714: /* restore state before parenthesis */ ! 715: op.idx = par.opx[par.idx] - 1; ! 716: val.idx = par.vax[par.idx] - 1; ! 717: par.idx --; ! 718: ! 719: /* next operator */ ! 720: id.valid = true; ! 721: } else ! 722: id.error = CLAC_PAR_ERR; ! 723: } else ! 724: id.error = CLAC_GEN_ERR; ! 725: ! 726: return value; ! 727: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.