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>
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 u_long get_ulong(struct number *);
63 static __inline void push_number(struct number *);
64 static __inline void push_string(char *);
65 static __inline void push(struct value *);
66 static __inline struct value *tos(void);
67 static __inline struct number *pop_number(void);
68 static __inline char *pop_string(void);
69 static __inline void clear_stack(void);
70 static __inline void print_tos(void);
71 static void print_err(void);
72 static void pop_print(void);
73 static void pop_printn(void);
74 static __inline void print_stack(void);
75 static __inline void dup(void);
76 static void swap(void);
77 static void drop(void);
79 static void get_scale(void);
80 static void set_scale(void);
81 static void get_obase(void);
82 static void set_obase(void);
83 static void get_ibase(void);
84 static void set_ibase(void);
85 static void stackdepth(void);
86 static void push_scale(void);
87 static u_int count_digits(const struct number *);
88 static void num_digits(void);
89 static void to_ascii(void);
90 static void push_line(void);
91 static void comment(void);
92 static void bexec(char *);
93 static void badd(void);
94 static void bsub(void);
95 static void bmul(void);
96 static void bdiv(void);
97 static void bmod(void);
98 static void bdivmod(void);
99 static void bexp(void);
100 static bool bsqrt_stop(const BIGNUM *, const BIGNUM *, u_int *);
101 static void bsqrt(void);
102 static void not(void);
103 static void equal_numbers(void);
104 static void less_numbers(void);
105 static void lesseq_numbers(void);
106 static void equal(void);
107 static void not_equal(void);
108 static void less(void);
109 static void not_less(void);
110 static void greater(void);
111 static void not_greater(void);
112 static void not_compare(void);
113 static bool compare_numbers(enum bcode_compare, struct number *,
115 static void compare(enum bcode_compare);
116 static int readreg(void);
117 static void load(void);
118 static void store(void);
119 static void load_stack(void);
120 static void store_stack(void);
121 static void load_array(void);
122 static void store_array(void);
123 static void nop(void);
124 static void quit(void);
125 static void quitN(void);
126 static void skipN(void);
127 static void skip_until_mark(void);
128 static void parse_number(void);
129 static void unknown(void);
130 static void eval_string(char *);
131 static void eval_line(void);
132 static void eval_tos(void);
135 typedef void (*opcode_function)(void);
142 static opcode_function jump_table[UCHAR_MAX];
144 static const struct jump_entry jump_table_data[] = {
146 { '!', not_compare },
149 { '(', less_numbers },
153 { '.', parse_number },
155 { '0', parse_number },
156 { '1', parse_number },
157 { '2', parse_number },
158 { '3', parse_number },
159 { '4', parse_number },
160 { '5', parse_number },
161 { '6', parse_number },
162 { '7', parse_number },
163 { '8', parse_number },
164 { '9', parse_number },
165 { ':', store_array },
171 { 'A', parse_number },
172 { 'B', parse_number },
173 { 'C', parse_number },
174 { 'D', parse_number },
175 { 'E', parse_number },
176 { 'F', parse_number },
177 { 'G', equal_numbers },
188 { 'S', store_stack },
197 { '_', parse_number },
199 { 'c', clear_stack },
202 { 'f', print_stack },
215 { '{', lesseq_numbers },
219 #define JUMP_TABLE_DATA_SIZE \
220 (sizeof(jump_table_data)/sizeof(jump_table_data[0]))
223 init_bmachine(bool extended_registers)
227 bmachine.extended_regs = extended_registers;
228 bmachine.reg_array_size = bmachine.extended_regs ?
229 REG_ARRAY_SIZE_BIG : REG_ARRAY_SIZE_SMALL;
231 bmachine.reg = calloc(bmachine.reg_array_size,
232 sizeof(bmachine.reg[0]));
233 if (bmachine.reg == NULL)
236 for (i = 0; i < UCHAR_MAX; i++)
237 jump_table[i] = unknown;
238 for (i = 0; i < JUMP_TABLE_DATA_SIZE; i++)
239 jump_table[jump_table_data[i].ch] = jump_table_data[i].f;
241 stack_init(&bmachine.stack);
243 for (i = 0; i < bmachine.reg_array_size; i++)
244 stack_init(&bmachine.reg[i]);
246 bmachine.readstack_sz = READSTACK_SIZE;
247 bmachine.readstack = calloc(sizeof(struct source),
248 bmachine.readstack_sz);
249 if (bmachine.readstack == NULL)
251 bmachine.obase = bmachine.ibase = 10;
257 return bmachine.scale;
260 /* Reset the things needed before processing a (new) file */
262 reset_bmachine(struct source *src)
266 bmachine.readstack[0] = *src;
272 struct source *src = &bmachine.readstack[bmachine.readsp];
274 return (src->vtable->readchar(src));
280 struct source *src = &bmachine.readstack[bmachine.readsp];
282 src->vtable->unreadchar(src);
285 static __inline char *
288 struct source *src = &bmachine.readstack[bmachine.readsp];
290 return (src->vtable->readline(src));
296 struct source *src = &bmachine.readstack[bmachine.readsp];
298 src->vtable->free(src);
303 pn(const char *str, const struct number *n)
305 char *p = BN_bn2dec(n->number);
308 err(1, "BN_bn2dec failed");
310 fprintf(stderr, " %s (%u)\n" , p, n->scale);
315 pbn(const char *str, const BIGNUM *n)
317 char *p = BN_bn2dec(n);
320 err(1, "BN_bn2dec failed");
322 fprintf(stderr, " %s\n", p);
328 static unsigned long factors[] = {
329 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
330 100000000, 1000000000
333 /* Multiply n by 10^s */
335 scale_number(BIGNUM *n, int s)
337 unsigned int abs_scale;
342 abs_scale = s > 0 ? s : -s;
344 if (abs_scale < sizeof(factors)/sizeof(factors[0])) {
346 bn_check(BN_mul_word(n, factors[abs_scale]));
348 BN_div_word(n, factors[abs_scale]);
360 bn_check(BN_set_word(a, 10));
361 bn_check(BN_set_word(p, abs_scale));
362 bn_check(BN_exp(a, a, p, ctx));
364 bn_check(BN_mul(n, n, a, ctx));
366 bn_check(BN_div(n, NULL, n, a, ctx));
374 split_number(const struct number *n, BIGNUM *i, BIGNUM *f)
378 bn_checkp(BN_copy(i, n->number));
380 if (n->scale == 0 && f != NULL)
381 bn_check(BN_zero(f));
382 else if (n->scale < sizeof(factors)/sizeof(factors[0])) {
383 rem = BN_div_word(i, factors[n->scale]);
385 bn_check(BN_set_word(f, rem));
397 bn_check(BN_set_word(a, 10));
398 bn_check(BN_set_word(p, n->scale));
399 bn_check(BN_exp(a, a, p, ctx));
400 bn_check(BN_div(i, f, n->number, a, ctx));
407 /* Change the scale of n to s. Reducing scale may truncate the mantissa */
409 normalize(struct number *n, u_int s)
412 scale_number(n->number, s - n->scale);
417 get_ulong(struct number *n)
421 return (BN_get_word(n->number));
425 negate(struct number *n)
427 BN_set_negative(n->number, !BN_is_negative(n->number));
431 push_number(struct number *n)
434 stack_pushnumber(&bmachine.stack, n);
438 push_string(char *string)
441 stack_pushstring(&bmachine.stack, string);
445 push(struct value *v)
448 stack_push(&bmachine.stack, v);
451 static __inline struct value *
455 return (stack_tos(&bmachine.stack));
458 static __inline struct value *
462 return (stack_pop(&bmachine.stack));
465 static __inline struct number *
469 return (stack_popnumber(&bmachine.stack));
472 static __inline char *
476 return (stack_popstring(&bmachine.stack));
483 stack_clear(&bmachine.stack);
490 stack_print(stdout, &bmachine.stack, "", bmachine.obase);
496 struct value *value = tos();
499 print_value(stdout, value, "", bmachine.obase);
503 warnx("stack empty");
509 struct value *value = tos();
511 print_value(stderr, value, "", bmachine.obase);
512 (void)putc('\n', stderr);
515 warnx("stack empty");
521 struct value *value = pop();
524 switch (value->type) {
528 normalize(value->u.num, 0);
529 print_ascii(stdout, value->u.num);
533 fputs(value->u.string, stdout);
537 stack_free_value(value);
544 struct value *value = pop();
547 print_value(stdout, value, "", bmachine.obase);
549 stack_free_value(value);
557 stack_dup(&bmachine.stack);
564 stack_swap(&bmachine.stack);
570 struct value *v = pop();
581 bn_check(BN_set_word(n->number, bmachine.scale));
593 if (BN_is_negative(n->number))
594 warnx("scale must be a nonnegative number");
596 scale = get_ulong(n);
597 if (scale != BN_MASK2 && scale <= UINT_MAX)
598 bmachine.scale = (u_int)scale;
600 warnx("scale too large");
612 bn_check(BN_set_word(n->number, bmachine.obase));
625 if (base != BN_MASK2 && base > 1 && base <= UINT_MAX)
626 bmachine.obase = (u_int)base;
628 warnx("output base must be a number greater than 1");
639 bn_check(BN_set_word(n->number, bmachine.ibase));
652 if (base != BN_MASK2 && 2 <= base && base <= 16)
653 bmachine.ibase = (u_int)base;
655 warnx("input base must be a number between 2 and 16 "
667 i = stack_size(&bmachine.stack);
669 bn_check(BN_set_word(n->number, i));
682 switch (value->type) {
686 scale = value->u.num->scale;
691 stack_free_value(value);
693 bn_check(BN_set_word(n->number, scale));
699 count_digits(const struct number *n)
701 struct number *int_part, *fract_part;
704 if (BN_is_zero(n->number))
705 return n->scale ? n->scale : 1;
707 int_part = new_number();
708 fract_part = new_number();
709 fract_part->scale = n->scale;
710 split_number(n, int_part->number, fract_part->number);
713 while (!BN_is_zero(int_part->number)) {
714 BN_div_word(int_part->number, 10);
717 free_number(int_part);
718 free_number(fract_part);
719 return (i + n->scale);
725 struct number *n = NULL;
731 switch (value->type) {
735 digits = count_digits(value->u.num);
737 bn_check(BN_set_word(n->number, digits));
740 digits = strlen(value->u.string);
742 bn_check(BN_set_word(n->number, digits));
745 stack_free_value(value);
760 switch (value->type) {
766 if (BN_num_bits(n->number) > 8)
767 bn_check(BN_mask_bits(n->number, 8));
768 str[0] = (char)BN_get_word(n->number);
771 str[0] = value->u.string[0];
774 stack_free_value(value);
775 push_string(bstrdup(str));
785 if (idx == 0xff && bmachine.extended_regs) {
788 if (ch1 == EOF || ch2 == EOF) {
789 warnx("unexpected eof");
792 idx = (ch1 << 8) + ch2 + UCHAR_MAX + 1;
794 if (idx < 0 || (unsigned)idx >= bmachine.reg_array_size) {
795 warnx("internal error: reg num = %d", idx);
811 v = stack_tos(&bmachine.reg[idx]);
814 bn_check(BN_zero(n->number));
817 push(stack_dup_value(v, ©));
833 stack_set_tos(&bmachine.reg[idx], val);
846 stack = &bmachine.reg[idx];
848 if (stack_size(stack) > 0) {
849 value = stack_pop(stack);
854 warnx("stack register '%c' (0%o) is empty",
870 stack_push(&bmachine.reg[idx], value);
877 struct number *inumber, *n;
886 inumber = pop_number();
889 idx = get_ulong(inumber);
890 if (BN_is_negative(inumber->number))
891 warnx("negative idx");
892 else if (idx == BN_MASK2 || idx > MAX_ARRAY_INDEX)
893 warnx("idx too big");
895 stack = &bmachine.reg[reg];
896 v = frame_retrieve(stack, idx);
897 if (v == NULL || v->type == BCODE_NONE) {
899 bn_check(BN_zero(n->number));
903 push(stack_dup_value(v, ©));
905 free_number(inumber);
912 struct number *inumber;
920 inumber = pop_number();
925 free_number(inumber);
928 idx = get_ulong(inumber);
929 if (BN_is_negative(inumber->number)) {
930 warnx("negative idx");
931 stack_free_value(value);
932 } else if (idx == BN_MASK2 || idx > MAX_ARRAY_INDEX) {
933 warnx("idx too big");
934 stack_free_value(value);
936 stack = &bmachine.reg[reg];
937 frame_assign(stack, idx, value);
939 free_number(inumber);
947 push_string(read_string(&bmachine.readstack[bmachine.readsp]));
968 struct number *a, *b, *r;
980 r->scale = max(a->scale, b->scale);
981 if (r->scale > a->scale)
982 normalize(a, r->scale);
983 else if (r->scale > b->scale)
984 normalize(b, r->scale);
985 bn_check(BN_add(r->number, a->number, b->number));
994 struct number *a, *b, *r;
1007 r->scale = max(a->scale, b->scale);
1008 if (r->scale > a->scale)
1009 normalize(a, r->scale);
1010 else if (r->scale > b->scale)
1011 normalize(b, r->scale);
1012 bn_check(BN_sub(r->number, b->number, a->number));
1019 bmul_number(struct number *r, struct number *a, struct number *b, u_int scale)
1023 /* Create copies of the scales, since r might be equal to a or b */
1024 u_int ascale = a->scale;
1025 u_int bscale = b->scale;
1026 u_int rscale = ascale + bscale;
1030 bn_check(BN_mul(r->number, a->number, b->number, ctx));
1034 if (rscale > bmachine.scale && rscale > ascale && rscale > bscale)
1035 normalize(r, max(scale, max(ascale, bscale)));
1041 struct number *a, *b, *r;
1053 bmul_number(r, a, b, bmachine.scale);
1063 struct number *a, *b, *r;
1074 r = div_number(b, a, bmachine.scale);
1084 struct number *a, *b, *r;
1098 scale = max(a->scale, b->scale);
1101 if (BN_is_zero(a->number))
1102 warnx("remainder by zero");
1104 normalize(a, scale);
1105 normalize(b, scale);
1109 bn_check(BN_mod(r->number, b->number, a->number, ctx));
1120 struct number *a, *b, *frac, *quotient, *rdiv, *remainder;
1133 rdiv = new_number();
1134 quotient = new_number();
1135 remainder = new_number();
1136 scale = max(a->scale, b->scale);
1138 remainder->scale = scale;
1139 quotient->scale = bmachine.scale;
1140 scale = max(a->scale, b->scale);
1142 if (BN_is_zero(a->number))
1143 warnx("divide by zero");
1145 normalize(a, scale);
1146 normalize(b, scale);
1151 * Unlike other languages' divmod operations, dc is specified
1152 * to return the remainder and the full quotient, rather than
1153 * the remainder and the floored quotient. bn(3) has no
1154 * function to calculate both. So we'll use BN_div to get the
1155 * remainder and floored quotient, then calculate the full
1156 * quotient from those.
1158 * quotient = rdiv + remainder / divisor
1160 bn_check(BN_div(rdiv->number, remainder->number,
1161 b->number, a->number, ctx));
1162 frac = div_number(remainder, a, bmachine.scale);
1163 normalize(rdiv, bmachine.scale);
1164 normalize(remainder, scale);
1165 bn_check(BN_add(quotient->number, rdiv->number, frac->number));
1169 push_number(quotient);
1170 push_number(remainder);
1179 struct number *a, *p;
1193 if (p->scale != 0) {
1199 split_number(p, i, f);
1201 warnx("Runtime warning: non-zero fractional part in exponent");
1209 if (BN_is_negative(p->number)) {
1212 rscale = bmachine.scale;
1214 /* Posix bc says min(a.scale * b, max(a.scale, scale) */
1218 b = BN_get_word(p->number);
1219 m = max(a->scale, bmachine.scale);
1220 rscale = a->scale * (u_int)b;
1221 if (rscale > m || (a->scale > 0 && (b == BN_MASK2 ||
1226 if (BN_is_zero(p->number)) {
1228 bn_check(BN_one(r->number));
1229 normalize(r, rscale);
1231 u_int ascale, mscale;
1234 while (!BN_is_bit_set(p->number, 0)) {
1236 bmul_number(a, a, a, ascale);
1237 bn_check(BN_rshift1(p->number, p->number));
1241 bn_check(BN_rshift1(p->number, p->number));
1244 while (!BN_is_zero(p->number)) {
1246 bmul_number(a, a, a, ascale);
1247 if (BN_is_bit_set(p->number, 0)) {
1249 bmul_number(r, r, a, mscale);
1251 bn_check(BN_rshift1(p->number, p->number));
1260 bn_check(BN_one(one));
1263 scale_number(one, r->scale + rscale);
1265 if (BN_is_zero(r->number))
1266 warnx("divide by zero");
1268 bn_check(BN_div(r->number, NULL, one,
1274 normalize(r, rscale);
1282 bsqrt_stop(const BIGNUM *x, const BIGNUM *y, u_int *onecount)
1289 bn_check(BN_sub(r, x, y));
1292 ret = BN_is_zero(r);
1294 return (ret || *onecount > 1);
1300 struct number *n, *r;
1303 u_int onecount, scale;
1309 if (BN_is_zero(n->number)) {
1312 } else if (BN_is_negative(n->number))
1313 warnx("square root of negative number");
1315 scale = max(bmachine.scale, n->scale);
1316 normalize(n, 2*scale);
1317 x = BN_dup(n->number);
1319 bn_check(BN_rshift(x, x, BN_num_bits(x)/2));
1325 bn_checkp(BN_copy(y, x));
1326 bn_check(BN_div(x, NULL, n->number, x, ctx));
1327 bn_check(BN_add(x, x, y));
1328 bn_check(BN_rshift1(x, x));
1329 if (bsqrt_stop(x, y, &onecount))
1332 r = bmalloc(sizeof(*r));
1352 bn_check(BN_set_word(a->number, BN_get_word(a->number) ? 0 : 1));
1360 compare(BCODE_EQUAL);
1366 struct number *a, *b, *r;
1377 bn_check(BN_set_word(r->number,
1378 compare_numbers(BCODE_EQUAL, a, b) ? 1 : 0));
1385 struct number *a, *b, *r;
1396 bn_check(BN_set_word(r->number,
1397 compare_numbers(BCODE_LESS, a, b) ? 1 : 0));
1402 lesseq_numbers(void)
1404 struct number *a, *b, *r;
1415 bn_check(BN_set_word(r->number,
1416 compare_numbers(BCODE_NOT_GREATER, a, b) ? 1 : 0));
1424 compare(BCODE_NOT_EQUAL);
1431 compare(BCODE_LESS);
1459 compare(BCODE_NOT_LESS);
1466 compare(BCODE_GREATER);
1473 compare(BCODE_NOT_GREATER);
1477 compare_numbers(enum bcode_compare type, struct number *a, struct number *b)
1482 scale = max(a->scale, b->scale);
1484 if (scale > a->scale)
1485 normalize(a, scale);
1486 else if (scale > b->scale)
1487 normalize(b, scale);
1489 cmp = BN_cmp(a->number, b->number);
1497 case BCODE_NOT_EQUAL:
1501 case BCODE_NOT_LESS:
1505 case BCODE_NOT_GREATER:
1512 compare(enum bcode_compare type)
1514 struct number *a, *b;
1521 if (readch() == 'e')
1522 elseidx = readreg();
1535 ok = compare_numbers(type, a, b);
1537 if (!ok && elseidx != NO_ELSE)
1540 if (idx >= 0 && (ok || (!ok && elseidx != NO_ELSE))) {
1541 v = stack_tos(&bmachine.reg[idx]);
1543 warnx("register '%c' (0%o) is empty", idx, idx);
1547 warnx("register '%c' (0%o) is empty", idx, idx);
1550 warn("eval called with non-string argument");
1553 eval_string(bstrdup(v->u.string));
1571 if (bmachine.readsp < 2)
1590 if (i == BN_MASK2 || i == 0)
1591 warnx("Q command requires a number >= 1");
1592 else if (bmachine.readsp < i)
1593 warnx("Q command argument exceeded string execution depth");
1613 warnx("J command requires a number >= 0");
1614 else if (i > 0 && bmachine.readsp < i)
1615 warnx("J command argument exceeded string execution depth");
1626 skip_until_mark(void)
1634 errx(1, "mark not found");
1646 if (readch() == 'e')
1652 free(read_string(&bmachine.readstack[bmachine.readsp]));
1660 if (readch() == 'e')
1681 push_number(readnumber(&bmachine.readstack[bmachine.readsp],
1682 bmachine.ibase, bmachine.scale));
1688 int ch = bmachine.readstack[bmachine.readsp].lastchar;
1689 warnx("%c (0%o) is unimplemented", ch, ch);
1693 eval_string(char *p)
1697 if (bmachine.readsp > 0) {
1698 /* Check for tail call. Do not recurse in that case. */
1702 src_setstring(&bmachine.readstack[bmachine.readsp], p);
1707 if (bmachine.readsp == bmachine.readstack_sz - 1) {
1708 size_t newsz = bmachine.readstack_sz * 2;
1709 struct source *stack;
1710 stack = reallocarray(bmachine.readstack, newsz,
1711 sizeof(struct source));
1713 err(1, "recursion too deep");
1714 bmachine.readstack_sz = newsz;
1715 bmachine.readstack = stack;
1717 src_setstring(&bmachine.readstack[++bmachine.readsp], p);
1723 /* Always read from stdin */
1728 src_setstream(&in, stdin);
1729 p = (*in.vtable->readline)(&in);
1751 if (bmachine.readsp == 0)
1758 fprintf(stderr, "# %c\n", ch);
1759 stack_print(stderr, &bmachine.stack, "* ",
1761 fprintf(stderr, "%zd =>\n", bmachine.readsp);
1764 if (0 <= ch && ch < (signed)UCHAR_MAX)
1765 (*jump_table[ch])();
1767 warnx("internal error: opcode %d", ch);
1770 stack_print(stderr, &bmachine.stack, "* ",
1772 fprintf(stderr, "%zd ==\n", bmachine.readsp);