2 * $OpenBSD: bcode.c,v 1.29 2005/04/02 18:05:04 otto Exp $
3 * $DragonFly: src/usr.bin/dc/bcode.c,v 1.3 2008/09/14 21:08:29 swildner Exp $
7 * Copyright (c) 2003, Otto Moerbeek <otto@drijf.net>
9 * Permission to use, copy, modify, and distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 #include <openssl/ssl.h>
34 /* #define DEBUGGING */
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)
50 size_t reg_array_size;
52 volatile sig_atomic_t interrupted;
53 struct source *readstack;
57 static struct bmachine bmachine;
58 static void sighandler(int);
60 static __inline int readch(void);
61 static __inline int unreadch(void);
62 static __inline char *readline(void);
63 static __inline void src_free(void);
65 static __inline u_int max(u_int, u_int);
66 static u_long get_ulong(struct number *);
68 static __inline void push_number(struct number *);
69 static __inline void push_string(char *);
70 static __inline void push(struct value *);
71 static __inline struct value *tos(void);
72 static __inline struct number *pop_number(void);
73 static __inline char *pop_string(void);
74 static __inline void clear_stack(void);
75 static __inline void print_tos(void);
76 static void pop_print(void);
77 static void pop_printn(void);
78 static __inline void print_stack(void);
79 static __inline void dup(void);
80 static void swap(void);
81 static void drop(void);
83 static void get_scale(void);
84 static void set_scale(void);
85 static void get_obase(void);
86 static void set_obase(void);
87 static void get_ibase(void);
88 static void set_ibase(void);
89 static void stackdepth(void);
90 static void push_scale(void);
91 static u_int count_digits(const struct number *);
92 static void num_digits(void);
93 static void to_ascii(void);
94 static void push_line(void);
95 static void comment(void);
96 static void bexec(char *);
97 static void badd(void);
98 static void bsub(void);
99 static void bmul(void);
100 static void bdiv(void);
101 static void bmod(void);
102 static void bdivmod(void);
103 static void bexp(void);
104 static bool bsqrt_stop(const BIGNUM *, const BIGNUM *, u_int *);
105 static void bsqrt(void);
106 static void not(void);
107 static void equal_numbers(void);
108 static void less_numbers(void);
109 static void lesseq_numbers(void);
110 static void equal(void);
111 static void not_equal(void);
112 static void less(void);
113 static void not_less(void);
114 static void greater(void);
115 static void not_greater(void);
116 static void not_compare(void);
117 static bool compare_numbers(enum bcode_compare, struct number *,
119 static void compare(enum bcode_compare);
120 static int readreg(void);
121 static void load(void);
122 static void store(void);
123 static void load_stack(void);
124 static void store_stack(void);
125 static void load_array(void);
126 static void store_array(void);
127 static void nop(void);
128 static void quit(void);
129 static void quitN(void);
130 static void skipN(void);
131 static void skip_until_mark(void);
132 static void parse_number(void);
133 static void unknown(void);
134 static void eval_string(char *);
135 static void eval_line(void);
136 static void eval_tos(void);
139 typedef void (*opcode_function)(void);
146 static opcode_function jump_table[UCHAR_MAX];
148 static const struct jump_entry jump_table_data[] = {
150 { '!', not_compare },
153 { '(', less_numbers },
157 { '.', parse_number },
159 { '0', parse_number },
160 { '1', parse_number },
161 { '2', parse_number },
162 { '3', parse_number },
163 { '4', parse_number },
164 { '5', parse_number },
165 { '6', parse_number },
166 { '7', parse_number },
167 { '8', parse_number },
168 { '9', parse_number },
169 { ':', store_array },
175 { 'A', parse_number },
176 { 'B', parse_number },
177 { 'C', parse_number },
178 { 'D', parse_number },
179 { 'E', parse_number },
180 { 'F', parse_number },
181 { 'G', equal_numbers },
192 { 'S', store_stack },
201 { '_', parse_number },
203 { 'c', clear_stack },
205 { 'f', print_stack },
218 { '{', lesseq_numbers },
222 #define JUMP_TABLE_DATA_SIZE \
223 (sizeof(jump_table_data)/sizeof(jump_table_data[0]))
226 sighandler(int ignored __unused)
228 bmachine.interrupted = true;
232 init_bmachine(bool extended_registers)
236 bmachine.extended_regs = extended_registers;
237 bmachine.reg_array_size = bmachine.extended_regs ?
238 REG_ARRAY_SIZE_BIG : REG_ARRAY_SIZE_SMALL;
240 bmachine.reg = malloc(bmachine.reg_array_size *
241 sizeof(bmachine.reg[0]));
242 if (bmachine.reg == NULL)
245 for (i = 0; i < UCHAR_MAX; i++)
246 jump_table[i] = unknown;
247 for (i = 0; i < JUMP_TABLE_DATA_SIZE; i++)
248 jump_table[jump_table_data[i].ch] = jump_table_data[i].f;
250 stack_init(&bmachine.stack);
252 for (i = 0; i < bmachine.reg_array_size; i++)
253 stack_init(&bmachine.reg[i]);
255 bmachine.readstack_sz = READSTACK_SIZE;
256 bmachine.readstack = malloc(sizeof(struct source) *
257 bmachine.readstack_sz);
258 if (bmachine.readstack == NULL)
260 bmachine.obase = bmachine.ibase = 10;
262 bn_check(BN_zero(&zero));
263 signal(SIGINT, sighandler);
266 /* Reset the things needed before processing a (new) file */
268 reset_bmachine(struct source *src)
271 bmachine.readstack[0] = *src;
277 struct source *src = &bmachine.readstack[bmachine.readsp];
279 return src->vtable->readchar(src);
285 struct source *src = &bmachine.readstack[bmachine.readsp];
287 return src->vtable->unreadchar(src);
290 static __inline char *
293 struct source *src = &bmachine.readstack[bmachine.readsp];
295 return src->vtable->readline(src);
301 struct source *src = &bmachine.readstack[bmachine.readsp];
303 src->vtable->free(src);
308 pn(const char *str, const struct number *n)
310 char *p = BN_bn2dec(n->number);
312 err(1, "BN_bn2dec failed");
314 fprintf(stderr, " %s (%u)\n" , p, n->scale);
319 pbn(const char *str, const BIGNUM *n)
321 char *p = BN_bn2dec(n);
323 err(1, "BN_bn2dec failed");
325 fprintf(stderr, " %s\n", p);
331 static __inline u_int
332 max(u_int a, u_int b)
334 return a > b ? a : b;
337 static unsigned long factors[] = {
338 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
339 100000000, 1000000000
343 scale_number(BIGNUM *n, int s)
350 abs_scale = s > 0 ? s : -s;
352 if (abs_scale < sizeof(factors)/sizeof(factors[0])) {
354 bn_check(BN_mul_word(n, factors[abs_scale]));
356 BN_div_word(n, factors[abs_scale]);
368 bn_check(BN_set_word(a, 10));
369 bn_check(BN_set_word(p, abs_scale));
370 bn_check(BN_exp(a, a, p, ctx));
372 bn_check(BN_mul(n, n, a, ctx));
374 bn_check(BN_div(n, NULL, n, a, ctx));
382 split_number(const struct number *n, BIGNUM *i, BIGNUM *f)
386 bn_checkp(BN_copy(i, n->number));
388 if (n->scale == 0 && f != NULL)
390 else if (n->scale < sizeof(factors)/sizeof(factors[0])) {
391 rem = BN_div_word(i, factors[n->scale]);
405 bn_check(BN_set_word(a, 10));
406 bn_check(BN_set_word(p, n->scale));
407 bn_check(BN_exp(a, a, p, ctx));
408 bn_check(BN_div(i, f, n->number, a, ctx));
416 normalize(struct number *n, u_int s)
418 scale_number(n->number, s - n->scale);
423 get_ulong(struct number *n)
426 return BN_get_word(n->number);
430 negate(struct number *n)
432 bn_check(BN_sub(n->number, &zero, n->number));
436 push_number(struct number *n)
438 stack_pushnumber(&bmachine.stack, n);
442 push_string(char *string)
444 stack_pushstring(&bmachine.stack, string);
448 push(struct value *v)
450 stack_push(&bmachine.stack, v);
453 static __inline struct value *
456 return stack_tos(&bmachine.stack);
459 static __inline struct value *
462 return stack_pop(&bmachine.stack);
465 static __inline struct number *
468 return stack_popnumber(&bmachine.stack);
471 static __inline char *
474 return stack_popstring(&bmachine.stack);
480 stack_clear(&bmachine.stack);
486 stack_print(stdout, &bmachine.stack, "", bmachine.obase);
492 struct value *value = tos();
494 print_value(stdout, value, "", bmachine.obase);
498 warnx("stack empty");
504 struct value *value = pop();
507 switch (value->type) {
511 normalize(value->u.num, 0);
512 print_ascii(stdout, value->u.num);
516 fputs(value->u.string, stdout);
520 stack_free_value(value);
527 struct value *value = pop();
530 print_value(stdout, value, "", bmachine.obase);
532 stack_free_value(value);
539 stack_dup(&bmachine.stack);
545 stack_swap(&bmachine.stack);
551 struct value *v = pop();
562 bn_check(BN_set_word(n->number, bmachine.scale));
574 if (BN_cmp(n->number, &zero) < 0)
575 warnx("scale must be a nonnegative number");
577 scale = get_ulong(n);
578 if (scale != BN_MASK2)
579 bmachine.scale = scale;
581 warnx("scale too large");
593 bn_check(BN_set_word(n->number, bmachine.obase));
606 if (base != BN_MASK2 && base > 1)
607 bmachine.obase = base;
609 warnx("output base must be a number greater than 1");
620 bn_check(BN_set_word(n->number, bmachine.ibase));
633 if (base != BN_MASK2 && 2 <= base && base <= 16)
634 bmachine.ibase = base;
636 warnx("input base must be a number between 2 and 16 "
648 i = stack_size(&bmachine.stack);
650 bn_check(BN_set_word(n->number, i));
664 switch (value->type) {
668 scale = value->u.num->scale;
673 stack_free_value(value);
675 bn_check(BN_set_word(n->number, scale));
681 count_digits(const struct number *n)
683 struct number *int_part, *fract_part;
686 if (BN_is_zero(n->number))
689 int_part = new_number();
690 fract_part = new_number();
691 fract_part->scale = n->scale;
692 split_number(n, int_part->number, fract_part->number);
695 while (!BN_is_zero(int_part->number)) {
696 BN_div_word(int_part->number, 10);
699 free_number(int_part);
700 free_number(fract_part);
709 struct number *n = NULL;
713 switch (value->type) {
717 digits = count_digits(value->u.num);
719 bn_check(BN_set_word(n->number, digits));
722 digits = strlen(value->u.string);
724 bn_check(BN_set_word(n->number, digits));
727 stack_free_value(value);
742 switch (value->type) {
748 if (BN_num_bits(n->number) > 8)
749 bn_check(BN_mask_bits(n->number, 8));
750 str[0] = BN_get_word(n->number);
753 str[0] = value->u.string[0];
756 stack_free_value(value);
757 push_string(bstrdup(str));
767 if (index == 0xff && bmachine.extended_regs) {
770 if (ch1 == EOF || ch2 == EOF) {
771 warnx("unexpected eof");
774 index = (ch1 << 8) + ch2 + UCHAR_MAX + 1;
776 if (index < 0 || index >= bmachine.reg_array_size) {
777 warnx("internal error: reg num = %d", index);
787 struct value *v, copy;
792 v = stack_tos(&bmachine.reg[index]);
795 bn_check(BN_zero(n->number));
798 push(stack_dup_value(v, ©));
814 stack_set_tos(&bmachine.reg[index], val);
823 struct value *value, copy;
827 stack = &bmachine.reg[index];
829 if (stack_size(stack) > 0) {
830 value = stack_pop(stack);
833 push(stack_dup_value(value, ©));
835 warnx("stack register '%c' (0%o) is empty",
851 stack_push(&bmachine.reg[index], value);
859 struct number *inumber, *n;
862 struct value *v, copy;
866 inumber = pop_number();
869 index = get_ulong(inumber);
870 if (BN_cmp(inumber->number, &zero) < 0)
871 warnx("negative index");
872 else if (index == BN_MASK2 || index > MAX_ARRAY_INDEX)
873 warnx("index too big");
875 stack = &bmachine.reg[reg];
876 v = frame_retrieve(stack, index);
879 bn_check(BN_zero(n->number));
883 push(stack_dup_value(v, ©));
885 free_number(inumber);
893 struct number *inumber;
900 inumber = pop_number();
905 free_number(inumber);
908 index = get_ulong(inumber);
909 if (BN_cmp(inumber->number, &zero) < 0) {
910 warnx("negative index");
911 stack_free_value(value);
912 } else if (index == BN_MASK2 || index > MAX_ARRAY_INDEX) {
913 warnx("index too big");
914 stack_free_value(value);
916 stack = &bmachine.reg[reg];
917 frame_assign(stack, index, value);
919 free_number(inumber);
926 push_string(read_string(&bmachine.readstack[bmachine.readsp]));
945 struct number *a, *b;
959 r->scale = max(a->scale, b->scale);
960 if (r->scale > a->scale)
961 normalize(a, r->scale);
962 else if (r->scale > b->scale)
963 normalize(b, r->scale);
964 bn_check(BN_add(r->number, a->number, b->number));
973 struct number *a, *b;
988 r->scale = max(a->scale, b->scale);
989 if (r->scale > a->scale)
990 normalize(a, r->scale);
991 else if (r->scale > b->scale)
992 normalize(b, r->scale);
993 bn_check(BN_sub(r->number, b->number, a->number));
1000 bmul_number(struct number *r, struct number *a, struct number *b)
1004 /* Create copies of the scales, since r might be equal to a or b */
1005 u_int ascale = a->scale;
1006 u_int bscale = b->scale;
1007 u_int rscale = ascale + bscale;
1011 bn_check(BN_mul(r->number, a->number, b->number, ctx));
1014 if (rscale > bmachine.scale && rscale > ascale && rscale > bscale) {
1016 normalize(r, max(bmachine.scale, max(ascale, bscale)));
1024 struct number *a, *b;
1038 bmul_number(r, a, b);
1048 struct number *a, *b;
1064 r->scale = bmachine.scale;
1065 scale = max(a->scale, b->scale);
1067 if (BN_is_zero(a->number))
1068 warnx("divide by zero");
1070 normalize(a, scale);
1071 normalize(b, scale + r->scale);
1075 bn_check(BN_div(r->number, NULL, b->number, a->number, ctx));
1086 struct number *a, *b;
1102 scale = max(a->scale, b->scale);
1103 r->scale = max(b->scale, a->scale + bmachine.scale);
1105 if (BN_is_zero(a->number))
1106 warnx("remainder by zero");
1108 normalize(a, scale);
1109 normalize(b, scale + bmachine.scale);
1113 bn_check(BN_mod(r->number, b->number, a->number, ctx));
1124 struct number *a, *b;
1125 struct number *rdiv, *rmod;
1139 rdiv = new_number();
1140 rmod = new_number();
1141 rdiv->scale = bmachine.scale;
1142 rmod->scale = max(b->scale, a->scale + bmachine.scale);
1143 scale = max(a->scale, b->scale);
1145 if (BN_is_zero(a->number))
1146 warnx("divide by zero");
1148 normalize(a, scale);
1149 normalize(b, scale + bmachine.scale);
1153 bn_check(BN_div(rdiv->number, rmod->number,
1154 b->number, a->number, ctx));
1166 struct number *a, *p;
1182 warnx("Runtime warning: non-zero scale in exponent");
1186 if (BN_cmp(p->number, &zero) < 0) {
1189 scale = bmachine.scale;
1191 /* Posix bc says min(a.scale * b, max(a.scale, scale) */
1195 b = BN_get_word(p->number);
1196 m = max(a->scale, bmachine.scale);
1197 scale = a->scale * b;
1198 if (scale > m || b == BN_MASK2)
1202 if (BN_is_zero(p->number)) {
1204 bn_check(BN_one(r->number));
1205 normalize(r, scale);
1207 while (!BN_is_bit_set(p->number, 0)) {
1208 bmul_number(a, a, a);
1209 bn_check(BN_rshift1(p->number, p->number));
1213 normalize(r, scale);
1214 bn_check(BN_rshift1(p->number, p->number));
1216 while (!BN_is_zero(p->number)) {
1217 bmul_number(a, a, a);
1218 if (BN_is_bit_set(p->number, 0))
1219 bmul_number(r, r, a);
1220 bn_check(BN_rshift1(p->number, p->number));
1232 scale_number(one, r->scale + scale);
1233 normalize(r, scale);
1234 bn_check(BN_div(r->number, NULL, one, r->number, ctx));
1238 normalize(r, scale);
1246 bsqrt_stop(const BIGNUM *x, const BIGNUM *y, u_int *onecount)
1253 bn_check(BN_sub(r, x, y));
1256 ret = BN_is_zero(r);
1258 return ret || *onecount > 1;
1267 u_int scale, onecount;
1275 if (BN_is_zero(n->number)) {
1278 } else if (BN_cmp(n->number, &zero) < 0)
1279 warnx("square root of negative number");
1281 scale = max(bmachine.scale, n->scale);
1282 normalize(n, 2*scale);
1283 x = BN_dup(n->number);
1285 bn_check(BN_rshift(x, x, BN_num_bits(x)/2));
1291 bn_checkp(BN_copy(y, x));
1292 bn_check(BN_div(x, NULL, n->number, x, ctx));
1293 bn_check(BN_add(x, x, y));
1294 bn_check(BN_rshift1(x, x));
1295 if (bsqrt_stop(x, y, &onecount))
1298 r = bmalloc(sizeof(*r));
1319 bn_check(BN_set_word(a->number, BN_get_word(a->number) ? 0 : 1));
1326 compare(BCODE_EQUAL);
1332 struct number *a, *b, *r;
1344 bn_check(BN_set_word(r->number,
1345 compare_numbers(BCODE_EQUAL, a, b) ? 1 : 0));
1352 struct number *a, *b, *r;
1364 bn_check(BN_set_word(r->number,
1365 compare_numbers(BCODE_LESS, a, b) ? 1 : 0));
1370 lesseq_numbers(void)
1372 struct number *a, *b, *r;
1384 bn_check(BN_set_word(r->number,
1385 compare_numbers(BCODE_NOT_GREATER, a, b) ? 1 : 0));
1392 compare(BCODE_NOT_EQUAL);
1398 compare(BCODE_LESS);
1424 compare(BCODE_NOT_LESS);
1430 compare(BCODE_GREATER);
1436 compare(BCODE_NOT_GREATER);
1440 compare_numbers(enum bcode_compare type, struct number *a, struct number *b)
1445 scale = max(a->scale, b->scale);
1447 if (scale > a->scale)
1448 normalize(a, scale);
1449 else if (scale > b->scale)
1450 normalize(b, scale);
1452 cmp = BN_cmp(a->number, b->number);
1460 case BCODE_NOT_EQUAL:
1464 case BCODE_NOT_LESS:
1468 case BCODE_NOT_GREATER:
1475 compare(enum bcode_compare type)
1477 int index, elseindex;
1478 struct number *a, *b;
1482 elseindex = NO_ELSE;
1484 if (readch() == 'e')
1485 elseindex = readreg();
1498 ok = compare_numbers(type, a, b);
1500 if (!ok && elseindex != NO_ELSE)
1503 if (index >= 0 && (ok || (!ok && elseindex != NO_ELSE))) {
1504 v = stack_tos(&bmachine.reg[index]);
1506 warnx("register '%c' (0%o) is empty", index, index);
1510 warnx("register '%c' (0%o) is empty",
1514 warn("eval called with non-string argument");
1517 eval_string(bstrdup(v->u.string));
1533 if (bmachine.readsp < 2)
1551 if (i == BN_MASK2 || i == 0)
1552 warnx("Q command requires a number >= 1");
1553 else if (bmachine.readsp < i)
1554 warnx("Q command argument exceeded string execution depth");
1574 warnx("J command requires a number >= 0");
1575 else if (i > 0 && bmachine.readsp < i)
1576 warnx("J command argument exceeded string execution depth");
1587 skip_until_mark(void)
1597 errx(1, "mark not found");
1609 if (readch() == 'e')
1615 free(read_string(&bmachine.readstack[bmachine.readsp]));
1618 switch (ch = readch()) {
1623 if (readch() == 'e')
1643 push_number(readnumber(&bmachine.readstack[bmachine.readsp],
1650 int ch = bmachine.readstack[bmachine.readsp].lastchar;
1651 warnx("%c (0%o) is unimplemented", ch, ch);
1655 eval_string(char *p)
1659 if (bmachine.readsp > 0) {
1660 /* Check for tail call. Do not recurse in that case. */
1664 src_setstring(&bmachine.readstack[bmachine.readsp], p);
1669 if (bmachine.readsp == bmachine.readstack_sz - 1) {
1670 size_t newsz = bmachine.readstack_sz * 2;
1671 struct source *stack;
1672 stack = realloc(bmachine.readstack, newsz *
1673 sizeof(struct source));
1675 err(1, "recursion too deep");
1676 bmachine.readstack_sz = newsz;
1677 bmachine.readstack = stack;
1679 src_setstring(&bmachine.readstack[++bmachine.readsp], p);
1685 /* Always read from stdin */
1689 src_setstream(&in, stdin);
1690 p = (*in.vtable->readline)(&in);
1713 if (bmachine.readsp == 0)
1719 if (bmachine.interrupted) {
1720 if (bmachine.readsp > 0) {
1725 bmachine.interrupted = false;
1728 fprintf(stderr, "# %c\n", ch);
1729 stack_print(stderr, &bmachine.stack, "* ",
1731 fprintf(stderr, "%d =>\n", bmachine.readsp);
1734 if (0 <= ch && ch < UCHAR_MAX)
1735 (*jump_table[ch])();
1737 warnx("internal error: opcode %d", ch);
1740 stack_print(stderr, &bmachine.stack, "* ",
1742 fprintf(stderr, "%d ==\n", bmachine.readsp);