1 /* $OpenBSD: bcode.c,v 1.45 2012/11/07 11:06:14 otto 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>
20 __FBSDID("$FreeBSD$");
24 #include <openssl/ssl.h>
32 /* #define DEBUGGING */
34 #define MAX_ARRAY_INDEX 2048
35 #define READSTACK_SIZE 8
37 #define NO_ELSE -2 /* -1 is EOF */
38 #define REG_ARRAY_SIZE_SMALL (UCHAR_MAX + 1)
39 #define REG_ARRAY_SIZE_BIG (UCHAR_MAX + 1 + USHRT_MAX + 1)
42 struct source *readstack;
49 size_t reg_array_size;
54 static struct bmachine bmachine;
56 static __inline int readch(void);
57 static __inline void unreadch(void);
58 static __inline char *readline(void);
59 static __inline void src_free(void);
61 static __inline u_int max(u_int, u_int);
62 static u_long get_ulong(struct number *);
64 static __inline void push_number(struct number *);
65 static __inline void push_string(char *);
66 static __inline void push(struct value *);
67 static __inline struct value *tos(void);
68 static __inline struct number *pop_number(void);
69 static __inline char *pop_string(void);
70 static __inline void clear_stack(void);
71 static __inline void print_tos(void);
72 static void print_err(void);
73 static void pop_print(void);
74 static void pop_printn(void);
75 static __inline void print_stack(void);
76 static __inline void dup(void);
77 static void swap(void);
78 static void drop(void);
80 static void get_scale(void);
81 static void set_scale(void);
82 static void get_obase(void);
83 static void set_obase(void);
84 static void get_ibase(void);
85 static void set_ibase(void);
86 static void stackdepth(void);
87 static void push_scale(void);
88 static u_int count_digits(const struct number *);
89 static void num_digits(void);
90 static void to_ascii(void);
91 static void push_line(void);
92 static void comment(void);
93 static void bexec(char *);
94 static void badd(void);
95 static void bsub(void);
96 static void bmul(void);
97 static void bdiv(void);
98 static void bmod(void);
99 static void bdivmod(void);
100 static void bexp(void);
101 static bool bsqrt_stop(const BIGNUM *, const BIGNUM *, u_int *);
102 static void bsqrt(void);
103 static void not(void);
104 static void equal_numbers(void);
105 static void less_numbers(void);
106 static void lesseq_numbers(void);
107 static void equal(void);
108 static void not_equal(void);
109 static void less(void);
110 static void not_less(void);
111 static void greater(void);
112 static void not_greater(void);
113 static void not_compare(void);
114 static bool compare_numbers(enum bcode_compare, struct number *,
116 static void compare(enum bcode_compare);
117 static int readreg(void);
118 static void load(void);
119 static void store(void);
120 static void load_stack(void);
121 static void store_stack(void);
122 static void load_array(void);
123 static void store_array(void);
124 static void nop(void);
125 static void quit(void);
126 static void quitN(void);
127 static void skipN(void);
128 static void skip_until_mark(void);
129 static void parse_number(void);
130 static void unknown(void);
131 static void eval_string(char *);
132 static void eval_line(void);
133 static void eval_tos(void);
136 typedef void (*opcode_function)(void);
143 static opcode_function jump_table[UCHAR_MAX];
145 static const struct jump_entry jump_table_data[] = {
147 { '!', not_compare },
150 { '(', less_numbers },
154 { '.', parse_number },
156 { '0', parse_number },
157 { '1', parse_number },
158 { '2', parse_number },
159 { '3', parse_number },
160 { '4', parse_number },
161 { '5', parse_number },
162 { '6', parse_number },
163 { '7', parse_number },
164 { '8', parse_number },
165 { '9', parse_number },
166 { ':', store_array },
172 { 'A', parse_number },
173 { 'B', parse_number },
174 { 'C', parse_number },
175 { 'D', parse_number },
176 { 'E', parse_number },
177 { 'F', parse_number },
178 { 'G', equal_numbers },
189 { 'S', store_stack },
198 { '_', parse_number },
200 { 'c', clear_stack },
203 { 'f', print_stack },
216 { '{', lesseq_numbers },
220 #define JUMP_TABLE_DATA_SIZE \
221 (sizeof(jump_table_data)/sizeof(jump_table_data[0]))
224 init_bmachine(bool extended_registers)
228 bmachine.extended_regs = extended_registers;
229 bmachine.reg_array_size = bmachine.extended_regs ?
230 REG_ARRAY_SIZE_BIG : REG_ARRAY_SIZE_SMALL;
232 bmachine.reg = calloc(bmachine.reg_array_size,
233 sizeof(bmachine.reg[0]));
234 if (bmachine.reg == NULL)
237 for (i = 0; i < UCHAR_MAX; i++)
238 jump_table[i] = unknown;
239 for (i = 0; i < JUMP_TABLE_DATA_SIZE; i++)
240 jump_table[jump_table_data[i].ch] = jump_table_data[i].f;
242 stack_init(&bmachine.stack);
244 for (i = 0; i < bmachine.reg_array_size; i++)
245 stack_init(&bmachine.reg[i]);
247 bmachine.readstack_sz = READSTACK_SIZE;
248 bmachine.readstack = calloc(sizeof(struct source),
249 bmachine.readstack_sz);
250 if (bmachine.readstack == NULL)
252 bmachine.obase = bmachine.ibase = 10;
258 return bmachine.scale;
261 /* Reset the things needed before processing a (new) file */
263 reset_bmachine(struct source *src)
267 bmachine.readstack[0] = *src;
273 struct source *src = &bmachine.readstack[bmachine.readsp];
275 return (src->vtable->readchar(src));
281 struct source *src = &bmachine.readstack[bmachine.readsp];
283 src->vtable->unreadchar(src);
286 static __inline char *
289 struct source *src = &bmachine.readstack[bmachine.readsp];
291 return (src->vtable->readline(src));
297 struct source *src = &bmachine.readstack[bmachine.readsp];
299 src->vtable->free(src);
304 pn(const char *str, const struct number *n)
306 char *p = BN_bn2dec(n->number);
309 err(1, "BN_bn2dec failed");
311 fprintf(stderr, " %s (%u)\n" , p, n->scale);
316 pbn(const char *str, const BIGNUM *n)
318 char *p = BN_bn2dec(n);
321 err(1, "BN_bn2dec failed");
323 fprintf(stderr, " %s\n", p);
329 static __inline u_int
330 max(u_int a, u_int b)
333 return (a > b ? a : b);
336 static unsigned long factors[] = {
337 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
338 100000000, 1000000000
342 scale_number(BIGNUM *n, int s)
344 unsigned int abs_scale;
349 abs_scale = s > 0 ? s : -s;
351 if (abs_scale < sizeof(factors)/sizeof(factors[0])) {
353 bn_check(BN_mul_word(n, factors[abs_scale]));
355 BN_div_word(n, factors[abs_scale]);
367 bn_check(BN_set_word(a, 10));
368 bn_check(BN_set_word(p, abs_scale));
369 bn_check(BN_exp(a, a, p, ctx));
371 bn_check(BN_mul(n, n, a, ctx));
373 bn_check(BN_div(n, NULL, n, a, ctx));
381 split_number(const struct number *n, BIGNUM *i, BIGNUM *f)
385 bn_checkp(BN_copy(i, n->number));
387 if (n->scale == 0 && f != NULL)
388 bn_check(BN_zero(f));
389 else if (n->scale < sizeof(factors)/sizeof(factors[0])) {
390 rem = BN_div_word(i, factors[n->scale]);
392 bn_check(BN_set_word(f, rem));
404 bn_check(BN_set_word(a, 10));
405 bn_check(BN_set_word(p, n->scale));
406 bn_check(BN_exp(a, a, p, ctx));
407 bn_check(BN_div(i, f, n->number, a, ctx));
415 normalize(struct number *n, u_int s)
418 scale_number(n->number, s - n->scale);
423 get_ulong(struct number *n)
427 return (BN_get_word(n->number));
431 negate(struct number *n)
433 BN_set_negative(n->number, !BN_is_negative(n->number));
437 push_number(struct number *n)
440 stack_pushnumber(&bmachine.stack, n);
444 push_string(char *string)
447 stack_pushstring(&bmachine.stack, string);
451 push(struct value *v)
454 stack_push(&bmachine.stack, v);
457 static __inline struct value *
461 return (stack_tos(&bmachine.stack));
464 static __inline struct value *
468 return (stack_pop(&bmachine.stack));
471 static __inline struct number *
475 return (stack_popnumber(&bmachine.stack));
478 static __inline char *
482 return (stack_popstring(&bmachine.stack));
489 stack_clear(&bmachine.stack);
496 stack_print(stdout, &bmachine.stack, "", bmachine.obase);
502 struct value *value = tos();
505 print_value(stdout, value, "", bmachine.obase);
509 warnx("stack empty");
515 struct value *value = tos();
517 print_value(stderr, value, "", bmachine.obase);
518 (void)putc('\n', stderr);
521 warnx("stack empty");
527 struct value *value = pop();
530 switch (value->type) {
534 normalize(value->u.num, 0);
535 print_ascii(stdout, value->u.num);
539 fputs(value->u.string, stdout);
543 stack_free_value(value);
550 struct value *value = pop();
553 print_value(stdout, value, "", bmachine.obase);
555 stack_free_value(value);
563 stack_dup(&bmachine.stack);
570 stack_swap(&bmachine.stack);
576 struct value *v = pop();
587 bn_check(BN_set_word(n->number, bmachine.scale));
599 if (BN_is_negative(n->number))
600 warnx("scale must be a nonnegative number");
602 scale = get_ulong(n);
603 if (scale != BN_MASK2 && scale <= UINT_MAX)
604 bmachine.scale = (u_int)scale;
606 warnx("scale too large");
618 bn_check(BN_set_word(n->number, bmachine.obase));
631 if (base != BN_MASK2 && base > 1 && base <= UINT_MAX)
632 bmachine.obase = (u_int)base;
634 warnx("output base must be a number greater than 1");
645 bn_check(BN_set_word(n->number, bmachine.ibase));
658 if (base != BN_MASK2 && 2 <= base && base <= 16)
659 bmachine.ibase = (u_int)base;
661 warnx("input base must be a number between 2 and 16 "
673 i = stack_size(&bmachine.stack);
675 bn_check(BN_set_word(n->number, i));
688 switch (value->type) {
692 scale = value->u.num->scale;
697 stack_free_value(value);
699 bn_check(BN_set_word(n->number, scale));
705 count_digits(const struct number *n)
707 struct number *int_part, *fract_part;
710 if (BN_is_zero(n->number))
711 return n->scale ? n->scale : 1;
713 int_part = new_number();
714 fract_part = new_number();
715 fract_part->scale = n->scale;
716 split_number(n, int_part->number, fract_part->number);
719 while (!BN_is_zero(int_part->number)) {
720 BN_div_word(int_part->number, 10);
723 free_number(int_part);
724 free_number(fract_part);
725 return (i + n->scale);
731 struct number *n = NULL;
737 switch (value->type) {
741 digits = count_digits(value->u.num);
743 bn_check(BN_set_word(n->number, digits));
746 digits = strlen(value->u.string);
748 bn_check(BN_set_word(n->number, digits));
751 stack_free_value(value);
766 switch (value->type) {
772 if (BN_num_bits(n->number) > 8)
773 bn_check(BN_mask_bits(n->number, 8));
774 str[0] = (char)BN_get_word(n->number);
777 str[0] = value->u.string[0];
780 stack_free_value(value);
781 push_string(bstrdup(str));
791 if (idx == 0xff && bmachine.extended_regs) {
794 if (ch1 == EOF || ch2 == EOF) {
795 warnx("unexpected eof");
798 idx = (ch1 << 8) + ch2 + UCHAR_MAX + 1;
800 if (idx < 0 || (unsigned)idx >= bmachine.reg_array_size) {
801 warnx("internal error: reg num = %d", idx);
817 v = stack_tos(&bmachine.reg[idx]);
820 bn_check(BN_zero(n->number));
823 push(stack_dup_value(v, ©));
839 stack_set_tos(&bmachine.reg[idx], val);
852 stack = &bmachine.reg[idx];
854 if (stack_size(stack) > 0) {
855 value = stack_pop(stack);
860 warnx("stack register '%c' (0%o) is empty",
876 stack_push(&bmachine.reg[idx], value);
883 struct number *inumber, *n;
892 inumber = pop_number();
895 idx = get_ulong(inumber);
896 if (BN_is_negative(inumber->number))
897 warnx("negative idx");
898 else if (idx == BN_MASK2 || idx > MAX_ARRAY_INDEX)
899 warnx("idx too big");
901 stack = &bmachine.reg[reg];
902 v = frame_retrieve(stack, idx);
903 if (v == NULL || v->type == BCODE_NONE) {
905 bn_check(BN_zero(n->number));
909 push(stack_dup_value(v, ©));
911 free_number(inumber);
918 struct number *inumber;
926 inumber = pop_number();
931 free_number(inumber);
934 idx = get_ulong(inumber);
935 if (BN_is_negative(inumber->number)) {
936 warnx("negative idx");
937 stack_free_value(value);
938 } else if (idx == BN_MASK2 || idx > MAX_ARRAY_INDEX) {
939 warnx("idx too big");
940 stack_free_value(value);
942 stack = &bmachine.reg[reg];
943 frame_assign(stack, idx, value);
945 free_number(inumber);
953 push_string(read_string(&bmachine.readstack[bmachine.readsp]));
974 struct number *a, *b, *r;
986 r->scale = max(a->scale, b->scale);
987 if (r->scale > a->scale)
988 normalize(a, r->scale);
989 else if (r->scale > b->scale)
990 normalize(b, r->scale);
991 bn_check(BN_add(r->number, a->number, b->number));
1000 struct number *a, *b, *r;
1013 r->scale = max(a->scale, b->scale);
1014 if (r->scale > a->scale)
1015 normalize(a, r->scale);
1016 else if (r->scale > b->scale)
1017 normalize(b, r->scale);
1018 bn_check(BN_sub(r->number, b->number, a->number));
1025 bmul_number(struct number *r, struct number *a, struct number *b, u_int scale)
1029 /* Create copies of the scales, since r might be equal to a or b */
1030 u_int ascale = a->scale;
1031 u_int bscale = b->scale;
1032 u_int rscale = ascale + bscale;
1036 bn_check(BN_mul(r->number, a->number, b->number, ctx));
1040 if (rscale > bmachine.scale && rscale > ascale && rscale > bscale)
1041 normalize(r, max(scale, max(ascale, bscale)));
1047 struct number *a, *b, *r;
1059 bmul_number(r, a, b, bmachine.scale);
1069 struct number *a, *b, *r;
1083 r->scale = bmachine.scale;
1084 scale = max(a->scale, b->scale);
1086 if (BN_is_zero(a->number))
1087 warnx("divide by zero");
1089 normalize(a, scale);
1090 normalize(b, scale + r->scale);
1094 bn_check(BN_div(r->number, NULL, b->number, a->number, ctx));
1105 struct number *a, *b, *r;
1119 scale = max(a->scale, b->scale);
1120 r->scale = max(b->scale, a->scale + bmachine.scale);
1122 if (BN_is_zero(a->number))
1123 warnx("remainder by zero");
1125 normalize(a, scale);
1126 normalize(b, scale + bmachine.scale);
1130 bn_check(BN_mod(r->number, b->number, a->number, ctx));
1141 struct number *a, *b, *rdiv, *rmod;
1154 rdiv = new_number();
1155 rmod = new_number();
1156 rdiv->scale = bmachine.scale;
1157 rmod->scale = max(b->scale, a->scale + bmachine.scale);
1158 scale = max(a->scale, b->scale);
1160 if (BN_is_zero(a->number))
1161 warnx("divide by zero");
1163 normalize(a, scale);
1164 normalize(b, scale + bmachine.scale);
1168 bn_check(BN_div(rdiv->number, rmod->number,
1169 b->number, a->number, ctx));
1181 struct number *a, *p;
1195 if (p->scale != 0) {
1201 split_number(p, i, f);
1203 warnx("Runtime warning: non-zero fractional part in exponent");
1211 if (BN_is_negative(p->number)) {
1214 rscale = bmachine.scale;
1216 /* Posix bc says min(a.scale * b, max(a.scale, scale) */
1220 b = BN_get_word(p->number);
1221 m = max(a->scale, bmachine.scale);
1222 rscale = a->scale * (u_int)b;
1223 if (rscale > m || (a->scale > 0 && (b == BN_MASK2 ||
1228 if (BN_is_zero(p->number)) {
1230 bn_check(BN_one(r->number));
1231 normalize(r, rscale);
1233 u_int ascale, mscale;
1236 while (!BN_is_bit_set(p->number, 0)) {
1238 bmul_number(a, a, a, ascale);
1239 bn_check(BN_rshift1(p->number, p->number));
1243 bn_check(BN_rshift1(p->number, p->number));
1246 while (!BN_is_zero(p->number)) {
1248 bmul_number(a, a, a, ascale);
1249 if (BN_is_bit_set(p->number, 0)) {
1251 bmul_number(r, r, a, mscale);
1253 bn_check(BN_rshift1(p->number, p->number));
1262 bn_check(BN_one(one));
1265 scale_number(one, r->scale + rscale);
1267 if (BN_is_zero(r->number))
1268 warnx("divide by zero");
1270 bn_check(BN_div(r->number, NULL, one,
1276 normalize(r, rscale);
1284 bsqrt_stop(const BIGNUM *x, const BIGNUM *y, u_int *onecount)
1291 bn_check(BN_sub(r, x, y));
1294 ret = BN_is_zero(r);
1296 return (ret || *onecount > 1);
1302 struct number *n, *r;
1305 u_int onecount, scale;
1311 if (BN_is_zero(n->number)) {
1314 } else if (BN_is_negative(n->number))
1315 warnx("square root of negative number");
1317 scale = max(bmachine.scale, n->scale);
1318 normalize(n, 2*scale);
1319 x = BN_dup(n->number);
1321 bn_check(BN_rshift(x, x, BN_num_bits(x)/2));
1327 bn_checkp(BN_copy(y, x));
1328 bn_check(BN_div(x, NULL, n->number, x, ctx));
1329 bn_check(BN_add(x, x, y));
1330 bn_check(BN_rshift1(x, x));
1331 if (bsqrt_stop(x, y, &onecount))
1334 r = bmalloc(sizeof(*r));
1354 bn_check(BN_set_word(a->number, BN_get_word(a->number) ? 0 : 1));
1362 compare(BCODE_EQUAL);
1368 struct number *a, *b, *r;
1379 bn_check(BN_set_word(r->number,
1380 compare_numbers(BCODE_EQUAL, a, b) ? 1 : 0));
1387 struct number *a, *b, *r;
1398 bn_check(BN_set_word(r->number,
1399 compare_numbers(BCODE_LESS, a, b) ? 1 : 0));
1404 lesseq_numbers(void)
1406 struct number *a, *b, *r;
1417 bn_check(BN_set_word(r->number,
1418 compare_numbers(BCODE_NOT_GREATER, a, b) ? 1 : 0));
1426 compare(BCODE_NOT_EQUAL);
1433 compare(BCODE_LESS);
1461 compare(BCODE_NOT_LESS);
1468 compare(BCODE_GREATER);
1475 compare(BCODE_NOT_GREATER);
1479 compare_numbers(enum bcode_compare type, struct number *a, struct number *b)
1484 scale = max(a->scale, b->scale);
1486 if (scale > a->scale)
1487 normalize(a, scale);
1488 else if (scale > b->scale)
1489 normalize(b, scale);
1491 cmp = BN_cmp(a->number, b->number);
1499 case BCODE_NOT_EQUAL:
1503 case BCODE_NOT_LESS:
1507 case BCODE_NOT_GREATER:
1514 compare(enum bcode_compare type)
1516 struct number *a, *b;
1523 if (readch() == 'e')
1524 elseidx = readreg();
1537 ok = compare_numbers(type, a, b);
1539 if (!ok && elseidx != NO_ELSE)
1542 if (idx >= 0 && (ok || (!ok && elseidx != NO_ELSE))) {
1543 v = stack_tos(&bmachine.reg[idx]);
1545 warnx("register '%c' (0%o) is empty", idx, idx);
1549 warnx("register '%c' (0%o) is empty", idx, idx);
1552 warn("eval called with non-string argument");
1555 eval_string(bstrdup(v->u.string));
1573 if (bmachine.readsp < 2)
1592 if (i == BN_MASK2 || i == 0)
1593 warnx("Q command requires a number >= 1");
1594 else if (bmachine.readsp < i)
1595 warnx("Q command argument exceeded string execution depth");
1615 warnx("J command requires a number >= 0");
1616 else if (i > 0 && bmachine.readsp < i)
1617 warnx("J command argument exceeded string execution depth");
1628 skip_until_mark(void)
1636 errx(1, "mark not found");
1648 if (readch() == 'e')
1654 free(read_string(&bmachine.readstack[bmachine.readsp]));
1662 if (readch() == 'e')
1683 push_number(readnumber(&bmachine.readstack[bmachine.readsp],
1690 int ch = bmachine.readstack[bmachine.readsp].lastchar;
1691 warnx("%c (0%o) is unimplemented", ch, ch);
1695 eval_string(char *p)
1699 if (bmachine.readsp > 0) {
1700 /* Check for tail call. Do not recurse in that case. */
1704 src_setstring(&bmachine.readstack[bmachine.readsp], p);
1709 if (bmachine.readsp == bmachine.readstack_sz - 1) {
1710 size_t newsz = bmachine.readstack_sz * 2;
1711 struct source *stack;
1712 stack = realloc(bmachine.readstack, newsz *
1713 sizeof(struct source));
1715 err(1, "recursion too deep");
1716 bmachine.readstack_sz = newsz;
1717 bmachine.readstack = stack;
1719 src_setstring(&bmachine.readstack[++bmachine.readsp], p);
1725 /* Always read from stdin */
1730 src_setstream(&in, stdin);
1731 p = (*in.vtable->readline)(&in);
1753 if (bmachine.readsp == 0)
1760 fprintf(stderr, "# %c\n", ch);
1761 stack_print(stderr, &bmachine.stack, "* ",
1763 fprintf(stderr, "%zd =>\n", bmachine.readsp);
1766 if (0 <= ch && ch < (signed)UCHAR_MAX)
1767 (*jump_table[ch])();
1769 warnx("internal error: opcode %d", ch);
1772 stack_print(stderr, &bmachine.stack, "* ",
1774 fprintf(stderr, "%zd ==\n", bmachine.readsp);