Skip to content

Commit

Permalink
chore: upgrade wasm package locally and other updates
Browse files Browse the repository at this point in the history
  • Loading branch information
harveyghq authored Jun 30, 2024
1 parent 04c8a2e commit 1280087
Show file tree
Hide file tree
Showing 14 changed files with 1,392 additions and 10 deletions.
39 changes: 39 additions & 0 deletions .github/workflows/dependency-review.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Dependency Review Action
#
# This Action will scan dependency manifest files that change as part of a Pull Request,
# surfacing known-vulnerable versions of the packages declared or updated in the PR.
# Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable
# packages will be blocked from merging.
#
# Source repository: https://github.com/actions/dependency-review-action
# Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement
name: 'Dependency review'
on:
pull_request:
branches: [ "main" ]

# If using a dependency submission action in this workflow this permission will need to be set to:
#
# permissions:
# contents: write
#
# https://docs.github.com/en/enterprise-cloud@latest/code-security/supply-chain-security/understanding-your-software-supply-chain/using-the-dependency-submission-api
permissions:
contents: read
# Write permissions for pull-requests are required for using the `comment-summary-in-pr` option, comment out if you aren't using this option
pull-requests: write

jobs:
dependency-review:
runs-on: ubuntu-latest
steps:
- name: 'Checkout repository'
uses: actions/checkout@v4
- name: 'Dependency Review'
uses: actions/dependency-review-action@v4
# Commonly enabled options, see https://github.com/actions/dependency-review-action#configuration-options for all available options.
with:
comment-summary-in-pr: always
# fail-on-severity: moderate
# deny-licenses: GPL-1.0-or-later, LGPL-2.0-or-later
# retry-on-snapshot-warnings: true
16 changes: 9 additions & 7 deletions build-rs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,23 @@ END_USAGE

build() {
if [ ! -f "$1" ]; then
error "File "$1" not exists."
error "File $1 not exists."
exit 1
fi
local dir_name=$(dirname "$1")
local file_name=$(basename "$1")
rustc "$1" -g --target wasm32-wasi --out-dir "$dir_name"
if [ "$?" -ne 0 ]; then
error "Failed to compile "$file_name" to wasm."

if ! rustc "$1" -g --target wasm32-wasi --out-dir "$dir_name"
then
error "Failed to compile $file_name to wasm."
exit 1
fi

local wasm_name="${file_name%.*}.wasm"
local wat_name="${file_name%.*}.wat"
wasm-tools demangle "$dir_name/$wasm_name" -o "$dir_name/$wasm_name"
if [ "$?" -ne 0 ]; then

if ! wasm-tools demangle "$dir_name/$wasm_name" -o "$dir_name/$wasm_name"
then
error "Failed to demangle "$dir_name/$wasm_name"."
exit 1
fi
Expand All @@ -56,7 +58,7 @@ build() {

traverse() {
if [ ! -d "$1" ]; then
error "Directory "$1" not exists."
error "Directory $1 not exists."
exit 1
fi
local d="$1/*"
Expand Down
3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@ leb128==1.0.4
pyelftools==0.27
pytest==6.2.5
sh==1.14.2
z3-solver==4.10.2.0
wasm==1.2
z3-solver==4.13.0.0
2 changes: 1 addition & 1 deletion seewasm/arch/wasm/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,7 @@ def cycle_is_same(cycle1, cycle2):
if len(cycle1) != len(cycle2):
return False

if cycle2.count(cycle1[0]) == 0:
if cycle2.count(cycle1[0]) == 0:
return False

cycle2_idx_offset = cycle2.index(cycle1[0])
Expand Down
124 changes: 124 additions & 0 deletions wasm/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
from __future__ import unicode_literals

__version__ = '1.2'

from .decode import (
decode_bytecode,
decode_module,
)

from .formatter import (
format_function,
format_instruction,
format_lang_type,
format_mutability,
)

from .modtypes import (
ModuleHeader,
FunctionImportEntryData,
ResizableLimits,
TableType,
MemoryType,
GlobalType,
ImportEntry,
ImportSection,
FuncType,
TypeSection,
FunctionSection,
TableSection,
MemorySection,
InitExpr,
GlobalEntry,
GlobalSection,
ExportEntry,
ExportSection,
StartSection,
ElementSegment,
ElementSection,
LocalEntry,
FunctionBody,
CodeSection,
DataSegment,
DataSection,
Naming,
NameMap,
LocalNames,
LocalNameMap,
NameSubSection,
Section,
)

from .immtypes import (
BlockImm,
BranchImm,
BranchTableImm,
CallImm,
CallIndirectImm,
LocalVarXsImm,
GlobalVarXsImm,
MemoryImm,
CurGrowMemImm,
I32ConstImm,
I64ConstImm,
F32ConstImm,
F64ConstImm,
)

from .opcodes import (
Opcode,
INSN_ENTER_BLOCK,
INSN_LEAVE_BLOCK,
INSN_BRANCH,
INSN_NO_FLOW,
)

for cur_op in opcodes.OPCODES:
globals()[
'OP_' + cur_op.mnemonic.upper().replace('.', '_').replace('/', '_')
] = cur_op.id

from .wasmtypes import (
UInt8Field,
UInt16Field,
UInt32Field,
UInt64Field,
VarUInt1Field,
VarUInt7Field,
VarUInt32Field,
VarInt7Field,
VarInt32Field,
VarInt64Field,
ElementTypeField,
ValueTypeField,
ExternalKindField,
BlockTypeField,
SEC_UNK,
SEC_TYPE,
SEC_IMPORT,
SEC_FUNCTION,
SEC_TABLE,
SEC_MEMORY,
SEC_GLOBAL,
SEC_EXPORT,
SEC_START,
SEC_ELEMENT,
SEC_CODE,
SEC_DATA,
SEC_NAME,
LANG_TYPE_I32,
LANG_TYPE_I64,
LANG_TYPE_F32,
LANG_TYPE_F64,
LANG_TYPE_ANYFUNC,
LANG_TYPE_FUNC,
LANG_TYPE_EMPTY,
VAL_TYPE_I32,
VAL_TYPE_I64,
VAL_TYPE_F32,
VAL_TYPE_F64,
NAME_SUBSEC_FUNCTION,
NAME_SUBSEC_LOCAL,
IMMUTABLE,
MUTABLE,
)
57 changes: 57 additions & 0 deletions wasm/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Testing & debug stuff."""
from __future__ import print_function, absolute_import, division, unicode_literals

import argparse
import sys

from .formatter import format_function
from .modtypes import SEC_CODE, SEC_TYPE, SEC_FUNCTION, Section
from .decode import decode_module


def dump():
parser = argparse.ArgumentParser()
parser.add_argument('wasm_file', type=str)
parser.add_argument('--disas', action='store_true', help="Disassemble code")
args = parser.parse_args()

try:
with open(args.wasm_file, 'rb') as raw:
raw = raw.read()
except IOError as exc:
print("[-] Can't open input file: " + str(exc), file=sys.stderr)
return

# Parse & print header.
mod_iter = iter(decode_module(raw, decode_name_subsections=False))
hdr, hdr_data = next(mod_iter)
print(hdr.to_string(hdr_data))

# Parse & print other sections.
code_sec = None
type_sec = None
func_sec = None
for cur_sec, cur_sec_data in mod_iter:
print(cur_sec.to_string(cur_sec_data))
if type(cur_sec) == Section:
if cur_sec_data.id == SEC_CODE:
code_sec = cur_sec_data.payload
elif cur_sec_data.id == SEC_TYPE:
type_sec = cur_sec_data.payload
elif cur_sec_data.id == SEC_FUNCTION:
func_sec = cur_sec_data.payload

# If ordered to disassemble, do so.
# TODO: We might want to make use of debug names, if available.
if args.disas and code_sec is not None:
for i, func_body in enumerate(code_sec.bodies):
print('{x} sub_{id:04X} {x}'.format(x='=' * 35, id=i))

# If we have type info, use it.
func_type = type_sec.entries[func_sec.types[i]] if (
None not in (type_sec, func_sec)
) else None

print()
print('\n'.join(format_function(func_body, func_type)))
print()
81 changes: 81 additions & 0 deletions wasm/compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""Defines compatibility quirks for Python 2.7."""
from __future__ import print_function, absolute_import, division, unicode_literals

import sys
import functools
import logging
import warnings


def add_metaclass(metaclass):
"""
Class decorator for creating a class with a metaclass.
Borrowed from `six` module.
"""
@functools.wraps(metaclass)
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper


def indent(text, prefix, predicate=None):
"""Adds 'prefix' to the beginning of selected lines in 'text'.
If 'predicate' is provided, 'prefix' will only be added to the lines
where 'predicate(line)' is True. If 'predicate' is not provided,
it will default to adding 'prefix' to all non-empty lines that do not
consist solely of whitespace characters.
Borrowed from Py3 `textwrap` module.
"""
if predicate is None:
def predicate(line):
return line.strip()

def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if predicate(line) else line)
return ''.join(prefixed_lines())


def deprecated_func(func):
"""Deprecates a function, printing a warning on the first usage."""

# We use a mutable container here to work around Py2's lack of
# the `nonlocal` keyword.
first_usage = [True]

@functools.wraps(func)
def wrapper(*args, **kwargs):
if first_usage[0]:
warnings.warn(
"Call to deprecated function {}.".format(func.__name__),
DeprecationWarning,
)
first_usage[0] = False
return func(*args, **kwargs)

return wrapper


if sys.version_info[0] >= 3:
def byte2int(x):
return x

elif sys.version_info[0] == 2:
def byte2int(x):
return ord(x) if type(x) == str else x

else:
raise Exception("Unsupported Python version")


Loading

0 comments on commit 1280087

Please sign in to comment.