Add wasm-mutator-fuzz test (#3420)

This commit is contained in:
Zhang, Yi 2024-05-21 12:01:13 +08:00 committed by GitHub
parent 33aada2133
commit a2f3c7298f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
34 changed files with 6621 additions and 0 deletions

View File

@ -0,0 +1,3 @@
portal_port=9999
server_port=16667
proxy=""

View File

@ -0,0 +1,3 @@
build/
workspace/build_*
error_restart_build_*

View File

@ -0,0 +1,138 @@
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
cmake_minimum_required (VERSION 2.8)
project(wasm_mutator)
add_definitions(-DUNIT_TEST)
set (CMAKE_BUILD_TYPE Debug)
set (CMAKE_C_COMPILER "clang")
set (CMAKE_CXX_COMPILER "clang++")
set (WAMR_BUILD_PLATFORM "linux")
# Reset default linker flags
set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")
set (CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "")
set (CMAKE_C_STANDARD 99)
# Set WAMR_BUILD_TARGET, currently values supported:
# "X86_64", "AMD_64", "X86_32", "AARCH64[sub]", "ARM[sub]", "THUMB[sub]",
# "MIPS", "XTENSA", "RISCV64[sub]", "RISCV32[sub]"
if (NOT DEFINED WAMR_BUILD_TARGET)
if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)")
set (WAMR_BUILD_TARGET "AARCH64")
elseif (CMAKE_SYSTEM_PROCESSOR STREQUAL "riscv64")
set (WAMR_BUILD_TARGET "RISCV64")
elseif (CMAKE_SIZEOF_VOID_P EQUAL 8)
# Build as X86_64 by default in 64-bit platform
set (WAMR_BUILD_TARGET "X86_64")
elseif (CMAKE_SIZEOF_VOID_P EQUAL 4)
# Build as X86_32 by default in 32-bit platform
set (WAMR_BUILD_TARGET "X86_32")
else ()
message(SEND_ERROR "Unsupported build target platform!")
endif ()
endif ()
if(CUSTOM_MUTATOR EQUAL 1)
add_compile_definitions(CUSTOM_MUTATOR)
endif()
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif ()
if (NOT DEFINED WAMR_BUILD_INTERP)
# Enable Interpreter by default
set (WAMR_BUILD_INTERP 1)
endif ()
if (NOT DEFINED WAMR_BUILD_AOT)
# Enable AOT by default.
set (WAMR_BUILD_AOT 1)
endif ()
if (NOT DEFINED WAMR_BUILD_JIT)
# Disable JIT by default.
set (WAMR_BUILD_JIT 0)
endif ()
if (NOT DEFINED WAMR_BUILD_LIBC_BUILTIN)
# Enable libc builtin support by default
set (WAMR_BUILD_LIBC_BUILTIN 1)
endif ()
if (NOT DEFINED WAMR_BUILD_LIBC_WASI)
# Enable libc wasi support by default
set (WAMR_BUILD_LIBC_WASI 1)
endif ()
if (NOT DEFINED WAMR_BUILD_FAST_INTERP)
# Enable fast interpreter
set (WAMR_BUILD_FAST_INTERP 1)
endif ()
if (NOT DEFINED WAMR_BUILD_MULTI_MODULE)
# Enable multiple modules
set (WAMR_BUILD_MULTI_MODULE 0)
endif ()
if (NOT DEFINED WAMR_BUILD_LIB_PTHREAD)
# Disable pthread library by default
set (WAMR_BUILD_LIB_PTHREAD 0)
endif ()
if (NOT DEFINED WAMR_BUILD_MINI_LOADER)
# Disable wasm mini loader by default
set (WAMR_BUILD_MINI_LOADER 0)
endif ()
if (NOT DEFINED WAMR_BUILD_SIMD)
# Enable SIMD by default
set (WAMR_BUILD_SIMD 1)
endif ()
if (NOT DEFINED WAMR_BUILD_REF_TYPES)
# Disable reference types by default
set (WAMR_BUILD_REF_TYPES 0)
endif ()
if (NOT DEFINED WAMR_BUILD_DEBUG_INTERP)
# Disable Debug feature by default
set (WAMR_BUILD_DEBUG_INTERP 0)
endif ()
if (WAMR_BUILD_DEBUG_INTERP EQUAL 1)
set (WAMR_BUILD_FAST_INTERP 0)
set (WAMR_BUILD_MINI_LOADER 0)
set (WAMR_BUILD_SIMD 0)
endif ()
set (REPO_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../../..)
message([ceith]:REPO_ROOT_DIR, ${REPO_ROOT_DIR})
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
add_definitions(-DWAMR_USE_MEM_POOL=0)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -fsanitize=signed-integer-overflow \
-fprofile-instr-generate -fcoverage-mapping \
-fsanitize=address,undefined,fuzzer")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fsanitize=signed-integer-overflow \
-fprofile-instr-generate -fcoverage-mapping \
-fsanitize=address,undefined,fuzzer")
include(${REPO_ROOT_DIR}/core/shared/utils/uncommon/shared_uncommon.cmake)
include(${REPO_ROOT_DIR}/build-scripts/runtime_lib.cmake)
add_library(vmlib
${WAMR_RUNTIME_LIB_SOURCE}
)
add_executable(wasm_mutator_fuzz wasm_mutator_fuzz.cc)
target_link_libraries(wasm_mutator_fuzz vmlib -lm)

View File

@ -0,0 +1,73 @@
# WAMR fuzz test framework
## install wasm-tools
```bash
1.git clone https://github.com/bytecodealliance/wasm-tools
$ cd wasm-tools
2.This project can be installed and compiled from source with this Cargo command:
$ cargo install wasm-tools
3.Installation can be confirmed with:
$ wasm-tools --version
4.Subcommands can be explored with:
$ wasm-tools help
```
## Build
```bash
mkdir build && cd build
# Without custom mutator (libfuzzer modify the buffer randomly)
cmake ..
# With custom mutator (wasm-tools mutate)
cmake .. -DCUSTOM_MUTATOR=1
make -j$(nproc)
```
## Manually generate wasm file in build
```bash
# wasm-tools smith generate some valid wasm file
# The generated wasm file is in corpus_dir under build
# N - Number of files to be generated
./smith_wasm.sh N
# running
``` bash
cd build
./wasm-mutate-fuzz CORPUS_DIR
```
## Fuzzing Server
```shell
1. Installation Dependent Environment
$ cd server
$ pip install -r requirements.txt
2. Database Migration
$ python3 app/manager.py db init
$ python3 app/manager.py db migrate
$ python3 app/manager.py db upgrade
3. Change localhost to your machine's IP address
$ cd ../portal
$ vim .env # Change localhost to your machine's IP address # http://<ip>:16667
4. Run Server and Portal
$ cd .. # Switch to the original directory
If you want to customize the front-end deployment port: # defaut 9999
$ vim .env # Please change the portal_port to the port you want to use
The server is deployed on port 16667 by default, If you want to change the server deployment port:
$ vim .env # Please change the server_port to the port you want to use
$ vim portal/.env # Please change the VITE_SERVER_URL to the port you want to use # http://ip:<port>
If your network needs to set up a proxy
$ vim .env # Change proxy to your proxy address
$ docker-compose up --build -d
Wait for completion, Access the port set by env
```

View File

@ -0,0 +1,29 @@
# yaml configuration
services:
web:
platform: linux/amd64
container_name: fuzz_web
build:
context: ./portal
dockerfile: Dockerfile
args:
- proxy=${proxy}
volumes:
- "./portal:/portal"
ports:
- "${portal_port}:80"
server:
build:
context: ../../..
dockerfile: ./tests/fuzz/wasm-mutator-fuzz/server/Dockerfile
args:
- proxy=${proxy}
ports:
- "${server_port}:16667"
container_name: fuzz_server
volumes:
- "./server/app/data.db:/wamr-test/tests/fuzz/wasm-mutator-fuzz/server/app/data.db"
- "./workspace:/wamr-test/tests/fuzz/wasm-mutator-fuzz/workspace"
environment:
- "TZ=Asia/Shanghai"
restart: on-failure

View File

@ -0,0 +1 @@
VITE_SERVER_URL=http://localhost:16667

View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -0,0 +1,24 @@
FROM node:16 as builder
WORKDIR /portal
COPY . .
ARG proxy=""
RUN if [ "$proxy" != "" ]; \
then npm config set proxy "$proxy" && npm config set https-proxy "$proxy"; \
else echo Do not set proxy; \
fi
RUN npm install && chmod +x node_modules/.bin/tsc \
&& chmod +x node_modules/.bin/vite \
&& npm run build
FROM nginx:alpine
WORKDIR /portal
COPY --from=builder /portal/dist/ /usr/share/nginx/html/
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/nginx.conf
COPY default.conf.template /etc/nginx/conf.d
# hadolint ignore=DL3025
CMD /bin/sh -c "envsubst '80' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'

View File

@ -0,0 +1,53 @@
server {
listen 80 default_server;
location ^~ / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location @router {
rewrite ^.*$ /index.html last; # important!
}
location ~* \.(?:manifest|appcache|html?|xml|json)$ {
root /usr/share/nginx/html;
if ($request_uri ~* .*[.](manifest|appcache|xml|json)$) {
add_header Cache-Control "public, max-age=2592000";
}
if ($request_filename ~* ^.*[.](html|htm)$) {
add_header Cache-Control "public, no-cache";
}
expires -1;
}
location ~* \.(?:js|css|map|jpg|png|svg|ico)$ {
root /usr/share/nginx/html;
try_files $uri =404;
expires 1y;
access_log off;
add_header Cache-Control "public";
}
location ~ ^.+\..+$ {
root /usr/share/nginx/html;
try_files $uri =404;
include /etc/nginx/mime.types;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WAMR fuzzing test system</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@ -0,0 +1,15 @@
error_log stderr;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
access_log /dev/stdout;
server_tokens off;
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,27 @@
{
"name": "my-react",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"@ant-design/icons": "^4.7.0",
"antd": "^4.22.8",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-highlight-words": "^0.18.0",
"react-router-dom": "^6.3.0",
"scripts": "^0.1.0"
},
"devDependencies": {
"@types/react": "^18.0.17",
"@types/react-dom": "^18.0.6",
"@vitejs/plugin-react": "^2.0.1",
"typescript": "^4.6.4",
"vite": "^3.0.7"
}
}

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1,50 @@
#root {
background-color: rgba(230, 240, 240, 0.9);
max-width: 100%;
height: 100%;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
.col-item-value {
overflow: hidden;
line-height: 35px;
white-space: nowrap;
text-overflow: ellipsis;
}

View File

@ -0,0 +1,110 @@
// Copyright (C) 2019 Intel Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
import { useEffect, useState } from "react";
import "./App.css";
import CardMenu from "./CardMenu";
import { Divider, Typography, Col, Row, Button } from "antd";
import { Empty, Spin } from "antd";
import Description from "./Descrpition";
const { Title } = Typography;
function App() {
const [dataList, setDataList] = useState<Array<any>>([]);
const [results, setResults] = useState<any>({});
const [id, setId] = useState<number>();
const [resultReload, setResultReload] = useState<number>(0);
const [tableLoading, setTableLoading] = useState<boolean>(false);
const [isLoaded, setIsLoaded] = useState<boolean>(false);
const [result, setResult] = useState<any>({});
useEffect(() => {
fetch(import.meta.env.VITE_SERVER_URL + "/get_list")
.then((res) => {
return res.json();
})
.then((body) => {
setDataList(body.results);
setIsLoaded(true);
});
const timer = setInterval(() => {
fetch(import.meta.env.VITE_SERVER_URL + "/get_list")
.then((res) => {
return res.json();
})
.then((body) => {
setDataList(body.results);
setIsLoaded(true);
});
}, 3000);
}, []);
useEffect(() => {
setTableLoading(true);
fetch(import.meta.env.VITE_SERVER_URL + `/get_list?id=${id}`)
.then((res) => {
return res.json();
})
.then((body) => {
setResults(body);
console.log(results);
setTableLoading(false);
});
}, [id, resultReload]);
const select_uuid = {
res: dataList,
setId,
setResult
};
if (!isLoaded) {
return (
<div className="App" style={{ width: document.body.clientWidth }}>
<Spin size="large" />
</div>
);
}
if (isLoaded && !dataList) {
return (
<div className="App" style={{ width: document.body.clientWidth }}>
<Empty />
</div>
);
}
return (
<div className="App">
<Typography>
<br />
<Title>WebAssembly Micro Runtime fuzzing test system</Title>
<Divider />
</Typography>
<Row gutter={16}>
<Col span={9}>
{/* {dataList && <RunTable {...select_uuid} />} */}
{<Description {...select_uuid} />}
</Col>
<Col span={15}>
{
<CardMenu
{...{
result: results,
detail_result: result,
tableLoading,
resultReload,
setResultReload
}}
/>
}
</Col>
</Row>
<Row gutter={16}>
<Col span={9}></Col>
</Row>
</div>
);
}
export default App;

View File

@ -0,0 +1,551 @@
// Copyright (C) 2019 Intel Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
import {
Button,
Modal,
Table,
Card,
TableColumnsType,
Tooltip,
Tag,
Form,
message,
Input,
Progress
} from "antd";
import React, { useEffect, useState } from "react";
import "antd/dist/antd.css";
import type { ColumnsType } from "antd/es/table";
import { SyncOutlined, ArrowDownOutlined } from "@ant-design/icons";
import { useSearchParams } from "react-router-dom";
const { TextArea } = Input;
const tabList2 = [
{
key: "error",
tab: "error"
},
{
key: "stdout",
tab: "stdout"
},
{
key: "stderr",
tab: "stderr"
}
];
interface ErrorDataType {
id: number;
name: string;
fuzzing_id: number;
data: any;
status: string;
create_time: string;
update_time: string;
comment: any;
}
const CardMenu: React.FC<{
result: any;
detail_result: any;
tableLoading: boolean;
resultReload: number;
setResultReload: any;
}> = ({ result, detail_result, tableLoading, resultReload, setResultReload }) => {
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
const [modalVisible, setModalVisible] = useState(false);
const [modal2Visible, setModal2Visible] = useState(false);
const [modal3Visible, setModal3Visible] = useState(false);
const [reloadLoading, setRelLoading] = useState(false);
const [errorTabData, setErrorTabData] = useState("");
const [downloadLoading, setDownLoading] = useState(false);
result.results &&
(result.results = result.results.map((t: any) => ({
key: t.id,
...t
})));
const error_columns: ColumnsType<ErrorDataType> = [
{
title: "ErrorName",
width: "13%",
dataIndex: "name",
render: (value) => {
return (
<Tooltip placement="topLeft" title={value}>
<div className="col-item-value">{value}</div>
</Tooltip>
);
}
},
{
title: "CreateTime",
dataIndex: "create_time",
width: "13%",
render: (value) => {
return (
<Tooltip placement="topLeft" title={value}>
<div className="col-item-value">{value}</div>
</Tooltip>
);
}
},
{
title: "UpdateTime",
dataIndex: "update_time",
width: "13.5%",
render: (value) => {
return (
<Tooltip placement="topLeft" title={value}>
<div className="col-item-value">{value}</div>
</Tooltip>
);
}
},
{
title: "Comment",
dataIndex: "comment",
width: "12%",
render: (value) => {
return (
<Tooltip placement="topLeft" title={value?.comment}>
<div className="col-item-value">{value?.comment}</div>
</Tooltip>
);
}
},
{
title: "Assign",
dataIndex: "comment",
width: "9%",
render: (value) => {
return (
<Tooltip placement="topLeft" title={value?.assign}>
<div className="col-item-value">{value?.assign}</div>
</Tooltip>
);
}
},
{
title: "Status",
dataIndex: "status",
width: "14%",
filters: [
{ text: "Pending", value: 2 },
{ text: "Error", value: 1 },
{ text: "OK", value: 0 }
],
onFilter: (value, record) => {
return record.status === value;
},
render: (value, Object) => {
var colors: string = "";
var val: string = "";
if (value === 1) {
colors = "red";
val = `Error(${Object.name.split("-")[0]})`;
} else if (value === 0) {
colors = "green";
val = "OK";
} else if (value === 2) {
colors = "";
val = "pending";
}
return (
<>
{/* <Tooltip placement="topLeft" title={Object?.wamr_commit}> */}
<div className="col-item-value">
<Tag color={colors}> {val} </Tag>
{/* <a
href={`https://github.com/bytecodealliance/wasm-micro-runtime/commit/${Object?.wamr_commit}`}
>
{Object?.wamr_commit}
</a>
</Tooltip> */}
</div>
</>
);
}
},
{
title: "Action",
dataIndex: "",
// width: "15%",
render: (value, Object) => {
return (
<>
<Button
type="primary"
onClick={() => {
console.log(Object.data);
fetch(import.meta.env.VITE_SERVER_URL + `/get_error_out?id=${Object.id}`)
.then((res) => {
return res.json();
})
.then((body) => {
setErrorTabData(body.result.std_out);
setModal3Visible(true);
});
}}
>
Priview
</Button>
<Button
key="0"
type="link"
onClick={async () => {
try {
const response = await fetch(
import.meta.env.VITE_SERVER_URL + `/get_error_txt?id=${Object.id}`,
{
method: "GET"
}
);
console.log(Object.name);
get_cases(response, Object.name);
} catch (err) {
message.error("Download timeout");
}
}}
>
<ArrowDownOutlined />
</Button>
</>
);
}
}
];
const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
console.log("selectedRowKeys changed: ", selectedRowKeys);
setSelectedRowKeys(newSelectedRowKeys);
};
const start = (repo: string, branch: string, build_args: string) => {
setRelLoading(true);
fetch(import.meta.env.VITE_SERVER_URL + "/error_restart", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
id: selectedRowKeys,
repo: repo,
branch: branch,
build_args: build_args
})
})
.then((res) => {
return res.json();
})
.then((body) => {
setRelLoading(false);
if (body?.status === 1) {
setResultReload(resultReload + 1);
message.loading("pending");
} else {
message.error(body?.msg ? body?.msg : "Server Error");
}
});
};
const rowSelection = {
selectedRowKeys,
onChange: onSelectChange,
getCheckboxProps: (record: ErrorDataType) => ({
disabled: Number(record.status) === 2
})
};
const hasSelected = selectedRowKeys.length > 0;
const [form] = Form.useForm();
const set_comment = (comment: string, assign: string) => {
setRelLoading(true);
fetch(import.meta.env.VITE_SERVER_URL + "/set_commend", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
id: selectedRowKeys,
comment: {
comment: comment,
assign: assign
}
})
})
.then((res) => {
return res.json();
})
.then((body) => {
setRelLoading(false);
if (body?.status === 1) {
setResultReload(resultReload + 1);
message.success("success");
} else {
message.error("Server Error");
}
});
};
const get_cases = async (response: Response, name: string) => {
try {
if (response.headers.get("content-type") !== "application/json") {
response
.blob()
.then((blob) => {
const a = window.document.createElement("a");
const downUrl = window.URL.createObjectURL(
new Blob([blob], { type: "multipart/form-data" })
);
//定义导出文件的命名
let filename = name;
if (
response.headers.get("content-disposition") &&
response.headers?.get("content-disposition")?.indexOf("filename=") !== -1
) {
filename =
response.headers?.get("content-disposition")?.split("filename=")[1] || name;
a.href = downUrl;
a.download = `${decodeURI(filename.split('"')[1])}` || name;
a.click();
window.URL.revokeObjectURL(downUrl);
} else {
a.href = downUrl;
a.download = name;
a.click();
window.URL.revokeObjectURL(downUrl);
}
})
.catch((error) => {
message.error(error);
});
} else {
let res = await response.json();
message.error(res.msg);
}
} catch (err) {
console.log(err);
message.error("Download timeout");
}
};
return (
<>
<br />
<Button></Button>
<Card
type={"inner"}
style={{
width: "100%",
height: document.body.clientHeight - 210,
textAlign: "left",
borderRadius: "10px",
overflow: "hidden"
}}
// headStyle={{ backgroundColor: "#87CEFAB7" }}
title="errors"
// extra={<a href="#">More</a>}
// tabList={tabList}
loading={tableLoading}
>
<div>
<div
style={{
marginBottom: 16,
textAlign: "left"
}}
>
<Button
loading={reloadLoading}
type="primary"
onClick={() => {
setModalVisible(true);
}}
disabled={!hasSelected}
>
Verify
</Button>
<> </>
<Button
loading={reloadLoading}
type="primary"
onClick={() => {
setModal2Visible(true);
}}
disabled={!hasSelected}
>
Comment
</Button>
<> </>
<Button
loading={downloadLoading}
type="primary"
onClick={async () => {
setDownLoading(true);
try {
const response = await fetch(import.meta.env.VITE_SERVER_URL + "/get_cases_zip", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
id: selectedRowKeys
})
});
get_cases(response, "cases.zip");
} catch (err) {
message.error("Download timeout");
}
setSelectedRowKeys([]);
setDownLoading(false);
}}
disabled={!hasSelected}
>
Download Selected
</Button>
<> </>
<Button
type="primary"
icon={<SyncOutlined spin={tableLoading} />}
onClick={() => {
setResultReload(resultReload + 1);
}}
/>
<span style={{ marginLeft: 8 }}>
{hasSelected ? `Selected ${selectedRowKeys.length} items` : ""}
</span>
</div>
<Modal
title="Priview"
centered
width={"60%"}
bodyStyle={{ height: 400 }}
visible={modal3Visible}
footer={
<>
{" "}
<Button key="close" onClick={() => setModal3Visible(false)}>
close
</Button>{" "}
</>
}
// onOk={() => setModal3Visible(false)}
onCancel={() => setModal3Visible(false)}
>
<div
style={{
whiteSpace: "pre-wrap",
height: "350px",
overflow: "auto"
}}
>
{errorTabData}
</div>
</Modal>
<Modal
title="verify"
centered
visible={modalVisible}
onOk={() => {
let repo = form.getFieldsValue(["repo", "branch", "build_args"]).repo;
let branch = form.getFieldsValue(["repo", "branch", "build_args"]).branch;
let build_args = form.getFieldsValue(["repo", "branch", "build_args"]).build_args;
if (repo === "" || branch === "") {
message.error("repo and branch cannot be empty");
return;
}
if (repo === undefined) {
repo = detail_result.repo;
}
if (branch === undefined) {
branch = detail_result.branch;
}
if (build_args === undefined) {
build_args = detail_result.build_args;
}
start(repo, branch, build_args);
setModalVisible(false);
setSelectedRowKeys([]);
}}
onCancel={() => {
setModalVisible(false);
}}
>
<Form form={form} name="domain" labelCol={{ span: 4 }} wrapperCol={{ span: 24 }}>
<Form.Item
label="repo"
name="repo"
rules={[{ required: true, message: "Please input your repo!" }]}
>
<TextArea defaultValue={detail_result.repo} placeholder="Please enter repo" />
</Form.Item>
<Form.Item
label="branch"
name="branch"
rules={[{ required: true, message: "Please input your branch!" }]}
>
<Input defaultValue={detail_result.branch} />
</Form.Item>
<Form.Item label="build_args" name="build_args">
<Input defaultValue={detail_result.build_args} placeholder="Please enter build" />
</Form.Item>
</Form>
</Modal>
<Modal
title="Write Comment and Assign"
centered
visible={modal2Visible}
onOk={() => {
const data_any = form.getFieldsValue(["comment", "assign"]);
const comment = data_any.comment;
const assign = data_any.assign;
set_comment(comment, assign);
setModal2Visible(false);
}}
onCancel={() => {
setModal2Visible(false);
}}
>
<Form
form={form}
name="domain"
// autoComplete="off"
labelCol={{ span: 4 }}
wrapperCol={{ span: 24 }}
>
<Form.Item label="comment" name="comment">
<TextArea placeholder="Please enter comment" />
</Form.Item>
<Form.Item label="assign" name="assign">
<Input placeholder="Please enter assign" />
</Form.Item>
</Form>
</Modal>
<Table
bordered
rowSelection={rowSelection}
columns={error_columns}
dataSource={result.results}
scroll={{ y: document.body.clientHeight - 450 }}
/>
</div>
</Card>
</>
);
};
export default CardMenu;

View File

@ -0,0 +1,389 @@
// Copyright (C) 2019 Intel Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
import {
Descriptions,
DatePicker,
Card,
Space,
Button,
Badge,
Divider,
Row,
Statistic,
Col,
Modal,
Form,
Input,
message,
Upload,
UploadFile
} from "antd";
import { useEffect, useState } from "react";
import moment from "moment";
import "antd/dist/antd.css";
import { UploadOutlined } from "@ant-design/icons";
import type { DatePickerProps, RangePickerProps } from "antd/es/date-picker";
const { TextArea } = Input;
interface DataType {
id: number;
branch: string;
build_args: string;
start_time: string;
end_time: string;
status: string;
repo: string;
data: any;
wamr_commit: string;
fuzz_time: number;
end_error: number;
error: number;
}
interface select_uuid {
res: Array<DataType>;
setId: any;
setResult: any;
}
const normFile = (e: any) => {
console.log("Upload event:", e);
if (Array.isArray(e)) {
return e;
}
return e?.fileList;
};
const Description = ({ res, setId, setResult }: select_uuid) => {
// const formRef = react
const range = (start: number, end: number) => {
const result = [];
for (let i = start; i < end; i++) {
result.push(i);
}
return result;
};
const [modalVisible, setModalVisible] = useState<boolean>(false);
const [modal2Visible, setModal2Visible] = useState<boolean>(false);
const [form] = Form.useForm();
// const [fileList, setFileList] = useState<UploadFile[]>([]);
const disabledDate: RangePickerProps["disabledDate"] = (current) => {
return current && current < moment().subtract(1, "day").endOf("day");
};
// let fileList: UploadFile[] = [];
var fileList: Array<string> = [];
const new_fuzzing = (repo: string, branch: string, fuzz_time: number, build_args: string) => {
fetch(import.meta.env.VITE_SERVER_URL + "/new_fuzzing", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
repo: repo,
branch: branch,
fuzz_time: fuzz_time,
build_args: build_args
})
})
.then((res) => {
return res.json();
})
.then((body) => {
if (body.status === 0) {
message.error(body.msg);
} else {
message.success("new fuzzing success");
}
});
};
return (
<>
<Row gutter={16}>
<Col span={5}>
<Button
type="primary"
style={{}}
onClick={() => {
setModalVisible(true);
}}
>
New fuzzing test
</Button>
</Col>
<> </>
<Col span={8}>
<Button
type="primary"
style={{}}
onClick={() => {
setModal2Visible(true);
}}
>
Upload Case
</Button>
</Col>
</Row>
<Modal
title="Write Comment and Assign"
centered
visible={modalVisible}
onOk={() => {
const fields_value = form.getFieldsValue(["repo", "branch", "end_time", "build_args"]);
let repo = fields_value.repo;
let branch = fields_value.branch;
let fuzz_time = fields_value.end_time;
const build_args = fields_value.build_args;
if (repo !== "" || branch !== "") {
repo =
repo === undefined
? "https://github.com/bytecodealliance/wasm-micro-runtime.git"
: repo;
branch = branch === undefined ? "main" : branch;
if (fuzz_time) {
const this_time = Date.parse(new Date().toString());
fuzz_time = Date.parse(fuzz_time);
if (fuzz_time > this_time) {
fuzz_time = (fuzz_time - this_time) / 1000;
} else {
fuzz_time = 1;
}
}
new_fuzzing(repo, branch, fuzz_time, build_args);
setModalVisible(false);
} else {
message.error("please enter repo and branch");
}
}}
onCancel={() => {
setModalVisible(false);
}}
>
<Form
form={form}
name="domain"
// autoComplete="off"
labelCol={{ span: 4 }}
wrapperCol={{ span: 24 }}
initialValues={{ remember: true }}
>
<Form.Item
label="repo"
name="repo"
rules={[{ required: true, message: "Please input your repo!" }]}
>
<TextArea
defaultValue="https://github.com/bytecodealliance/wasm-micro-runtime.git"
placeholder="Please enter repo"
/>
</Form.Item>
<Form.Item
label="branch"
name="branch"
rules={[{ required: true, message: "Please input your branch!" }]}
>
<Input defaultValue="main" placeholder="Please enter branch" />
</Form.Item>
<Form.Item label="end_time" name="end_time">
<DatePicker
format="YYYY-MM-DD HH:mm:ss"
disabledDate={disabledDate}
// disabledTime={disabledDateTime}
showTime={{ defaultValue: moment("00:00:00", "HH:mm:ss") }}
/>
</Form.Item>
<Form.Item label="build_args" name="build_args">
<Input placeholder="Please enter build_args" />
</Form.Item>
</Form>
</Modal>
<Modal
title="Upload Cases"
footer={[]}
onCancel={() => {
form.resetFields();
setModal2Visible(false);
}}
onOk={() => {
// console.log(123123, fileList);
form.resetFields();
setModal2Visible(false);
}}
visible={modal2Visible}
>
<Form
form={form}
name="upload"
// action={import.meta.env.VITE_SERVER_URL + "/uplad_case"}
// method="post"
// encType="multipart/form-data"
autoComplete="off"
labelCol={{ span: 4 }}
wrapperCol={{ span: 24 }}
initialValues={{ remember: true }}
>
<Form.Item
name="upload"
label="upload"
valuePropName="fileList"
getValueFromEvent={normFile}
>
{/* <input type="file" /> */}
<Upload
name="file"
listType="picture"
action={import.meta.env.VITE_SERVER_URL + "/upload_case"}
// action=""
// fileList={fileList}
beforeUpload={(file) => {
return new Promise((resolve, reject) => {
let fileName = file.name;
const file_config = fileName.split(".");
if (file_config[file_config.length - 1] !== "wasm") {
message.error("Wrong file type");
return reject(false);
}
return resolve(true);
});
}}
onRemove={(file) => {
// import.meta.env.VITE_SERVER_URL + "/remove_case"
// console.log(file.name);
fetch(import.meta.env.VITE_SERVER_URL + "/remove_case", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
filename: file.name
})
});
}}
>
<Button icon={<UploadOutlined />}>Click to upload</Button>
</Upload>
</Form.Item>
</Form>
</Modal>
<br />
<Space
direction="vertical"
size="middle"
style={{
display: "flex",
height: document.body.clientHeight - 210,
overflow: "auto"
}}
>
{Object.keys(res).map((r: any) => (
<Card
type="inner"
title={res[r].repo + ": " + res[r].branch}
style={{
width: "99.9%",
textAlign: "left",
borderRadius: "10px",
overflow: "hidden"
}}
headStyle={{ backgroundColor: "#87CEFAB7" }}
>
<Descriptions
size="default"
column={2}
// title={"pid: " + (res[r].data?.pid ? res[r].data?.pid : "")}
extra={
Number(res[r].status) === 2 ? (
res[r].data?.error ? (
<Badge status="error" text={res[r].data?.error} />
) : (
<Badge status="processing" text="to be operated" />
)
) : Number(res[r].status) === 1 ? (
<Badge status="processing" text="Running" />
) : (
<Badge status="default" text="End" />
)
}
>
<Descriptions.Item label="Start time">{res[r].start_time}</Descriptions.Item>
<Descriptions.Item label="End time">{res[r].end_time}</Descriptions.Item>
<Descriptions.Item label="Build args">{res[r].build_args}</Descriptions.Item>
<Descriptions.Item label="WAMR commit">
<a
href={`https://github.com/bytecodealliance/wasm-micro-runtime/commit/${res[r]?.wamr_commit}`}
>
{res[r]?.wamr_commit}
</a>
</Descriptions.Item>
<Descriptions.Item label="">
<Row gutter={24}>
<Col span={10}>
<Button
type="primary"
onClick={() => {
setId(res[r].id);
setResult(res[r]);
}}
>
Detail
</Button>
</Col>
<Col span={10}>
<Button
disabled={Number(res[r].status) !== 1}
type="primary"
danger
onClick={() => {
fetch(import.meta.env.VITE_SERVER_URL + "/end_fuzzing", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
id: res[r].id
})
})
.then((res) => {
return res.json();
})
.then((body) => {
if (body.status === 0) {
message.error(body.msg);
} else {
message.success("Stop fuzzing success");
}
});
}}
>
Stop
</Button>
</Col>
</Row>
</Descriptions.Item>
</Descriptions>
<Divider />
<Row gutter={24}>
<Col span={6}>
<Statistic title="Total Error" value={res[r].error + res[r].end_error} />
</Col>
<Col span={6}>
<Statistic title="Fixed" value={res[r].end_error} />
</Col>
<Col span={8}>
<Statistic title="Remaining Errors" value={res[r].error} />
</Col>
</Row>
</Card>
))}
</Space>
</>
);
};
export default Description;

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -0,0 +1,70 @@
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@ -0,0 +1,13 @@
// Copyright (C) 2019 Intel Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
);

View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View File

@ -0,0 +1,9 @@
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}

View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()]
})

View File

@ -0,0 +1,4 @@
data.db
Dockerfile copy*
migrations/
app/test.py

View File

@ -0,0 +1,39 @@
FROM ubuntu:20.04
WORKDIR /wamr-test/tests/fuzz/wasm-mutator-fuzz/server
COPY ./tests/fuzz/wasm-mutator-fuzz/server/requirements.txt /requirements.txt
ARG proxy=""
RUN if [ "$proxy" != "" ]; \
then export http_proxy="$proxy" && export https_proxy="$proxy"; \
else echo Do not set proxy; \
fi
ARG DEBIAN_FRONTEND=noninteractive
ENV TZ=Asian/Shanghai
# hadolint ignore=DL3008
RUN apt-get -o Acquire::http::proxy="$proxy" update \
&& apt-get -o Acquire::http::proxy="$proxy" install \
curl clang rustc cargo python3 python3-pip git \
gcc build-essential cmake g++-multilib libunwind-dev \
wget -y --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& pip install --no-cache-dir -U -r /requirements.txt --proxy=$proxy
COPY ./tests/fuzz /wamr-test/tests/fuzz
RUN if [ "$proxy" != "" ]; \
then git config --global http.proxy $proxy && git config --global https.proxy $proxy; \
else echo Do not set proxy for git; \
fi
WORKDIR /wamr-test/tests/fuzz/wasm-mutator-fuzz
RUN wget --progress=dot:giga -e "https_proxy=$proxy" \
https://github.com/bytecodealliance/wasm-tools/releases/download/v1.201.0/wasm-tools-1.201.0-x86_64-linux.tar.gz \
&& tar -xzf wasm-tools-1.201.0-x86_64-linux.tar.gz && mv wasm-tools-1.201.0-x86_64-linux wasm-tools
ENV PATH="/wamr-test/tests/fuzz/wasm-mutator-fuzz/wasm-tools:$PATH"
WORKDIR /wamr-test/tests/fuzz/wasm-mutator-fuzz/server/app
# hadolint ignore=DL3025
CMD nohup sh -c 'python3 main.py'

View File

@ -0,0 +1,518 @@
#!/usr/bin/env python
#
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# coding=utf-8
from sched import scheduler
from flask import Flask, request, jsonify, send_file
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS, cross_origin
from datetime import datetime, timedelta
from urllib.parse import quote
from pathlib import Path
from flask_caching import Cache
from flask_apscheduler import APScheduler
from zipfile import ZipFile, ZIP_DEFLATED
from io import BytesIO
from multiprocessing import Process
import os
import sys
import copy
import getopt
import signal
import psutil
import shutil
import subprocess
current_dir = Path(__file__).parent.resolve()
wasm_mutator_dir = current_dir.parent.parent
fuzz_dir = wasm_mutator_dir.parent
app = Flask(__name__)
# cors
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
scheduler = APScheduler()
# sqlite URI
WIN = sys.platform.startswith('win')
if WIN:
prefix = 'sqlite:///'
else:
prefix = 'sqlite:////'
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv(
'DATABASE_URL', prefix + os.path.join(app.root_path, 'data.db'))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = "hwhefsewljfejrlesjfl"
db = SQLAlchemy(app)
def to_json(inst, cls):
ret_dict = {}
for i in cls.__table__.columns:
value = getattr(inst, i.name)
if isinstance(value, datetime):
value = value.strftime('%Y-%m-%d %H:%M:%S')
ret_dict[i.name] = value
return ret_dict
class Fuzzing(db.Model):
__tablename__ = 'fazzing_task'
id = db.Column(db.Integer, autoincrement=True,
primary_key=True, nullable=False)
repo = db.Column(db.String(200), nullable=False, default='')
branch = db.Column(db.String(200), nullable=False, default='')
build_args = db.Column(db.String(200), nullable=False, default='')
fuzz_time = db.Column(db.Integer, default=0)
wamr_commit = db.Column(
db.String(200), nullable=False, default='')
data = db.Column(db.JSON)
start_time = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow() + timedelta(hours=8))
end_time = db.Column(db.DateTime)
status = db.Column(db.Integer, default=2)
@property
def serialize(self):
return to_json(self, self.__class__)
class TaskError(db.Model):
__tablename__ = 'task_error'
id = db.Column(db.Integer, autoincrement=True,
primary_key=True, nullable=False)
fazzing_id = db.Column(db.Integer, db.ForeignKey("fazzing_task.id"))
name = db.Column(db.String(200), nullable=False, default='')
std_out = db.Column(db.Text, default='')
data = db.Column(db.JSON)
comment = db.Column(db.JSON)
create_time = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow() + timedelta(hours=8))
update_time = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow() + timedelta(hours=8))
status = db.Column(db.Integer, default=1)
@property
def serialize(self):
return to_json(self, self.__class__)
def to_data(data):
data['data']['id'] = data['id']
return data['data']
def error_count(data):
error = len(TaskError.query.filter(
TaskError.fazzing_id == data.get('id'), TaskError.status.in_([1, 2])).all())
end_error = len(TaskError.query.filter(
TaskError.fazzing_id == data.get('id'), TaskError.status == 0).all())
data['error'] = error
data['end_error'] = end_error
return data
def getstatusoutput(cmd):
try:
data = subprocess.check_output(
cmd, shell=True, text=True, stderr=subprocess.STDOUT, executable='/bin/bash')
exitcode = 0
except subprocess.CalledProcessError as ex:
data = ex.output
exitcode = ex.returncode
if data[-1:] == '\n':
data = data[:-1]
return exitcode, data
def get_wamr_commit(repo_root_dir):
wamr_repo_dir = repo_root_dir / 'wamr'
cmd = f'cd {wamr_repo_dir} && git log -1 --pretty=format:"%h"'
status, resp = getstatusoutput(cmd)
if status != 0:
return "-"
return resp
@app.route('/get_list', methods=["GET"])
@cross_origin()
def show_fuzz_list():
data = request.args
id = data.get('id')
if id:
all_error = TaskError.query.filter(
TaskError.fazzing_id == id).with_entities(TaskError.id, TaskError.fazzing_id,
TaskError.create_time, TaskError.data,
TaskError.name, TaskError.status,
TaskError.update_time, TaskError.comment).order_by(TaskError.status.desc(), TaskError.update_time.desc(), TaskError.id.desc()).all()
data_message = [{'id': error['id'], "fuzzing_id": error['fazzing_id'],
"name": error['name'], "data": error['data'],
'create_time': error['create_time'].strftime('%Y-%m-%d %H:%M:%S'),
'update_time': error['update_time'].strftime('%Y-%m-%d %H:%M:%S'),
'status': error['status'], "comment": error["comment"]} for error in all_error]
return jsonify({"status": 1, "results": data_message, 'msg': "success", "count": len(data_message)})
else:
all_fuzz = Fuzzing.query.order_by(
Fuzzing.status.desc(), Fuzzing.end_time.desc(), Fuzzing.id.desc()).all()
data_message = list(map(lambda i: i.serialize, all_fuzz))
data_message = list(map(error_count, data_message))
return jsonify({"status": 1, "results": data_message, 'msg': "success", "count": len(data_message)})
@app.route('/new_fuzzing', methods=["POST"])
@cross_origin()
def New_fuzzing():
data = request.json
repo = data.get('repo', '')
branch = data.get('branch', '')
build_args = data.get('build_args', '')
fuzz_time = data.get('fuzz_time', 0)
if not repo or not branch:
return jsonify({"status": 0, "result": "", 'msg': "repo and branch are required !"})
fuzz = Fuzzing(repo=repo, branch=branch,
build_args=build_args, fuzz_time=fuzz_time, start_time=datetime.utcnow() + timedelta(hours=8))
db.session.add(fuzz)
db.session.commit()
fuzz_cmd = wasm_mutator_dir / \
'workspace' / f'build_{fuzz.id}'
Path(fuzz_cmd).mkdir(exist_ok=True)
os.system(
f'cd {fuzz_cmd} && git clone --branch {branch} --depth=1 {repo} wamr')
if not Path(fuzz_cmd / 'wamr').exists():
print('------ error: clone repo not folder exists ------')
# curd.set_error_status_to(list(map(lambda x: x.id, error_list)), db)
# Fuzzing.query.filter_by(id=fuzz.id).delete()
fuzz.data = {'error': "Clone repo Error"}
db.commit()
return jsonify({"status": 0, "result": "", "msg": "Clone repo Error"})
wamr_path_parent = fuzz_dir.parent.parent
wamr_path = wamr_path_parent / 'wamr'
wamr_path_to = wamr_path_parent / f'wamr_{fuzz.id}'
wamr_folder = Path(wamr_path).exists()
try:
if wamr_folder:
os.rename(wamr_path, wamr_path_to)
except Exception as e:
print(f'------ error: fail wamr folder rename, error: {e} ------')
return jsonify({"status": 0, "result": "", "msg": "fail wamr folder rename"})
try:
os.system(f'ln -s {fuzz_cmd / "wamr"} {wamr_path_parent}')
except Exception as e:
print('------ error: fail wamr_repo to wamr ------')
if wamr_folder:
os.rename(wamr_path_to, wamr_path)
return jsonify({"status": 0, "result": "", "msg": "fail wamr_repo to wamr"})
os.system(
f'cd {fuzz_cmd} && cmake .. -DCUSTOM_MUTATOR=1 {build_args} && make -j$(nproc)')
os.system(f'rm -rf {wamr_path}')
if wamr_folder:
os.rename(wamr_path_to, wamr_path)
os.system(
f"ln -s {wasm_mutator_dir / 'build' / 'CORPUS_DIR'} {fuzz_cmd}")
cmd_max_time = ''
if fuzz_time != 0:
cmd_max_time = f"-max_total_time={fuzz_time}"
cmd = f'cd {fuzz_cmd} && ./wasm_mutator_fuzz CORPUS_DIR {cmd_max_time} -ignore_crashes=1 -fork=2'
process_tcpdump = subprocess.Popen(
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=os.setsid)
commit_id = get_wamr_commit(fuzz_cmd)
fuzz.data = {"pid": process_tcpdump.pid}
fuzz.status = 1
fuzz.wamr_commit = commit_id
db.session.commit()
return jsonify({'status': 1, 'msg': 'success', 'result': ''})
@app.route('/end_fuzzing', methods=["POST"])
@cross_origin()
def End_fuzzing():
data = request.json
id = data.get('id')
if not id:
return jsonify({'status': 0, 'msg': 'id must pass'})
fuzz_model = Fuzzing.query.get(id)
pid = fuzz_model.data.get('pid')
try:
os.killpg(pid, signal.SIGTERM)
except Exception as e:
pass
fuzz_model.status = 0
fuzz_model.end_time = datetime.utcnow() + timedelta(hours=8)
db.session.commit()
return jsonify({'status': 1, 'msg': 'success'})
@scheduler.task('interval', id="run_task", seconds=5, misfire_grace_time=60)
def scheduler_run_task():
fuzz_query = Fuzzing.query.filter(Fuzzing.status == 1).all()
for fuzz in fuzz_query:
# if fuzz.fuzz_time == 0:
# continue
if fuzz.data.get('pid', 0) not in psutil.pids() or psutil.Process(fuzz.data.get('pid', 0)).status() == "zombie":
fuzz.status = 0
fuzz.end_time = datetime.utcnow() + timedelta(hours=8)
db.session.commit()
for fuzz in fuzz_query:
all_error = TaskError.query.filter(
TaskError.fazzing_id == fuzz.id).with_entities(TaskError.name).all()
fuzz_cmd = wasm_mutator_dir / \
'workspace' / f'build_{fuzz.id}'
dir_list = filter(lambda x: x.startswith(
'crash-') or x.startswith('oom-') or x.startswith('slow-unit-') or x.startswith('leak-'), os.listdir(fuzz_cmd))
all_error = [error['name'] for error in all_error]
dir_list = list(filter(lambda x: x not in all_error, dir_list))
for dir in dir_list:
cmd = f'cd {fuzz_cmd} && ./wasm_mutator_fuzz {dir}'
status, resp = getstatusoutput(cmd)
task_error = TaskError(name=dir, std_out=resp, fazzing_id=fuzz.id,
create_time=datetime.utcnow() + timedelta(hours=8))
db.session.add(task_error)
db.session.commit()
@app.route("/get_error_out", methods=["GET"])
def get_error_out():
data = request.args
id = data.get('id')
if id:
error = TaskError.query.get(id)
data_message = error.serialize
return jsonify({"status": 1, "result": data_message, 'msg': "success"})
return jsonify({"status": 0, "results": [], 'msg': "Error"})
@app.route("/get_error_txt", methods=["GET"])
def get_error_txt():
data = request.args
id = data.get('id')
if not id:
return jsonify({"status": 0, "results": [], 'msg': "Error"})
error = TaskError.query.get(id)
fuzz_cmd = wasm_mutator_dir / \
'workspace' / f'build_{error.fazzing_id}'
file_cmd = fuzz_cmd / error.name
response = send_file(file_cmd, as_attachment=True,
attachment_filename=error.name)
response.headers['Content-Disposition'] += "; filename*=utf-8''{}".format(
error.name)
return response
@app.route("/set_commend", methods=["POST"])
def set_commend():
data = request.json
id = data.get('id')
comment = data.get('comment')
if not id:
return jsonify({"status": 0, "results": [], 'msg': "Error"})
try:
TaskError.query.filter(TaskError.id.in_(
id)).update({"comment": comment, "update_time": datetime.utcnow() + timedelta(hours=8)})
db.session.commit()
except Exception as e:
return jsonify({"status": 0, "results": [], 'msg': "Update error"})
return jsonify({"status": 1, "results": [], 'msg': "Success"})
@app.route("/get_cases_zip", methods=["POST"])
def get_cases_zip():
data = request.json
id_list = data.get('id')
task_query = TaskError.query.filter(TaskError.id.in_(id_list)).all()
memory_file = BytesIO()
with ZipFile(memory_file, "w", ZIP_DEFLATED) as zf:
for task_error in task_query:
fuzz_cmd = wasm_mutator_dir / \
'workspace' / f'build_{task_error.fazzing_id}'
file_cmd = fuzz_cmd / task_error.name
zf.write(str(file_cmd), arcname=task_error.name)
memory_file.seek(0)
return send_file(memory_file, attachment_filename='cases.zip', as_attachment=True)
class processClass:
def __init__(self, fuzz_cmd, restart_cmd, error_query):
p = Process(target=self.run, args=(fuzz_cmd, restart_cmd, error_query))
p.daemon = True # Daemonize it
p.start() # Start the execution
def run(self, fuzz_cmd, restart_cmd, error_query):
for error in error_query:
shutil.copyfile(fuzz_cmd / error.name, restart_cmd / error.name)
commit = get_wamr_commit(restart_cmd)
cmd = f"cd {restart_cmd} && ./wasm_mutator_fuzz {error.name}"
status, resp = getstatusoutput(cmd)
data = copy.deepcopy(error.data)
if type(data) == dict:
data['wamr_commit'] = commit
else:
data = {'wamr_commit': commit}
error.data = data
error.status = 0 if status == 0 else 1
error.update_time = datetime.utcnow() + timedelta(hours=8)
error.std_out = resp if status != 0 else error.std_out
db.session.commit()
#
# This might take several minutes to complete
@app.route("/error_restart", methods=["POST"])
def error_restart():
data = request.json
id_list = data.get('id')
repo = data.get('repo')
branch = data.get('branch')
build_args = data.get('build_args', '')
if len(id_list) == [] or repo == "":
return jsonify({"status": 0, "msg": 'parameter is incorrect'})
run_status = cache.get('runStatus')
if run_status:
return jsonify({"status": 0, "results": [], 'msg': "There are already tasks in progress"})
task_query = TaskError.query.filter(TaskError.id.in_(id_list)).all()
fuzzing_id = task_query[0].fazzing_id
fuzz_cmd = wasm_mutator_dir / \
'workspace' / f'build_{fuzzing_id}'
restart_cmd = wasm_mutator_dir / \
'workspace' / f'error_restart_build_{fuzzing_id}'
if not Path(restart_cmd).exists():
Path(restart_cmd).mkdir(exist_ok=True)
os.system(
f'cd {restart_cmd} && git clone --branch {branch} --depth=1 {repo} wamr')
if not Path(restart_cmd / 'wamr').exists():
print('------ error: clone repo not folder exists ------')
# fuzz.data = {'error': "Clone repo Error"}
db.commit()
return jsonify({"status": 0, "result": "", "msg": "Clone repo Error"})
wamr_path_parent = fuzz_dir.parent.parent
wamr_path = wamr_path_parent / 'wamr'
wamr_path_to = wamr_path_parent / f'wamr_restart_{fuzzing_id}'
wamr_folder = Path(wamr_path).exists()
try:
if wamr_folder:
os.rename(wamr_path, wamr_path_to)
except Exception as e:
print(f'------ error: fail wamr folder rename, error: {e} ------')
return jsonify({"status": 0, "result": "", "msg": "fail wamr folder rename"})
try:
os.system(f'ln -s {restart_cmd / "wamr"} {wamr_path_parent}')
except Exception as e:
print('------ error: fail wamr_repo to wamr ------')
if wamr_folder:
os.rename(wamr_path_to, wamr_path)
return jsonify({"status": 0, "result": "", "msg": "fail wamr_repo to wamr"})
os.system(
f'cd {restart_cmd} && cmake .. -DCUSTOM_MUTATOR=1 {build_args} && make -j$(nproc)')
os.system(f'rm -rf {wamr_path}')
if wamr_folder:
os.rename(wamr_path_to, wamr_path)
cache.delete('runStatus')
TaskError.query.filter(TaskError.id.in_(id_list)).update(
{'status': 2, "update_time": datetime.utcnow() + timedelta(hours=8)})
db.session.commit()
processClass(fuzz_cmd, restart_cmd, task_query)
return jsonify({"status": 1, "result": "", "msg": "Pending"})
@app.route('/upload_case', methods=['POST'])
def do_upload():
file = request.files['file']
filename = file.filename
upload_file_cmd = wasm_mutator_dir / "upload_path"
build_cmd = wasm_mutator_dir / "build" / "CORPUS_DIR"
if not Path(upload_file_cmd).exists():
Path(upload_file_cmd).mkdir(exist_ok=True)
file.save(str(upload_file_cmd / filename))
file.save(str(build_cmd / filename))
# os.system(f"copy {upload_file_cmd / file} {build_cmd / file}")
return jsonify({"status": 1, "result": "", "msg": "success"})
@app.route('/remove_case', methods=['POST'])
def remove_case():
file = request.json
filename = file.get('filename')
print(filename)
upload_file_cmd = wasm_mutator_dir / "upload_path" / filename
build_cmd = wasm_mutator_dir / "build" / "CORPUS_DIR" / filename
os.system(f'rm -rf "{upload_file_cmd}" "{build_cmd}"')
return jsonify({"status": 1, "result": "", "msg": "success"})
if __name__ == '__main__':
scheduler.init_app(app)
scheduler.start()
os.chdir(wasm_mutator_dir)
os.system('./smith_wasm.sh 100')
os.chdir(current_dir)
try:
opts, args = getopt.getopt(sys.argv[1:], "hp:d:", [
"help", "port=", "debug="])
except getopt.GetoptError:
print(
'test_arg.py -h <host> -p <port> -d <debug? True: False>')
print(
' or: test_arg.py --host=<host> --port=<port> --debug=<True: False>')
print('''
host: default[0.0.0.0]
port: default[16667]
debug: default[False]
''')
sys.exit(2)
run_dict = {
"host": "0.0.0.0",
"port": 16667,
"debug": False
}
for opt, arg in opts:
if opt in ("-h", "--help"):
print(
'test_arg.py -h <host> -p <port> -d <debug? True: False>')
print(
' or: test_arg.py --host=<host> --port=<port> --debug=<True: False>')
print('''
host: default[0.0.0.0]
port: default[16667]
debug: default[False]
''')
sys.exit()
elif opt in ('-h', '--host'):
run_dict['host'] = arg
elif opt in ("-p", "--port"):
run_dict['port'] = int(arg)
elif opt in ("-d", "--debug"):
run_dict['debug'] = bool(arg)
app.run(**run_dict)

View File

@ -0,0 +1,18 @@
#!/usr/bin/env python
#
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from main import app, db
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command("db", MigrateCommand)
if __name__ == "__main__":
manager.run()

View File

@ -0,0 +1,11 @@
Flask==1.1.4
Flask_SQLAlchemy==2.5.1
flask-migrate==2.7.0
flask-script==2.0.6
flask-cors==3.0.10
flask-caching==2.0.0
werkzeug==1.0.1
markupsafe==2.0.1
flask-apscheduler==1.12.4
psutil==5.9.2
SQLAlchemy==1.4.39

View File

@ -0,0 +1,58 @@
#!/bin/bash
#
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# 1.check parameter
if [ ! $1 ]; then
echo "Parameter is empty, please enter parameter !"
exit
fi
# 2.check dir
buildPath="./build"
corpusPath="$buildPath/CORPUS_DIR"
if [[ ! -d "$buildPath" ]]; then
echo "auto create the build folder !"
mkdir build
else # build Folder exists
if [[ -d "$buildPath" ]]; then # CORPUS_DIR exists
rm -rf $corpusPath
fi
fi
# 3.change dir
# cd build && mkdir CORPUS_DIR && cd CORPUS_DIR
cd build && mkdir CORPUS_DIR && cd CORPUS_DIR
# 4.generate *.wasm file
echo "Generate $@ files according to user requirements"
for((i=1; i<($@+1); i++));
do
head -c 100 /dev/urandom | wasm-tools smith -o test_$i.wasm
done
# 5.check wasm file
dir=$(pwd)
d=$(find . ! -name "." -type d -prune -o -type f -name "*.wasm" -print)
#echo "current dir=$dir"
num=0
for((i=1; i<($@+1); i++));
do
wasmFile="test_$i.wasm"
if [[ ! -f "$wasmFile" ]]; then
echo "The file $wasmFile is not exists !"
else
let "num++"
fi
done
echo "$@ user requirements, $num actually generated !"
if [ $num == $@ ]; then echo "Wasm file generated successfully !"
else echo "Wasm file generated faild !"
fi

View File

@ -0,0 +1,133 @@
// Copyright (C) 2019 Intel Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "wasm_runtime_common.h"
#include "wasm_export.h"
#include "bh_read_file.h"
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;
extern "C" WASMModuleCommon *
wasm_runtime_load(uint8 *buf, uint32 size, char *error_buf,
uint32 error_buf_size);
extern "C" WASMModuleInstanceCommon *
wasm_runtime_instantiate(WASMModuleCommon *module, uint32 stack_size,
uint32 heap_size, char *error_buf,
uint32 error_buf_size);
extern "C" int
LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
{
/* libfuzzer don't allow us to modify the given Data, so we copy the data
* here */
std::vector<uint8_t> myData(Data, Data + Size);
/* init runtime environment */
wasm_runtime_init();
wasm_module_t module =
wasm_runtime_load((uint8_t *)myData.data(), Size, nullptr, 0);
if (module) {
wasm_runtime_unload(module);
}
/* destroy runtime environment */
wasm_runtime_destroy();
return 0; /* Values other than 0 and -1 are reserved for future use. */
}
/* Forward-declare the libFuzzer's mutator callback. */
extern "C" size_t
LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize);
/* The custom mutator: */
#ifdef CUSTOM_MUTATOR
extern "C" size_t
LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size, size_t MaxSize,
unsigned int Seed)
{
if ((NULL != Data) && (Size > 10)) {
int mutate_ret = -1;
/* delete */
if (access("./cur.wasm", 0) == 0) {
remove("./cur.wasm");
}
/* 1.write data to cur.wasm */
FILE *fwrite_fp = fopen("./cur.wasm", "wb");
if (NULL == fwrite_fp) {
printf("Faild to open cur.wasm file!\n");
return 0;
}
fwrite(Data, sizeof(uint8_t), Size, fwrite_fp);
fclose(fwrite_fp);
fwrite_fp = NULL;
/* 2.wasm-tools mutate modify cur.wasm */
char cmd_tmp[150] = { 0 };
/* clang-format off */
const char *preserve_semantic = (Seed % 2) ? "--preserve-semantics" : "";
sprintf(cmd_tmp, "wasm-tools mutate cur.wasm --seed %d -o modified.wasm %s > /dev/null 2>&1", Seed, preserve_semantic);
/* clang-format on */
mutate_ret = system(cmd_tmp);
memset(cmd_tmp, 0, sizeof(cmd_tmp));
if (mutate_ret != 0) {
/* If source file not valid, use libfuzzer's own modifier */
return LLVMFuzzerMutate(Data, Size, MaxSize);
}
/* 3.read modified file */
int read_len = 0;
int file_len = 0;
int res = 0;
uint8_t *buf = NULL;
FILE *fread_fp = fopen("./modified.wasm", "rb");
if (NULL == fread_fp) {
printf("Faild to open modified.wasm file!\n");
exit(0);
}
fseek(fread_fp, 0, SEEK_END); /* location to file end */
file_len = ftell(fread_fp); /* get file size */
buf = (uint8_t *)malloc(file_len);
if (NULL != buf) {
fseek(fread_fp, 0, SEEK_SET); /* location to file start */
read_len = fread(buf, 1, file_len, fread_fp);
if ((read_len == file_len) && (read_len < MaxSize)) {
/* 4.fill Data buffer */
memcpy(Data, buf, read_len);
res = read_len;
}
else {
res = 0;
}
}
else {
res = 0;
}
memset(buf, 0, file_len);
free(buf);
fclose(fread_fp);
fread_fp = NULL;
return res;
}
else {
if (access("./modified.wasm", 0) == 0) {
remove("./modified.wasm");
}
memset(Data, 0, Size);
Size = 0;
return 0;
}
}
#endif // CUSTOM_MUTATOR

View File

@ -0,0 +1,138 @@
# Copyright (C) 2019 Intel Corporation. All rights reserved.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
cmake_minimum_required (VERSION 2.8)
project(wasm_mutator)
add_definitions(-DUNIT_TEST)
set (CMAKE_BUILD_TYPE Debug)
set (CMAKE_C_COMPILER "clang")
set (CMAKE_CXX_COMPILER "clang++")
set (WAMR_BUILD_PLATFORM "linux")
# Reset default linker flags
set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")
set (CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "")
set (CMAKE_C_STANDARD 99)
# Set WAMR_BUILD_TARGET, currently values supported:
# "X86_64", "AMD_64", "X86_32", "AARCH64[sub]", "ARM[sub]", "THUMB[sub]",
# "MIPS", "XTENSA", "RISCV64[sub]", "RISCV32[sub]"
if (NOT DEFINED WAMR_BUILD_TARGET)
if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)")
set (WAMR_BUILD_TARGET "AARCH64")
elseif (CMAKE_SYSTEM_PROCESSOR STREQUAL "riscv64")
set (WAMR_BUILD_TARGET "RISCV64")
elseif (CMAKE_SIZEOF_VOID_P EQUAL 8)
# Build as X86_64 by default in 64-bit platform
set (WAMR_BUILD_TARGET "X86_64")
elseif (CMAKE_SIZEOF_VOID_P EQUAL 4)
# Build as X86_32 by default in 32-bit platform
set (WAMR_BUILD_TARGET "X86_32")
else ()
message(SEND_ERROR "Unsupported build target platform!")
endif ()
endif ()
if(CUSTOM_MUTATOR EQUAL 1)
add_compile_definitions(CUSTOM_MUTATOR)
endif()
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif ()
if (NOT DEFINED WAMR_BUILD_INTERP)
# Enable Interpreter by default
set (WAMR_BUILD_INTERP 1)
endif ()
if (NOT DEFINED WAMR_BUILD_AOT)
# Enable AOT by default.
set (WAMR_BUILD_AOT 1)
endif ()
if (NOT DEFINED WAMR_BUILD_JIT)
# Disable JIT by default.
set (WAMR_BUILD_JIT 0)
endif ()
if (NOT DEFINED WAMR_BUILD_LIBC_BUILTIN)
# Enable libc builtin support by default
set (WAMR_BUILD_LIBC_BUILTIN 1)
endif ()
if (NOT DEFINED WAMR_BUILD_LIBC_WASI)
# Enable libc wasi support by default
set (WAMR_BUILD_LIBC_WASI 1)
endif ()
if (NOT DEFINED WAMR_BUILD_FAST_INTERP)
# Enable fast interpreter
set (WAMR_BUILD_FAST_INTERP 1)
endif ()
if (NOT DEFINED WAMR_BUILD_MULTI_MODULE)
# Enable multiple modules
set (WAMR_BUILD_MULTI_MODULE 0)
endif ()
if (NOT DEFINED WAMR_BUILD_LIB_PTHREAD)
# Disable pthread library by default
set (WAMR_BUILD_LIB_PTHREAD 0)
endif ()
if (NOT DEFINED WAMR_BUILD_MINI_LOADER)
# Disable wasm mini loader by default
set (WAMR_BUILD_MINI_LOADER 0)
endif ()
if (NOT DEFINED WAMR_BUILD_SIMD)
# Enable SIMD by default
set (WAMR_BUILD_SIMD 1)
endif ()
if (NOT DEFINED WAMR_BUILD_REF_TYPES)
# Disable reference types by default
set (WAMR_BUILD_REF_TYPES 0)
endif ()
if (NOT DEFINED WAMR_BUILD_DEBUG_INTERP)
# Disable Debug feature by default
set (WAMR_BUILD_DEBUG_INTERP 0)
endif ()
if (WAMR_BUILD_DEBUG_INTERP EQUAL 1)
set (WAMR_BUILD_FAST_INTERP 0)
set (WAMR_BUILD_MINI_LOADER 0)
set (WAMR_BUILD_SIMD 0)
endif ()
set (REPO_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../../../..)
message([ceith]:REPO_ROOT_DIR, ${REPO_ROOT_DIR})
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
add_definitions(-DWAMR_USE_MEM_POOL=0)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -fsanitize=signed-integer-overflow \
-fprofile-instr-generate -fcoverage-mapping \
-fsanitize=address,undefined,fuzzer")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fsanitize=signed-integer-overflow \
-fprofile-instr-generate -fcoverage-mapping \
-fsanitize=address,undefined,fuzzer")
include(${REPO_ROOT_DIR}/wamr/core/shared/utils/uncommon/shared_uncommon.cmake)
include(${REPO_ROOT_DIR}/wamr/build-scripts/runtime_lib.cmake)
add_library(vmlib
${WAMR_RUNTIME_LIB_SOURCE}
)
add_executable(wasm_mutator_fuzz wasm_mutator_fuzz.cc)
target_link_libraries(wasm_mutator_fuzz vmlib -lm)

View File

@ -0,0 +1,133 @@
// Copyright (C) 2019 Intel Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "wasm_runtime_common.h"
#include "wasm_export.h"
#include "bh_read_file.h"
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;
extern "C" WASMModuleCommon *
wasm_runtime_load(uint8 *buf, uint32 size, char *error_buf,
uint32 error_buf_size);
extern "C" WASMModuleInstanceCommon *
wasm_runtime_instantiate(WASMModuleCommon *module, uint32 stack_size,
uint32 heap_size, char *error_buf,
uint32 error_buf_size);
extern "C" int
LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
{
/* libfuzzer don't allow us to modify the given Data, so we copy the data
* here */
std::vector<uint8_t> myData(Data, Data + Size);
/* init runtime environment */
wasm_runtime_init();
wasm_module_t module =
wasm_runtime_load((uint8_t *)myData.data(), Size, nullptr, 0);
if (module) {
wasm_runtime_unload(module);
}
/* destroy runtime environment */
wasm_runtime_destroy();
return 0; /* Values other than 0 and -1 are reserved for future use. */
}
/* Forward-declare the libFuzzer's mutator callback. */
extern "C" size_t
LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize);
/* The custom mutator: */
#ifdef CUSTOM_MUTATOR
extern "C" size_t
LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size, size_t MaxSize,
unsigned int Seed)
{
if ((NULL != Data) && (Size > 10)) {
int mutate_ret = -1;
/* delete */
if (access("./cur.wasm", 0) == 0) {
remove("./cur.wasm");
}
/* 1.write data to cur.wasm */
FILE *fwrite_fp = fopen("./cur.wasm", "wb");
if (NULL == fwrite_fp) {
printf("Faild to open cur.wasm file!\n");
return 0;
}
fwrite(Data, sizeof(uint8_t), Size, fwrite_fp);
fclose(fwrite_fp);
fwrite_fp = NULL;
/* 2.wasm-tools mutate modify cur.wasm */
char cmd_tmp[150] = { 0 };
/* clang-format off */
const char *preserve_semantic = (Seed % 2) ? "--preserve-semantics" : "";
sprintf(cmd_tmp, "wasm-tools mutate cur.wasm --seed %d -o modified.wasm %s > /dev/null 2>&1", Seed, preserve_semantic);
/* clang-format on */
mutate_ret = system(cmd_tmp);
memset(cmd_tmp, 0, sizeof(cmd_tmp));
if (mutate_ret != 0) {
/* If source file not valid, use libfuzzer's own modifier */
return LLVMFuzzerMutate(Data, Size, MaxSize);
}
/* 3.read modified file */
int read_len = 0;
int file_len = 0;
int res = 0;
uint8_t *buf = NULL;
FILE *fread_fp = fopen("./modified.wasm", "rb");
if (NULL == fread_fp) {
printf("Faild to open modified.wasm file!\n");
exit(0);
}
fseek(fread_fp, 0, SEEK_END); /* location to file end */
file_len = ftell(fread_fp); /* get file size */
buf = (uint8_t *)malloc(file_len);
if (NULL != buf) {
fseek(fread_fp, 0, SEEK_SET); /* location to file start */
read_len = fread(buf, 1, file_len, fread_fp);
if ((read_len == file_len) && (read_len < MaxSize)) {
/* 4.fill Data buffer */
memcpy(Data, buf, read_len);
res = read_len;
}
else {
res = 0;
}
}
else {
res = 0;
}
memset(buf, 0, file_len);
free(buf);
fclose(fread_fp);
fread_fp = NULL;
return res;
}
else {
if (access("./modified.wasm", 0) == 0) {
remove("./modified.wasm");
}
memset(Data, 0, Size);
Size = 0;
return 0;
}
}
#endif // CUSTOM_MUTATOR