1 /* $OpenBSD: bcode.c,v 1.40 2009/10/27 23:59:37 deraadt 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>
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 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 },
201 { 'f', print_stack },
214 { '{', lesseq_numbers },
218 #define JUMP_TABLE_DATA_SIZE \
219 (sizeof(jump_table_data)/sizeof(jump_table_data[0]))
222 init_bmachine(bool extended_registers)
226 bmachine.extended_regs = extended_registers;
227 bmachine.reg_array_size = bmachine.extended_regs ?
228 REG_ARRAY_SIZE_BIG : REG_ARRAY_SIZE_SMALL;
230 bmachine.reg = calloc(bmachine.reg_array_size,
231 sizeof(bmachine.reg[0]));
232 if (bmachine.reg == NULL)
235 for (i = 0; i < UCHAR_MAX; i++)
236 jump_table[i] = unknown;
237 for (i = 0; i < JUMP_TABLE_DATA_SIZE; i++)
238 jump_table[jump_table_data[i].ch] = jump_table_data[i].f;
240 stack_init(&bmachine.stack);
242 for (i = 0; i < bmachine.reg_array_size; i++)
243 stack_init(&bmachine.reg[i]);
245 bmachine.readstack_sz = READSTACK_SIZE;
246 bmachine.readstack = calloc(sizeof(struct source),
247 bmachine.readstack_sz);
248 if (bmachine.readstack == NULL)
250 bmachine.obase = bmachine.ibase = 10;
256 return (bmachine.scale);
259 /* Reset the things needed before processing a (new) file */
261 reset_bmachine(struct source *src)
265 bmachine.readstack[0] = *src;
271 struct source *src = &bmachine.readstack[bmachine.readsp];
273 return (src->vtable->readchar(src));
279 struct source *src = &bmachine.readstack[bmachine.readsp];
281 src->vtable->unreadchar(src);
284 static __inline char *
287 struct source *src = &bmachine.readstack[bmachine.readsp];
289 return (src->vtable->readline(src));
295 struct source *src = &bmachine.readstack[bmachine.readsp];
297 src->vtable->free(src);
302 pn(const char *str, const struct number *n)
304 char *p = BN_bn2dec(n->number);
307 err(1, "BN_bn2dec failed");
309 fprintf(stderr, " %s (%u)\n" , p, n->scale);
314 pbn(const char *str, const BIGNUM *n)
316 char *p = BN_bn2dec(n);
319 err(1, "BN_bn2dec failed");
321 fprintf(stderr, " %s\n", p);
327 static __inline u_int
328 max(u_int a, u_int b)
331 return (a > b ? a : b);
334 static unsigned long factors[] = {
335 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
336 100000000, 1000000000
340 scale_number(BIGNUM *n, int s)
342 unsigned int abs_scale;
347 abs_scale = s > 0 ? s : -s;
349 if (abs_scale < sizeof(factors)/sizeof(factors[0])) {
351 bn_check(BN_mul_word(n, factors[abs_scale]));
353 BN_div_word(n, factors[abs_scale]);
365 bn_check(BN_set_word(a, 10));
366 bn_check(BN_set_word(p, abs_scale));
367 bn_check(BN_exp(a, a, p, ctx));
369 bn_check(BN_mul(n, n, a, ctx));
371 bn_check(BN_div(n, NULL, n, a, ctx));
379 split_number(const struct number *n, BIGNUM *i, BIGNUM *f)
383 bn_checkp(BN_copy(i, n->number));
385 if (n->scale == 0 && f != NULL)
386 bn_check(BN_zero(f));
387 else if (n->scale < sizeof(factors)/sizeof(factors[0])) {
388 rem = BN_div_word(i, factors[n->scale]);
390 bn_check(BN_set_word(f, rem));
402 bn_check(BN_set_word(a, 10));
403 bn_check(BN_set_word(p, n->scale));
404 bn_check(BN_exp(a, a, p, ctx));
405 bn_check(BN_div(i, f, n->number, a, ctx));
413 normalize(struct number *n, u_int s)
416 scale_number(n->number, s - n->scale);
421 get_ulong(struct number *n)
425 return (BN_get_word(n->number));
429 negate(struct number *n)
432 BN_set_negative(n->number, !BN_is_negative(n->number));
436 push_number(struct number *n)
439 stack_pushnumber(&bmachine.stack, n);
443 push_string(char *string)
446 stack_pushstring(&bmachine.stack, string);
450 push(struct value *v)
453 stack_push(&bmachine.stack, v);
456 static __inline struct value *
460 return (stack_tos(&bmachine.stack));
463 static __inline struct value *
467 return (stack_pop(&bmachine.stack));
470 static __inline struct number *
474 return (stack_popnumber(&bmachine.stack));
477 static __inline char *
481 return (stack_popstring(&bmachine.stack));
488 stack_clear(&bmachine.stack);
495 stack_print(stdout, &bmachine.stack, "", bmachine.obase);
501 struct value *value = tos();
504 print_value(stdout, value, "", bmachine.obase);
508 warnx("stack empty");
514 struct value *value = pop();
517 switch (value->type) {
521 normalize(value->u.num, 0);
522 print_ascii(stdout, value->u.num);
526 fputs(value->u.string, stdout);
530 stack_free_value(value);
537 struct value *value = pop();
540 print_value(stdout, value, "", bmachine.obase);
542 stack_free_value(value);
550 stack_dup(&bmachine.stack);
557 stack_swap(&bmachine.stack);
563 struct value *v = pop();
574 bn_check(BN_set_word(n->number, bmachine.scale));
586 if (BN_is_negative(n->number))
587 warnx("scale must be a nonnegative number");
589 scale = get_ulong(n);
590 if (scale != BN_MASK2 && scale <= UINT_MAX)
591 bmachine.scale = (u_int)scale;
593 warnx("scale too large");
605 bn_check(BN_set_word(n->number, bmachine.obase));
618 if (base != BN_MASK2 && base > 1 && base <= UINT_MAX)
619 bmachine.obase = (u_int)base;
621 warnx("output base must be a number greater than 1");
632 bn_check(BN_set_word(n->number, bmachine.ibase));
645 if (base != BN_MASK2 && 2 <= base && base <= 16)
646 bmachine.ibase = (u_int)base;
648 warnx("input base must be a number between 2 and 16 "
660 i = stack_size(&bmachine.stack);
662 bn_check(BN_set_word(n->number, i));
675 switch (value->type) {
679 scale = value->u.num->scale;
684 stack_free_value(value);
686 bn_check(BN_set_word(n->number, scale));
692 count_digits(const struct number *n)
694 struct number *int_part, *fract_part;
697 if (BN_is_zero(n->number))
698 return (n->scale ? n->scale : 1);
700 int_part = new_number();
701 fract_part = new_number();
702 fract_part->scale = n->scale;
703 split_number(n, int_part->number, fract_part->number);
706 while (!BN_is_zero(int_part->number)) {
707 BN_div_word(int_part->number, 10);
710 free_number(int_part);
711 free_number(fract_part);
712 return (i + n->scale);
718 struct number *n = NULL;
724 switch (value->type) {
728 digits = count_digits(value->u.num);
730 bn_check(BN_set_word(n->number, digits));
733 digits = strlen(value->u.string);
735 bn_check(BN_set_word(n->number, digits));
738 stack_free_value(value);
753 switch (value->type) {
759 if (BN_num_bits(n->number) > 8)
760 bn_check(BN_mask_bits(n->number, 8));
761 str[0] = (char)BN_get_word(n->number);
764 str[0] = value->u.string[0];
767 stack_free_value(value);
768 push_string(bstrdup(str));
778 if (idx == 0xff && bmachine.extended_regs) {
781 if (ch1 == EOF || ch2 == EOF) {
782 warnx("unexpected eof");
785 idx = (ch1 << 8) + ch2 + UCHAR_MAX + 1;
787 if (idx < 0 || (unsigned)idx >= bmachine.reg_array_size) {
788 warnx("internal error: reg num = %d", idx);
804 v = stack_tos(&bmachine.reg[idx]);
807 bn_check(BN_zero(n->number));
810 push(stack_dup_value(v, ©));
826 stack_set_tos(&bmachine.reg[idx], val);
839 stack = &bmachine.reg[idx];
841 if (stack_size(stack) > 0) {
842 value = stack_pop(stack);
847 warnx("stack register '%c' (0%o) is empty",
863 stack_push(&bmachine.reg[idx], value);
870 struct number *inumber, *n;
879 inumber = pop_number();
882 idx = get_ulong(inumber);
883 if (BN_is_negative(inumber->number))
884 warnx("negative idx");
885 else if (idx == BN_MASK2 || idx > MAX_ARRAY_INDEX)
886 warnx("idx too big");
888 stack = &bmachine.reg[reg];
889 v = frame_retrieve(stack, idx);
890 if (v == NULL || v->type == BCODE_NONE) {
892 bn_check(BN_zero(n->number));
896 push(stack_dup_value(v, ©));
898 free_number(inumber);
905 struct number *inumber;
913 inumber = pop_number();
918 free_number(inumber);
921 idx = get_ulong(inumber);
922 if (BN_is_negative(inumber->number)) {
923 warnx("negative idx");
924 stack_free_value(value);
925 } else if (idx == BN_MASK2 || idx > MAX_ARRAY_INDEX) {
926 warnx("idx too big");
927 stack_free_value(value);
929 stack = &bmachine.reg[reg];
930 frame_assign(stack, idx, value);
932 free_number(inumber);
940 push_string(read_string(&bmachine.readstack[bmachine.readsp]));
961 struct number *a, *b, *r;
974 r->scale = max(a->scale, b->scale);
975 if (r->scale > a->scale)
976 normalize(a, r->scale);
977 else if (r->scale > b->scale)
978 normalize(b, r->scale);
979 bn_check(BN_add(r->number, a->number, b->number));
988 struct number *a, *b, *r;
1002 r->scale = max(a->scale, b->scale);
1003 if (r->scale > a->scale)
1004 normalize(a, r->scale);
1005 else if (r->scale > b->scale)
1006 normalize(b, r->scale);
1007 bn_check(BN_sub(r->number, b->number, a->number));
1014 bmul_number(struct number *r, struct number *a, struct number *b, u_int scale)
1018 /* Create copies of the scales, since r might be equal to a or b */
1019 u_int ascale = a->scale;
1020 u_int bscale = b->scale;
1021 u_int rscale = ascale + bscale;
1025 bn_check(BN_mul(r->number, a->number, b->number, ctx));
1029 if (rscale > bmachine.scale && rscale > ascale && rscale > bscale)
1030 normalize(r, max(scale, max(ascale, bscale)));
1036 struct number *a, *b, *r;
1049 bmul_number(r, a, b, bmachine.scale);
1059 struct number *a, *b, *r;
1074 r->scale = bmachine.scale;
1075 scale = max(a->scale, b->scale);
1077 if (BN_is_zero(a->number))
1078 warnx("divide by zero");
1080 normalize(a, scale);
1081 normalize(b, scale + r->scale);
1085 bn_check(BN_div(r->number, NULL, b->number, a->number, ctx));
1096 struct number *a, *b, *r;
1111 scale = max(a->scale, b->scale);
1112 r->scale = max(b->scale, a->scale + bmachine.scale);
1114 if (BN_is_zero(a->number))
1115 warnx("remainder by zero");
1117 normalize(a, scale);
1118 normalize(b, scale + bmachine.scale);
1122 bn_check(BN_mod(r->number, b->number, a->number, ctx));
1133 struct number *a, *b, *rdiv, *rmod;
1147 rdiv = new_number();
1148 rmod = new_number();
1149 rdiv->scale = bmachine.scale;
1150 rmod->scale = max(b->scale, a->scale + bmachine.scale);
1151 scale = max(a->scale, b->scale);
1153 if (BN_is_zero(a->number))
1154 warnx("divide by zero");
1156 normalize(a, scale);
1157 normalize(b, scale + bmachine.scale);
1161 bn_check(BN_div(rdiv->number, rmod->number,
1162 b->number, a->number, ctx));
1174 struct number *a, *p, *r;
1188 if (p->scale != 0) {
1194 split_number(p, i, f);
1196 warnx("Runtime warning: non-zero fractional part "
1205 if (BN_is_negative(p->number)) {
1208 rscale = bmachine.scale;
1210 /* Posix bc says min(a.scale * b, max(a.scale, scale) */
1214 b = BN_get_word(p->number);
1215 m = max(a->scale, bmachine.scale);
1216 rscale = a->scale * (u_int)b;
1217 if (rscale > m || (a->scale > 0 && (b == BN_MASK2 ||
1222 if (BN_is_zero(p->number)) {
1224 bn_check(BN_one(r->number));
1225 normalize(r, rscale);
1227 u_int ascale, mscale;
1230 while (!BN_is_bit_set(p->number, 0)) {
1232 bmul_number(a, a, a, ascale);
1233 bn_check(BN_rshift1(p->number, p->number));
1237 bn_check(BN_rshift1(p->number, p->number));
1240 while (!BN_is_zero(p->number)) {
1242 bmul_number(a, a, a, ascale);
1243 if (BN_is_bit_set(p->number, 0)) {
1245 bmul_number(r, r, a, mscale);
1247 bn_check(BN_rshift1(p->number, p->number));
1256 bn_check(BN_one(one));
1259 scale_number(one, r->scale + rscale);
1261 if (BN_is_zero(r->number))
1262 warnx("divide by zero");
1264 bn_check(BN_div(r->number, NULL, one,
1270 normalize(r, rscale);
1278 bsqrt_stop(const BIGNUM *x, const BIGNUM *y, u_int *onecount)
1285 bn_check(BN_sub(r, x, y));
1288 ret = BN_is_zero(r);
1290 return (ret || *onecount > 1);
1296 struct number *n, *r;
1299 u_int onecount, scale;
1306 if (BN_is_zero(n->number)) {
1309 } else if (BN_is_negative(n->number))
1310 warnx("square root of negative number");
1312 scale = max(bmachine.scale, n->scale);
1313 normalize(n, 2*scale);
1314 x = BN_dup(n->number);
1316 bn_check(BN_rshift(x, x, BN_num_bits(x)/2));
1322 bn_checkp(BN_copy(y, x));
1323 bn_check(BN_div(x, NULL, n->number, x, ctx));
1324 bn_check(BN_add(x, x, y));
1325 bn_check(BN_rshift1(x, x));
1326 if (bsqrt_stop(x, y, &onecount))
1329 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;
1376 bn_check(BN_set_word(r->number,
1377 compare_numbers(BCODE_EQUAL, a, b) ? 1 : 0));
1384 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;
1416 bn_check(BN_set_word(r->number,
1417 compare_numbers(BCODE_NOT_GREATER, a, b) ? 1 : 0));
1425 compare(BCODE_NOT_EQUAL);
1432 compare(BCODE_LESS);
1460 compare(BCODE_NOT_LESS);
1467 compare(BCODE_GREATER);
1474 compare(BCODE_NOT_GREATER);
1478 compare_numbers(enum bcode_compare type, struct number *a, struct number *b)
1483 scale = max(a->scale, b->scale);
1485 if (scale > a->scale)
1486 normalize(a, scale);
1487 else if (scale > b->scale)
1488 normalize(b, scale);
1490 cmp = BN_cmp(a->number, b->number);
1498 case BCODE_NOT_EQUAL:
1502 case BCODE_NOT_LESS:
1506 case BCODE_NOT_GREATER:
1513 compare(enum bcode_compare type)
1515 struct number *a, *b;
1522 if (readch() == 'e')
1523 elseidx = readreg();
1536 ok = compare_numbers(type, a, b);
1538 if (!ok && elseidx != NO_ELSE)
1541 if (idx >= 0 && (ok || (!ok && elseidx != NO_ELSE))) {
1542 v = stack_tos(&bmachine.reg[idx]);
1544 warnx("register '%c' (0%o) is empty", idx, idx);
1548 warnx("register '%c' (0%o) is empty", idx, idx);
1551 warn("eval called with non-string argument");
1554 eval_string(bstrdup(v->u.string));
1572 if (bmachine.readsp < 2)
1591 if (i == BN_MASK2 || i == 0)
1592 warnx("Q command requires a number >= 1");
1593 else if (bmachine.readsp < i)
1594 warnx("Q command argument exceeded string execution depth");
1614 warnx("J command requires a number >= 0");
1615 else if (i > 0 && bmachine.readsp < i)
1616 warnx("J command argument exceeded string execution depth");
1627 skip_until_mark(void)
1635 errx(1, "mark not found");
1647 if (readch() == 'e')
1653 free(read_string(&bmachine.readstack[bmachine.readsp]));
1661 if (readch() == 'e')
1682 push_number(readnumber(&bmachine.readstack[bmachine.readsp],
1689 int ch = bmachine.readstack[bmachine.readsp].lastchar;
1690 warnx("%c (0%o) is unimplemented", ch, ch);
1694 eval_string(char *p)
1698 if (bmachine.readsp > 0) {
1699 /* Check for tail call. Do not recurse in that case. */
1703 src_setstring(&bmachine.readstack[bmachine.readsp], p);
1708 if (bmachine.readsp == bmachine.readstack_sz - 1) {
1709 size_t newsz = bmachine.readstack_sz * 2;
1710 struct source *stack;
1711 stack = realloc(bmachine.readstack, newsz *
1712 sizeof(struct source));
1714 err(1, "recursion too deep");
1715 bmachine.readstack_sz = newsz;
1716 bmachine.readstack = stack;
1718 src_setstring(&bmachine.readstack[++bmachine.readsp], p);
1724 /* Always read from stdin */
1729 src_setstream(&in, stdin);
1730 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);