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 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)
431 BN_set_negative(n->number, !BN_is_negative(n->number));
435 push_number(struct number *n)
438 stack_pushnumber(&bmachine.stack, n);
442 push_string(char *string)
445 stack_pushstring(&bmachine.stack, string);
449 push(struct value *v)
452 stack_push(&bmachine.stack, v);
455 static __inline struct value *
459 return (stack_tos(&bmachine.stack));
462 static __inline struct value *
466 return (stack_pop(&bmachine.stack));
469 static __inline struct number *
473 return (stack_popnumber(&bmachine.stack));
476 static __inline char *
480 return (stack_popstring(&bmachine.stack));
487 stack_clear(&bmachine.stack);
494 stack_print(stdout, &bmachine.stack, "", bmachine.obase);
500 struct value *value = tos();
503 print_value(stdout, value, "", bmachine.obase);
507 warnx("stack empty");
513 struct value *value = pop();
516 switch (value->type) {
520 normalize(value->u.num, 0);
521 print_ascii(stdout, value->u.num);
525 fputs(value->u.string, stdout);
529 stack_free_value(value);
536 struct value *value = pop();
539 print_value(stdout, value, "", bmachine.obase);
541 stack_free_value(value);
549 stack_dup(&bmachine.stack);
556 stack_swap(&bmachine.stack);
562 struct value *v = pop();
573 bn_check(BN_set_word(n->number, bmachine.scale));
585 if (BN_is_negative(n->number))
586 warnx("scale must be a nonnegative number");
588 scale = get_ulong(n);
589 if (scale != BN_MASK2 && scale <= UINT_MAX)
590 bmachine.scale = (u_int)scale;
592 warnx("scale too large");
604 bn_check(BN_set_word(n->number, bmachine.obase));
617 if (base != BN_MASK2 && base > 1 && base <= UINT_MAX)
618 bmachine.obase = (u_int)base;
620 warnx("output base must be a number greater than 1");
631 bn_check(BN_set_word(n->number, bmachine.ibase));
644 if (base != BN_MASK2 && 2 <= base && base <= 16)
645 bmachine.ibase = (u_int)base;
647 warnx("input base must be a number between 2 and 16 "
659 i = stack_size(&bmachine.stack);
661 bn_check(BN_set_word(n->number, i));
674 switch (value->type) {
678 scale = value->u.num->scale;
683 stack_free_value(value);
685 bn_check(BN_set_word(n->number, scale));
691 count_digits(const struct number *n)
693 struct number *int_part, *fract_part;
696 if (BN_is_zero(n->number))
697 return n->scale ? n->scale : 1;
699 int_part = new_number();
700 fract_part = new_number();
701 fract_part->scale = n->scale;
702 split_number(n, int_part->number, fract_part->number);
705 while (!BN_is_zero(int_part->number)) {
706 BN_div_word(int_part->number, 10);
709 free_number(int_part);
710 free_number(fract_part);
711 return (i + n->scale);
717 struct number *n = NULL;
723 switch (value->type) {
727 digits = count_digits(value->u.num);
729 bn_check(BN_set_word(n->number, digits));
732 digits = strlen(value->u.string);
734 bn_check(BN_set_word(n->number, digits));
737 stack_free_value(value);
752 switch (value->type) {
758 if (BN_num_bits(n->number) > 8)
759 bn_check(BN_mask_bits(n->number, 8));
760 str[0] = (char)BN_get_word(n->number);
763 str[0] = value->u.string[0];
766 stack_free_value(value);
767 push_string(bstrdup(str));
777 if (idx == 0xff && bmachine.extended_regs) {
780 if (ch1 == EOF || ch2 == EOF) {
781 warnx("unexpected eof");
784 idx = (ch1 << 8) + ch2 + UCHAR_MAX + 1;
786 if (idx < 0 || (unsigned)idx >= bmachine.reg_array_size) {
787 warnx("internal error: reg num = %d", idx);
803 v = stack_tos(&bmachine.reg[idx]);
806 bn_check(BN_zero(n->number));
809 push(stack_dup_value(v, ©));
825 stack_set_tos(&bmachine.reg[idx], val);
838 stack = &bmachine.reg[idx];
840 if (stack_size(stack) > 0) {
841 value = stack_pop(stack);
846 warnx("stack register '%c' (0%o) is empty",
862 stack_push(&bmachine.reg[idx], value);
869 struct number *inumber, *n;
878 inumber = pop_number();
881 idx = get_ulong(inumber);
882 if (BN_is_negative(inumber->number))
883 warnx("negative idx");
884 else if (idx == BN_MASK2 || idx > MAX_ARRAY_INDEX)
885 warnx("idx too big");
887 stack = &bmachine.reg[reg];
888 v = frame_retrieve(stack, idx);
889 if (v == NULL || v->type == BCODE_NONE) {
891 bn_check(BN_zero(n->number));
895 push(stack_dup_value(v, ©));
897 free_number(inumber);
904 struct number *inumber;
912 inumber = pop_number();
917 free_number(inumber);
920 idx = get_ulong(inumber);
921 if (BN_is_negative(inumber->number)) {
922 warnx("negative idx");
923 stack_free_value(value);
924 } else if (idx == BN_MASK2 || idx > MAX_ARRAY_INDEX) {
925 warnx("idx too big");
926 stack_free_value(value);
928 stack = &bmachine.reg[reg];
929 frame_assign(stack, idx, value);
931 free_number(inumber);
939 push_string(read_string(&bmachine.readstack[bmachine.readsp]));
960 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;
999 r->scale = max(a->scale, b->scale);
1000 if (r->scale > a->scale)
1001 normalize(a, r->scale);
1002 else if (r->scale > b->scale)
1003 normalize(b, r->scale);
1004 bn_check(BN_sub(r->number, b->number, a->number));
1011 bmul_number(struct number *r, struct number *a, struct number *b, u_int scale)
1015 /* Create copies of the scales, since r might be equal to a or b */
1016 u_int ascale = a->scale;
1017 u_int bscale = b->scale;
1018 u_int rscale = ascale + bscale;
1022 bn_check(BN_mul(r->number, a->number, b->number, ctx));
1026 if (rscale > bmachine.scale && rscale > ascale && rscale > bscale)
1027 normalize(r, max(scale, max(ascale, bscale)));
1033 struct number *a, *b, *r;
1045 bmul_number(r, a, b, bmachine.scale);
1055 struct number *a, *b, *r;
1069 r->scale = bmachine.scale;
1070 scale = max(a->scale, b->scale);
1072 if (BN_is_zero(a->number))
1073 warnx("divide by zero");
1075 normalize(a, scale);
1076 normalize(b, scale + r->scale);
1080 bn_check(BN_div(r->number, NULL, b->number, a->number, ctx));
1091 struct number *a, *b, *r;
1105 scale = max(a->scale, b->scale);
1106 r->scale = max(b->scale, a->scale + bmachine.scale);
1108 if (BN_is_zero(a->number))
1109 warnx("remainder by zero");
1111 normalize(a, scale);
1112 normalize(b, scale + bmachine.scale);
1116 bn_check(BN_mod(r->number, b->number, a->number, ctx));
1127 struct number *a, *b, *rdiv, *rmod;
1140 rdiv = new_number();
1141 rmod = new_number();
1142 rdiv->scale = bmachine.scale;
1143 rmod->scale = max(b->scale, a->scale + bmachine.scale);
1144 scale = max(a->scale, b->scale);
1146 if (BN_is_zero(a->number))
1147 warnx("divide by zero");
1149 normalize(a, scale);
1150 normalize(b, scale + bmachine.scale);
1154 bn_check(BN_div(rdiv->number, rmod->number,
1155 b->number, a->number, ctx));
1167 struct number *a, *p;
1181 if (p->scale != 0) {
1187 split_number(p, i, f);
1189 warnx("Runtime warning: non-zero fractional part in exponent");
1197 if (BN_is_negative(p->number)) {
1200 rscale = bmachine.scale;
1202 /* Posix bc says min(a.scale * b, max(a.scale, scale) */
1206 b = BN_get_word(p->number);
1207 m = max(a->scale, bmachine.scale);
1208 rscale = a->scale * (u_int)b;
1209 if (rscale > m || (a->scale > 0 && (b == BN_MASK2 ||
1214 if (BN_is_zero(p->number)) {
1216 bn_check(BN_one(r->number));
1217 normalize(r, rscale);
1219 u_int ascale, mscale;
1222 while (!BN_is_bit_set(p->number, 0)) {
1224 bmul_number(a, a, a, ascale);
1225 bn_check(BN_rshift1(p->number, p->number));
1229 bn_check(BN_rshift1(p->number, p->number));
1232 while (!BN_is_zero(p->number)) {
1234 bmul_number(a, a, a, ascale);
1235 if (BN_is_bit_set(p->number, 0)) {
1237 bmul_number(r, r, a, mscale);
1239 bn_check(BN_rshift1(p->number, p->number));
1248 bn_check(BN_one(one));
1251 scale_number(one, r->scale + rscale);
1253 if (BN_is_zero(r->number))
1254 warnx("divide by zero");
1256 bn_check(BN_div(r->number, NULL, one,
1262 normalize(r, rscale);
1270 bsqrt_stop(const BIGNUM *x, const BIGNUM *y, u_int *onecount)
1277 bn_check(BN_sub(r, x, y));
1280 ret = BN_is_zero(r);
1282 return (ret || *onecount > 1);
1288 struct number *n, *r;
1291 u_int onecount, scale;
1297 if (BN_is_zero(n->number)) {
1300 } else if (BN_is_negative(n->number))
1301 warnx("square root of negative number");
1303 scale = max(bmachine.scale, n->scale);
1304 normalize(n, 2*scale);
1305 x = BN_dup(n->number);
1307 bn_check(BN_rshift(x, x, BN_num_bits(x)/2));
1313 bn_checkp(BN_copy(y, x));
1314 bn_check(BN_div(x, NULL, n->number, x, ctx));
1315 bn_check(BN_add(x, x, y));
1316 bn_check(BN_rshift1(x, x));
1317 if (bsqrt_stop(x, y, &onecount))
1320 r = bmalloc(sizeof(*r));
1340 bn_check(BN_set_word(a->number, BN_get_word(a->number) ? 0 : 1));
1348 compare(BCODE_EQUAL);
1354 struct number *a, *b, *r;
1365 bn_check(BN_set_word(r->number,
1366 compare_numbers(BCODE_EQUAL, a, b) ? 1 : 0));
1373 struct number *a, *b, *r;
1384 bn_check(BN_set_word(r->number,
1385 compare_numbers(BCODE_LESS, a, b) ? 1 : 0));
1390 lesseq_numbers(void)
1392 struct number *a, *b, *r;
1403 bn_check(BN_set_word(r->number,
1404 compare_numbers(BCODE_NOT_GREATER, a, b) ? 1 : 0));
1412 compare(BCODE_NOT_EQUAL);
1419 compare(BCODE_LESS);
1447 compare(BCODE_NOT_LESS);
1454 compare(BCODE_GREATER);
1461 compare(BCODE_NOT_GREATER);
1465 compare_numbers(enum bcode_compare type, struct number *a, struct number *b)
1470 scale = max(a->scale, b->scale);
1472 if (scale > a->scale)
1473 normalize(a, scale);
1474 else if (scale > b->scale)
1475 normalize(b, scale);
1477 cmp = BN_cmp(a->number, b->number);
1485 case BCODE_NOT_EQUAL:
1489 case BCODE_NOT_LESS:
1493 case BCODE_NOT_GREATER:
1500 compare(enum bcode_compare type)
1502 struct number *a, *b;
1509 if (readch() == 'e')
1510 elseidx = readreg();
1523 ok = compare_numbers(type, a, b);
1525 if (!ok && elseidx != NO_ELSE)
1528 if (idx >= 0 && (ok || (!ok && elseidx != NO_ELSE))) {
1529 v = stack_tos(&bmachine.reg[idx]);
1531 warnx("register '%c' (0%o) is empty", idx, idx);
1535 warnx("register '%c' (0%o) is empty", idx, idx);
1538 warn("eval called with non-string argument");
1541 eval_string(bstrdup(v->u.string));
1559 if (bmachine.readsp < 2)
1578 if (i == BN_MASK2 || i == 0)
1579 warnx("Q command requires a number >= 1");
1580 else if (bmachine.readsp < i)
1581 warnx("Q command argument exceeded string execution depth");
1601 warnx("J command requires a number >= 0");
1602 else if (i > 0 && bmachine.readsp < i)
1603 warnx("J command argument exceeded string execution depth");
1614 skip_until_mark(void)
1622 errx(1, "mark not found");
1634 if (readch() == 'e')
1640 free(read_string(&bmachine.readstack[bmachine.readsp]));
1648 if (readch() == 'e')
1669 push_number(readnumber(&bmachine.readstack[bmachine.readsp],
1676 int ch = bmachine.readstack[bmachine.readsp].lastchar;
1677 warnx("%c (0%o) is unimplemented", ch, ch);
1681 eval_string(char *p)
1685 if (bmachine.readsp > 0) {
1686 /* Check for tail call. Do not recurse in that case. */
1690 src_setstring(&bmachine.readstack[bmachine.readsp], p);
1695 if (bmachine.readsp == bmachine.readstack_sz - 1) {
1696 size_t newsz = bmachine.readstack_sz * 2;
1697 struct source *stack;
1698 stack = realloc(bmachine.readstack, newsz *
1699 sizeof(struct source));
1701 err(1, "recursion too deep");
1702 bmachine.readstack_sz = newsz;
1703 bmachine.readstack = stack;
1705 src_setstring(&bmachine.readstack[++bmachine.readsp], p);
1711 /* Always read from stdin */
1716 src_setstream(&in, stdin);
1717 p = (*in.vtable->readline)(&in);
1739 if (bmachine.readsp == 0)
1746 fprintf(stderr, "# %c\n", ch);
1747 stack_print(stderr, &bmachine.stack, "* ",
1749 fprintf(stderr, "%zd =>\n", bmachine.readsp);
1752 if (0 <= ch && ch < (signed)UCHAR_MAX)
1753 (*jump_table[ch])();
1755 warnx("internal error: opcode %d", ch);
1758 stack_print(stderr, &bmachine.stack, "* ",
1760 fprintf(stderr, "%zd ==\n", bmachine.readsp);