Skip to content

Commit 1b725dd

Browse files
authored
Catch runtime divide-by-zero arithmetic error. (#6)
1 parent d80f698 commit 1b725dd

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

src/deep_interp.c

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
//
22
// Created by xj on 2021/3/30.
33
//
4+
#include <math.h>
5+
#include <stdint.h>
46
#include <stdio.h>
57
#include <stdlib.h>
6-
#include <stdint.h>
7-
#include <math.h>
88
#include <string.h>
99
#include "deep_interp.h"
1010
#include "deep_loader.h"
11+
#include "deep_log.h"
1112
#include "deep_mem.h"
1213
#include "deep_opcode.h"
1314
#include "deep_log.h"
@@ -26,6 +27,12 @@
2627

2728
#define STACK_CAPACITY 100
2829

30+
// 安全除法
31+
#define DIVIDE(TYPE, DIVIDEND, DIVISOR) \
32+
(((TYPE)DIVISOR == 0) && \
33+
(error("Arithmetic Error: Divide by Zero!"), exit(1), 0) \
34+
|| (TYPE)DIVIDEND / (TYPE)DIVISOR)
35+
2936
//创建操作数栈
3037
DEEPStack *stack_cons(void) {
3138
DEEPStack *stack = (DEEPStack *) deep_malloc(sizeof(DEEPStack));
@@ -158,14 +165,14 @@ void exec_instructions(DEEPExecEnv *current_env, DEEPModule *module) {
158165
ip++;
159166
int32_t a = popS32();
160167
int32_t b = popS32();
161-
pushS32(b / a);
168+
pushS32(DIVIDE(int32_t, b, a));
162169
break;
163170
}
164171
case i32_divu: {
165172
ip++;
166173
uint32_t a = popU32();
167174
uint32_t b = popU32();
168-
pushU32(b / a);
175+
pushU32(DIVIDE(uint32_t, b, a));
169176
break;
170177
}
171178
case i32_const: {
@@ -242,7 +249,7 @@ void exec_instructions(DEEPExecEnv *current_env, DEEPModule *module) {
242249
ip++;
243250
float a = popF32();
244251
float b = popF32();
245-
pushF32(b / a);
252+
pushF32(DIVIDE(float, b, a));
246253
break;
247254
}
248255
case f32_min: {

0 commit comments

Comments
 (0)