blob: efb599b5a74b97a4db91ad0d5d40e595637c075e (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
/*
* nanowasm, a tiny WebAssembly/Wasm interpreter
* Copyright (C) 2023-2025 Xavier Del Campo Romero
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
/* The functions below is a (somewhat heavily) modified version of that
* provided by the wac project: https://github.com/kanaka/wac
*
* Copyright (C) Joel Martin <github@martintribe.org>
* The wac project is licensed under the MPL 2.0 (Mozilla Public License
* 2.0). The text of the MPL 2.0 license is included below and can be
* found at https://www.mozilla.org/MPL/2.0/
*/
#include <nanowasm/types.h>
#include <nw/io.h>
#include <nw/log.h>
enum nw_state nwp_leb128(const struct nw_io_cfg *const cfg,
struct nw_sm_leb128 *const l, const unsigned maxbits, const int sign,
void *const user)
{
unsigned char byte;
for (;;)
{
const int n = cfg->read(&byte, sizeof byte, user);
unsigned long v;
if (n < 0)
return NW_FATAL;
else if (!n)
return NW_AGAIN;
v = (unsigned long)(byte & 0x7f) << l->shift;;
if (l->shift < 32)
l->result.low |= v;
else
l->result.hi |= v;
l->shift += 7;
if (!(byte & 0x80))
break;
else if (++l->bcnt > (maxbits + 7u - 1u) / 7u)
{
#ifdef NW_LOG
long offset;
const enum nw_state n = cfg->tell(&offset, cfg->user);
if (n)
return n;
nwp_log("leb128 overflow, offset=%#lx\n", (unsigned long)offset);
#endif
return NW_FATAL;
}
}
if (sign && (l->shift < maxbits) && (byte & 0x40))
{
if (l->shift < 32)
l->result.low |= -1l << (l->shift);
else
l->result.hi |= -1l << (l->shift);
}
return NW_OK;
}
|