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>
36 #define MAX_ARRAY_INDEX 2048
37 #define READSTACK_SIZE 8
39 #define NO_ELSE -2 /* -1 is EOF */
40 #define REG_ARRAY_SIZE_SMALL (UCHAR_MAX + 1)
41 #define REG_ARRAY_SIZE_BIG (UCHAR_MAX + 1 + USHRT_MAX + 1)
44 struct source *readstack;
51 size_t reg_array_size;
56 static struct bmachine bmachine;
58 static __inline int readch(void);
59 static __inline void unreadch(void);
60 static __inline char *readline(void);
61 static __inline void src_free(void);
63 static __inline u_int max(u_int, u_int);
64 static u_long get_ulong(struct number *);
66 static __inline void push_number(struct number *);
67 static __inline void push_string(char *);
68 static __inline void push(struct value *);
69 static __inline struct value *tos(void);
70 static __inline struct number *pop_number(void);
71 static __inline char *pop_string(void);
72 static __inline void clear_stack(void);
73 static __inline void print_tos(void);
74 static void pop_print(void);
75 static void pop_printn(void);
76 static __inline void print_stack(void);
77 static __inline void dup(void);
78 static void swap(void);
79 static void drop(void);
81 static void get_scale(void);
82 static void set_scale(void);
83 static void get_obase(void);
84 static void set_obase(void);
85 static void get_ibase(void);
86 static void set_ibase(void);
87 static void stackdepth(void);
88 static void push_scale(void);
89 static u_int count_digits(const struct number *);
90 static void num_digits(void);
91 static void to_ascii(void);
92 static void push_line(void);
93 static void comment(void);
94 static void bexec(char *);
95 static void badd(void);
96 static void bsub(void);
97 static void bmul(void);
98 static void bdiv(void);
99 static void bmod(void);
100 static void bdivmod(void);
101 static void bexp(void);
102 static bool bsqrt_stop(const BIGNUM *, const BIGNUM *, u_int *);
103 static void bsqrt(void);
104 static void not(void);
105 static void equal_numbers(void);
106 static void less_numbers(void);
107 static void lesseq_numbers(void);
108 static void equal(void);
109 static void not_equal(void);
110 static void less(void);
111 static void not_less(void);
112 static void greater(void);
113 static void not_greater(void);
114 static void not_compare(void);
115 static bool compare_numbers(enum bcode_compare, struct number *,
117 static void compare(enum bcode_compare);
118 static int readreg(void);
119 static void load(void);
120 static void store(void);
121 static void load_stack(void);
122 static void store_stack(void);
123 static void load_array(void);
124 static void store_array(void);
125 static void nop(void);
126 static void quit(void);
127 static void quitN(void);
128 static void skipN(void);
129 static void skip_until_mark(void);
130 static void parse_number(void);
131 static void unknown(void);
132 static void eval_string(char *);
133 static void eval_line(void);
134 static void eval_tos(void);
137 typedef void (*opcode_function)(void);
144 static opcode_function jump_table[UCHAR_MAX];
146 static const struct jump_entry jump_table_data[] = {
148 { '!', not_compare },
151 { '(', less_numbers },
155 { '.', parse_number },
157 { '0', parse_number },
158 { '1', parse_number },
159 { '2', parse_number },
160 { '3', parse_number },
161 { '4', parse_number },
162 { '5', parse_number },
163 { '6', parse_number },
164 { '7', parse_number },
165 { '8', parse_number },
166 { '9', parse_number },
167 { ':', store_array },
173 { 'A', parse_number },
174 { 'B', parse_number },
175 { 'C', parse_number },
176 { 'D', parse_number },
177 { 'E', parse_number },
178 { 'F', parse_number },
179 { 'G', equal_numbers },
190 { 'S', store_stack },
199 { '_', parse_number },
201 { '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;
254 bn_check(BN_zero(&zero));
257 /* Reset the things needed before processing a (new) file */
259 reset_bmachine(struct source *src)
263 bmachine.readstack[0] = *src;
269 struct source *src = &bmachine.readstack[bmachine.readsp];
271 return (src->vtable->readchar(src));
277 struct source *src = &bmachine.readstack[bmachine.readsp];
279 src->vtable->unreadchar(src);
282 static __inline char *
285 struct source *src = &bmachine.readstack[bmachine.readsp];
287 return (src->vtable->readline(src));
293 struct source *src = &bmachine.readstack[bmachine.readsp];
295 src->vtable->free(src);
300 pn(const char *str, const struct number *n)
302 char *p = BN_bn2dec(n->number);
305 err(1, "BN_bn2dec failed");
307 fprintf(stderr, " %s (%u)\n" , p, n->scale);
312 pbn(const char *str, const BIGNUM *n)
314 char *p = BN_bn2dec(n);
317 err(1, "BN_bn2dec failed");
319 fprintf(stderr, " %s\n", p);
325 static __inline u_int
326 max(u_int a, u_int b)
329 return (a > b ? a : b);
332 static unsigned long factors[] = {
333 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
334 100000000, 1000000000
338 scale_number(BIGNUM *n, int s)
340 unsigned int abs_scale;
345 abs_scale = s > 0 ? s : -s;
347 if (abs_scale < sizeof(factors)/sizeof(factors[0])) {
349 bn_check(BN_mul_word(n, factors[abs_scale]));
351 BN_div_word(n, factors[abs_scale]);
363 bn_check(BN_set_word(a, 10));
364 bn_check(BN_set_word(p, abs_scale));
365 bn_check(BN_exp(a, a, p, ctx));
367 bn_check(BN_mul(n, n, a, ctx));
369 bn_check(BN_div(n, NULL, n, a, ctx));
377 split_number(const struct number *n, BIGNUM *i, BIGNUM *f)
381 bn_checkp(BN_copy(i, n->number));
383 if (n->scale == 0 && f != NULL)
384 bn_check(BN_zero(f));
385 else if (n->scale < sizeof(factors)/sizeof(factors[0])) {
386 rem = BN_div_word(i, factors[n->scale]);
388 bn_check(BN_set_word(f, rem));
400 bn_check(BN_set_word(a, 10));
401 bn_check(BN_set_word(p, n->scale));
402 bn_check(BN_exp(a, a, p, ctx));
403 bn_check(BN_div(i, f, n->number, a, ctx));
411 normalize(struct number *n, u_int s)
414 scale_number(n->number, s - n->scale);
419 get_ulong(struct number *n)
423 return (BN_get_word(n->number));
427 negate(struct number *n)
430 bn_check(BN_sub(n->number, &zero, n->number));
434 push_number(struct number *n)
437 stack_pushnumber(&bmachine.stack, n);
441 push_string(char *string)
444 stack_pushstring(&bmachine.stack, string);
448 push(struct value *v)
451 stack_push(&bmachine.stack, v);
454 static __inline struct value *
458 return (stack_tos(&bmachine.stack));
461 static __inline struct value *
465 return (stack_pop(&bmachine.stack));
468 static __inline struct number *
472 return (stack_popnumber(&bmachine.stack));
475 static __inline char *
479 return (stack_popstring(&bmachine.stack));
486 stack_clear(&bmachine.stack);
493 stack_print(stdout, &bmachine.stack, "", bmachine.obase);
499 struct value *value = tos();
502 print_value(stdout, value, "", bmachine.obase);
506 warnx("stack empty");
512 struct value *value = pop();
515 switch (value->type) {
519 normalize(value->u.num, 0);
520 print_ascii(stdout, value->u.num);
524 fputs(value->u.string, stdout);
528 stack_free_value(value);
535 struct value *value = pop();
538 print_value(stdout, value, "", bmachine.obase);
540 stack_free_value(value);
548 stack_dup(&bmachine.stack);
555 stack_swap(&bmachine.stack);
561 struct value *v = pop();
572 bn_check(BN_set_word(n->number, bmachine.scale));
584 if (BN_cmp(n->number, &zero) < 0)
585 warnx("scale must be a nonnegative number");
587 scale = get_ulong(n);
588 if (scale != BN_MASK2 && scale <= UINT_MAX)
589 bmachine.scale = (u_int)scale;
591 warnx("scale too large");
603 bn_check(BN_set_word(n->number, bmachine.obase));
616 if (base != BN_MASK2 && base > 1 && base <= UINT_MAX)
617 bmachine.obase = (u_int)base;
619 warnx("output base must be a number greater than 1");
630 bn_check(BN_set_word(n->number, bmachine.ibase));
643 if (base != BN_MASK2 && 2 <= base && base <= 16)
644 bmachine.ibase = (u_int)base;
646 warnx("input base must be a number between 2 and 16 "
658 i = stack_size(&bmachine.stack);
660 bn_check(BN_set_word(n->number, i));
673 switch (value->type) {
677 scale = value->u.num->scale;
682 stack_free_value(value);
684 bn_check(BN_set_word(n->number, scale));
690 count_digits(const struct number *n)
692 struct number *int_part, *fract_part;
695 if (BN_is_zero(n->number))
698 int_part = new_number();
699 fract_part = new_number();
700 fract_part->scale = n->scale;
701 split_number(n, int_part->number, fract_part->number);
704 while (!BN_is_zero(int_part->number)) {
705 BN_div_word(int_part->number, 10);
708 free_number(int_part);
709 free_number(fract_part);
710 return (i + n->scale);
716 struct number *n = NULL;
722 switch (value->type) {
726 digits = count_digits(value->u.num);
728 bn_check(BN_set_word(n->number, digits));
731 digits = strlen(value->u.string);
733 bn_check(BN_set_word(n->number, digits));
736 stack_free_value(value);
751 switch (value->type) {
757 if (BN_num_bits(n->number) > 8)
758 bn_check(BN_mask_bits(n->number, 8));
759 str[0] = (char)BN_get_word(n->number);
762 str[0] = value->u.string[0];
765 stack_free_value(value);
766 push_string(bstrdup(str));
776 if (idx == 0xff && bmachine.extended_regs) {
779 if (ch1 == EOF || ch2 == EOF) {
780 warnx("unexpected eof");
783 idx = (ch1 << 8) + ch2 + UCHAR_MAX + 1;
785 if (idx < 0 || (unsigned)idx >= bmachine.reg_array_size) {
786 warnx("internal error: reg num = %d", idx);
802 v = stack_tos(&bmachine.reg[idx]);
805 bn_check(BN_zero(n->number));
808 push(stack_dup_value(v, ©));
824 stack_set_tos(&bmachine.reg[idx], val);
837 stack = &bmachine.reg[idx];
839 if (stack_size(stack) > 0) {
840 value = stack_pop(stack);
845 warnx("stack register '%c' (0%o) is empty",
861 stack_push(&bmachine.reg[idx], value);
868 struct number *inumber, *n;
877 inumber = pop_number();
880 idx = get_ulong(inumber);
881 if (BN_cmp(inumber->number, &zero) < 0)
882 warnx("negative idx");
883 else if (idx == BN_MASK2 || idx > MAX_ARRAY_INDEX)
884 warnx("idx too big");
886 stack = &bmachine.reg[reg];
887 v = frame_retrieve(stack, idx);
888 if (v == NULL || v->type == BCODE_NONE) {
890 bn_check(BN_zero(n->number));
894 push(stack_dup_value(v, ©));
896 free_number(inumber);
903 struct number *inumber;
911 inumber = pop_number();
916 free_number(inumber);
919 idx = get_ulong(inumber);
920 if (BN_cmp(inumber->number, &zero) < 0) {
921 warnx("negative idx");
922 stack_free_value(value);
923 } else if (idx == BN_MASK2 || idx > MAX_ARRAY_INDEX) {
924 warnx("idx too big");
925 stack_free_value(value);
927 stack = &bmachine.reg[reg];
928 frame_assign(stack, idx, value);
930 free_number(inumber);
938 push_string(read_string(&bmachine.readstack[bmachine.readsp]));
959 struct number *a, *b, *r;
972 r->scale = max(a->scale, b->scale);
973 if (r->scale > a->scale)
974 normalize(a, r->scale);
975 else if (r->scale > b->scale)
976 normalize(b, r->scale);
977 bn_check(BN_add(r->number, a->number, b->number));
986 struct number *a, *b, *r;
1000 r->scale = max(a->scale, b->scale);
1001 if (r->scale > a->scale)
1002 normalize(a, r->scale);
1003 else if (r->scale > b->scale)
1004 normalize(b, r->scale);
1005 bn_check(BN_sub(r->number, b->number, a->number));
1012 bmul_number(struct number *r, struct number *a, struct number *b)
1016 /* Create copies of the scales, since r might be equal to a or b */
1017 u_int ascale = a->scale;
1018 u_int bscale = b->scale;
1019 u_int rscale = ascale + bscale;
1023 bn_check(BN_mul(r->number, a->number, b->number, ctx));
1026 if (rscale > bmachine.scale && rscale > ascale && rscale > bscale) {
1028 normalize(r, max(bmachine.scale, max(ascale, bscale)));
1036 struct number *a, *b, *r;
1049 bmul_number(r, a, b);
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;
1189 warnx("Runtime warning: non-zero scale in exponent");
1193 if (BN_cmp(p->number, &zero) < 0) {
1196 scale = bmachine.scale;
1198 /* Posix bc says min(a.scale * b, max(a.scale, scale) */
1202 b = BN_get_word(p->number);
1203 m = max(a->scale, bmachine.scale);
1204 scale = a->scale * (u_int)b;
1205 if (scale > m || (a->scale > 0 && (b == BN_MASK2 ||
1210 if (BN_is_zero(p->number)) {
1212 bn_check(BN_one(r->number));
1213 normalize(r, scale);
1215 while (!BN_is_bit_set(p->number, 0)) {
1216 bmul_number(a, a, a);
1217 bn_check(BN_rshift1(p->number, p->number));
1221 normalize(r, scale);
1222 bn_check(BN_rshift1(p->number, p->number));
1224 while (!BN_is_zero(p->number)) {
1225 bmul_number(a, a, a);
1226 if (BN_is_bit_set(p->number, 0))
1227 bmul_number(r, r, a);
1228 bn_check(BN_rshift1(p->number, p->number));
1237 bn_check(BN_one(one));
1240 scale_number(one, r->scale + scale);
1241 normalize(r, scale);
1242 bn_check(BN_div(r->number, NULL, one, r->number, ctx));
1246 normalize(r, scale);
1254 bsqrt_stop(const BIGNUM *x, const BIGNUM *y, u_int *onecount)
1261 bn_check(BN_sub(r, x, y));
1264 ret = BN_is_zero(r);
1266 return (ret || *onecount > 1);
1272 struct number *n, *r;
1275 u_int onecount, scale;
1282 if (BN_is_zero(n->number)) {
1285 } else if (BN_cmp(n->number, &zero) < 0)
1286 warnx("square root of negative number");
1288 scale = max(bmachine.scale, n->scale);
1289 normalize(n, 2*scale);
1290 x = BN_dup(n->number);
1292 bn_check(BN_rshift(x, x, BN_num_bits(x)/2));
1298 bn_checkp(BN_copy(y, x));
1299 bn_check(BN_div(x, NULL, n->number, x, ctx));
1300 bn_check(BN_add(x, x, y));
1301 bn_check(BN_rshift1(x, x));
1302 if (bsqrt_stop(x, y, &onecount))
1305 r = bmalloc(sizeof(*r));
1326 bn_check(BN_set_word(a->number, BN_get_word(a->number) ? 0 : 1));
1334 compare(BCODE_EQUAL);
1340 struct number *a, *b, *r;
1352 bn_check(BN_set_word(r->number,
1353 compare_numbers(BCODE_EQUAL, a, b) ? 1 : 0));
1360 struct number *a, *b, *r;
1372 bn_check(BN_set_word(r->number,
1373 compare_numbers(BCODE_LESS, a, b) ? 1 : 0));
1378 lesseq_numbers(void)
1380 struct number *a, *b, *r;
1392 bn_check(BN_set_word(r->number,
1393 compare_numbers(BCODE_NOT_GREATER, a, b) ? 1 : 0));
1401 compare(BCODE_NOT_EQUAL);
1408 compare(BCODE_LESS);
1436 compare(BCODE_NOT_LESS);
1443 compare(BCODE_GREATER);
1450 compare(BCODE_NOT_GREATER);
1454 compare_numbers(enum bcode_compare type, struct number *a, struct number *b)
1459 scale = max(a->scale, b->scale);
1461 if (scale > a->scale)
1462 normalize(a, scale);
1463 else if (scale > b->scale)
1464 normalize(b, scale);
1466 cmp = BN_cmp(a->number, b->number);
1474 case BCODE_NOT_EQUAL:
1478 case BCODE_NOT_LESS:
1482 case BCODE_NOT_GREATER:
1489 compare(enum bcode_compare type)
1491 struct number *a, *b;
1498 if (readch() == 'e')
1499 elseidx = readreg();
1512 ok = compare_numbers(type, a, b);
1514 if (!ok && elseidx != NO_ELSE)
1517 if (idx >= 0 && (ok || (!ok && elseidx != NO_ELSE))) {
1518 v = stack_tos(&bmachine.reg[idx]);
1520 warnx("register '%c' (0%o) is empty", idx, idx);
1524 warnx("register '%c' (0%o) is empty", idx, idx);
1527 warn("eval called with non-string argument");
1530 eval_string(bstrdup(v->u.string));
1548 if (bmachine.readsp < 2)
1567 if (i == BN_MASK2 || i == 0)
1568 warnx("Q command requires a number >= 1");
1569 else if (bmachine.readsp < i)
1570 warnx("Q command argument exceeded string execution depth");
1590 warnx("J command requires a number >= 0");
1591 else if (i > 0 && bmachine.readsp < i)
1592 warnx("J command argument exceeded string execution depth");
1603 skip_until_mark(void)
1611 errx(1, "mark not found");
1623 if (readch() == 'e')
1629 free(read_string(&bmachine.readstack[bmachine.readsp]));
1637 if (readch() == 'e')
1658 push_number(readnumber(&bmachine.readstack[bmachine.readsp],
1665 int ch = bmachine.readstack[bmachine.readsp].lastchar;
1666 warnx("%c (0%o) is unimplemented", ch, ch);
1670 eval_string(char *p)
1674 if (bmachine.readsp > 0) {
1675 /* Check for tail call. Do not recurse in that case. */
1679 src_setstring(&bmachine.readstack[bmachine.readsp], p);
1684 if (bmachine.readsp == bmachine.readstack_sz - 1) {
1685 size_t newsz = bmachine.readstack_sz * 2;
1686 struct source *stack;
1687 stack = realloc(bmachine.readstack, newsz *
1688 sizeof(struct source));
1690 err(1, "recursion too deep");
1691 bmachine.readstack_sz = newsz;
1692 bmachine.readstack = stack;
1694 src_setstring(&bmachine.readstack[++bmachine.readsp], p);
1700 /* Always read from stdin */
1705 src_setstream(&in, stdin);
1706 p = (*in.vtable->readline)(&in);
1729 if (bmachine.readsp == 0)
1736 fprintf(stderr, "# %c\n", ch);
1737 stack_print(stderr, &bmachine.stack, "* ",
1739 fprintf(stderr, "%zd =>\n", bmachine.readsp);
1742 if (0 <= ch && ch < (signed)UCHAR_MAX)
1743 (*jump_table[ch])();
1745 warnx("internal error: opcode %d", ch);
1748 stack_print(stderr, &bmachine.stack, "* ",
1750 fprintf(stderr, "%zd ==\n", bmachine.readsp);