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;
973 r->scale = max(a->scale, b->scale);
974 if (r->scale > a->scale)
975 normalize(a, r->scale);
976 else if (r->scale > b->scale)
977 normalize(b, r->scale);
978 bn_check(BN_add(r->number, a->number, b->number));
987 struct number *a, *b, *r;
1001 r->scale = max(a->scale, b->scale);
1002 if (r->scale > a->scale)
1003 normalize(a, r->scale);
1004 else if (r->scale > b->scale)
1005 normalize(b, r->scale);
1006 bn_check(BN_sub(r->number, b->number, a->number));
1013 bmul_number(struct number *r, struct number *a, struct number *b, u_int scale)
1017 /* Create copies of the scales, since r might be equal to a or b */
1018 u_int ascale = a->scale;
1019 u_int bscale = b->scale;
1020 u_int rscale = ascale + bscale;
1024 bn_check(BN_mul(r->number, a->number, b->number, ctx));
1028 if (rscale > bmachine.scale && rscale > ascale && rscale > bscale)
1029 normalize(r, max(scale, max(ascale, bscale)));
1035 struct number *a, *b, *r;
1048 bmul_number(r, a, b, bmachine.scale);
1058 struct number *a, *b, *r;
1073 r->scale = bmachine.scale;
1074 scale = max(a->scale, b->scale);
1076 if (BN_is_zero(a->number))
1077 warnx("divide by zero");
1079 normalize(a, scale);
1080 normalize(b, scale + r->scale);
1084 bn_check(BN_div(r->number, NULL, b->number, a->number, ctx));
1095 struct number *a, *b, *r;
1110 scale = max(a->scale, b->scale);
1111 r->scale = max(b->scale, a->scale + bmachine.scale);
1113 if (BN_is_zero(a->number))
1114 warnx("remainder by zero");
1116 normalize(a, scale);
1117 normalize(b, scale + bmachine.scale);
1121 bn_check(BN_mod(r->number, b->number, a->number, ctx));
1132 struct number *a, *b, *rdiv, *rmod;
1146 rdiv = new_number();
1147 rmod = new_number();
1148 rdiv->scale = bmachine.scale;
1149 rmod->scale = max(b->scale, a->scale + bmachine.scale);
1150 scale = max(a->scale, b->scale);
1152 if (BN_is_zero(a->number))
1153 warnx("divide by zero");
1155 normalize(a, scale);
1156 normalize(b, scale + bmachine.scale);
1160 bn_check(BN_div(rdiv->number, rmod->number,
1161 b->number, a->number, ctx));
1173 struct number *a, *p;
1188 if (p->scale != 0) {
1194 split_number(p, i, f);
1196 warnx("Runtime warning: non-zero fractional part in exponent");
1204 if (BN_is_negative(p->number)) {
1207 rscale = bmachine.scale;
1209 /* Posix bc says min(a.scale * b, max(a.scale, scale) */
1213 b = BN_get_word(p->number);
1214 m = max(a->scale, bmachine.scale);
1215 rscale = a->scale * (u_int)b;
1216 if (rscale > m || (a->scale > 0 && (b == BN_MASK2 ||
1221 if (BN_is_zero(p->number)) {
1223 bn_check(BN_one(r->number));
1224 normalize(r, rscale);
1226 u_int ascale, mscale;
1229 while (!BN_is_bit_set(p->number, 0)) {
1231 bmul_number(a, a, a, ascale);
1232 bn_check(BN_rshift1(p->number, p->number));
1236 bn_check(BN_rshift1(p->number, p->number));
1239 while (!BN_is_zero(p->number)) {
1241 bmul_number(a, a, a, ascale);
1242 if (BN_is_bit_set(p->number, 0)) {
1244 bmul_number(r, r, a, mscale);
1246 bn_check(BN_rshift1(p->number, p->number));
1255 bn_check(BN_one(one));
1258 scale_number(one, r->scale + rscale);
1260 if (BN_is_zero(r->number))
1261 warnx("divide by zero");
1263 bn_check(BN_div(r->number, NULL, one,
1269 normalize(r, rscale);
1277 bsqrt_stop(const BIGNUM *x, const BIGNUM *y, u_int *onecount)
1284 bn_check(BN_sub(r, x, y));
1287 ret = BN_is_zero(r);
1289 return (ret || *onecount > 1);
1295 struct number *n, *r;
1298 u_int onecount, scale;
1305 if (BN_is_zero(n->number)) {
1308 } else if (BN_is_negative(n->number))
1309 warnx("square root of negative number");
1311 scale = max(bmachine.scale, n->scale);
1312 normalize(n, 2*scale);
1313 x = BN_dup(n->number);
1315 bn_check(BN_rshift(x, x, BN_num_bits(x)/2));
1321 bn_checkp(BN_copy(y, x));
1322 bn_check(BN_div(x, NULL, n->number, x, ctx));
1323 bn_check(BN_add(x, x, y));
1324 bn_check(BN_rshift1(x, x));
1325 if (bsqrt_stop(x, y, &onecount))
1328 r = bmalloc(sizeof(*r));
1349 bn_check(BN_set_word(a->number, BN_get_word(a->number) ? 0 : 1));
1357 compare(BCODE_EQUAL);
1363 struct number *a, *b, *r;
1375 bn_check(BN_set_word(r->number,
1376 compare_numbers(BCODE_EQUAL, a, b) ? 1 : 0));
1383 struct number *a, *b, *r;
1395 bn_check(BN_set_word(r->number,
1396 compare_numbers(BCODE_LESS, a, b) ? 1 : 0));
1401 lesseq_numbers(void)
1403 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],
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 = realloc(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);
1752 if (bmachine.readsp == 0)
1759 fprintf(stderr, "# %c\n", ch);
1760 stack_print(stderr, &bmachine.stack, "* ",
1762 fprintf(stderr, "%zd =>\n", bmachine.readsp);
1765 if (0 <= ch && ch < (signed)UCHAR_MAX)
1766 (*jump_table[ch])();
1768 warnx("internal error: opcode %d", ch);
1771 stack_print(stderr, &bmachine.stack, "* ",
1773 fprintf(stderr, "%zd ==\n", bmachine.readsp);