1 /* $OpenBSD: bcode.c,v 1.46 2014/10/08 03:59:56 doug Exp $ */
4 * Copyright (c) 2003, Otto Moerbeek <otto@drijf.net>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/cdefs.h>
22 #include <openssl/ssl.h>
30 /* #define DEBUGGING */
32 #define MAX_ARRAY_INDEX 2048
33 #define READSTACK_SIZE 8
35 #define NO_ELSE -2 /* -1 is EOF */
36 #define REG_ARRAY_SIZE_SMALL (UCHAR_MAX + 1)
37 #define REG_ARRAY_SIZE_BIG (UCHAR_MAX + 1 + USHRT_MAX + 1)
40 struct source *readstack;
47 size_t reg_array_size;
52 static struct bmachine bmachine;
54 static __inline int readch(void);
55 static __inline void unreadch(void);
56 static __inline char *readline(void);
57 static __inline void src_free(void);
59 static u_long get_ulong(struct number *);
61 static __inline void push_number(struct number *);
62 static __inline void push_string(char *);
63 static __inline void push(struct value *);
64 static __inline struct value *tos(void);
65 static __inline struct number *pop_number(void);
66 static __inline char *pop_string(void);
67 static __inline void clear_stack(void);
68 static __inline void print_tos(void);
69 static void print_err(void);
70 static void pop_print(void);
71 static void pop_printn(void);
72 static __inline void print_stack(void);
73 static __inline void dup(void);
74 static void swap(void);
75 static void drop(void);
77 static void get_scale(void);
78 static void set_scale(void);
79 static void get_obase(void);
80 static void set_obase(void);
81 static void get_ibase(void);
82 static void set_ibase(void);
83 static void stackdepth(void);
84 static void push_scale(void);
85 static u_int count_digits(const struct number *);
86 static void num_digits(void);
87 static void to_ascii(void);
88 static void push_line(void);
89 static void comment(void);
90 static void bexec(char *);
91 static void badd(void);
92 static void bsub(void);
93 static void bmul(void);
94 static void bdiv(void);
95 static void bmod(void);
96 static void bdivmod(void);
97 static void bexp(void);
98 static bool bsqrt_stop(const BIGNUM *, const BIGNUM *, u_int *);
99 static void bsqrt(void);
100 static void not(void);
101 static void equal_numbers(void);
102 static void less_numbers(void);
103 static void lesseq_numbers(void);
104 static void equal(void);
105 static void not_equal(void);
106 static void less(void);
107 static void not_less(void);
108 static void greater(void);
109 static void not_greater(void);
110 static void not_compare(void);
111 static bool compare_numbers(enum bcode_compare, struct number *,
113 static void compare(enum bcode_compare);
114 static int readreg(void);
115 static void load(void);
116 static void store(void);
117 static void load_stack(void);
118 static void store_stack(void);
119 static void load_array(void);
120 static void store_array(void);
121 static void nop(void);
122 static void quit(void);
123 static void quitN(void);
124 static void skipN(void);
125 static void skip_until_mark(void);
126 static void parse_number(void);
127 static void unknown(void);
128 static void eval_string(char *);
129 static void eval_line(void);
130 static void eval_tos(void);
133 typedef void (*opcode_function)(void);
140 static opcode_function jump_table[UCHAR_MAX];
142 static const struct jump_entry jump_table_data[] = {
144 { '!', not_compare },
147 { '(', less_numbers },
151 { '.', parse_number },
153 { '0', parse_number },
154 { '1', parse_number },
155 { '2', parse_number },
156 { '3', parse_number },
157 { '4', parse_number },
158 { '5', parse_number },
159 { '6', parse_number },
160 { '7', parse_number },
161 { '8', parse_number },
162 { '9', parse_number },
163 { ':', store_array },
169 { 'A', parse_number },
170 { 'B', parse_number },
171 { 'C', parse_number },
172 { 'D', parse_number },
173 { 'E', parse_number },
174 { 'F', parse_number },
175 { 'G', equal_numbers },
186 { 'S', store_stack },
195 { '_', parse_number },
197 { 'c', clear_stack },
200 { 'f', print_stack },
213 { '{', lesseq_numbers },
217 #define JUMP_TABLE_DATA_SIZE \
218 (sizeof(jump_table_data)/sizeof(jump_table_data[0]))
221 init_bmachine(bool extended_registers)
225 bmachine.extended_regs = extended_registers;
226 bmachine.reg_array_size = bmachine.extended_regs ?
227 REG_ARRAY_SIZE_BIG : REG_ARRAY_SIZE_SMALL;
229 bmachine.reg = calloc(bmachine.reg_array_size,
230 sizeof(bmachine.reg[0]));
231 if (bmachine.reg == NULL)
234 for (i = 0; i < UCHAR_MAX; i++)
235 jump_table[i] = unknown;
236 for (i = 0; i < JUMP_TABLE_DATA_SIZE; i++)
237 jump_table[jump_table_data[i].ch] = jump_table_data[i].f;
239 stack_init(&bmachine.stack);
241 for (i = 0; i < bmachine.reg_array_size; i++)
242 stack_init(&bmachine.reg[i]);
244 bmachine.readstack_sz = READSTACK_SIZE;
245 bmachine.readstack = calloc(sizeof(struct source),
246 bmachine.readstack_sz);
247 if (bmachine.readstack == NULL)
249 bmachine.obase = bmachine.ibase = 10;
255 return bmachine.scale;
258 /* Reset the things needed before processing a (new) file */
260 reset_bmachine(struct source *src)
264 bmachine.readstack[0] = *src;
270 struct source *src = &bmachine.readstack[bmachine.readsp];
272 return (src->vtable->readchar(src));
278 struct source *src = &bmachine.readstack[bmachine.readsp];
280 src->vtable->unreadchar(src);
283 static __inline char *
286 struct source *src = &bmachine.readstack[bmachine.readsp];
288 return (src->vtable->readline(src));
294 struct source *src = &bmachine.readstack[bmachine.readsp];
296 src->vtable->free(src);
301 pn(const char *str, const struct number *n)
303 char *p = BN_bn2dec(n->number);
306 err(1, "BN_bn2dec failed");
308 fprintf(stderr, " %s (%u)\n" , p, n->scale);
313 pbn(const char *str, const BIGNUM *n)
315 char *p = BN_bn2dec(n);
318 err(1, "BN_bn2dec failed");
320 fprintf(stderr, " %s\n", p);
326 static unsigned long factors[] = {
327 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
328 100000000, 1000000000
331 /* Multiply n by 10^s */
333 scale_number(BIGNUM *n, int s)
335 unsigned int abs_scale;
340 abs_scale = s > 0 ? s : -s;
342 if (abs_scale < sizeof(factors)/sizeof(factors[0])) {
344 bn_check(BN_mul_word(n, factors[abs_scale]));
346 BN_div_word(n, factors[abs_scale]);
358 bn_check(BN_set_word(a, 10));
359 bn_check(BN_set_word(p, abs_scale));
360 bn_check(BN_exp(a, a, p, ctx));
362 bn_check(BN_mul(n, n, a, ctx));
364 bn_check(BN_div(n, NULL, n, a, ctx));
372 split_number(const struct number *n, BIGNUM *i, BIGNUM *f)
376 bn_checkp(BN_copy(i, n->number));
378 if (n->scale == 0 && f != NULL)
380 else if (n->scale < sizeof(factors)/sizeof(factors[0])) {
381 rem = BN_div_word(i, factors[n->scale]);
383 bn_check(BN_set_word(f, rem));
395 bn_check(BN_set_word(a, 10));
396 bn_check(BN_set_word(p, n->scale));
397 bn_check(BN_exp(a, a, p, ctx));
398 bn_check(BN_div(i, f, n->number, a, ctx));
405 /* Change the scale of n to s. Reducing scale may truncate the mantissa */
407 normalize(struct number *n, u_int s)
410 scale_number(n->number, s - n->scale);
415 get_ulong(struct number *n)
419 return (BN_get_word(n->number));
423 negate(struct number *n)
425 BN_set_negative(n->number, !BN_is_negative(n->number));
429 push_number(struct number *n)
432 stack_pushnumber(&bmachine.stack, n);
436 push_string(char *string)
439 stack_pushstring(&bmachine.stack, string);
443 push(struct value *v)
446 stack_push(&bmachine.stack, v);
449 static __inline struct value *
453 return (stack_tos(&bmachine.stack));
456 static __inline struct value *
460 return (stack_pop(&bmachine.stack));
463 static __inline struct number *
467 return (stack_popnumber(&bmachine.stack));
470 static __inline char *
474 return (stack_popstring(&bmachine.stack));
481 stack_clear(&bmachine.stack);
488 stack_print(stdout, &bmachine.stack, "", bmachine.obase);
494 struct value *value = tos();
497 print_value(stdout, value, "", bmachine.obase);
501 warnx("stack empty");
507 struct value *value = tos();
509 print_value(stderr, value, "", bmachine.obase);
510 (void)putc('\n', stderr);
513 warnx("stack empty");
519 struct value *value = pop();
522 switch (value->type) {
526 normalize(value->u.num, 0);
527 print_ascii(stdout, value->u.num);
531 fputs(value->u.string, stdout);
535 stack_free_value(value);
542 struct value *value = pop();
545 print_value(stdout, value, "", bmachine.obase);
547 stack_free_value(value);
555 stack_dup(&bmachine.stack);
562 stack_swap(&bmachine.stack);
568 struct value *v = pop();
579 bn_check(BN_set_word(n->number, bmachine.scale));
591 if (BN_is_negative(n->number))
592 warnx("scale must be a nonnegative number");
594 scale = get_ulong(n);
595 if (scale != ULONG_MAX && scale <= UINT_MAX)
596 bmachine.scale = (u_int)scale;
598 warnx("scale too large");
610 bn_check(BN_set_word(n->number, bmachine.obase));
623 if (base != ULONG_MAX && base > 1 && base <= UINT_MAX)
624 bmachine.obase = (u_int)base;
626 warnx("output base must be a number greater than 1");
637 bn_check(BN_set_word(n->number, bmachine.ibase));
650 if (base != ULONG_MAX && 2 <= base && base <= 16)
651 bmachine.ibase = (u_int)base;
653 warnx("input base must be a number between 2 and 16 "
665 i = stack_size(&bmachine.stack);
667 bn_check(BN_set_word(n->number, i));
680 switch (value->type) {
684 scale = value->u.num->scale;
689 stack_free_value(value);
691 bn_check(BN_set_word(n->number, scale));
697 count_digits(const struct number *n)
699 struct number *int_part, *fract_part;
702 if (BN_is_zero(n->number))
703 return n->scale ? n->scale : 1;
705 int_part = new_number();
706 fract_part = new_number();
707 fract_part->scale = n->scale;
708 split_number(n, int_part->number, fract_part->number);
711 while (!BN_is_zero(int_part->number)) {
712 BN_div_word(int_part->number, 10);
715 free_number(int_part);
716 free_number(fract_part);
717 return (i + n->scale);
723 struct number *n = NULL;
729 switch (value->type) {
733 digits = count_digits(value->u.num);
735 bn_check(BN_set_word(n->number, digits));
738 digits = strlen(value->u.string);
740 bn_check(BN_set_word(n->number, digits));
743 stack_free_value(value);
758 switch (value->type) {
764 if (BN_num_bits(n->number) > 8)
765 bn_check(BN_mask_bits(n->number, 8));
766 str[0] = (char)BN_get_word(n->number);
769 str[0] = value->u.string[0];
772 stack_free_value(value);
773 push_string(bstrdup(str));
783 if (idx == 0xff && bmachine.extended_regs) {
786 if (ch1 == EOF || ch2 == EOF) {
787 warnx("unexpected eof");
790 idx = (ch1 << 8) + ch2 + UCHAR_MAX + 1;
792 if (idx < 0 || (unsigned)idx >= bmachine.reg_array_size) {
793 warnx("internal error: reg num = %d", idx);
809 v = stack_tos(&bmachine.reg[idx]);
815 push(stack_dup_value(v, ©));
831 stack_set_tos(&bmachine.reg[idx], val);
844 stack = &bmachine.reg[idx];
846 if (stack_size(stack) > 0) {
847 value = stack_pop(stack);
852 warnx("stack register '%c' (0%o) is empty",
868 stack_push(&bmachine.reg[idx], value);
875 struct number *inumber, *n;
884 inumber = pop_number();
887 idx = get_ulong(inumber);
888 if (BN_is_negative(inumber->number))
889 warnx("negative idx");
890 else if (idx == ULONG_MAX || idx > MAX_ARRAY_INDEX)
891 warnx("idx too big");
893 stack = &bmachine.reg[reg];
894 v = frame_retrieve(stack, idx);
895 if (v == NULL || v->type == BCODE_NONE) {
901 push(stack_dup_value(v, ©));
903 free_number(inumber);
910 struct number *inumber;
918 inumber = pop_number();
923 free_number(inumber);
926 idx = get_ulong(inumber);
927 if (BN_is_negative(inumber->number)) {
928 warnx("negative idx");
929 stack_free_value(value);
930 } else if (idx == ULONG_MAX || idx > MAX_ARRAY_INDEX) {
931 warnx("idx too big");
932 stack_free_value(value);
934 stack = &bmachine.reg[reg];
935 frame_assign(stack, idx, value);
937 free_number(inumber);
945 push_string(read_string(&bmachine.readstack[bmachine.readsp]));
966 struct number *a, *b, *r;
978 r->scale = max(a->scale, b->scale);
979 if (r->scale > a->scale)
980 normalize(a, r->scale);
981 else if (r->scale > b->scale)
982 normalize(b, r->scale);
983 bn_check(BN_add(r->number, a->number, b->number));
992 struct number *a, *b, *r;
1005 r->scale = max(a->scale, b->scale);
1006 if (r->scale > a->scale)
1007 normalize(a, r->scale);
1008 else if (r->scale > b->scale)
1009 normalize(b, r->scale);
1010 bn_check(BN_sub(r->number, b->number, a->number));
1017 bmul_number(struct number *r, struct number *a, struct number *b, u_int scale)
1021 /* Create copies of the scales, since r might be equal to a or b */
1022 u_int ascale = a->scale;
1023 u_int bscale = b->scale;
1024 u_int rscale = ascale + bscale;
1028 bn_check(BN_mul(r->number, a->number, b->number, ctx));
1032 if (rscale > bmachine.scale && rscale > ascale && rscale > bscale)
1033 normalize(r, max(scale, max(ascale, bscale)));
1039 struct number *a, *b, *r;
1051 bmul_number(r, a, b, bmachine.scale);
1061 struct number *a, *b, *r;
1072 r = div_number(b, a, bmachine.scale);
1082 struct number *a, *b, *r;
1096 scale = max(a->scale, b->scale);
1099 if (BN_is_zero(a->number))
1100 warnx("remainder by zero");
1102 normalize(a, scale);
1103 normalize(b, scale);
1107 bn_check(BN_mod(r->number, b->number, a->number, ctx));
1118 struct number *a, *b, *frac, *quotient, *rdiv, *remainder;
1131 rdiv = new_number();
1132 quotient = new_number();
1133 remainder = new_number();
1134 scale = max(a->scale, b->scale);
1136 remainder->scale = scale;
1137 quotient->scale = bmachine.scale;
1138 scale = max(a->scale, b->scale);
1140 if (BN_is_zero(a->number))
1141 warnx("divide by zero");
1143 normalize(a, scale);
1144 normalize(b, scale);
1149 * Unlike other languages' divmod operations, dc is specified
1150 * to return the remainder and the full quotient, rather than
1151 * the remainder and the floored quotient. bn(3) has no
1152 * function to calculate both. So we'll use BN_div to get the
1153 * remainder and floored quotient, then calculate the full
1154 * quotient from those.
1156 * quotient = rdiv + remainder / divisor
1158 bn_check(BN_div(rdiv->number, remainder->number,
1159 b->number, a->number, ctx));
1160 frac = div_number(remainder, a, bmachine.scale);
1161 normalize(rdiv, bmachine.scale);
1162 normalize(remainder, scale);
1163 bn_check(BN_add(quotient->number, rdiv->number, frac->number));
1167 push_number(quotient);
1168 push_number(remainder);
1177 struct number *a, *p;
1191 if (p->scale != 0) {
1197 split_number(p, i, f);
1199 warnx("Runtime warning: non-zero fractional part in exponent");
1207 if (BN_is_negative(p->number)) {
1210 rscale = bmachine.scale;
1212 /* Posix bc says min(a.scale * b, max(a.scale, scale) */
1216 b = BN_get_word(p->number);
1217 m = max(a->scale, bmachine.scale);
1218 rscale = a->scale * (u_int)b;
1219 if (rscale > m || (a->scale > 0 && (b == ULONG_MAX ||
1224 if (BN_is_zero(p->number)) {
1226 bn_check(BN_one(r->number));
1227 normalize(r, rscale);
1229 u_int ascale, mscale;
1232 while (!BN_is_bit_set(p->number, 0)) {
1234 bmul_number(a, a, a, ascale);
1235 bn_check(BN_rshift1(p->number, p->number));
1239 bn_check(BN_rshift1(p->number, p->number));
1242 while (!BN_is_zero(p->number)) {
1244 bmul_number(a, a, a, ascale);
1245 if (BN_is_bit_set(p->number, 0)) {
1247 bmul_number(r, r, a, mscale);
1249 bn_check(BN_rshift1(p->number, p->number));
1258 bn_check(BN_one(one));
1261 scale_number(one, r->scale + rscale);
1263 if (BN_is_zero(r->number))
1264 warnx("divide by zero");
1266 bn_check(BN_div(r->number, NULL, one,
1272 normalize(r, rscale);
1280 bsqrt_stop(const BIGNUM *x, const BIGNUM *y, u_int *onecount)
1287 bn_check(BN_sub(r, x, y));
1290 ret = BN_is_zero(r);
1292 return (ret || *onecount > 1);
1298 struct number *n, *r;
1301 u_int onecount, scale;
1307 if (BN_is_zero(n->number)) {
1310 } else if (BN_is_negative(n->number))
1311 warnx("square root of negative number");
1313 scale = max(bmachine.scale, n->scale);
1314 normalize(n, 2*scale);
1315 x = BN_dup(n->number);
1317 bn_check(BN_rshift(x, x, BN_num_bits(x)/2));
1323 bn_checkp(BN_copy(y, x));
1324 bn_check(BN_div(x, NULL, n->number, x, ctx));
1325 bn_check(BN_add(x, x, y));
1326 bn_check(BN_rshift1(x, x));
1327 if (bsqrt_stop(x, y, &onecount))
1330 r = bmalloc(sizeof(*r));
1350 bn_check(BN_set_word(a->number, BN_get_word(a->number) ? 0 : 1));
1358 compare(BCODE_EQUAL);
1364 struct number *a, *b, *r;
1375 bn_check(BN_set_word(r->number,
1376 compare_numbers(BCODE_EQUAL, a, b) ? 1 : 0));
1383 struct number *a, *b, *r;
1394 bn_check(BN_set_word(r->number,
1395 compare_numbers(BCODE_LESS, a, b) ? 1 : 0));
1400 lesseq_numbers(void)
1402 struct number *a, *b, *r;
1413 bn_check(BN_set_word(r->number,
1414 compare_numbers(BCODE_NOT_GREATER, a, b) ? 1 : 0));
1422 compare(BCODE_NOT_EQUAL);
1429 compare(BCODE_LESS);
1457 compare(BCODE_NOT_LESS);
1464 compare(BCODE_GREATER);
1471 compare(BCODE_NOT_GREATER);
1475 compare_numbers(enum bcode_compare type, struct number *a, struct number *b)
1480 scale = max(a->scale, b->scale);
1482 if (scale > a->scale)
1483 normalize(a, scale);
1484 else if (scale > b->scale)
1485 normalize(b, scale);
1487 cmp = BN_cmp(a->number, b->number);
1495 case BCODE_NOT_EQUAL:
1499 case BCODE_NOT_LESS:
1503 case BCODE_NOT_GREATER:
1510 compare(enum bcode_compare type)
1512 struct number *a, *b;
1519 if (readch() == 'e')
1520 elseidx = readreg();
1533 ok = compare_numbers(type, a, b);
1535 if (!ok && elseidx != NO_ELSE)
1538 if (idx >= 0 && (ok || (!ok && elseidx != NO_ELSE))) {
1539 v = stack_tos(&bmachine.reg[idx]);
1541 warnx("register '%c' (0%o) is empty", idx, idx);
1545 warnx("register '%c' (0%o) is empty", idx, idx);
1548 warn("eval called with non-string argument");
1551 eval_string(bstrdup(v->u.string));
1569 if (bmachine.readsp < 2)
1588 if (i == ULONG_MAX || i == 0)
1589 warnx("Q command requires a number >= 1");
1590 else if (bmachine.readsp < i)
1591 warnx("Q command argument exceeded string execution depth");
1611 warnx("J command requires a number >= 0");
1612 else if (i > 0 && bmachine.readsp < i)
1613 warnx("J command argument exceeded string execution depth");
1624 skip_until_mark(void)
1632 errx(1, "mark not found");
1644 if (readch() == 'e')
1650 free(read_string(&bmachine.readstack[bmachine.readsp]));
1658 if (readch() == 'e')
1679 push_number(readnumber(&bmachine.readstack[bmachine.readsp],
1680 bmachine.ibase, bmachine.scale));
1686 int ch = bmachine.readstack[bmachine.readsp].lastchar;
1687 warnx("%c (0%o) is unimplemented", ch, ch);
1691 eval_string(char *p)
1695 if (bmachine.readsp > 0) {
1696 /* Check for tail call. Do not recurse in that case. */
1700 src_setstring(&bmachine.readstack[bmachine.readsp], p);
1705 if (bmachine.readsp == bmachine.readstack_sz - 1) {
1706 size_t newsz = bmachine.readstack_sz * 2;
1707 struct source *stack;
1708 stack = reallocarray(bmachine.readstack, newsz,
1709 sizeof(struct source));
1711 err(1, "recursion too deep");
1712 bmachine.readstack_sz = newsz;
1713 bmachine.readstack = stack;
1715 src_setstring(&bmachine.readstack[++bmachine.readsp], p);
1721 /* Always read from stdin */
1726 src_setstream(&in, stdin);
1727 p = (*in.vtable->readline)(&in);
1749 if (bmachine.readsp == 0)
1756 fprintf(stderr, "# %c\n", ch);
1757 stack_print(stderr, &bmachine.stack, "* ",
1759 fprintf(stderr, "%zd =>\n", bmachine.readsp);
1762 if (0 <= ch && ch < (signed)UCHAR_MAX)
1763 (*jump_table[ch])();
1765 warnx("internal error: opcode %d", ch);
1768 stack_print(stderr, &bmachine.stack, "* ",
1770 fprintf(stderr, "%zd ==\n", bmachine.readsp);