diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-05 12:08:03 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-05 12:08:18 +0000 |
commit | 5da14042f70711ea5cf66e034699730335462f66 (patch) | |
tree | 0f6354ccac934ed87a2d555f45be4c831cf92f4a /src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools | |
parent | Releasing debian version 1.44.3-2. (diff) | |
download | netdata-5da14042f70711ea5cf66e034699730335462f66.tar.xz netdata-5da14042f70711ea5cf66e034699730335462f66.zip |
Merging upstream version 1.45.3+dfsg.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools')
211 files changed, 15515 insertions, 0 deletions
diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/.gitignore b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/.gitignore new file mode 100644 index 000000000..6aa8dc0ee --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/.gitignore @@ -0,0 +1 @@ +/wasi-sdk diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/README.md b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/README.md new file mode 100644 index 000000000..266255c0c --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/README.md @@ -0,0 +1,50 @@ +# IoT Application Store +Wasm application management portal for WAMR + +## Start the server + +### Using docker +1. install docker and docker-compose + ``` bash + sudo apt install docker.io docker-compose + ``` + +2. start + ``` bash + docker-compose up + ``` +### Using commands +> Note: must use python3.5. If you don't have python3.5 on your machine, had better using docker +1. install the required package + ``` bash + pip3 install django + ``` + +2. Start device server + ``` bash + cd wasm_django/server + python3 wasm_server.py + ``` + +3. Start IoT application management web portal + ``` bash + cd wasm_django + python3 manage.py runserver 0.0.0.0:80 + ``` + +## Start the runtime +1. Download WAMR runtime from [help](http://localhost/help/) page + > NOTE: You need to start the server before accessing this link! + +2. Start a WAMR runtime from localhost + ``` bash + chmod +x simple + ./simple + ``` + or from other computers + ``` bash + ./simple -a [your.server.ip.address] + ``` + +## Online demo + http://82.156.57.236/ diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/docker-compose.yml b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/docker-compose.yml new file mode 100644 index 000000000..331d064cd --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/docker-compose.yml @@ -0,0 +1,22 @@ +version: '2.0' + +services: + web_portal: + build: ./wasm_django + network_mode: "host" + depends_on: + - 'device_server' + restart: always + volumes: + - store:/app/static/upload/ + device_server: + build: + context: ./wasm_django + dockerfile: ./server/Dockerfile + network_mode: "host" + restart: always + volumes: + - store:/app/static/upload/ + +volumes: + store:
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/Dockerfile b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/Dockerfile new file mode 100644 index 000000000..a796725fa --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.5 + +WORKDIR /app +COPY . /app + +# hadolint ignore=DL3013 +RUN pip install django --no-cache-dir + +ENTRYPOINT ["python", "manage.py", "runserver", "0.0.0.0:80"] diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/db.sqlite3 b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/db.sqlite3 Binary files differnew file mode 100755 index 000000000..211576ca3 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/db.sqlite3 diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/__init__.py new file mode 100755 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/admin.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/admin.py new file mode 100755 index 000000000..8c38f3f3d --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/apps.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/apps.py new file mode 100755 index 000000000..d43cc4b66 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class DevicesConfig(AppConfig): + name = 'devices' diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/migrations/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/migrations/__init__.py new file mode 100755 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/migrations/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/models.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/models.py new file mode 100755 index 000000000..71a836239 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/application.html b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/application.html new file mode 100644 index 000000000..0b2ea7faf --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/application.html @@ -0,0 +1,141 @@ +<!-- +/* Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ +--> + +{% load static %} +<!DOCTYPE html> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> + +<head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0,shrink-to-fit=no"> + <title> Wasm-Micro-Runtime </title> + <link rel="stylesheet" type="text/css" href="{%static 'css/application.css'%}"/> + +<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css"> +<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> +<script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script> +<script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script> +</head> + +<body style="background-image: linear-gradient(to right, rgb(248, 248, 248) , rgb(194, 194, 190))"> + +<div id="container" style="background-image: url('{%static 'photo//totalblack.png'%}')"> + <div id="content"> + <div id= "mainnav"> + <ul> + <li ><a href="https://github.com/intel/wasm-micro-runtime">GitHub</a></li> + <li ><a href="/">Devices</a></li> + <li ><a href="/appstore/">App Store</a></li> + <li ><a href="/help/">Help</a></li> + </ul> + </div> + </div> + <div class="headers" style="background-image: url('{%static 'photo/milky-way-2695569_1280.jpg'%}')"> + <h1 id="maintitle">WebAssembly Micro Runtime - APP Store Demo</h1> + </div> +</div> + + + +<div class="row"> + <div class="col-sm-2 col-md-2 col-lg-2 col-xl-2"></div> + <div class="col-sm-8 col-md-8 col-lg-8 col-xl-8" id="section"> + <div id="photo"> + <p> + <img src="{%static 'photo/net_device.png'%}" ;height="65" width="65" /> + </p> + </div> + <div id="IPs">IP : </div> + <div id="ports">Port : </div> + <div id="installs">Installed apps : </div> + </div> + <div class="col-sm-2 col-md-2 col-lg-2 col-xl-2"></div> +</div> + + <div class="middlebox" style="display:none;"> + <div class="warning">Dialog Box</div> + <div class="findapp"> APP </div> + <button class="surebtn" type="button" value="sure">OK</button> + </div> + + <div class="deletebox" style="display:none;"> + <div class="warning2">Dialog Box</div> + <div class="findapp"> APP </div> + <button class="suresbtn" type="button" value="sure">OK</button> + <button class="cancelsbtn" type="button" value="Cancel">Cancel</button> + </div> + + <div id="loading"> + <p class="loadapp"> app is downloading now </p> + <div id="preloader"> + <div id="loader"></div> + </div> + </div> + + +<div class="main"> + <div class="mainbox"> + <div class= "close"> × </div> + <div class="hotapps">HOT Applications</div> + <div class="col-sm-6" id="searchbar"> + <form method="post" action="/apps/" id="form_addServiceInfoAll"> + {% csrf_token %} + <div class="input-group"> + <input type="text" name="mykey" class="form-control" placeholder="Input the product name" required /> + <input type="hidden" name="voip" id="aa" value=""> + <input type="hidden" name="voport" id="bb" value=""> + <span class="input-group-btn"> + <input type="submit" class="btn btn-default" value="Search" /> + </span> + </div> + </form> + </div> + <div id="scrollba"> + <div id="Dapplications"> + <div id="appslogo" style="width:45px; height:25px; float:left; "><img src="{%static 'photo/application.png'%}" ;height="35" width="35" /></div> + <p id="appsinfo1" style="font-size:15px;font-family:'sansationlight';width:310px; height:25px; float:left; "> Product Name: </p> + <p id="appsinfo2" style="font-size:15px;font-family:'sansationlight';width:120px; height:25px; float:left; "> Current Version: </p> + <button class="mybtn2" type="button" onclick="getthis(this)" value="downloadit"> ↓ Install</button> + </div> + </div> + </div> +</div> + + + <div class="col-sm-8 col-md-8 col-lg-8 col-xl-8" id="download"> + <p class = "explain pull-left" >List of Installed Apps:</p> + <button id="btn" class="btn btn-outline-primary pull-right" style="float:right" type="button" value="add">Install Application</button> + </div> + + + <div id="APPS" class="sourceapp"> + <div id="applications"> + <div id="applogo"><img src="{%static 'photo/app(1).png'%}" ;height="35" width="35" /></div> + <div id="appinfo1"> Product Name: </div> + <div id="appinfo2"> Staus: </div> + <div id="appinfo3"> Current Version: </div> + </div> + <div id="delete" ><img class="mybtn" style="cursor:pointer" src="{%static 'photo/delete.png'%}" ;height="35" width="35" /></div> + </div> + +<footer class="footer"> Copyright© intel.com</footer> + + + +<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script> +<script> +var alist = {{alist|safe}}; /*alist is a list of downloaded apps under the current device*/ +var dlist = {{dlist|safe}}; /*dlist saves the device info that includes its IP, Port and number of apps*/ +var llist = {{llist|safe}}; /*llist is a list of apps avaliable for installing that are synchronously updated with appstore*/ +var open_status ={{open_status|safe}};/*check is the search bar working&searching,otherwise, close window and return to the main page*/ +var search_node ={{search_node|safe}};/*THe queried app node*/ +</script> +<script type="text/javascript" src="{%static 'js/application.js'%}"></script> + +</body> + +</html> + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/appstore.html b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/appstore.html new file mode 100644 index 000000000..46ecedf15 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/appstore.html @@ -0,0 +1,98 @@ +<!-- +/* Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ +--> + +{% load static %} +<!DOCTYPE html> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> + +<head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0,shrink-to-fit=no"> + + <title> Wasm-Micro-Runtime </title> + <link rel="stylesheet" type="text/css" href="{%static 'css/appstore.css'%}"/> + +<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css"> +<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> +<script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script> +<script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script> +</head> + +<body style="background-color:rgb(240, 240, 240)"> + +<div id="container" style="background-image: url('{%static 'photo//totalblack.png'%}')"> + <div id="content"> + <div id= "mainnav"> + <ul> + <li ><a href="https://github.com/intel/wasm-micro-runtime">GitHub</a></li> + <li ><a href="/">Devices</a></li> + <li ><a href="/appstore/">App Store</a></li> + <li ><a href="/help/">Help</a></li> + </ul> + </div> + </div> + <div class="headers" style="background-image: url('{%static 'photo/milky-way-2695569_1280.jpg'%}')"> + <h1 id="maintitle">WebAssembly Micro Runtime - APP Store Demo</h1> + </div> +</div> +<!-- <div id="introinfo"></div> --> +<!-- <div class="style-one"></div> --> + +<div class="deletebox" style="display:none;"> + <div class="warning2">Dialog Box</div> + <div class="findapp"> APP </div> + <button class="suresbtn" type="button" value="sure">OK</button> + <button class="delsbtn" type="button" value="Cancel">Cancel</button> +</div> + + <div id = "introstore"> + <div id="applicationlist"> + <div class="bar"> + <div class="leftpart">The products </div> + <div style="position:relative; float:left; left:50px; font-size:14px; height:50px; top:10px;">Application List</div> + <div class="rightpart"> + <form action="/upload" method = "POST" enctype="multipart/form-data"> + {%csrf_token%} + <div class="stylehere"> + <input type ="file" required name="myfile" class = "file"> + <a href="#" class="choosestyle">Choose File</a> + </div> + <div class="stylehere"> + <input type="submit" value = "upload" class="btn btn-info"> + </div> + </form> + </div> + </div> + <div class = "appbook"> + <div id="applications"> + <div id="appimage" ><img class="mysoftware" src="{%static 'photo/software-icon-32081.png'%}" ;height="50" width="40"/></div> + <p id="appinfo1" style="position:relative; font-size:15px;width:35%; height:25px; float:left; left:5%;"> Product Name: </p> + <p id="appinfo2" style="position:relative; font-size:15px;width:30%; height:25px; float:left; left:5%;"> Product Version: </p> + <p id="lable" style="position:relative;font-size:11px;font-family:'logo';width:10%; height:25px; float:left; left:5%;"> Preloaded Apps </p> + <button id="delbutton" type="button" style="position: relative; height:25px; float:left; left:5%;" onclick="deleteClick(this)" method = "get" name="delete">Remove</button> + </div> + </div> + <br> + </div> + </div> +</div> + +<footer class="footer"> + Copyright© intel.com +</footer> + +<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script> +<script> +var elist = {{staticlist|safe}}/*saves all the apps that preloaded and are not able to be removed from applestore*/ +var flist = {{flist|safe}} /*a list of locally uploaded apps installed by users*/ +var ulist = {{ulist|safe}} /*Declare about is the app avaliable for uploading to the appstore: wasm_file OR preloaded already*/ +</script> +<script type="text/javascript" src="{%static 'js/appstore.js'%}"></script> + +</body> + +</html> + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/empty.html b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/empty.html new file mode 100644 index 000000000..5610a2d84 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/empty.html @@ -0,0 +1,125 @@ +<!-- +/* Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ +--> + +<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> + +<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no"> +<title>wasm-micro-runtime</title> + +<style type="text/css"> +html, body{overflow:hidden;margin:0;background:#000;} +body{font-family:'Open Sans', 'Helvetica Neue', 'Hiragino Sans GB', 'LiHei Pro', Arial, sans-serif;color:#333;} +#wrapper{position:absolute;left:0;width:320px;text-align:center;top:50%;left:50%;margin-left:-160px;margin-top:-160px;-webkit-user-select:none;-moz-user-select:none;user-select:none;} +h1{font-family:'Montserrat', 'Helvetica Neue', Arial, sans-serif;font-weight:700;font-size:50px;letter-spacing:9px;text-transform:uppercase;color:#eee;margin:12px 0;left:4px;} +h2{color:#999;font-weight:normal;font-size:20px;letter-spacing:.200em;margin-bottom:30px;left:3px;} +h1, h2{position:relative;} +p{font-size:14px;line-height:2em;margin:0;letter-spacing:2px;} +canvas{position:absolute;top:0;left:0;z-index:0;width:100%;height:100%;pointer-events:none;} +a{color:#999;text-decoration:none;transition:color .2s ease;} +a:hover{color:#f33;} +</style> + + + +</head> +<body> + +<script type="text/javascript" src="./js/jquery.min.js"></script> + +<div id="wrapper"> + <h1>404</h1> + <h2>Server Not Found</h2> + <p><a href="https://github.com/intel/wasm-micro-runtime" target="_blank">Github</a></p> +</div> + + +<canvas width="1920" height="917"></canvas> + +<script type="text/javascript"> +document.addEventListener('touchmove', function (e) { + e.preventDefault() +}) +var c = document.getElementsByTagName('canvas')[0], + x = c.getContext('2d'), + pr = window.devicePixelRatio || 1, + w = window.innerWidth, + h = window.innerHeight, + f = 90, + q, + m = Math, + r = 0, + u = m.PI*2, + v = m.cos, + z = m.random +c.width = w*pr +c.height = h*pr +x.scale(pr, pr) +x.globalAlpha = 0.6 +function i(){ + x.clearRect(0,0,w,h) + q=[{x:0,y:h*.7+f},{x:0,y:h*.7-f}] + while(q[1].x<w+f) d(q[0], q[1]) +} +function d(i,j){ + x.beginPath() + x.moveTo(i.x, i.y) + x.lineTo(j.x, j.y) + var k = j.x + (z()*2-0.25)*f, + n = y(j.y) + x.lineTo(k, n) + x.closePath() + r-=u/-50 + x.fillStyle = '#'+(v(r)*127+128<<16 | v(r+u/3)*127+128<<8 | v(r+u/3*2)*127+128).toString(16) + x.fill() + q[0] = q[1] + q[1] = {x:k,y:n} +} +function y(p){ + var t = p + (z()*2-1.1)*f + return (t>h||t<0) ? y(p) : t +} +document.onclick = i +document.ontouchstart = i +i() +</script> + +<script type="text/javascript"> +var snow = function() { +if(1==1) { +$("body").append('<canvas id="christmasCanvas" style="top: 0px; left: 0px; z-index: 5000; position: fixed; pointer-events: none;"></canvas>'); +var b = document.getElementById("christmasCanvas"), a = b.getContext("2d"), d = window.innerWidth, c = window.innerHeight; +b.width = d; +b.height = c; +for(var e = [], b = 0;b < 70;b++) { +e.push({x:Math.random() * d, y:Math.random() * c, r:Math.random() * 4 + 1, d:Math.random() * 70}) +} +var h = 0; +window.intervral4Christmas = setInterval(function() { +a.clearRect(0, 0, d, c); +a.fillStyle = "rgba(255, 255, 255, 0.6)"; +a.shadowBlur = 5; +a.shadowColor = "rgba(255, 255, 255, 0.9)"; +a.beginPath(); +for(var b = 0;b < 70;b++) { +var f = e[b]; +a.moveTo(f.x, f.y); +a.arc(f.x, f.y, f.r, 0, Math.PI * 2, !0) +} +a.fill(); +h += 0.01; +for(b = 0;b < 70;b++) { +if(f = e[b], f.y += Math.cos(h + f.d) + 1 + f.r / 2, f.x += Math.sin(h) * 2, f.x > d + 5 || f.x < -5 || f.y > c) { +e[b] = b % 3 > 0 ? {x:Math.random() * d, y:-10, r:f.r, d:f.d} : Math.sin(h) > 0 ? {x:-5, y:Math.random() * c, r:f.r, d:f.d} : {x:d + 5, y:Math.random() * c, r:f.r, d:f.d} +} +} +}, 70) +} +} +snow(); +</script><canvas id="christmasCanvas" style="top: 0px; left: 0px; z-index: 5000; position: fixed; pointer-events: none;" width="1920" height="917"></canvas> + + +</body></html> diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/help.html b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/help.html new file mode 100755 index 000000000..4ad7427ba --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/help.html @@ -0,0 +1,102 @@ +<!--
+/* Copyright (C) 2019 Intel Corporation. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+ */
+-->
+
+{% load static %}
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title> Wasm-Micro-Runtime </title>
+ <script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>
+ <!-- <link rel="stylesheet" type="text/css" href="{%static%/css/index.css"/> -->
+ <!-- <link rel="stylesheet" type="text/css" href="/home/xujun/mysite/static/css/index.css"/> -->
+
+ <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
+ <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
+ <script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
+ <script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
+
+ <head>
+
+ <body>
+ <div class="container">
+ <div class="row clearfix">
+ <div class="col-md-12 column">
+ <div class="jumbotron">
+ <h1>
+ How to use?
+ </h1>
+ <p>
+ 1. Download a simple runtime (build for ubuntu 20.04 64 bits, other platforms please build
+ from the <a href="https://github.com/bytecodealliance/wasm-micro-runtime/tree/main/samples/simple">source code</a>)
+ </p>
+ <p>
+ 2. In the terminal: <code>cd ~/Download && ./simple -a 82.156.57.236</code>
+ </p>
+ <div class="span12">
+ <div class="alert alert-info">
+ <!-- <button class="close" type="button" data-dismiss="alert">×</button> -->
+ <h5>
+ Notes:
+ </h5> We also have a <strong>UI-enabled runtime</strong>, please <a
+ href="../static/upload/wasm_runtime_wgl">download here</a> and enjoy.</strong> It may require
+ a few more setups.
+ <p>Before running the UI-enabled runtime, please install some required softwares:</p>
+ <p><code>sudo apt-get install libsdl2-2.0-0:i386</code> </p>
+ <p>For more details please refer to this <a
+ href="https://github.com/bytecodealliance/wasm-micro-runtime/tree/main/samples/littlevgl">guide</a>
+ </p>
+ <p><code>cd ~/Download && ./wasm_runtime_wgl -a 82.156.57.236</code></p>
+ </div>
+ </div>
+ <p>
+ 3. Return to device page, find your device according to the IP address and click it, you
+ will enter application installation page
+ </p>
+ <p>
+ 4. In the application installation page, click the Install Application button, and chose an
+ app to install. (The "ui_app" is only for UI_enabled_runtimes, simple runtime can't install
+ this app)
+ </p>
+ <p>
+ 5. If you want to upload a new application, go to App Store page, choose a file and click
+ upload
+ </p>
+ <p>
+ <a class="btn btn-primary btn-large" href="/">Go Back</a>
+ <a class="btn btn-primary btn-large" href="../static/upload/simple">Download
+ simple_runtime</a>
+ <a class="btn btn-primary btn-large" href="../static/upload/wasm_runtime_wgl">Download
+ UI_enabled_runtime</a>
+ </p>
+ </div>
+ <div class="container">
+ <div class="card">
+ <div class="card-body">
+ <h4 class="card-title">Like this project?</h4>
+ <p class="card-text">Join us and build a powerful and interesting world for embedded
+ devices!</p>
+ <iframe
+ src="https://ghbtns.com/github-btn.html?user=intel&repo=wasm-micro-runtime&type=star&count=true&size=large"
+ frameborder="0" scrolling="0" width="160px" height="30px"></iframe>
+ <iframe
+ src="https://ghbtns.com/github-btn.html?user=intel&repo=wasm-micro-runtime&type=fork&count=true&size=large"
+ frameborder="0" scrolling="0" width="158px" height="30px"></iframe>
+ <p>
+ <a href="https://github.com/intel/wasm-micro-runtime" class="btn btn-success">View
+ on GitHub</a>
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </body>
+
+</html>
diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/mysite.html b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/mysite.html new file mode 100644 index 000000000..3832791d1 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/templates/mysite.html @@ -0,0 +1,91 @@ +<!--
+/* Copyright (C) 2019 Intel Corporation. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+ */
+-->
+
+{% load static %}
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0,shrink-to-fit=no">
+ <title> Wasm-Micro-Runtime </title>
+ <link rel="stylesheet" type="text/css" href="{%static 'css/index.css'%}"/>
+
+<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
+<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
+<script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
+<script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
+</head>
+
+
+<body>
+<div id="container" style="background-image: url('{%static 'photo/totalblack.png'%}')">
+ <div id="content">
+ <div id= "mainnav">
+ <ul>
+ <li ><a href="https://github.com/intel/wasm-micro-runtime">GitHub</a></li>
+ <li ><a href="/">Devices</a></li>
+ <li ><a href="/appstore/">App Store</a></li>
+ <li ><a href="/help/">Help</a></li>
+ </ul>
+ </div>
+ </div>
+ <div class="headers" style="background-image: url('{%static 'photo/milky-way-2695569_1280.jpg'%}')">
+ <h1 id="maintitle">WebAssembly Micro Runtime - APP Store Demo</h1>
+ </div>
+</div>
+
+<div class="row">
+ <div class="col-sm-1 col-md-1 col-lg-1 col-xl-1"></div>
+ <div class="col-sm-4 col-md-4 col-lg-4 col-xl-4">
+ <div id="photo2">
+ <p>
+ <img src="{%static 'photo/net_device.png'%}" ;height="45" width="45" />
+ </p>
+ </div>
+ <div id="devic"><p style="font-size:22px;">The devices</p></div>
+ </div>
+</div>
+
+<div id="dividebar"></div>
+
+
+<div id="devices" class="devics">
+ <div class="deviceClick" style="cursor:pointer" onclick="deviceClick(this)">
+ <div id="section">
+ <div id="photo">
+ <p>
+ <img src="{%static 'photo/net_device.png'%}" ;height="60" width="60" />
+ </p>
+ </div>
+ <div id="IPs">IP : </div>
+ <div id="ports">Port : </div>
+ <div id="installs">Installed apps : </div>
+ </div>
+ <div class="smenu">
+ <p id="del" style="cursor:pointer">
+ <img class = "toapps" src="{%static 'photo/menu.png'%}" href= "javascript:void(0);" height="30" width="30" />
+ </p>
+ </div>
+ </div>
+</div>
+
+<!-- <button class="prev" type="button" value="prev" onclick="prevpage(this)">Previous</button>-->
+<!-- <button class="next" type="button" value="next" onclick="nextpage(this)">Next</button> -->
+
+<footer class="footer">
+ Copyright© intel.com
+</footer>
+
+
+<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
+<script>
+var dlist = {{dlist|safe}};/*Devices List that render to the current page*/
+</script>
+<script type="text/javascript" src="{%static 'js/index.js'%}"></script>
+</body>
+
+</html>
diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/tests.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/tests.py new file mode 100755 index 000000000..7ce503c2d --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/views.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/views.py new file mode 100755 index 000000000..1afa1f954 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/devices/views.py @@ -0,0 +1,273 @@ +''' + /* Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ +''' + +# _*_ +from django.shortcuts import render, render_to_response +from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound +import json +import socket +import os + +# Create your views here. + + +avaliable_list = [ + {'ID': 'timer', 'Version': '1.0'}, + {'ID': 'connection', 'Version': '1.0'}, + {'ID': 'event_publisher', 'Version': '3.0'}, + {'ID': 'event_subscriber', 'Version': '1.0'}, + {'ID': 'request_handler', 'Version': '1.0'}, + {'ID': 'sensor', 'Version': '1.0'}, + {'ID': 'ui_app', 'Version': '1.0'} +] + +# Help +def help(req): +# return "Help" page + return render(req, "help.html") + +# View +def index(req): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + + host = '127.0.0.1' + port = 8889 + msg = "" + err = "" + + try: + s.connect((host, port)) + s.send(bytes("query:all", encoding='utf8')) + s.settimeout(10) + msg = s.recv(1024) + except socket.timeout as e: + err = "empty" + print("no client connected") + except socket.error as e: + err = "refused" + print("server not started") + + s.close() + + device_list = [] + if msg != "": + devices = msg.decode('utf-8').split("*") + for dev in devices: + dev_info = eval(dev) + addr = dev_info['addr'] + port = dev_info['port'] + apps = dev_info['num'] + device_list.append({'IP': addr, 'Port': port, 'apps': apps}) + else: + if err == "refused": + return render(req, "empty.html") + + dlist = device_list + + return render(req, 'mysite.html', {'dlist': json.dumps(dlist)}) + + +def apps(req): + open_status = '' + search_node = [] + if req.method == "POST": + dev_search = req.POST['mykey'] + dev_addr = req.POST['voip'] + dev_port = req.POST['voport'] + open_status = 'open' + for i in avaliable_list: + if i['ID'] == dev_search: + search_node = [{'ID':dev_search, 'Version': '1.0'}] + print("search_node:",search_node) + break + else: + search_node = ["Nothing find"] + print( "final:",search_node) + else: + dev_addr = req.GET['ip'] + dev_port = req.GET['port'] + open_status = 'close' + + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + host = '127.0.0.1' + port = 8889 + msg = "" + err = "" + + try: + s.connect((host, port)) + s.send(bytes("query:"+dev_addr+":"+str(dev_port), encoding='utf8')) + msg = s.recv(1024) + except socket.error as e: + print("unable to connect to server") + msg = b"fail" + s.close() + + app_list = [] + + if msg != "": + if msg.decode() == "fail": + return render(req, "empty.html") + else: + dic = eval(msg.decode(encoding='utf8')) + app_num = dic["num"] + for i in range(app_num): + app_list.append( + {'pname': dic["applet"+str(i+1)], 'status': 'Installed', 'current_version': '1.0'}) + + alist = app_list + device_info = [] + device_info.append( + {'IP': dev_addr, 'Port': str(dev_port), 'apps': app_num}) + + print(device_info) + return render(req, 'application.html', {'alist': json.dumps(alist), 'dlist': json.dumps(device_info), 'llist': json.dumps(avaliable_list), + "open_status":json.dumps(open_status),"search_node": json.dumps(search_node),}) + + +def appDownload(req): + dev_addr = req.GET['ip'] + dev_port = req.GET['port'] + app_name = req.GET['name'] + + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + + host = '127.0.0.1' + port = 8889 + msg = "" + + app_path = os.path.abspath(os.path.join(os.getcwd(), "static", "upload")) + if app_path[-1] != '/': + app_path += '/' + + try: + s.connect((host, port)) + s.send(bytes("install:"+dev_addr+":"+str(dev_port)+":"+app_name + + ":"+app_path + app_name + ".wasm", encoding='utf8')) + msg = s.recv(1024) + except socket.error as e: + print("unable to connect to server") + s.close() + + success = "ok" + fail = "Fail!" + status = [success, fail] + print(msg) + if msg == b"fail": + return HttpResponse(json.dumps({ + "status": fail + })) + elif msg == b"success": + return HttpResponse(json.dumps({ + "status": success + })) + else: + return HttpResponse(json.dumps({ + "status": eval(msg.decode())["error message"].split(':')[1] + })) + + +def appDelete(req): + dev_addr = req.GET['ip'] + dev_port = req.GET['port'] + app_name = req.GET['name'] + + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + + host = '127.0.0.1' + port = 8889 + s.connect((host, port)) + s.send(bytes("uninstall:"+dev_addr+":" + + str(dev_port)+":"+app_name, encoding='utf8')) + msg = s.recv(1024) + s.close() + r = HttpResponse("ok") + return r + +static_list = [{'ID': 'timer', 'Version': '1.0'}, {'ID': 'connection', 'Version': '1.0'}, {'ID': 'event_publisher', 'Version': '3.0'}, { + 'ID': 'event_subscriber', 'Version': '1.0'}, {'ID': 'reuqest_handler', 'Version': '1.0'}, {'ID': 'sensor', 'Version': '1.0'}, {'ID': 'ui_app', 'Version': '1.0'}] + +def store(req): + + store_path = os.path.join('static', 'upload') + status = [] + + print(user_file_list) + return render(req, 'appstore.html', {'staticlist': json.dumps(static_list), 'flist': json.dumps(user_file_list),'ulist':json.dumps(status)}) + +user_file_list = [] +files_list = [] +def uploadapps(req): + status = [] + local_list = ['timer','connection','event_publisher','event_subscriber','reuqest_handler','sensor'] + req.encoding = 'utf-8' + if req.method == 'POST': + myfile = req.FILES.get("myfile", None) + obj = req.FILES.get('myfile') + store_path = os.path.join('static', 'upload') + file_path = os.path.join('static', 'upload', obj.name) + + if not os.path.exists(store_path): + os.makedirs(store_path) + + file_name = obj.name.split(".")[0] + file_prefix = obj.name.split(".")[-1] + + + if file_prefix != "wasm": + status = ["Not a wasm file"] + elif file_name in local_list: + status = ["This App is preloaded"] + elif file_name in files_list: + status = ["This App is already uploaded"] + else: + status = [] + avaliable_list.append({'ID': file_name, 'Version': '1.0'}) + user_file_list.append({'ID': file_name, 'Version': '1.0'}) + files_list.append(file_name) + + print(user_file_list) + f = open(file_path, 'wb') + for chunk in obj.chunks(): + f.write(chunk) + f.close() + return render(req, 'appstore.html', {'staticlist': json.dumps(static_list), 'flist': json.dumps(user_file_list),'ulist':json.dumps(status)}) + +appname_list = [] + +def addapps(request): + types = '' + print("enter addapps") + request.encoding = 'utf-8' + app_dic = {'ID': '', 'Version': ''} + + # if request.method == 'get': + if "NAME" in request.GET: + a_name = request.GET['NAME'] + if a_name != "" and a_name not in appname_list: + appname_list.append(a_name) + message = request.GET['NAME'] + request.GET['Version'] + app_dic['ID'] = request.GET['NAME'] + app_dic['Version'] = request.GET['Version'] + avaliable_list.append(app_dic) + else: + types = "Exist" + print(avaliable_list) + return render(request, 'appstore.html', {'alist': json.dumps(avaliable_list)}) + +def removeapps(req): + app_name = req.GET['name'] + app_version = req.GET['version'] + remove_app = {'ID': app_name, 'Version': app_version} + avaliable_list.remove(remove_app) + user_file_list.remove(remove_app) + files_list.remove(app_name) + return render(req, 'appstore.html', {'alist': json.dumps(avaliable_list),'flist': json.dumps(user_file_list)}) + +# Test +# if __name__ == "__main__": +# print(device_list[0]['IP']) +# print(device['IP']) diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/manage.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/manage.py new file mode 100755 index 000000000..341863cf6 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/__init__.py new file mode 100755 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/settings.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/settings.py new file mode 100755 index 000000000..7eb3685c4 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/settings.py @@ -0,0 +1,136 @@ +""" +Django settings for mysite project. + +Generated by 'django-admin startproject' using Django 2.2.2. + +For more information on this file, see +https://docs.djangoproject.com/en/2.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/2.2/ref/settings/ +""" + +import os +from django.conf.global_settings import STATIC_ROOT + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = '8m05#6yx5wcygj*a+v6+=-y(#o+(z58-3!epq$u@5)64!mmu8q' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['*'] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + + 'devices', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'mysite.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'mysite.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/2.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/2.2/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + +APPEND_SLASH = False + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/2.2/howto/static-files/ + +STATIC_URL = '/static/' +HERE = os.path.dirname(os.path.abspath(__file__)) +HERE = os.path.join(HERE,'../') +STATICFILES_DIRS = (os.path.join(HERE,'static/'),) +#STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),) +#STATIC_ROOT = (os.path.join(os.path.dirname(_file_),'static') +#templates +TEMPLATE_DIRS=[ + '/home/xujun/mysite/templates', +] + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/urls.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/urls.py new file mode 100755 index 000000000..8a74b5509 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/urls.py @@ -0,0 +1,41 @@ +#config:utf-8 + +"""mysite URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/2.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +#from django.conf.urls import include,url +from django.urls import path,include +from devices import views as devices_views +#from login import views as login_views + + +urlpatterns = [ + + path('admin/', admin.site.urls), + path('',devices_views.index), + path('apps/',devices_views.apps), + path('appDownload/', devices_views.appDownload), + path('appDelete/', devices_views.appDelete), + path('appstore/',devices_views.store), +## path('apps/appstore/',devices_views.storeofdevic), +## path('search/',devices_views.search), + path('upload',devices_views.uploadapps), + path('removeapps/',devices_views.removeapps), + path('help/',devices_views.help), + +] + + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/wsgi.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/wsgi.py new file mode 100755 index 000000000..45e28c9a1 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/mysite/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for mysite project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') + +application = get_wsgi_application() diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/server/Dockerfile b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/server/Dockerfile new file mode 100644 index 000000000..371fa45b0 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/server/Dockerfile @@ -0,0 +1,6 @@ +FROM python:3.5 + +WORKDIR /app +COPY server/wasm_server.py /app/server/ + +ENTRYPOINT ["python", "server/wasm_server.py"] diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/server/wasm_server.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/server/wasm_server.py new file mode 100755 index 000000000..970ec6f60 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/server/wasm_server.py @@ -0,0 +1,621 @@ +''' + /* Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ +''' +import select +import socket +import queue +from time import sleep +import struct +import threading +import time +from ctypes import * +import json +import logging +import os + +attr_type_list = [ + "ATTR_TYPE_BYTE", # = ATTR_TYPE_INT8 + "ATTR_TYPE_SHORT",# = ATTR_TYPE_INT16 + "ATTR_TYPE_INT", # = ATTR_TYPE_INT32 + "ATTR_TYPE_INT64", + "ATTR_TYPE_UINT8", + "ATTR_TYPE_UINT16", + "ATTR_TYPE_UINT32", + "ATTR_TYPE_UINT64", + "ATTR_TYPE_FLOAT", + "ATTR_TYPE_DOUBLE", + "ATTR_NONE", + "ATTR_NONE", + "ATTR_TYPE_BOOLEAN", + "ATTR_TYPE_STRING", + "ATTR_TYPE_BYTEARRAY" +] + + +Phase_Non_Start = 0 +Phase_Leading = 1 +Phase_Type = 2 +Phase_Size = 3 +Phase_Payload = 4 + + + +class imrt_link_message(object): + def __init__(self): + self.leading = bytes([0x12, 0x34]) + self.phase = Phase_Non_Start + self.size_in_phase = 0 + self.message_type = bytes() + self.message_size = bytes() + self.payload = bytes() + self.msg = bytes() + + def set_recv_phase(self, phase): + self.phase = phase + + def on_imrt_link_byte_arrive(self, ch): + self.msg += ch + if self.phase == Phase_Non_Start: + if ch == b'\x12': + self.set_recv_phase(Phase_Leading) + else: + return -1 + elif self.phase == Phase_Leading: + if ch == b'\x34': + self.set_recv_phase(Phase_Type) + else: + self.set_recv_phase(Phase_Non_Start) + return -1 + elif self.phase == Phase_Type: + self.message_type += ch + self.size_in_phase += 1 + + if self.size_in_phase == 2: + (self.message_type, ) = struct.unpack('!H', self.message_type) + self.size_in_phase = 0 + self.set_recv_phase(Phase_Size) + elif self.phase == Phase_Size: + self.message_size += ch + self.size_in_phase += 1 + + if self.size_in_phase == 4: + (self.message_size, ) = struct.unpack('!I', self.message_size) + self.size_in_phase = 0 + self.set_recv_phase(Phase_Payload) + + if self.message_size == b'\x00': + self.set_recv_phase(Phase_Non_Start) + return 0 + + self.set_recv_phase(Phase_Payload) + + elif self.phase == Phase_Payload: + self.payload += ch + self.size_in_phase += 1 + + if self.size_in_phase == self.message_size: + self.set_recv_phase(Phase_Non_Start) + return 0 + + return 2 + + return 1 + + + +def read_file_to_buffer(file_name): + file_object = open(file_name, 'rb') + buffer = None + + if not os.path.exists(file_name): + logging.error("file {} not found.".format(file_name)) + return "file not found" + + try: + buffer = file_object.read() + finally: + file_object.close() + + return buffer + +def decode_attr_container(msg): + + attr_dict = {} + + buf = msg[26 : ] + (total_len, tag_len) = struct.unpack('@IH', buf[0 : 6]) + tag_name = buf[6 : 6 + tag_len].decode() + buf = buf[6 + tag_len : ] + (attr_num, ) = struct.unpack('@H', buf[0 : 2]) + buf = buf[2 : ] + + logging.info("parsed attr:") + logging.info("total_len:{}, tag_len:{}, tag_name:{}, attr_num:{}" + .format(str(total_len), str(tag_len), str(tag_name), str(attr_num))) + + for i in range(attr_num): + (key_len, ) = struct.unpack('@H', buf[0 : 2]) + key_name = buf[2 : 2 + key_len - 1].decode() + buf = buf[2 + key_len : ] + (type_index, ) = struct.unpack('@c', buf[0 : 1]) + + attr_type = attr_type_list[int(type_index[0])] + buf = buf[1 : ] + + if attr_type == "ATTR_TYPE_BYTE": # = ATTR_TYPE_INT8 + (attr_value, ) = struct.unpack('@c', buf[0 : 1]) + buf = buf[1 : ] + # continue + elif attr_type == "ATTR_TYPE_SHORT": # = ATTR_TYPE_INT16 + (attr_value, ) = struct.unpack('@h', buf[0 : 2]) + buf = buf[2 : ] + # continue + elif attr_type == "ATTR_TYPE_INT": # = ATTR_TYPE_INT32 + (attr_value, ) = struct.unpack('@i', buf[0 : 4]) + buf = buf[4 : ] + # continue + elif attr_type == "ATTR_TYPE_INT64": + (attr_value, ) = struct.unpack('@q', buf[0 : 8]) + buf = buf[8 : ] + # continue + elif attr_type == "ATTR_TYPE_UINT8": + (attr_value, ) = struct.unpack('@B', buf[0 : 1]) + buf = buf[1 : ] + # continue + elif attr_type == "ATTR_TYPE_UINT16": + (attr_value, ) = struct.unpack('@H', buf[0 : 2]) + buf = buf[2 : ] + # continue + elif attr_type == "ATTR_TYPE_UINT32": + (attr_value, ) = struct.unpack('@I', buf[0 : 4]) + buf = buf[4 : ] + # continue + elif attr_type == "ATTR_TYPE_UINT64": + (attr_value, ) = struct.unpack('@Q', buf[0 : 8]) + buf = buf[8 : ] + # continue + elif attr_type == "ATTR_TYPE_FLOAT": + (attr_value, ) = struct.unpack('@f', buf[0 : 4]) + buf = buf[4 : ] + # continue + elif attr_type == "ATTR_TYPE_DOUBLE": + (attr_value, ) = struct.unpack('@d', buf[0 : 8]) + buf = buf[8 : ] + # continue + elif attr_type == "ATTR_TYPE_BOOLEAN": + (attr_value, ) = struct.unpack('@?', buf[0 : 1]) + buf = buf[1 : ] + # continue + elif attr_type == "ATTR_TYPE_STRING": + (str_len, ) = struct.unpack('@H', buf[0 : 2]) + attr_value = buf[2 : 2 + str_len - 1].decode() + buf = buf[2 + str_len : ] + # continue + elif attr_type == "ATTR_TYPE_BYTEARRAY": + (byte_len, ) = struct.unpack('@I', buf[0 : 4]) + attr_value = buf[4 : 4 + byte_len] + buf = buf[4 + byte_len : ] + # continue + + attr_dict[key_name] = attr_value + + logging.info(str(attr_dict)) + return attr_dict + +class Request(): + mid = 0 + url = "" + action = 0 + fmt = 0 + payload = "" + payload_len = 0 + sender = 0 + + def __init__(self, url, action, fmt, payload, payload_len): + self.url = url + self.action = action + self.fmt = fmt + # if type(payload) == bytes: + # self.payload = bytes(payload, encoding = "utf8") + # else: + self.payload_len = payload_len + if self.payload_len > 0: + self.payload = payload + + + def pack_request(self): + url_len = len(self.url) + 1 + buffer_len = url_len + self.payload_len + + req_buffer = struct.pack('!2BH2IHI',1, self.action, self.fmt, self.mid, self.sender, url_len, self.payload_len) + for i in range(url_len - 1): + req_buffer += struct.pack('!c', bytes(self.url[i], encoding = "utf8")) + req_buffer += bytes([0]) + for i in range(self.payload_len): + req_buffer += struct.pack('!B', self.payload[i]) + + return req_buffer, len(req_buffer) + + + def send(self, conn, is_install): + leading = struct.pack('!2B', 0x12, 0x34) + + if not is_install: + msg_type = struct.pack('!H', 0x0002) + else: + msg_type = struct.pack('!H', 0x0004) + buff, buff_len = self.pack_request() + lenth = struct.pack('!I', buff_len) + + try: + conn.send(leading) + conn.send(msg_type) + conn.send(lenth) + conn.send(buff) + except socket.error as e: + logging.error("device closed") + for dev in tcpserver.devices: + if dev.conn == conn: + tcpserver.devices.remove(dev) + return -1 + + +def query(conn): + req = Request("/applet", 1, 0, "", 0) + if req.send(conn, False) == -1: + return "fail" + time.sleep(0.05) + try: + receive_context = imrt_link_message() + start = time.time() + while True: + if receive_context.on_imrt_link_byte_arrive(conn.recv(1)) == 0: + break + elif time.time() - start >= 5.0: + return "fail" + query_resp = receive_context.msg + print(query_resp) + except OSError as e: + logging.error("OSError exception occur") + return "fail" + + res = decode_attr_container(query_resp) + + logging.info('Query device infomation success') + return res + +def install(conn, app_name, wasm_file): + wasm = read_file_to_buffer(wasm_file) + if wasm == "file not found": + return "failed to install: file not found" + + print("wasm file len:") + print(len(wasm)) + req = Request("/applet?name=" + app_name, 3, 98, wasm, len(wasm)) + if req.send(conn, True) == -1: + return "fail" + time.sleep(0.05) + try: + receive_context = imrt_link_message() + start = time.time() + while True: + if receive_context.on_imrt_link_byte_arrive(conn.recv(1)) == 0: + break + elif time.time() - start >= 5.0: + return "fail" + msg = receive_context.msg + except OSError as e: + logging.error("OSError exception occur") + # TODO: check return message + + if len(msg) == 24 and msg[8 + 1] == 65: + logging.info('Install application success') + return "success" + else: + res = decode_attr_container(msg) + logging.warning('Install application failed: %s' % (str(res))) + print(str(res)) + + return str(res) + + +def uninstall(conn, app_name): + req = Request("/applet?name=" + app_name, 4, 99, "", 0) + if req.send(conn, False) == -1: + return "fail" + time.sleep(0.05) + try: + receive_context = imrt_link_message() + start = time.time() + while True: + if receive_context.on_imrt_link_byte_arrive(conn.recv(1)) == 0: + break + elif time.time() - start >= 5.0: + return "fail" + msg = receive_context.msg + except OSError as e: + logging.error("OSError exception occur") + # TODO: check return message + + if len(msg) == 24 and msg[8 + 1] == 66: + logging.info('Uninstall application success') + return "success" + else: + res = decode_attr_container(msg) + logging.warning('Uninstall application failed: %s' % (str(res))) + print(str(res)) + + return str(res) + +class Device: + def __init__(self, conn, addr, port): + self.conn = conn + self.addr = addr + self.port = port + self.app_num = 0 + self.apps = [] + +cmd = [] + +class TCPServer: + def __init__(self, server, server_address, inputs, outputs, message_queues): + # Create a TCP/IP + self.server = server + self.server.setblocking(False) + + # Bind the socket to the port + self.server_address = server_address + print('starting up on %s port %s' % self.server_address) + self.server.bind(self.server_address) + + # Listen for incoming connections + self.server.listen(10) + + self.cmd_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.cmd_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) + + self.cmd_sock.bind(('127.0.0.1', 8889)) + self.cmd_sock.listen(5) + + + # Sockets from which we expect to read + self.inputs = inputs + self.inputs.append(self.cmd_sock) + + # Sockets to which we expect to write + # 处理要发送的消息 + self.outputs = outputs + # Outgoing message queues (socket: Queue) + self.message_queues = message_queues + + self.devices = [] + self.conn_dict = {} + + def handler_recever(self, readable): + # Handle inputs + for s in readable: + if s is self.server: + # A "readable" socket is ready to accept a connection + connection, client_address = s.accept() + self.client_address = client_address + print('connection from', client_address) + # this is connection not server + # connection.setblocking(0) + self.inputs.append(connection) + + # Give the connection a queue for data we want to send + # self.message_queues[connection] = queue.Queue() + + res = query(connection) + + if res != "fail": + dev = Device(connection, client_address[0], client_address[1]) + self.devices.append(dev) + self.conn_dict[client_address] = connection + + dev_info = {} + dev_info['addr'] = dev.addr + dev_info['port'] = dev.port + dev_info['apps'] = 0 + + logging.info('A new client connected from ("%s":"%s")' % (dev.conn, dev.port)) + + elif s is self.cmd_sock: + connection, client_address = s.accept() + print("web server socket connected") + logging.info("Django server connected") + self.inputs.append(connection) + self.message_queues[connection] = queue.Queue() + + else: + data = s.recv(1024) + if data != b'': + # A readable client socket has data + logging.info('received "%s" from %s' % (data, s.getpeername())) + + # self.message_queues[s].put(data) + # # Add output channel for response + + # if s not in self.outputs: + # self.outputs.append(s) + + if(data.decode().split(':')[0] == "query"): + if data.decode().split(':')[1] == "all": + resp = [] + print('start query all devices') + for dev in self.devices: + dev_info = query(dev.conn) + if dev_info == "fail": + continue + dev_info["addr"] = dev.addr + dev_info["port"] = dev.port + resp.append(str(dev_info)) + + print(resp) + + if self.message_queues[s] is not None: + # '*' is used in web server to sperate the string + self.message_queues[s].put(bytes("*".join(resp), encoding = 'utf8')) + if s not in self.outputs: + self.outputs.append(s) + else: + client_addr = (data.decode().split(':')[1],int(data.decode().split(':')[2])) + + if client_addr in self.conn_dict.keys(): + print('start query device from (%s:%s)' % (client_addr[0], client_addr[1])) + resp = query(self.conn_dict[client_addr]) + print(resp) + + if self.message_queues[s] is not None: + self.message_queues[s].put(bytes(str(resp), encoding = 'utf8')) + if s not in self.outputs: + self.outputs.append(s) + else: # no connection + if self.message_queues[s] is not None: + self.message_queues[s].put(bytes(str("fail"), encoding = 'utf8')) + if s not in self.outputs: + self.outputs.append(s) + elif(data.decode().split(':')[0] == "install"): + client_addr = (data.decode().split(':')[1],int(data.decode().split(':')[2])) + app_name = data.decode().split(':')[3] + app_file = data.decode().split(':')[4] + + if client_addr in self.conn_dict.keys(): + print('start install application %s to ("%s":"%s")' % (app_name, client_addr[0], client_addr[1])) + res = install(self.conn_dict[client_addr], app_name, app_file) + if self.message_queues[s] is not None: + logging.info("response {} to cmd server".format(res)) + self.message_queues[s].put(bytes(res, encoding = 'utf8')) + if s not in self.outputs: + self.outputs.append(s) + elif(data.decode().split(':')[0] == "uninstall"): + client_addr = (data.decode().split(':')[1],int(data.decode().split(':')[2])) + app_name = data.decode().split(':')[3] + + if client_addr in self.conn_dict.keys(): + print("start uninstall") + res = uninstall(self.conn_dict[client_addr], app_name) + if self.message_queues[s] is not None: + logging.info("response {} to cmd server".format(res)) + self.message_queues[s].put(bytes(res, encoding = 'utf8')) + if s not in self.outputs: + self.outputs.append(s) + + + # if self.message_queues[s] is not None: + # self.message_queues[s].put(data) + # if s not in self.outputs: + # self.outputs.append(s) + else: + logging.warning(data) + + # Interpret empty result as closed connection + try: + for dev in self.devices: + if s == dev.conn: + self.devices.remove(dev) + # Stop listening for input on the connection + if s in self.outputs: + self.outputs.remove(s) + self.inputs.remove(s) + + # Remove message queue + if s in self.message_queues.keys(): + del self.message_queues[s] + s.close() + except OSError as e: + logging.error("OSError raised, unknown connection") + return "got it" + + def handler_send(self, writable): + # Handle outputs + for s in writable: + try: + message_queue = self.message_queues.get(s) + send_data = '' + if message_queue is not None: + send_data = message_queue.get_nowait() + except queue.Empty: + self.outputs.remove(s) + else: + # print "sending %s to %s " % (send_data, s.getpeername) + # print "send something" + if message_queue is not None: + s.send(send_data) + else: + print("client has closed") + # del message_queues[s] + # writable.remove(s) + # print "Client %s disconnected" % (client_address) + return "got it" + + def handler_exception(self, exceptional): + # # Handle "exceptional conditions" + for s in exceptional: + print('exception condition on', s.getpeername()) + # Stop listening for input on the connection + self.inputs.remove(s) + if s in self.outputs: + self.outputs.remove(s) + s.close() + + # Remove message queue + del self.message_queues[s] + return "got it" + + +def event_loop(tcpserver, inputs, outputs): + while inputs: + # Wait for at least one of the sockets to be ready for processing + print('waiting for the next event') + readable, writable, exceptional = select.select(inputs, outputs, inputs) + if readable is not None: + tcp_recever = tcpserver.handler_recever(readable) + if tcp_recever == 'got it': + print("server have received") + if writable is not None: + tcp_send = tcpserver.handler_send(writable) + if tcp_send == 'got it': + print("server have send") + if exceptional is not None: + tcp_exception = tcpserver.handler_exception(exceptional) + if tcp_exception == 'got it': + print("server have exception") + + + sleep(0.1) + +def run_wasm_server(): + server_address = ('localhost', 8888) + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) + inputs = [server] + outputs = [] + message_queues = {} + tcpserver = TCPServer(server, server_address, inputs, outputs, message_queues) + + task = threading.Thread(target=event_loop,args=(tcpserver,inputs,outputs)) + task.start() + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG, + filename='wasm_server.log', + filemode='a', + format= + '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s' + ) + server_address = ('0.0.0.0', 8888) + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) + inputs = [server] + outputs = [] + message_queues = {} + tcpserver = TCPServer(server, server_address, inputs, outputs, message_queues) + logging.info("TCP Server start at {}:{}".format(server_address[0], "8888")) + + task = threading.Thread(target=event_loop,args=(tcpserver,inputs,outputs)) + task.start() + + # event_loop(tcpserver, inputs, outputs)
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/application.css b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/application.css new file mode 100644 index 000000000..220d4b618 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/application.css @@ -0,0 +1,400 @@ +/* Copyright (C) 2019 Intel Corporation. All rights reserved. +* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +*/ + +{% load static %} +<style> +#container{ + position:relative; + margin:0px; + height:110px; +} +#content { + margin:0px 20% 0px 18%; + border:solid 1.5px; + border-color: white black white black; + height:50%; +} +#mainnav{ + display:table; + margin: 0 auto; +} +#mainnav li{ + display: table-cell; + padding-left:10px; +} +#mainnav ul li a{ + width:120px; + height:30px; + background:black; + color:white; + margin:0px 50px; + font-size:21px; + font-family:'sansationlight'; + display:block; + text-align:center; + text-decoration:none; +} +#mainnav ul li a:hover{ + width:120px; + height:33px; + line-height:30px; + border:solid 1.5px; + border-color: black black white black; + color:#3FC3DF; + background:black; +} +.headers{ + background-image: url("{%static 'photo/milky-way-2695569_1280.jpg'%}"); + background-repeat: no-repeat; + background-size: 100% 100%; + color:white; + clear:both; + height:50%; + text-align:center; + padding:10px; + margin:0px; +} +#maintitle{ + font-size:25px; + font-family:'sansationlight'; +} + +#section { + position:relative; + top:5px; + width:100%; + float:left; + height:120px; + border-style:double solid; + border-color:black rgb(194, 194, 190) black rgb(248, 248, 248) ; + border-width:0.5px; + padding:10px; +} +#photo{ + position: relative; + float: left; + top:18%; + left:10%; + widows: 60px; +} +#IPs{ + position: relative; + left: 20%; + top:10%; + width:35%; + font-size:17px; + font-family:'sansationlight'; +} +#ports{ + position: relative; + left: 20%; + top:30%; + bottom: 5%; + width:35%; + font-size:17px; + font-family:'sansationlight'; +} +#installs{ + position: relative; + float: left; + left:55%; + bottom:40%; + font-size:17px; + font-family:'sansationlight'; +} + +#download{ + position:relative; + text-align: center; + left:15%; + width:70%; + top:40px; + height:40px; + /*border-color:#192C4F;*/ +} +.explain{ + width:250px; + height:40px; + top:50%; + float:left; + font-size:18px; +} +#btn{ + float:right; +} + + +#APPS { + position:relative; + top:30px; + left:16.67%; + width:75%; +} +#applications{ + position:relative; + float:left; + background-color:white; + width:88.9%; + height:45px; + padding:2px; + margin:5px 0px; + border-style:double solid; + border-color:black; + border-width:0.5px; +} +#applogo{ + position:relative; + float:left; + top:10% +} +#appinfo1{ position:relative; float:left; left:40px; width:34%;font-size:15px;height:25px;top:33%} +#appinfo2{ position:relative; float:left; left:20px; width:24%;font-size:15px;height:25px;top:33%} +#appinfo3{ position:relative; float:left; left:20px; width:34%;font-size:15px;height:25px;top:33%} + +#delete{ + position:relative; + margin:8px 0px; + float:right; + right:7%; +} +.main{ + position: absolute; + float:left; + width:650px; + height:350px; + z-index: 9999; + background-color: white; + display:none; + border:solid 1px rgb(4, 30, 66); + border-width: 1.5px; + border-radius: 10px; +} +.close{ + background-color: black; + color:white; + border-top-right-radius: 10px; + border-top-left-radius: 10px; +} +.hotapps{ + background-color:rgb(202, 202, 202); + font-size: 16px; + font-family:'days'; + height:30px; + text-align: justify; + border:solid 2px; + border-color: rgb(202, 202, 202) rgb(202, 202, 202) rgb(202, 202, 202) black; +} +#scrollba{ + overflow-x: None; + overflow-y: scroll; + height: 270px; + width:650px; +} +#Dapplications{ + width:630px; + margin:4px 10px 0px 10px; + height:45px; + border:solid 1px; + border-color: rgb(221, 221, 221) white white white; + /* background-color: rgb(233, 233, 233); */ +} +.mybtn2{ + position: relative; + float:left; + left:45px; + top:3px; + height:33px; + border-radius: 10px; + background-color: rgb(22, 109, 121); + color:white; +} +#types{ + background-color: rgb(3, 90, 90); + color:white; + text-align: left +} + + +#loading{ + position:relative; + float:left; + width: 100%; + display:None; + height:40px; + top:10px; + z-index:1010; +} +.loadapp{ + font-size:20px; + text-align: center; + color:rgb(24, 77, 24); +} +#preloader { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; +} +#loader { + display: block; + position: relative; + left: 50%; + top: 50%; + width: 150px; + height: 150px; + margin: -75px 0 0 -75px; + border-radius: 50%; + border: 3px solid transparent; + border-top-color: rgb(135, 155, 241); + -webkit-animation: spin 2s linear infinite; + animation: spin 2s linear infinite; +} +#loader:before { + content: ""; + position: absolute; + top: 5px; + left: 5px; + right: 5px; + bottom: 5px; + border-radius: 50%; + border: 3px solid transparent; + border-top-color: rgb(23, 62, 146); + -webkit-animation: spin 3s linear infinite; + animation: spin 3s linear infinite; +} +#loader:after { + content: ""; + position: absolute; + top: 15px; + left: 15px; + right: 15px; + bottom: 15px; + border-radius: 50%; + border: 3px solid transparent; + border-top-color: rgb(21, 44, 87); + -webkit-animation: spin 1.5s linear infinite; + animation: spin 1.5s linear infinite; +} +@-webkit-keyframes spin { + 0% { + -webkit-transform: rotate(0deg); + -ms-transform: rotate(0deg); + transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(360deg); + -ms-transform: rotate(360deg); + transform: rotate(360deg); + } +} +@keyframes spin { + 0% { + -webkit-transform: rotate(0deg); + -ms-transform: rotate(0deg); + transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(360deg); + -ms-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +.middlebox{ + position:absolute; + z-index:1003; + height:180px; + width:340px; + background-color: white; + border-radius: 7px; + border-style:double; + border-color:rgb(2, 37, 11) solid; + border-width: 0.8px; + display: none; +} +.warning{ + position: absolute; + left:10%; + top:6%; + FONT-size:18px; + color:rgb(0, 85, 0); + height:20%; + width:80%; + border-style:none none dashed none; + border-width: 1px; + border-color:rgb(0, 85, 0); +} +.surebtn{ + position:relative; + float:left; + left:44%; + top:75%; +} +.findapp{ + position:absolute; + left:10%; + height:25%; + top:40%; + width:80%; + font-size:15px; + text-align: center; + border-style:none none solid none; + border-color:rgb(182, 182, 182); + border-width:0.5px; +} + +.deletebox{ + position:absolute; + z-index:1003; + height:180px; + width:340px; + background-color: white; + border-radius: 7px; + border-style:double; + border-color:rgb(43, 9, 1) solid; + border-width: 0.8px; + display: none; +} +.warning2{ + position: absolute; + left:10%; + top:6%; + FONT-size:18px; + color:rgb(185, 0, 0); + height:20%; + width:80%; + border-style:none none dashed none; + border-width: 1px; + border-color:rgb(185, 0, 0); +} +.suresbtn{ + position:relative; + float:left; + left:24%; + top:75%; + color:green +} +.cancelsbtn{ + position:relative; + float:right; + right:20%; + top:75%; + color:red +} +.footer { + position:absolute; + bottom:0px; + left:0px; + background-color:black; + color:white; + clear:both; + text-align:center; + padding:1px; + width:100%; + height:4%; + z-index: 999; +} + + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/appstore.css b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/appstore.css new file mode 100644 index 000000000..1cebcefe9 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/appstore.css @@ -0,0 +1,216 @@ +/* Copyright (C) 2019 Intel Corporation. All rights reserved. +* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +*/ +{% load static %} +<style> +#container{ + position:relative; + margin:0px; + height:110px; +} +#content { + margin:0px 20% 0px 18%; + border:solid 1.5px; + border-color: white black white black; + height:50%; +} +#mainnav{ + display:table; + margin: 0 auto; +} +#mainnav li{ + display: table-cell; + padding-left:10px; +} +#mainnav ul li a{ + width:120px; + height:30px; + background:black; + color:white; + margin:0px 50px; + font-size:21px; + font-family:'sansationlight'; + display:block; + text-align:center; + text-decoration:none; +} +#mainnav ul li a:hover{ + width:120px; + height:33px; + line-height:30px; + border:solid 1.5px; + border-color: black black white black; + color:#3FC3DF; + background:black; +} +.headers{ + background-image: url("{%static 'photo/milky-way-2695569_1280.jpg'%}"); + background-repeat: no-repeat; + background-size: 100% 100%; + color:white; + clear:both; + height:50%; + text-align:center; + padding:10px; + margin:0px; +} +#maintitle{ + font-size:25px; + font-family:'sansationlight'; +} + +#introstore{ + z-index:1003; + top:10px; + margin:10px 220px 10px 220px; + height:108px; +} +#applicationlist{ + margin:26px 0px 0px 0px; + height:100%; +} +.bar{ + height:50px; + top:2px; +} +.leftpart{ + position:relative; + float:left; + left:30px; + font-size:22px; + display:inline-block; + height:30px; + border:solid 1px black; + border-style: none none solid none; +} +.rightpart{ + position:relative; + float:right; + height:50px; + right:20px; + font-size:17px; +} +.rightpart .file{ + width: 120px; + height: 35px; + position: absolute; + left: 0px; + top: 0px; + opacity: 0; + z-index: 2; +} +.stylehere{ + position: relative; + display: inline-block; + width: 120px; + overflow: hidden; + height: 35px; + line-height: 35px; +} +.choosestyle{ + position: absolute; + width: 120px;height: 35px; + background-color: rgb(0, 121, 202);color:white; + text-align: center; + left: 0px;top: 0px; + font-size:14px; + border-radius: 4px +} +.appbook{ + margin:0px; + border:solid; + border-width: 1.5px; + border-color: white rgb(194, 194, 194) white rgb(194, 194, 194); + background-image:linear-gradient(to right, rgb(245, 243, 240),white) +} +#applications{ + margin:1px; + left:0px; + width:100%; + height:50px; + border-style:none none solid none; + border-color:rgb(172, 172, 172); + border-width:0.5px; + padding:5px; +} +#delbutton{ + width:100px; + height:40px; +} +#appimage{ + float:left; + left:5%; +} +#lable{ + color: red; + opacity:50} + .suresbtn{ + position:relative; + float:left; + left:50px; + top:135px; + color:green +} +.deletebox{ + position:absolute; + z-index:1003; + height:180px; + width:340px; + background-color: white; + border-radius: 7px; + border-style:double; + border-color:rgb(43, 9, 1) solid; + border-width: 0.8px; + display: none; +} +.warning2{ + position: absolute; + left:10%; + top:6%; + FONT-size:18px; + color:rgb(185, 0, 0); + height:20%; + width:80%; + border-style:none none dashed none; + border-width: 1px; + border-color:rgb(185, 0, 0); +} +.findapp{ + position:absolute; + left:10%; + height:25%; + top:40%; + width:80%; + font-size:15px; + text-align: center; + border-style:none none solid none; + border-color:rgb(182, 182, 182); + border-width:0.5px; +} +.suresbtn{ + position:relative; + float:left; + left:24%; + top:75%; + color:green +} +.delsbtn{ + position:relative; + float:right; + right:20%; + top:75%; + color:red +} +.footer { + position:absolute; + bottom:0px; + left:0px; + background-color:black; + color:white; + clear:both; + text-align:center; + padding:1px; + width:100%; + height:4%; + z-index: 999; +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/index.css b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/index.css new file mode 100755 index 000000000..d459469a4 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/css/index.css @@ -0,0 +1,197 @@ +/* Copyright (C) 2019 Intel Corporation. All rights reserved. +* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +*/ +{% load static %} +<style> +#container{ + position:relative; + margin:0px; + height:110px; +} +#content { + margin:0px 20% 0px 18%; + border:solid 1.5px; + border-color: white black white black; + height:50%; +} +#mainnav{ + display:table; + margin: 0 auto; +} +#mainnav li{ + display: table-cell; + padding-left:10px; +} +#mainnav ul li a{ + width:120px; + height:30px; + background:black; + color:white; + margin:0px 50px; + font-size:21px; + font-family:'sansationlight'; + display:block; + text-align:center; + text-decoration:none; +} +#mainnav ul li a:hover{ + width:120px; + height:33px; + line-height:30px; + border:solid 1.5px; + border-color: black black white black; + color:#3FC3DF; + background:black; +} +.headers{ + background-image: url("{%static 'photo/milky-way-2695569_1280.jpg'%}"); + background-repeat: no-repeat; + background-size: 100% 100%; + color:white; + clear:both; + height:50%; + text-align:center; + padding:10px; + margin:0px; +} +#maintitle{ + font-size:25px; + font-family:'sansationlight'; +} + +#photo2{ + position: relative; + float: left; + top:10%; + left:20%; +} +#devic{ + position: relative; + font-size:22px; + float: left; + left:25%; + top:30%; + width:40%; +} +#dividebar{ + position: absolute; + top:210px; + margin:10px; + width:100%; + height:1px +} + +#devices { + position:relative; + bottom: 2px; + background-color: #F2F2F2; + height:125px; + width:80%; + margin:8px 10%; +} +#section { + position:relative; + background-color:white; + top:14px; + left:13%; + width: 70%; + float:left; + height:96px; + border-style:double solid; + border-color:black; + border-width:0.5px; + padding:10px; +} +#photo{ + position: relative; + float: left; + top:0px; + left:6%; +} +#ID{ + position:relative; + float:left; + left:12%; + height:20px; + width:8%; + top:75%; + z-index:9999; + /* display:none; */ + font-size:15px; + color:rgba(7, 38, 85, 0.87); +} +#IPs{ + position: relative; + left: 14%; + top:10%; + width:30%; + font-size:17px; + font-family:'sansationlight'; +} +#ports{ + position: relative; + left: 14%; + top:25%; + bottom: 5px; + width:30%; + font-size:17px; + font-family:'sansationlight'; +} +#installs{ + position: relative; + float: right; + right: 20%; + bottom:57%; + font-size:17px; + font-family:'sansationlight'; +} +.smenu{ + position: relative; + float: right; + top:45px; + right: 5%; + width: 6%; +} + +.prev{ + position:absolute; + left:72%; + clear:both; + text-align:center; + padding:1px; + width:100px; + height:30px; + color:grey; + background-color:white; + border-radius:5px; + z-index: 996; +} + +.next{ + position:absolute; + left:80%; + clear:both; + text-align:center; + padding:1px; + width:100px; + height:30px; + color:grey; + background-color:white; + border-radius:5px; + z-index: 996; +} + +.footer { + position:absolute; + bottom:0px; + left:0px; + background-color:black; + color:white; + clear:both; + text-align:center; + padding:1px; + width:100%; + height:4%; + z-index: 999; +} +</style> diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/application.js b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/application.js new file mode 100644 index 000000000..0510fb901 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/application.js @@ -0,0 +1,217 @@ +/* Copyright (C) 2019 Intel Corporation. All rights reserved. +* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +*/ + +/* + * Dom Location + * + */ + + function setDivCenter(divname) +// make qn element center aligned + { + var Top =($(window).height()-$(divname).height())/2; + var Left = ($(window).width()-$(divname).width())/2; + var scrollTop = $(document).scrollTop(); + var scrollLeft = $(document).scrollLeft(); + $(divname).css({posisiton:'absolute','top':Top+scrollTop,'left':Left+scrollLeft}); + +}; + +setDivCenter(".middlebox"); +setDivCenter(".deletebox"); + +function setmain(divname){ +// Set the pop-up window of apps for download at the right place + var x = $('#btn').offset().top; + var Top = x + $('#btn').height()+15; + var y = $('#btn').offset().left; + var Left = y + ($('#btn').width()/2)-($(divname).width()/2); + console.log(Top,Left) + $(divname).css({'top':Top,'left':Left}); +} +setmain(".main") + +/* + * download apps + * + */ + +function getthis(val) +//Telling background which app to be loaded from appstore_list and to be installed in the current device. +{ + + /* Get the ip adress and the port of a device, as well as the application ID to be downloaded on this device*/ + var ip,port,name,version; + var ipArr=$("#IPs").text().split(":"); + ip=ipArr[1]; + var portArr=$("#ports").text().split(":"); + port=portArr[1]; + name = $(val).parent().find("#appsinfo1").text().split(":")[1]; + version = $(val).parent().find("#appsinfo2").text().split(":")[1]; + $(".main").fadeOut(); + + for (num in alist){ + if (alist[num]['pname'].trim() == name.trim()) + {alert("This app has been downloaded."); + return;}}; + $("#loading").fadeIn(); + var sNode = document.getElementById("APPS"); + var tempNode= sNode.cloneNode(true); + sNode.parentNode.appendChild(tempNode); + $("#appinfo1").html("Product Name : "+ name); + $("#appinfo2").html("Status : "+"Installing"); + $("#appinfo3").html("Current_Version : "+ version); + + $.get("/appDownload/",{'ip':ip.trim(),'port':port.trim(),'name':name.trim(),},function (ret) { + var status = $.trim(ret.split(":")[1].split("}")[0]); + $(".loadapp").html(name+" is downloading now"); + var msg = JSON.parse(status) + console.log(msg) + if (JSON.parse(status)=="ok"){ + $(".middlebox").fadeIn(); + $(".sourceapp").fadeOut(); + $("#loading").fadeOut(); + $(".findapp").html("Download "+name +" successfully"); + $(".surebtn").click(function (){ + $(".middlebox").fadeOut(); + window.location.reload(); + })} + else if (JSON.parse(status)=="Fail!"){ + alert("Download failed!"); + $("#loading").fadeOut(); + sNode.remove(); + } + else { + alert("Install app failed:" + msg) + $("#loading").fadeOut(); + sNode.remove(); + } + }) +}; + +window.onload = function clone() +//Add & Delete apps to the device. +{ + /*Install Apps*/ + var sourceNode = document.getElementById("APPS"); + if (alist.length != 0) + { + $("#appinfo1").html("Product Name : "+ alist[0]['pname']); + $("#appinfo2").html("Status : "+ alist[0]['status']); + $("#appinfo3").html("Current_Version : "+ alist[0]['current_version']); + $("#delete").attr('class','delet0'); + $("#APPS").attr('class','app0'); + + for (var i=1; i<alist.length; i++) + { + var cloneNode= sourceNode.cloneNode(true); + sourceNode.parentNode.appendChild(cloneNode); + $("#appinfo1").html("Product Name : "+ alist[i]['pname']); + $("#appinfo2").html("Status : "+ alist[i]['status']); + $("#appinfo3").html("Current_Version : "+ alist[i]['current_version']); + $("#delete").attr('class','delet'+i); + $("#APPS").attr('class','app'+i); + } + } + $("#IPs").html("IP : "+ dlist[0]['IP']); + $("#ports").html("Port : "+ dlist[0]['Port']); + $("#installs").html("Installed Apps : "+ dlist[0]['apps']); + + + + $(".mybtn").click(function () + { + /*uninstall apps*/ + var thisitem = $(this).parent().attr('class'); + var indexa = thisitem.match(/\d+\b/); + var pname = $(".app"+indexa).find('#appinfo1').text(); + + var ip,port; + var ipArr=$("#IPs").text().split(":"); + ip=ipArr[1]; + var portArr=$("#ports").text().split(":"); + port=portArr[1]; + + var name = pname.split(':')[1].trim(); + $(".deletebox").fadeIn(); + $(".findapp").html("Are you sure to delete "+name); + $(".suresbtn").click(function (){ + $(".app"+indexa).remove(); + $.get("/appDelete/",{'ip':ip.trim(),'port':port.trim(),"name":pname.split(':')[1].trim()},function (ret) { + console.log(ret);}); + $(".deletebox").fadeOut(); + window.location.reload(); + }) + $(".cancelsbtn").click(function (){ + $(".deletebox").fadeOut(); }) + }); + +}; + +function getdownloadapps() +{ +/*Acquire apps for download from Appstore simultaneously whenever appstore is updated*/ + if (search_node[0] == "Nothing find"){ + alert(search_node[0]) + } + if (search_node.length == 1 && search_node[0] != "Nothing find" ){ + $("#appsinfo1").html("Product Name : "+ search_node[0]['ID']); + $("#appsinfo2").html("Version : "+ search_node[0]['Version']); + } + else{ + var sourceNode = document.getElementById("Dapplications"); + if (llist.length != 0) + { + $("#appsinfo1").html("Product Name : "+ llist[0]['ID']); + $("#appsinfo2").html("Version : "+ llist[0]['Version']); + $("#Dapplications").attr('class','dapp0'); + + for (var i=1; i<llist.length; i++) + { + var cloneNode= sourceNode.cloneNode(true); + sourceNode.parentNode.appendChild(cloneNode); + $("#appsinfo1").html("Product Name : "+ llist[i]['ID']); + $("#appsinfo2").html("Version : "+ llist[i]['Version']); + $("#Dapplications").attr('class','dapp'+i); + } + }}; +}; + +getdownloadapps(); + +function givevalue(){ + var ip=dlist[0]['IP'].trim(); + var port=dlist[0]['Port'].trim(); + document.getElementById("aa").value = ip; + document.getElementById("bb").value = port; + if (open_status == "open"){ + $(".main").fadeIn(); + $(".close").click(function(){ + $(".main").fadeOut(); + var newurl = "?"+"ip="+ip+"&port="+port; + window.location.href= newurl;}); + $(".mybtn2").click(function(){ + if (alist.length >=3){ + alert("Install app failed: exceed max app installations.") + } + $(".main").fadeOut(); + getthis(".mybtn2"); + var newurl = "?"+"ip="+ip+"&port="+port; + window.location.href= newurl; + }); + + } +} +givevalue(); + +function popbox(){ +/*Open and close the "install apps" window*/ + $(".btn").click(function(){ + $(".main").fadeIn(); + }); + $(".close").click(function(){ + $(".main").fadeOut(); + }); +}; +popbox(); diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/appstore.js b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/appstore.js new file mode 100644 index 000000000..71d029efa --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/appstore.js @@ -0,0 +1,125 @@ +/* Copyright (C) 2019 Intel Corporation. All rights reserved. +* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +*/ + +function setDivCenter(divname) +//Center a dom +{ + var Top =($(window).height()-$(divname).height())/2; + var Left = ($(window).width()-$(divname).width())/2; + var scrollTop = $(document).scrollTop(); + var scrollLeft = $(document).scrollLeft(); + $(divname).css({posisiton:'absolute','top':Top+scrollTop,'left':Left+scrollLeft}); + +}; +setDivCenter(".deletebox"); + +function setDivheight(divname) +//set the height of "appbook" to contain all its child elements. +{ + var leng = elist.length + flist.length; + var heig = 51 * leng; + $(divname).css({height:'heig'}); +}; +setDivheight(".appbook"); + +function setfooterposition(divname) +//Locate footer on the right place +{ + var Top = flist.length* $("#devices").height()+300; + var scrollTop = $(document).scrollTop(); + if (flist.length >=4){ + $(divname).css({posisiton:'absolute','top':Top+scrollTop}); + } +} +setfooterposition(".footer"); + +function deleteClick (obj) +//Remove an app from apppstore if clicks the "OK" button +{ + var indexapp = $(obj).attr('class').match(/\d+\b/); + var removeitem = $(".applic"+indexapp); + var name=removeitem.find('#appinfo1').text().split(":")[1].trim(); + var version=removeitem.find('#appinfo2').text().split(":")[1].trim(); + + if (flist.length >= 1){ + $(".deletebox").fadeIn(); + $(".findapp").html("Are you sure to delete "+name); + $(".suresbtn").click(function (){ + removeitem.remove(); + $.get("/removeapps/",{'name':name,'version':version},function (ret) { + console.log(ret);}); + $(".deletebox").fadeOut(); + window.location.href="/appstore/"; + }) + $(".delsbtn").click(function (){ + $(".deletebox").fadeOut(); })} +}; + +function upload_file() +//Make sure the uploading file is eligible +{ + var type = ulist[0]; + console.log(type); + if (type == "Not a wasm file"){ + alert(type); + window.location.href="/appstore/"; + } + if (type == "This App is preloaded"){ + alert(type); + window.location.href="/appstore/"; + } + if (type == "This App is already uploaded"){ + alert(type); + window.location.href="/appstore/"; + } +}; +upload_file(); + + +function clone() +//Render a interface that shows all the apps for installing in appstore, +//including preloaded ones and locally uploaded ones. +{ + + var sourceNode = document.getElementById("applications"); + $("#appinfo1").html("product name : "+ elist[0]['ID']); + $("#appinfo2").html("product Version : "+ elist[0]['Version']); + $("#delbutton").attr('class','del0'); + $("#applications").attr('class','applic0'); + + + for (var i=1; i<elist.length; i++) + { + var cloneNode= sourceNode.cloneNode(true); + sourceNode.parentNode.appendChild(cloneNode); + $("#appinfo1").html("product name : "+ elist[i]['ID']); + $("#appinfo2").html("product Version : "+ elist[i]['Version']); + $("#delbutton").attr('class','del'+i); + $("#applications").attr('class','applic'+i); + + } + + for (var i = elist.length; i< elist.length + flist.length; i++) + { + var cloneNode= sourceNode.cloneNode(true); + sourceNode.parentNode.appendChild(cloneNode); + $("#appinfo1").html("product name : "+ flist[i - elist.length]['ID']); + $("#appinfo2").html("product Version : "+ flist[i - elist.length]['Version']); + $("#lable").html("Custom Apps").css("color","green"); + $("#delbutton").attr('class','del'+i); + $("#applications").attr('class','applic'+i); + + } + + for(var i = 0; i < elist.length; i++) + { + var tmp_node = document.getElementsByClassName("del" + i)[0] + tmp_node.disabled = true + } + +}; + +clone(); + + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/index.js b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/index.js new file mode 100644 index 000000000..b5850bd13 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/js/index.js @@ -0,0 +1,51 @@ +/* Copyright (C) 2019 Intel Corporation. All rights reserved. +* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +*/ + +function setfooterposition(divname) +//Locate footer on the right place +{ + var Top = dlist.length* $("#devices").height()+300; + var scrollTop = $(document).scrollTop(); + if (dlist.length >=4){ + $(divname).css({posisiton:'absolute','top':Top+scrollTop}); + } +} +setfooterposition(".footer"); + +window.onload = function clone() +//Show the list of connected devices +{ + var sourceNode = document.getElementById("devices"); + $("#IPs").html("IP : "+ dlist[0]['IP']); + $("#ports").html("Port : "+ dlist[0]['Port']); + $("#installs").html("Installed Apps : "+ dlist[0]['apps']); + $("#devices").attr('class','devic0'); + $("#dbutton").attr('class','bt0'); + $("#choose").attr('class','chos0'); + + for (var i=1; i<dlist.length; i++) + { + var cloneNode= sourceNode.cloneNode(true); + sourceNode.parentNode.appendChild(cloneNode); + $("#IPs").html("IP : "+ dlist[i]['IP']); + $("#ports").html("Port : "+ dlist[i]['Port']); + $("#installs").html("Installed Apps : "+ dlist[i]['apps']); + $("#devices").attr('class','devic'+i); + $("#dbutton").attr('class','bt'+i); + $("#choose").attr('class','chos'+i); + } + +}; + +function deviceClick(obj){ +//Render to the application.html + var deviceObj=$(obj); + var ip=deviceObj.find('#IPs').text(); + ip=ip.split(':')[1].split(' ')[1] + var port=deviceObj.find('#ports').text(); + port=port.split(':')[1].split(' ')[1] + var newurl = "apps/?"+"ip="+ip+"&port="+port; + window.location.href= newurl; +} + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/app(1).png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/app(1).png Binary files differnew file mode 100644 index 000000000..661750e54 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/app(1).png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/application.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/application.png Binary files differnew file mode 100755 index 000000000..f4c7a3e90 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/application.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/delete.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/delete.png Binary files differnew file mode 100755 index 000000000..73e456815 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/delete.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/download(1).png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/download(1).png Binary files differnew file mode 100644 index 000000000..9a68da599 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/download(1).png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/menu.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/menu.png Binary files differnew file mode 100755 index 000000000..919da3519 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/menu.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/milky-way-2695569_1280.jpg b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/milky-way-2695569_1280.jpg Binary files differnew file mode 100755 index 000000000..61d935b7f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/milky-way-2695569_1280.jpg diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/net_device.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/net_device.png Binary files differnew file mode 100755 index 000000000..e988a6aa1 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/net_device.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/software-icon-32081.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/software-icon-32081.png Binary files differnew file mode 100644 index 000000000..cab8cdaef --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/software-icon-32081.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/totalblack.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/totalblack.png Binary files differnew file mode 100644 index 000000000..85723f893 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/photo/totalblack.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/connection.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/connection.wasm Binary files differnew file mode 100644 index 000000000..936e80cf6 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/connection.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/event_publisher.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/event_publisher.wasm Binary files differnew file mode 100644 index 000000000..31dc1018f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/event_publisher.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/event_subscriber.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/event_subscriber.wasm Binary files differnew file mode 100644 index 000000000..1dce622f4 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/event_subscriber.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/request_handler.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/request_handler.wasm Binary files differnew file mode 100644 index 000000000..85959790f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/request_handler.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/request_sender.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/request_sender.wasm Binary files differnew file mode 100644 index 000000000..ce9a6f6e8 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/request_sender.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sensor.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sensor.wasm Binary files differnew file mode 100644 index 000000000..f24bd1009 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sensor.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/simple b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/simple Binary files differnew file mode 100755 index 000000000..478a0f85f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/simple diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/connection.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/connection.wasm Binary files differnew file mode 100644 index 000000000..936e80cf6 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/connection.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/event_publisher.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/event_publisher.wasm Binary files differnew file mode 100644 index 000000000..31dc1018f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/event_publisher.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/event_subscriber.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/event_subscriber.wasm Binary files differnew file mode 100644 index 000000000..1dce622f4 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/event_subscriber.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/request_handler.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/request_handler.wasm Binary files differnew file mode 100644 index 000000000..85959790f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/request_handler.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/request_sender.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/request_sender.wasm Binary files differnew file mode 100644 index 000000000..ce9a6f6e8 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/request_sender.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/timer.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/timer.wasm Binary files differnew file mode 100644 index 000000000..0bb3c920f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/sys/timer.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/timer.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/timer.wasm Binary files differnew file mode 100644 index 000000000..0bb3c920f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/timer.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/ui_app.wasm b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/ui_app.wasm Binary files differnew file mode 100644 index 000000000..1182ca291 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/ui_app.wasm diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/wasm_runtime_wgl b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/wasm_runtime_wgl Binary files differnew file mode 100755 index 000000000..30f8e92e2 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/IoT-APP-Store-Demo/wasm_django/static/upload/wasm_runtime_wgl diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/binarydump-tool/CMakeLists.txt b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/binarydump-tool/CMakeLists.txt new file mode 100644 index 000000000..d322b42b6 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/binarydump-tool/CMakeLists.txt @@ -0,0 +1,11 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required (VERSION 2.9) + +project(binarydump) + +add_definitions (-Wextra -pedantic -Wno-unused-parameter) + +add_executable (binarydump binarydump.c) + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/binarydump-tool/binarydump.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/binarydump-tool/binarydump.c new file mode 100644 index 000000000..050de6dfa --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/binarydump-tool/binarydump.c @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include <stdio.h> +#include <stdlib.h> +#include <stdbool.h> +#include <string.h> + +static unsigned char * +read_file_to_buffer(const char *filename, int *ret_size) +{ + unsigned char *buffer; + FILE *file; + int file_size, read_size; + + if (!(file = fopen(filename, "r"))) + return NULL; + + fseek(file, 0, SEEK_END); + file_size = ftell(file); + fseek(file, 0, SEEK_SET); + + if (!(buffer = malloc(file_size))) { + fclose(file); + return NULL; + } + + read_size = fread(buffer, 1, file_size, file); + fclose(file); + + if (read_size < file_size) { + free(buffer); + return NULL; + } + + *ret_size = file_size; + + return buffer; +} + +static int +print_help() +{ + printf("Usage: binarydump -o <file> -n <name> input_file\n"); + printf("Options:\n"); + printf(" -o <file> Place the output into <file>\n"); + printf(" -n <name> The name of array <file>\n"); + + return -1; +} + +static bool +bin_file_dump(const unsigned char *file, int size, const char *bin_file_output, + const char *array_name) +{ + unsigned i = 0; + const unsigned char *p = file, *p_end = file + size; + FILE *file_output = fopen(bin_file_output, "wb+"); + + if (!file_output) + return false; + + fprintf(file_output, "\nunsigned char __aligned(4) %s[] = {\n ", + array_name); + + while (p < p_end) { + fprintf(file_output, "0x%02X", *p++); + + if (p == p_end) + break; + + fprintf(file_output, ","); + + if ((++i % 12) != 0) + fprintf(file_output, " "); + else + fprintf(file_output, "\n "); + } + + fprintf(file_output, "\n};\n"); + + fclose(file_output); + return true; +} + +int +main(int argc, char *argv[]) +{ + unsigned char *file; + int size; + bool ret; + const char *bin_file_input, *array_file_output = NULL, *array_name = NULL; + + for (argc--, argv++; argc > 0 && argv[0][0] == '-'; argc--, argv++) { + if (!strcmp(argv[0], "-o")) { + ++argv; + if (--argc == 0) + return print_help(); + array_file_output = *argv; + } + else if (!strcmp(argv[0], "-n")) { + ++argv; + if (--argc == 0) + return print_help(); + array_name = *argv; + } + else + return print_help(); + } + + if (!array_file_output || !array_name) + return print_help(); + + bin_file_input = *argv; + + if (!(file = read_file_to_buffer(bin_file_input, &size))) + return -1; + + ret = bin_file_dump(file, size, array_file_output, array_name); + + free(file); + + return ret ? 0 : -1; +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/README.md b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/README.md new file mode 100644 index 000000000..c72d0fcb8 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/README.md @@ -0,0 +1,56 @@ +# Component Test + +The purpose of this test suite is to verify the basic components of WAMR work well in combination. It is highly recommended to run pass all suites before each commitment. + +Prerequisites +============== +- clang is available to build wasm application. +- python is installed to run test script. + + +Run the test +============= +``` +start.py [-h] [-s SUITE_ID [SUITE_ID ...]] [-t CASE_ID [CASE_ID ...]] + [-n REPEAT_TIME] [--shuffle_all] + [--cases_list CASES_LIST_FILE_PATH] [--skip_proc] + [-b BINARIES] [-d] [--rebuild] +``` +It builds out the simple project binary including WAMR runtime binary ```simple``` and the testing tool ```host_tool``` before running the test suites. + +Test output is like: +``` +Test Execution Summary: + Success: 8 + Cases fails: 0 + Setup fails: 0 + Case load fails: 0 + + +------------------------------------------------------------ +The run folder is [run-03-23-16-29] +that's all. bye +kill to quit.. +Killed +``` + +The detailed report and log is generated in ```run``` folder. The binaries copy is also put in that folder. + +Usage samples +============== + +Run default test suite: +</br> +```python start.py``` + +Rebuild all test apps and then run default test suite: +</br> +```python start.py --rebuild``` + +Run a specified test suite: +</br> +```python start.py -s 01-life-cycle``` + +Run a specified test case: +</br> +```python start.py -t 01-install```
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/__init__.py new file mode 100644 index 000000000..fd734d561 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/__init__.py @@ -0,0 +1,11 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +__all__ = [ + "net_manager", "wifi_daemon_utils" +] + +__author__ = "" +__package__ = "model" +__version__ = "1.0" diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/__init__.py new file mode 100644 index 000000000..fd734d561 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/__init__.py @@ -0,0 +1,11 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +__all__ = [ + "net_manager", "wifi_daemon_utils" +] + +__author__ = "" +__package__ = "model" +__version__ = "1.0" diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/case_base.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/case_base.py new file mode 100644 index 000000000..311de5eaa --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/case_base.py @@ -0,0 +1,29 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import os +import json +from test.test_support import _run_suite + +class CTestCaseBase(object): + def __init__(self, suite): + self.m_suite = suite + return + def on_get_case_description(self): + return "Undefined" + + def on_setup_case(self): + return True, '' + + def on_cleanup_case(self): + return True, '' + + # called by the framework + def on_run_case(self): + return True, '' + + def get_suite(self): + return self.m_suite + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/engine.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/engine.py new file mode 100644 index 000000000..6c68a1eb1 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/engine.py @@ -0,0 +1,39 @@ +from __future__ import print_function +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import datetime +import os +import pprint +import random +import re +import shlex +import subprocess +import signal +import sys +import time + +from .test_utils import * +from .test_api import * + + + + +def read_cases_from_file(file_path): + if not os.path.exists(file_path): + return False, None + + with open(file_path, 'r') as f: + content = f.readlines() + + content = [x.strip() for x in content] + print(content) + if len(content) == 0: + return False, None + + return True, content + + + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/framework.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/framework.py new file mode 100644 index 000000000..99f0b0772 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/framework.py @@ -0,0 +1,288 @@ +from __future__ import print_function +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import datetime +import os +import pprint +import random +import re +import shlex +import subprocess +import signal +import sys +import time +import shutil + +from .test_api import * +import this + + +''' +The run evironment dir structure: + + run/ + run{date-time}/ + suites/ + {suite name}/ + -- target/ (the target software being tested) + -- tools/ (the tools for testing the target software) +''' + + +framework=None + +def get_framework(): + global framework + return framework + +def my_import(name): + mod = __import__(name) + components = name.split('.') + for comp in components[1:]: + mod = getattr(mod, comp) + return mod + + +# we maintain a root path apart from framework location +# so the suites can be located in anywhere +class CTestFramework(object): + + def __init__(self, path): + self.running_case = '' + self.running_suite = '' + self.target_suites = {} + self.target_cases = {} + self.root_path = path + self.running_folder='' + self.report = None + self.sucess_cases = 0 + self.failed_cases = 0 + self.setup_fails = 0 + self.load_fails = 0; + global framework + framework = self + + api_set_root_path(path) + + print("root_path is " + self.root_path) + + def gen_execution_stats(self): + return '\nTest Execution Summary: ' \ + '\n\tSuccess: {}' \ + '\n\tCases fails: {}' \ + '\n\tSetup fails: {}' \ + '\n\tCase load fails: {}'.format( + self.sucess_cases, self.failed_cases, self.setup_fails, self.load_fails) + + def report_result(self, success, message, case_description): + if self.report is None: + return + + case_pass = "pass" + if not success: + case_pass = "fail" + + self.report.write(case_pass + ": [" + self.running_case + "]\n\treason: " + \ + message + "\n\tcase: " + case_description + "\n") + return + + def get_running_path(self): + return self.root_path + "/run/" + self.running_folder + + def load_suites(self): + self.target_suites = os.listdir(self.root_path + "/suites") + return + + def run_case(self, suite_instance, case): + # load the test case module + case_description = '' + suite = suite_instance.m_name + api_log("\n>>start run [" + case + "] >>") + module_name = 'suites.' + suite + ".cases." + case + ".case" + try: + module = my_import(module_name) + except Exception as e: + report_fail("load case fail: " + str(e)) + api_log_error("load case fail: " + str(e)) + self.load_fails = self.load_fails +1 + print(traceback.format_exc()) + return False + + try: + case = module.CTestCase(suite_instance) + except Exception as e: + report_fail("initialize case fail: " + str(e)) + api_log_error("initialize case fail: " + str(e)) + self.load_fails = self.load_fails +1 + return False + + # call the case on setup callback + try: + case_description = case.on_get_case_description() + result, message = case.on_setup_case() + except Exception as e: + result = False + message = str(e); + if not result: + api_log_error(message) + report_fail (message, case_description) + self.failed_cases = self.failed_cases+1 + return False + + # call the case execution callaback + try: + result, message = case.on_run_case() + except Exception as e: + result = False + message = str(e); + if not result: + report_fail (message, case_description) + api_log_error(message) + self.failed_cases = self.failed_cases+1 + else: + report_success(case_description) + self.sucess_cases = self.sucess_cases +1 + + # call the case cleanup callback + try: + clean_result, message = case.on_cleanup_case() + except Exception as e: + clean_result = False + message = str(e) + + if not clean_result: + api_log(message) + + return result + + def run_suite(self, suite, cases): + # suite setup + message = '' + api_log("\n>>> Suite [" + suite + "] starting >>>") + running_folder = self.get_running_path()+ "/suites/" + suite; + + module_name = 'suites.' + suite + ".suite_setup" + try: + module = my_import(module_name) + except Exception as e: + report_fail("load suite [" + suite +"] fail: " + str(e)) + self.load_fails = self.load_fails +1 + return False + + try: + suite_instance = module.CTestSuite(suite, \ + self.root_path + '/suites/' + suite, running_folder) + except Exception as e: + report_fail("initialize suite fail: " + str(e)) + self.load_fails = self.load_fails +1 + return False + + result, message = suite_instance.load_settings() + if not result: + report_fail("load settings fail: " + str(e)) + self.load_fails = self.load_fails +1 + return False + + try: + result, message = suite_instance.on_suite_setup() + except Exception as e: + result = False + message = str(e); + if not result: + api_log_error(message) + report_fail (message) + self.setup_fails = self.setup_fails + 1 + return False + + self.running_suite = suite + + cases.sort() + + # run cases + for case in cases: + if not os.path.isdir(self.root_path + '/suites/' + suite + '/cases/' + case): + continue + + self.running_case = case + self.run_case(suite_instance, case) + self.running_case = '' + + # suites cleanup + self.running_suite = '' + try: + result, message = suite_instance.on_suite_cleanup() + except Exception as e: + result = False + message = str(e); + if not result: + api_log_error(message) + report_fail (message) + self.setup_fails = self.setup_fails + 1 + return + + def start_run(self): + if self.target_suites is None: + print("\n\nstart run: no target suites, exit..") + return + + cur_time = time.localtime() + time_prefix = "{:02}-{:02}-{:02}-{:02}".format( + cur_time.tm_mon, cur_time.tm_mday, cur_time.tm_hour, cur_time.tm_min) + + debug = api_get_value('debug', False) + if debug: + self.running_folder = 'debug' + else: + self.running_folder = 'run-' + time_prefix + + folder = self.root_path + "/run/" +self.running_folder; + + if os.path.exists(folder): + shutil.rmtree(folder, ignore_errors=True) + + if not os.path.exists(folder): + os.makedirs(folder ) + os.makedirs(folder + "/suites") + + api_init_log(folder + "/test.log") + + self.report = open(folder + "/report.txt", 'a') + + self.target_suites.sort() + + for suite in self.target_suites: + if not os.path.isdir(self.root_path + '/suites/' + suite): + continue + self.report.write("suite " + suite + " cases:\n") + if self.target_cases is None: + cases = os.listdir(self.root_path + "/suites/" + suite + "/cases") + self.run_suite(suite, cases) + else: + self.run_suite(suite, self.target_cases) + self.report.write("\n") + + self.report.write("\n\n") + summary = self.gen_execution_stats() + self.report.write(summary); + self.report.flush() + self.report.close() + print(summary) + + +def report_fail(message, case_description=''): + global framework + if framework is not None: + framework.report_result(False, message, case_description) + + api_log_error(message) + + return + +def report_success(case_description=''): + global framework + if framework is not None: + framework.report_result(True , "OK", case_description) + return diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/suite.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/suite.py new file mode 100644 index 000000000..2b690b08f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/suite.py @@ -0,0 +1,40 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import os +import json + +class CTestSuiteBase(object): + def __init__(self, name, suite_path, run_path): + self.suite_path=suite_path + self.run_path=run_path + self.m_name = name + self.settings = {} + + def get_settings_item(self, item): + if item in self.settings: + return self.settings[item] + else: + return None + + def load_settings(self): + path = self.suite_path + "/settings.cfg" + if os.path.isfile(path): + try: + fp = open(path, 'r') + self.settings = json.load(fp) + fp.close() + except Exception, e: + return False, 'Load settings fail: ' + e.message + return True, 'OK' + else: + return True, 'No file' + + def on_suite_setup(self): + return True, 'OK' + + def on_suite_cleanup(self): + return True, 'OK' + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/test_api.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/test_api.py new file mode 100644 index 000000000..82a7e6dd0 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/test_api.py @@ -0,0 +1,99 @@ +from __future__ import print_function +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import logging +import threading +from .test_utils import * + +global logger +logger = None + +def api_init_log(log_path): + global logger + print("api_init_log: " + log_path) + logger = logging.getLogger(__name__) + + logger.setLevel(level = logging.INFO) + handler = logging.FileHandler(log_path) + handler.setLevel(logging.INFO) + formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') + handler.setFormatter(formatter) + + console = logging.StreamHandler() + console.setLevel(logging.INFO) + + logger.addHandler(handler) + logger.addHandler(console) + + return + +def api_log(message): + global logger + if logger is None: + print(message) + else: + logger.info (message) + return + +def api_log_error(message): + global logger + if logger is None: + print(message) + else: + logger.error (message) + return + +def api_logv(message): + global logger + if logger is None: + print(message) + else: + logger.info(message) + return + +#####################################3 +global g_case_runner_event +def api_wait_case_event(timeout): + global g_case_runner_event + g_case_runner_event.clear() + g_case_runner_event.wait(timeout) + +def api_notify_case_runner(): + global g_case_runner_event + g_case_runner_event.set() + +def api_create_case_event(): + global g_case_runner_event + g_case_runner_event = threading.Event() + +####################################### + +def api_init_globals(): + global _global_dict + _global_dict = {} + +def api_set_value(name, value): + _global_dict[name] = value + +def api_get_value(name, defValue=None): + try: + return _global_dict[name] + except KeyError: + return defValue + + +######################################### +global root_path +def api_set_root_path(root): + global root_path + root_path = root + +def api_get_root_path(): + global root_path + return root_path; + + + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/test_utils.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/test_utils.py new file mode 100644 index 000000000..e3eb645ae --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/framework/test_utils.py @@ -0,0 +1,71 @@ +from __future__ import print_function +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import datetime +import os +import random +import re +import shlex +import subprocess +import sys +import time +import shutil +from subprocess import check_output, CalledProcessError + +def t_getPIDs(process): + try: + pidlist = map(int, check_output(["pidof", process]).split()) + except CalledProcessError: + pidlist = [] + #print process + ':list of PIDs = ' + ', '.join(str(e) for e in pidlist) + return pidlist + + +def t_kill_process_by_name(p_keywords): + pid_list = [] + ps_info = subprocess.check_output(shlex.split("ps aux")).split("\n") + for p in ps_info: + if p_keywords in p: + tmp = p.split(" ") + tmp = [x for x in tmp if len(x) > 0] + pid_list.append(tmp[1]) + + for pid in pid_list: + cmd = "kill -9 {}".format(pid) + subprocess.call(shlex.split(cmd)) + + return pid_list + + + +#proc -> name of the process +#kill = 1 -> search for pid for kill +#kill = 0 -> search for name (default) + +def t_process_exists(proc, kill = 0): + ret = False + processes = t_getPIDs(proc) + + for pid in processes: + if kill == 0: + return True + else: + print("kill [" + proc + "], pid=" + str(pid)) + os.kill((pid), 9) + ret = True + return ret + +def t_copy_files(source_dir, pattern, dest_dir): + files = os.listdir(source_dir) + for file in files: + if file in ('/', '.', '..'): + continue + + if pattern in ('*', '') or files.endswith(pattern): + shutil.copy(source_dir+"/"+ file, dest_dir) + + + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/harness/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/harness/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/harness/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/harness/harness_api.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/harness/harness_api.py new file mode 100644 index 000000000..e35aa6b4c --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/harness/harness_api.py @@ -0,0 +1,150 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import os +import shutil +import subprocess +import json +import time + +from framework import test_api +from framework.test_utils import * + +output = "output.txt" + +def start_env(): + os.system("./start.sh") + +def stop_env(): + os.system("./stop.sh") + time.sleep(0.5) + os.chdir("../") #reset path for other cases in the same suite + +def check_is_timeout(): + line_num = 0 + ft = open(output, 'r') + lines = ft.readlines() + + for line in reversed(lines): + if (line[0:36] == "--------one operation begin.--------"): + break + line_num = line_num + 1 + + ft.close() + if (lines[-(line_num)] == "operation timeout"): + return True + else: + return False + +def parse_ret(file): + ft = open(file, 'a') + ft.writelines("\n") + ft.writelines("--------one operation finish.--------") + ft.writelines("\n") + ft.close() + + ft = open(file, 'r') + for line in reversed(ft.readlines()): + if (line[0:16] == "response status "): + ret = line[16:] + ft.close() + return int(ret) + +def run_host_tool(cmd, file): + ft = open(file, 'a') + ft.writelines("--------one operation begin.--------") + ft.writelines("\n") + ft.close() + os.system(cmd + " -o" + file) + if (check_is_timeout() == True): + return -1 + return parse_ret(file) + +def install_app(app_name, file_name): + return run_host_tool("./host_tool -i " + app_name + " -f ../test-app/" + file_name, output) + +def uninstall_app(app_name): + return run_host_tool("./host_tool -u " + app_name, output) + +def query_app(): + return run_host_tool("./host_tool -q ", output) + +def send_request(url, action, payload): + if (payload is None): + return run_host_tool("./host_tool -r " + url + " -A " + action, output) + else: + return run_host_tool("./host_tool -r " + url + " -A " + action + " -p " + payload, output) + +def register(url, timeout, alive_time): + return run_host_tool("./host_tool -s " + url + " -t " + str(timeout) + " -a " + str(alive_time), output) + +def deregister(url): + return run_host_tool("./host_tool -d " + url, output) + +def get_response_payload(): + line_num = 0 + ft = open(output, 'r') + lines = ft.readlines() + + for line in reversed(lines): + if (line[0:16] == "response status "): + break + line_num = line_num + 1 + + payload_lines = lines[-(line_num):-1] + ft.close() + + return payload_lines + +def check_query_apps(expected_app_list): + if (check_is_timeout() == True): + return False + json_lines = get_response_payload() + json_str = " ".join(json_lines) + json_dict = json.loads(json_str) + app_list = [] + + for key, value in json_dict.items(): + if key[0:6] == "applet": + app_list.append(value) + + if (sorted(app_list) == sorted(expected_app_list)): + return True + else: + return False + +def check_response_payload(expected_payload): + if (check_is_timeout() == True): + return False + json_lines = get_response_payload() + json_str = " ".join(json_lines) + + if (json_str.strip() != ""): + json_dict = json.loads(json_str) + else: + json_dict = {} + + if (json_dict == expected_payload): + return True + else: + return False + +def check_get_event(): + line_num = 0 + ft = open(output, 'r') + lines = ft.readlines() + + for line in reversed(lines): + if (line[0:16] == "response status "): + break + line_num = line_num + 1 + + payload_lines = lines[-(line_num):-1] + ft.close() + + if (payload_lines[1][0:17] == "received an event"): + return True + else: + return False diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/host-clients/src/host_app_sample.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/host-clients/src/host_app_sample.c new file mode 100644 index 000000000..c4010de6a --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/host-clients/src/host_app_sample.c @@ -0,0 +1,301 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include <stdio.h> +#include <string.h> +#include <pthread.h> +#include <unistd.h> +#include "host_api.h" +#include "bi-inc/attr_container.h" +#include "er-coap-constants.h" + +static char * +read_file_to_buffer(const char *filename, int *ret_size); +int send_request_to_applet_success = 0; +const char *label_for_request = "request1"; +int event_listener_counter = 0; +char *applet_buf[1024 * 1024]; +const char *host_agent_ip = "127.0.0.1"; +void +f_aee_response_handler(void *usr_ctx, aee_response_t *response) +{ + if (response == NULL) { + printf("########## request timeout!!! \n"); + } + else { + char *str = (char *)usr_ctx; + printf("#### dump response ####\n"); + printf("#### user data: %s \n", str); + printf("#### status: %d \n", response->status); + if (response->payload != NULL) + attr_container_dump((attr_container_t *)response->payload); + } +} + +void +f_aee_event_listener(const char *url, void *event, int fmt) +{ + printf("######## event is received. url: %s, fmt:%d ############\n", url, + fmt); + + attr_container_t *attr_obj = (attr_container_t *)event; + + attr_container_dump(attr_obj); + /* + if (0 == strcmp(url, "alert/overheat")) + { + event_listener_counter++; + printf("event :%d \n", event_listener_counter); + } + */ +} + +static int +print_menu_and_select(void) +{ + char s[256]; + int choice; + do { + printf("\n"); + printf("1. Install TestApplet1\n"); + printf("2. Install TestApplet2\n"); + printf("3. Install TestApplet3\n"); + printf("4. Uninstall TestApplet1\n"); + printf("5. Uninstall TestApplet2\n"); + printf("6. Uninstall TestApplet3\n"); + printf("7. Send Request to TestApplet1\n"); + printf("8. Register Event to TestApplet1\n"); + printf("9. UnRegister Event to TestApplet1\n"); + printf("a. Query Applets\n"); + printf("t. Auto Test\n"); + printf("q. Exit\n"); + printf("Please Select: "); + + if (fgets(s, sizeof(s), stdin)) { + if (!strncmp(s, "q", 1)) + return 0; + if (!strncmp(s, "a", 1)) + return 10; + if (!strncmp(s, "t", 1)) + return 20; + choice = atoi(s); + if (choice >= 1 && choice <= 9) + return choice; + } + } while (1); + return 0; +} + +static void +install_applet(int index) +{ + char applet_name[64]; + char applet_file_name[64]; + char *buf; + int size; + int ret; + + printf("Installing TestApplet%d...\n", index); + snprintf(applet_name, sizeof(applet_name), "TestApplet%d", index); + snprintf(applet_file_name, sizeof(applet_file_name), "./TestApplet%d.wasm", + index); + buf = read_file_to_buffer(applet_file_name, &size); + if (!buf) { + printf("Install Applet failed: read file %s error.\n", + applet_file_name); + return; + } + + // step2. install applet + ret = aee_applet_install(buf, "wasm", size, applet_name, 5000); + if (ret) { + printf("%s install success\n", applet_name); + } + free(buf); +} + +static void +uninstall_applet(int index) +{ + int ret; + char applet_name[64]; + snprintf(applet_name, sizeof(applet_name), "TestApplet%d", index); + ret = aee_applet_uninstall(applet_name, "wasm", 5000); + if (ret) { + printf("uninstall %s success\n", applet_name); + } + else { + printf("uninstall %s failed\n", applet_name); + } +} + +static void +send_request(int index) +{ + char url[64]; + int ret; + aee_request_t req; + const char *user_context = "label for request"; + attr_container_t *attr_obj = + attr_container_create("Send Request to Applet"); + attr_container_set_string(&attr_obj, "String key", "Hello"); + attr_container_set_int(&attr_obj, "Int key", 1000); + attr_container_set_int64(&attr_obj, "Int64 key", 0x77BBCCDD11223344LL); + + // specify the target wasm app + snprintf(url, sizeof(url), "/app/TestApplet%d/url1", index); + + // not specify the target wasm app + // snprintf(url, sizeof(url), "url1"); + aee_request_init(&req, url, COAP_PUT); + aee_request_set_payload(&req, attr_obj, + attr_container_get_serialize_length(attr_obj), + PAYLOAD_FORMAT_ATTRIBUTE_OBJECT); + ret = aee_request_send(&req, f_aee_response_handler, (void *)user_context, + 10000); + + if (ret) { + printf("send request to TestApplet1 success\n"); + } +} + +static void +register_event(const char *event_path) +{ + hostclient_register_event(event_path, f_aee_event_listener); +} + +static void +unregister_event(const char *event_path) +{ + hostclient_unregister_event(event_path); +} + +static void +query_applets() +{ + aee_applet_list_t applet_lst; + aee_applet_list_init(&applet_lst); + aee_applet_list(5000, &applet_lst); + aee_applet_list_clean(&applet_lst); +} + +static char * +read_file_to_buffer(const char *filename, int *ret_size) +{ + FILE *fl = NULL; + char *buffer = NULL; + int file_size = 0; + if (!(fl = fopen(filename, "rb"))) { + printf("file open failed\n"); + return NULL; + } + + fseek(fl, 0, SEEK_END); + file_size = ftell(fl); + + if (file_size == 0) { + printf("file length 0\n"); + return NULL; + } + + if (!(buffer = (char *)malloc(file_size))) { + fclose(fl); + return NULL; + } + + fseek(fl, 0, SEEK_SET); + + if (!fread(buffer, 1, file_size, fl)) { + printf("file read failed\n"); + return NULL; + } + + fclose(fl); + *ret_size = file_size; + return buffer; +} + +static void +auto_test() +{ + int i; + int interval = 1000; /* ms */ + while (1) { + uninstall_applet(1); + uninstall_applet(2); + uninstall_applet(3); + install_applet(1); + install_applet(2); + install_applet(3); + + for (i = 0; i < 60 * 1000 / interval; i++) { + query_applets(); + send_request(1); + send_request(2); + send_request(3); + usleep(interval * 1000); + } + } +} + +void +exit_program() +{ + hostclient_shutdown(); + exit(0); +} + +int + +main() +{ + bool ret; + + // step1. host client init + ret = hostclient_initialize(host_agent_ip, 3456); + + if (!ret) { + printf("host client initialize failed\n"); + return -1; + } + + do { + int choice = print_menu_and_select(); + printf("\n"); + + if (choice == 0) + exit_program(); + if (choice <= 3) + install_applet(choice); + else if (choice <= 6) + uninstall_applet(choice - 3); + else if (choice <= 7) + send_request(1); + else if (choice <= 8) + register_event("alert/overheat"); + else if (choice <= 9) + unregister_event("alert/overheat"); + else if (choice == 10) + query_applets(); + else if (choice == 20) + auto_test(); + } while (1); + + return 0; +} + +// Run program: Ctrl + F5 or Debug > Start Without Debugging menu +// Debug program: F5 or Debug > Start Debugging menu + +// Tips for Getting Started: +// 1. Use the Solution Explorer window to add/manage files +// 2. Use the Team Explorer window to connect to source control +// 3. Use the Output window to see build output and other messages +// 4. Use the Error List window to view errors +// 5. Go to Project > Add New Item to create new code files, or +// Project > Add Existing Item to add existing code files to the project +// 6. In the future, to open this project again, go to File > Open > Project +// and select the .sln file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/host-clients/src/makefile b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/host-clients/src/makefile new file mode 100644 index 000000000..763a60c38 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/host-clients/src/makefile @@ -0,0 +1,44 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +CC = gcc +CFLAGS := -Wall -g + +# Add this to make compiler happy +CFLAGS += -DWASM_ENABLE_INTERP=1 + +host_api_c=../../../../host-agent/host-api-c +attr_container_dir=../../../../wamr/core/app-framework/app-native-shared +coap_dir=../../../../host-agent/coap +shared_dir=../../../../wamr/core/shared + +# core +INCLUDE_PATH = -I$(host_api_c)/src -I$(attr_container_dir)/ \ + -I$(coap_dir)/er-coap -I$(coap_dir)/er-coap/extension \ + -I$(shared_dir)/include \ + -I$(shared_dir)/utils \ + -I$(shared_dir)/platform/include/ \ + -I$(shared_dir)/platform/linux/ + +LIB := $(host_api_c)/src/libhostapi.a +EXE := ./hostapp + +App_C_Files := host_app_sample.c + +OBJS := $(App_C_Files:.c=.o) + +all: $(EXE) + +%.o: %.c + @$(CC) $(CFLAGS) -c $< -o $@ $(INCLUDE_PATH) + +$(EXE): $(OBJS) + @rm -f $(EXE) + @$(CC) $(OBJS) -o $(EXE) $(LIB) -lpthread -lrt + @rm -f $(OBJS) + +.PHONY: clean +clean: + rm -f $(OBJS) $(EXE) diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/set_dev_env.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/set_dev_env.sh new file mode 100755 index 000000000..1abe23b80 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/set_dev_env.sh @@ -0,0 +1,7 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +#!/bin/sh + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/start.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/start.py new file mode 100755 index 000000000..2cbc4fe63 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/start.py @@ -0,0 +1,152 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +#!/usr/bin/env python + +# -*- coding: utf-8 -*- +""" +It is the entrance of the iagent test framework. + +""" +from __future__ import print_function + +import argparse +import datetime +import os +import pprint +import random +import re +import shlex +import subprocess +import signal +import sys +import time + +sys.path.append('../../../app-sdk/python') +from framework.test_utils import * +from framework.framework import * + + +def signal_handler(signal, frame): + print('Pressed Ctrl+C!') + sys.exit(0) + +def Register_signal_handler(): + signal.signal(signal.SIGINT, signal_handler) +# signal.pause() + + +def flatten_args_list(l): + if l is None: + return None + + return [x for y in l for x in y] + + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description = "to run specific case(s) "\ + "in specific suite(s) with FC test framework") + parser.add_argument('-s', dest = 'suite_id', action = 'append', + nargs = '+', + help = 'one or multiple suite ids, which are also setup ids.'\ + 'by default if it isn\'t passed from argument, all '\ + 'suites are going to be run.') + parser.add_argument('-t', dest = 'case_id', action = 'append', + nargs = '+', + help = 'one or multiple cases ids.'\ + 'by default if it isn\'t passed from argument, all '\ + 'cases in specific suites are going to be run.') + parser.add_argument('-n', dest = 'repeat_time', action = 'store', + default = 1, + help = 'how many times do you want to run. there is 40s '\ + 'break time between two rounds. each round includs '\ + 'init_setup, run_test_case and deinit_setup.') + parser.add_argument('--shuffle_all', dest = 'shuffle_all', + default = False, action = 'store_true', + help = 'shuffle_all test cases in per test suite '\ + 'by default, all cases under per suite should '\ + 'be executed by input order.') + parser.add_argument('--cases_list', dest='cases_list_file_path', + default=None, + action='store', + help="read cases list from a flie ") + parser.add_argument('--skip_proc', dest='skip_proc', + default = False, action = 'store_true', + help='do not start the test process.'\ + 'sometimes the gw_broker process will be started in eclipse for debug purpose') + parser.add_argument('-b', dest = 'binaries', action = 'store', + help = 'The path of target folder ') + parser.add_argument('-d', dest = 'debug', action = 'store_true', + help = 'wait user to attach the target process after launch processes ') + parser.add_argument('--rebuild', dest = 'rebuild', action = 'store_true', + help = 'rebuild all test binaries') + args = parser.parse_args() + + print("------------------------------------------------------------") + print("parsing arguments ... ...") + print(args) + + ''' + logger = logging.getLogger('coapthon.server.coap') + logger.setLevel(logging.DEBUG) + console = logging.StreamHandler() + console.setLevel(logging.DEBUG) + logger.addHandler(console) + ''' + print("------------------------------------------------------------") + print("preparing wamr binary and test tools ... ...") + os.system("cd ../../samples/simple/ && bash build.sh -p host-interp") + + Register_signal_handler() + + api_init_globals(); + + api_create_case_event(); + + suites_list = flatten_args_list(args.suite_id) + cases_list = flatten_args_list(args.case_id) + + dirname, filename = os.path.split(os.path.abspath(sys.argv[0])) + api_set_root_path(dirname); + + framework = CTestFramework(dirname); + framework.repeat_time = int(args.repeat_time) + framework.shuffle_all = args.shuffle_all + framework.skip_proc=args.skip_proc + + api_set_value('keep_env', args.skip_proc) + api_set_value('debug', args.debug) + api_set_value('rebuild', args.rebuild) + + binary_path = args.binaries + if binary_path is None: + binary_path = os.path.abspath(dirname + '/../..') + + print("checking execution binary path: " + binary_path) + if not os.path.exists(binary_path): + print("The execution binary path was not available. quit...") + os._exit(0) + api_set_value('binary_path', binary_path) + + if suites_list is not None: + framework.target_suites = suites_list + else: + framework.load_suites() + + framework.target_cases = cases_list + framework.start_run() + + print("\n\n------------------------------------------------------------") + print("The run folder is [" + framework.running_folder +"]") + print("that's all. bye") + + print("kill to quit..") + t_kill_process_by_name("start.py") + + sys.exit(0) + os._exit() + + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/01-install/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/01-install/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/01-install/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/01-install/case.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/01-install/case.py new file mode 100644 index 000000000..b8d2c38b8 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/01-install/case.py @@ -0,0 +1,94 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import sys +import time +import random +import logging +import json + +from framework.case_base import * +from framework.test_api import * +from harness.harness_api import * + +class CTestCase(CTestCaseBase): + def __init__(self, suite): + CTestCaseBase.__init__(self, suite) + + def get_case_name(self): + case_path = os.path.dirname(os.path.abspath( __file__ )) + return os.path.split(case_path)[1] + + def on_get_case_description(self): + return "startup the executables" + + def on_setup_case(self): + os.chdir(self.get_case_name()) + start_env() + api_log_error("on_setup_case OK") + return True, '' + + def on_cleanup_case(self): + stop_env() + api_log_error("on_cleanup_case OK") + return True, '' + + # called by the framework + def on_run_case(self): + time.sleep(0.5) + + #uninstall inexistent App1 + ret = uninstall_app("App1") + if (ret != 160): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps([]) + if (ret == False): + return False, '' + + #install App1 + ret = install_app("App1", "01_install.wasm") + if (ret != 65): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps(["App1"]) + if (ret == False): + return False, '' + + #install App2 + ret = install_app("App2", "01_install.wasm") + if (ret != 65): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps(["App1","App2"]) + if (ret == False): + return False, '' + + #uninstall App2 + ret = uninstall_app("App2") + if (ret != 66): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps(["App1"]) + if (ret == False): + return False, '' + + return True, '' diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/02-request/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/02-request/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/02-request/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/02-request/case.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/02-request/case.py new file mode 100644 index 000000000..e2192d5fa --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/02-request/case.py @@ -0,0 +1,73 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import sys +import time +import random +import logging +import json + +from framework.case_base import * +from framework.test_api import * +from harness.harness_api import * + +class CTestCase(CTestCaseBase): + def __init__(self, suite): + CTestCaseBase.__init__(self, suite) + + def get_case_name(self): + case_path = os.path.dirname(os.path.abspath( __file__ )) + return os.path.split(case_path)[1] + + def on_get_case_description(self): + return "startup the executables" + + def on_setup_case(self): + os.chdir(self.get_case_name()) + start_env() + api_log_error("on_setup_case OK") + return True, '' + + def on_cleanup_case(self): + stop_env() + api_log_error("on_cleanup_case OK") + return True, '' + + # called by the framework + def on_run_case(self): + time.sleep(0.5) + + #install App1 + ret = install_app("App1", "02_request.wasm") + if (ret != 65): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps(["App1"]) + if (ret == False): + return False, '' + + #send request to App1 + ret = send_request("/res1", "GET", None) + if (ret != 69): + return False, '' + expect_response_payload = {"key1":"value1","key2":"value2"} + ret = check_response_payload(expect_response_payload) + if (ret == False): + return False, '' + + #send request to App1 + ret = send_request("/res2", "DELETE", None) + if (ret != 66): + return False, '' + expect_response_payload = {} + ret = check_response_payload(expect_response_payload) + if (ret == False): + return False, '' + + return True, '' diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/03-event/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/03-event/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/03-event/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/03-event/case.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/03-event/case.py new file mode 100644 index 000000000..3886cb820 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/03-event/case.py @@ -0,0 +1,67 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +import sys +import time +import random +import logging +import json + +from framework.case_base import * +from framework.test_api import * +from harness.harness_api import * + +class CTestCase(CTestCaseBase): + def __init__(self, suite): + CTestCaseBase.__init__(self, suite) + + def get_case_name(self): + case_path = os.path.dirname(os.path.abspath( __file__ )) + return os.path.split(case_path)[1] + + def on_get_case_description(self): + return "startup the executables" + + def on_setup_case(self): + os.chdir(self.get_case_name()) + start_env() + api_log_error("on_setup_case OK") + return True, '' + + def on_cleanup_case(self): + stop_env() + api_log_error("on_cleanup_case OK") + return True, '' + + # called by the framework + def on_run_case(self): + time.sleep(0.5) + + #install App1 + ret = install_app("App1", "03_event.wasm") + if (ret != 65): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps(["App1"]) + if (ret == False): + return False, '' + + #register event + ret = register("/alert/overheat", 2000, 5000) + if (ret != 69): + return False, '' + ret = check_get_event() + if (ret == False): + return False, '' + + #deregister event + ret = deregister("/alert/overheat") + if (ret != 69): + return False, '' + + return True, '' diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/case.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/case.py new file mode 100644 index 000000000..bf395f58b --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/04-request-internal/case.py @@ -0,0 +1,80 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import sys +import time +import random +import logging +import json + +from framework.case_base import * +from framework.test_api import * +from harness.harness_api import * + +class CTestCase(CTestCaseBase): + def __init__(self, suite): + CTestCaseBase.__init__(self, suite) + + def get_case_name(self): + case_path = os.path.dirname(os.path.abspath( __file__ )) + return os.path.split(case_path)[1] + + def on_get_case_description(self): + return "startup the executables" + + def on_setup_case(self): + os.chdir(self.get_case_name()) + start_env() + api_log_error("on_setup_case OK") + return True, '' + + def on_cleanup_case(self): + stop_env() + api_log_error("on_cleanup_case OK") + return True, '' + + # called by the framework + def on_run_case(self): + time.sleep(0.5) + + #install App1 + ret = install_app("App1", "04_request_internal_resp.wasm") + if (ret != 65): + return False, '' + + #install App2 + ret = install_app("App2", "04_request_internal_req.wasm") + if (ret != 65): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps(["App1","App2"]) + if (ret == False): + return False, '' + + #send request to App2 + ret = send_request("/res1", "GET", None) + if (ret != 69): + return False, '' + time.sleep(2) + expect_response_payload = {"key1":"value1","key2":"value2"} + ret = check_response_payload(expect_response_payload) + if (ret == False): + return False, '' + + #send request to App2 + ret = send_request("/res2", "GET", None) + if (ret != 69): + return False, '' + time.sleep(2) + expect_response_payload = {"key1":"value1","key2":"value2"} + ret = check_response_payload(expect_response_payload) + if (ret == False): + return False, '' + + return True, '' diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/case.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/case.py new file mode 100644 index 000000000..79c328749 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/05-event-internal/case.py @@ -0,0 +1,70 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import sys +import time +import random +import logging +import json + +from framework.case_base import * +from framework.test_api import * +from harness.harness_api import * + +class CTestCase(CTestCaseBase): + def __init__(self, suite): + CTestCaseBase.__init__(self, suite) + + def get_case_name(self): + case_path = os.path.dirname(os.path.abspath( __file__ )) + return os.path.split(case_path)[1] + + def on_get_case_description(self): + return "startup the executables" + + def on_setup_case(self): + os.chdir(self.get_case_name()) + start_env() + api_log_error("on_setup_case OK") + return True, '' + + def on_cleanup_case(self): + stop_env() + api_log_error("on_cleanup_case OK") + return True, '' + + # called by the framework + def on_run_case(self): + time.sleep(0.5) + + #install App1 + ret = install_app("App1", "05_event_internal_provider.wasm") + if (ret != 65): + return False, '' + + #install App2 + ret = install_app("App2", "05_event_internal_subscriber.wasm") + if (ret != 65): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps(["App1","App2"]) + if (ret == False): + return False, '' + + #send request to App2 + ret = send_request("/res1", "GET", None) + if (ret != 69): + return False, '' + time.sleep(2) + expect_response_payload = {"key1":"value1","key2":"value2"} + ret = check_response_payload(expect_response_payload) + if (ret == False): + return False, '' + + return True, '' diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/06-timer/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/06-timer/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/06-timer/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/06-timer/case.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/06-timer/case.py new file mode 100644 index 000000000..90af4d5d9 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/06-timer/case.py @@ -0,0 +1,70 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import sys +import time +import random +import logging +import json + +from framework.case_base import * +from framework.test_api import * +from harness.harness_api import * + +class CTestCase(CTestCaseBase): + def __init__(self, suite): + CTestCaseBase.__init__(self, suite) + + def get_case_name(self): + case_path = os.path.dirname(os.path.abspath( __file__ )) + return os.path.split(case_path)[1] + + def on_get_case_description(self): + return "startup the executables" + + def on_setup_case(self): + os.chdir(self.get_case_name()) + start_env() + api_log_error("on_setup_case OK") + return True, '' + + def on_cleanup_case(self): + stop_env() + api_log_error("on_cleanup_case OK") + return True, '' + + # called by the framework + def on_run_case(self): + time.sleep(0.5) + + #install App1 + ret = install_app("App1", "06_timer.wasm") + if (ret != 65): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps(["App1"]) + if (ret == False): + return False, '' + + #send request to App1 + ret = send_request("/res1", "GET", None) + if (ret != 69): + return False, '' + + time.sleep(3) + + ret = send_request("/check_timer", "GET", None) + if (ret != 69): + return False, '' + expect_response_payload = {"num":2} + ret = check_response_payload(expect_response_payload) + if (ret == False): + return False, '' + + return True, '' diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/case.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/case.py new file mode 100644 index 000000000..2bb756203 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/07-sensor/case.py @@ -0,0 +1,65 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import sys +import time +import random +import logging +import json + +from framework.case_base import * +from framework.test_api import * +from harness.harness_api import * + +class CTestCase(CTestCaseBase): + def __init__(self, suite): + CTestCaseBase.__init__(self, suite) + + def get_case_name(self): + case_path = os.path.dirname(os.path.abspath( __file__ )) + return os.path.split(case_path)[1] + + def on_get_case_description(self): + return "startup the executables" + + def on_setup_case(self): + os.chdir(self.get_case_name()) + start_env() + api_log_error("on_setup_case OK") + return True, '' + + def on_cleanup_case(self): + stop_env() + api_log_error("on_cleanup_case OK") + return True, '' + + # called by the framework + def on_run_case(self): + time.sleep(0.5) + + #install App1 + ret = install_app("App1", "07_sensor.wasm") + if (ret != 65): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps(["App1"]) + if (ret == False): + return False, '' + + #send request to App1 + ret = send_request("/res1", "GET", None) + if (ret != 69): + return False, '' + time.sleep(2) + expect_response_payload = {"key1":"value1","key2":"value2"} + ret = check_response_payload(expect_response_payload) + if (ret == False): + return False, '' + + return True, '' diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/case.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/case.py new file mode 100644 index 000000000..99a4512ee --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/08-on-destroy/case.py @@ -0,0 +1,78 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import sys +import time +import random +import logging +import json + +from framework.case_base import * +from framework.test_api import * +from harness.harness_api import * + +class CTestCase(CTestCaseBase): + def __init__(self, suite): + CTestCaseBase.__init__(self, suite) + + def get_case_name(self): + case_path = os.path.dirname(os.path.abspath( __file__ )) + return os.path.split(case_path)[1] + + def on_get_case_description(self): + return "startup the executables" + + def on_setup_case(self): + os.chdir(self.get_case_name()) + start_env() + api_log_error("on_setup_case OK") + return True, '' + + def on_cleanup_case(self): + stop_env() + api_log_error("on_cleanup_case OK") + return True, '' + + # called by the framework + def on_run_case(self): + time.sleep(0.5) + + #install App1 + ret = install_app("App1", "08_on_destroy.wasm") + if (ret != 65): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps(["App1"]) + if (ret == False): + return False, '' + + #send request to App1 + ret = send_request("/res1", "GET", None) + if (ret != 69): + return False, '' + time.sleep(2) + expect_response_payload = {"key1":"value1"} + ret = check_response_payload(expect_response_payload) + if (ret == False): + return False, '' + + #uninstall App1 + ret = uninstall_app("App1") + if (ret != 66): + return False, '' + + #query Apps + ret = query_app() + if (ret != 69): + return False, '' + ret = check_query_apps([]) + if (ret == False): + return False, '' + + return True, '' diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/cases/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/suite_setup.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/suite_setup.py new file mode 100644 index 000000000..2307186f7 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/suite_setup.py @@ -0,0 +1,56 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +import os +import shutil +import types +import time +import glob + +from framework.test_api import * +from framework.test_utils import * +from harness.harness_api import * +from framework.suite import * + +class CTestSuite(CTestSuiteBase): + setup_path = "" + def __init__(self, name, suite_path, run_path): + CTestSuiteBase.__init__(self, name, suite_path, run_path) + + def on_suite_setup(self): + global setup_path + setup_path = os.getcwd() + cases = os.listdir(self.suite_path + "/cases/") + cases.sort() + + if api_get_value("rebuild", False): + path_tmp = os.getcwd() + os.chdir(self.suite_path + "/test-app") + os.system(self.suite_path + "/test-app" + "/build.sh") + os.chdir(path_tmp) + + os.makedirs(self.run_path + "/test-app") + + for case in cases: + if case != "__init__.pyc" and case != "__init__.py": + os.makedirs(self.run_path + "/" + case) + #copy each case's host_tool, simple, wasm files, start/stop scripts to the run directory, + shutil.copy(setup_path + "/../../samples/simple/out/simple", self.run_path + "/" + case) + shutil.copy(setup_path + "/../../samples/simple/out/host_tool", self.run_path + "/" + case) + for file in glob.glob(self.suite_path + "/test-app/" + "/*.wasm"): + shutil.copy(file, self.run_path + "/test-app") + shutil.copy(self.suite_path + "/tools/product/start.sh", self.run_path + "/" + case) + shutil.copy(self.suite_path + "/tools/product/stop.sh", self.run_path + "/" + case) + + os.chdir(self.run_path) + + return True, 'OK' + + def on_suite_cleanup(self): + global setup_path + os.chdir(setup_path) + api_log("stopping env..") + + return True, 'OK' diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/01_install.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/01_install.c new file mode 100644 index 000000000..5c7153588 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/01_install.c @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" + +void +on_init() +{ + printf("Hello, I was installed.\n"); +} + +void +on_destroy() +{ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/02_request.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/02_request.c new file mode 100644 index 000000000..251de6ff4 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/02_request.c @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" +#include "wa-inc/request.h" + +void +res1_handler(request_t *request) +{ + response_t response[1]; + attr_container_t *payload; + + printf("### user resource 1 handler called\n"); + + printf("###### dump request ######\n"); + printf("sender: %lu\n", request->sender); + printf("url: %s\n", request->url); + printf("action: %d\n", request->action); + printf("payload:\n"); + if (request->payload != NULL && request->payload_len > 0 + && request->fmt == FMT_ATTR_CONTAINER) + attr_container_dump((attr_container_t *)request->payload); + printf("#### dump request end ###\n"); + + payload = attr_container_create("wasm app response payload"); + if (payload == NULL) + return; + + attr_container_set_string(&payload, "key1", "value1"); + attr_container_set_string(&payload, "key2", "value2"); + + make_response_for_request(request, response); + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); + printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); + api_response_send(response); + + attr_container_destroy(payload); +} + +void +res2_handler(request_t *request) +{ + response_t response[1]; + make_response_for_request(request, response); + set_response(response, DELETED_2_02, 0, NULL, 0); + api_response_send(response); + + printf("### user resource 2 handler called\n"); +} + +void +on_init() +{ + /* register resource uri */ + api_register_resource_handler("/res1", res1_handler); + api_register_resource_handler("/res2", res2_handler); +} + +void +on_destroy() +{ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/03_event.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/03_event.c new file mode 100644 index 000000000..59cfd0097 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/03_event.c @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" +#include "wa-inc/timer_wasm_app.h" +#include "wa-inc/request.h" + +int num = 0; + +void +publish_overheat_event() +{ + attr_container_t *event; + + event = attr_container_create("event"); + attr_container_set_string(&event, "warning", "temperature is over high"); + + printf("###app publish event begin ###\n"); + + api_publish_event("alert/overheat", FMT_ATTR_CONTAINER, event, + attr_container_get_serialize_length(event)); + + printf("###app publish event end ###\n"); + + attr_container_destroy(event); +} + +/* Timer callback */ +void +timer1_update(user_timer_t timer) +{ + printf("Timer update %d\n", num++); + publish_overheat_event(); +} + +void +start_timer() +{ + user_timer_t timer; + + /* set up a timer */ + timer = api_timer_create(1000, true, false, timer1_update); + api_timer_restart(timer, 1000); +} + +void +on_init() +{ + start_timer(); +} + +void +on_destroy() +{ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_req.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_req.c new file mode 100644 index 000000000..99bab9704 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_req.c @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" +#include "wa-inc/request.h" + +uint32 mid; +unsigned long sender; + +void +my_response_handler(response_t *response, void *user_data) +{ + attr_container_t *payload; + printf("### user resource 1 handler called\n"); + + payload = attr_container_create("wasm app response payload"); + if (payload == NULL) + return; + + attr_container_set_string(&payload, "key1", "value1"); + attr_container_set_string(&payload, "key2", "value2"); + + response->mid = mid; + response->reciever = sender; + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); + printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); + api_response_send(response); + + attr_container_destroy(payload); +} + +static void +test_send_request(const char *url, const char *tag) +{ + request_t request[1]; + + init_request(request, (char *)url, COAP_PUT, 0, NULL, 0); + api_send_request(request, my_response_handler, (void *)tag); +} + +void +res1_handler(request_t *request) +{ + mid = request->mid; + sender = request->sender; + test_send_request("url1", "a general request"); +} + +void +res2_handler(request_t *request) +{ + mid = request->mid; + sender = request->sender; + test_send_request("/app/App1/url1", "a general request"); +} + +void +on_init() +{ + /* register resource uri */ + api_register_resource_handler("/res1", res1_handler); + api_register_resource_handler("/res2", res2_handler); +} + +void +on_destroy() +{ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_resp.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_resp.c new file mode 100644 index 000000000..13aecb43a --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/04_request_internal_resp.c @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" +#include "wa-inc/request.h" + +void +res1_handler(request_t *request) +{ + response_t response[1]; + attr_container_t *payload; + + printf("[resp] ### user resource 1 handler called\n"); + + printf("[resp] ###### dump request ######\n"); + printf("[resp] sender: %lu\n", request->sender); + printf("[resp] url: %s\n", request->url); + printf("[resp] action: %d\n", request->action); + printf("[resp] payload:\n"); + if (request->payload != NULL && request->fmt == FMT_ATTR_CONTAINER) + attr_container_dump((attr_container_t *)request->payload); + printf("[resp] #### dump request end ###\n"); + + payload = attr_container_create("wasm app response payload"); + if (payload == NULL) + return; + + attr_container_set_string(&payload, "key1", "value1"); + attr_container_set_string(&payload, "key2", "value2"); + + make_response_for_request(request, response); + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); + printf("[resp] response payload len %d\n", + attr_container_get_serialize_length(payload)); + printf("[resp] reciver: %lu, mid:%d\n", response->reciever, response->mid); + api_response_send(response); + + attr_container_destroy(payload); +} + +void +on_init() +{ + /* register resource uri */ + api_register_resource_handler("/url1", res1_handler); +} + +void +on_destroy() +{ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_provider.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_provider.c new file mode 100644 index 000000000..59cfd0097 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_provider.c @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" +#include "wa-inc/timer_wasm_app.h" +#include "wa-inc/request.h" + +int num = 0; + +void +publish_overheat_event() +{ + attr_container_t *event; + + event = attr_container_create("event"); + attr_container_set_string(&event, "warning", "temperature is over high"); + + printf("###app publish event begin ###\n"); + + api_publish_event("alert/overheat", FMT_ATTR_CONTAINER, event, + attr_container_get_serialize_length(event)); + + printf("###app publish event end ###\n"); + + attr_container_destroy(event); +} + +/* Timer callback */ +void +timer1_update(user_timer_t timer) +{ + printf("Timer update %d\n", num++); + publish_overheat_event(); +} + +void +start_timer() +{ + user_timer_t timer; + + /* set up a timer */ + timer = api_timer_create(1000, true, false, timer1_update); + api_timer_restart(timer, 1000); +} + +void +on_init() +{ + start_timer(); +} + +void +on_destroy() +{ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c new file mode 100644 index 000000000..00e451369 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/05_event_internal_subscriber.c @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" +#include "wa-inc/request.h" + +uint32 mid; +unsigned long sender; + +void +over_heat_event_handler(request_t *request) +{ + response_t response[1]; + attr_container_t *payload; + + payload = attr_container_create("wasm app response payload"); + if (payload == NULL) + return; + + attr_container_set_string(&payload, "key1", "value1"); + attr_container_set_string(&payload, "key2", "value2"); + + response->mid = mid; + response->reciever = sender; + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); + printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); + api_response_send(response); + + attr_container_destroy(payload); +} + +void +res1_handler(request_t *request) +{ + mid = request->mid; + sender = request->sender; + api_subscribe_event("alert/overheat", over_heat_event_handler); +} + +void +on_init() +{ + /* register resource uri */ + api_register_resource_handler("/res1", res1_handler); +} + +void +on_destroy() +{ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/06_timer.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/06_timer.c new file mode 100644 index 000000000..6aa107d5c --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/06_timer.c @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" +#include "wa-inc/request.h" +#include "wa-inc/timer_wasm_app.h" + +/* User global variable */ +int num = 0; + +/* Timer callback */ +void +timer1_update(user_timer_t timer) +{ + if (num < 2) + num++; +} + +void +res1_handler(request_t *request) +{ + user_timer_t timer; + + /* set up a timer */ + timer = api_timer_create(1000, true, false, timer1_update); + api_timer_restart(timer, 1000); + + response_t response[1]; + + make_response_for_request(request, response); + + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, NULL, 0); + + api_response_send(response); +} + +void +res2_handler(request_t *request) +{ + response_t response[1]; + attr_container_t *payload; + + if (num == 2) { + attr_container_t *payload; + printf("### user resource 1 handler called\n"); + + payload = attr_container_create("wasm app response payload"); + if (payload == NULL) + return; + + attr_container_set_int(&payload, "num", num); + + make_response_for_request(request, response); + + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); + printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); + api_response_send(response); + + attr_container_destroy(payload); + } +} + +void +on_init() +{ + /* register resource uri */ + api_register_resource_handler("/res1", res1_handler); + api_register_resource_handler("/check_timer", res2_handler); +} + +void +on_destroy() +{ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/07_sensor.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/07_sensor.c new file mode 100644 index 000000000..a6c24a8bc --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/07_sensor.c @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" +#include "wa-inc/request.h" +#include "wa-inc/sensor.h" + +uint32 mid; +unsigned long sender; + +/* Sensor event callback*/ +void +sensor_event_handler(sensor_t sensor, attr_container_t *event, void *user_data) +{ + printf("### app get sensor event\n"); + + response_t response[1]; + attr_container_t *payload; + + payload = attr_container_create("wasm app response payload"); + if (payload == NULL) + return; + + attr_container_set_string(&payload, "key1", "value1"); + attr_container_set_string(&payload, "key2", "value2"); + + response->mid = mid; + response->reciever = sender; + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); + printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); + api_response_send(response); + + attr_container_destroy(payload); +} + +void +res1_handler(request_t *request) +{ + mid = request->mid; + sender = request->sender; + + sensor_t sensor; + char *user_data; + attr_container_t *config; + + printf("### app on_init 1\n"); + /* open a sensor */ + user_data = malloc(100); + printf("### app on_init 2\n"); + sensor = sensor_open("sensor_test", 0, sensor_event_handler, user_data); + printf("### app on_init 3\n"); + + /* config the sensor */ + sensor_config(sensor, 2000, 0, 0); + printf("### app on_init 4\n"); +} + +void +on_init() +{ + /* register resource uri */ + api_register_resource_handler("/res1", res1_handler); +} + +void +on_destroy() +{ + /* real destroy work including killing timer and closing sensor is + * accomplished in wasm app library version of on_destroy() */ +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/08_on_destroy.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/08_on_destroy.c new file mode 100644 index 000000000..ac05a77da --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/08_on_destroy.c @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "wasm_app.h" +#include "wa-inc/request.h" +#include "wa-inc/sensor.h" + +uint32 mid; +unsigned long sender; +sensor_t sensor; + +/* Sensor event callback*/ +void +sensor_event_handler(sensor_t sensor, attr_container_t *event, void *user_data) +{ + printf("### app get sensor event\n"); + + response_t response[1]; + attr_container_t *payload; + + payload = attr_container_create("wasm app response payload"); + if (payload == NULL) + return; + + attr_container_set_string(&payload, "key1", "value1"); + + response->mid = mid; + response->reciever = sender; + set_response(response, CONTENT_2_05, FMT_ATTR_CONTAINER, + (const char *)payload, + attr_container_get_serialize_length(payload)); + printf("reciver: %lu, mid:%d\n", response->reciever, response->mid); + api_response_send(response); + + attr_container_destroy(payload); +} + +void +res1_handler(request_t *request) +{ + mid = request->mid; + sender = request->sender; + + char *user_data; + attr_container_t *config; + + printf("### app on_init 1\n"); + /* open a sensor */ + user_data = malloc(100); + printf("### app on_init 2\n"); + sensor = sensor_open("sensor_test", 0, sensor_event_handler, user_data); + printf("### app on_init 3\n"); +} + +void +on_init() +{ + /* register resource uri */ + api_register_resource_handler("/res1", res1_handler); +} + +void +on_destroy() +{ + if (NULL != sensor) { + sensor_close(sensor); + } +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/build.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/build.sh new file mode 100755 index 000000000..4b5428051 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/test-app/build.sh @@ -0,0 +1,39 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +. ../../../set_dev_env.sh + +CC=/opt/wasi-sdk/bin/clang +APP_DIR=$PWD +WAMR_DIR=${APP_DIR}/../../../../../ +SDK_DIR=${WAMR_DIR}/wamr-sdk/out/simple-host-interp +APP_FRAMEWORK_DIR=${SDK_DIR}/app-sdk/wamr-app-framework +DEPS_DIR=${WAMR_DIR}/core/deps + +for i in `ls *.c` +do +APP_SRC="$i" +OUT_FILE=${i%.*}.wasm +/opt/wasi-sdk/bin/clang -O3 \ + -Wno-int-conversion \ + -I${APP_FRAMEWORK_DIR}/include \ + -I${DEPS_DIR} \ + -O3 -z stack-size=4096 -Wl,--initial-memory=65536 \ + --sysroot=${SDK_DIR}/app-sdk/libc-builtin-sysroot \ + -L${APP_FRAMEWORK_DIR}/lib -lapp_framework \ + -Wl,--allow-undefined-file=${SDK_DIR}/app-sdk/libc-builtin-sysroot/share/defined-symbols.txt \ + -Wl,--strip-all,--no-entry -nostdlib \ + -Wl,--export=on_init -Wl,--export=on_destroy \ + -Wl,--export=on_request -Wl,--export=on_response \ + -Wl,--export=on_sensor_event -Wl,--export=on_timer_callback \ + -Wl,--export=on_connection_data \ + -o ${OUT_FILE} \ + ${APP_SRC} +if [ -f ${OUT_FILE} ]; then + echo "build ${OUT_FILE} success" +else + echo "build ${OUT_FILE} fail" +fi +done diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/tools/product/start.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/tools/product/start.sh new file mode 100755 index 000000000..f83e39356 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/tools/product/start.sh @@ -0,0 +1,10 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +#!/bin/bash + +cd $(dirname "$0") + +./simple -s > /dev/null 2>&1 & diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/tools/product/stop.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/tools/product/stop.sh new file mode 100755 index 000000000..b7bc2c8d2 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/01-life-cycle/tools/product/stop.sh @@ -0,0 +1,9 @@ +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +#!/bin/bash + +ps aux | grep -ie host_tool | awk '{print $2}' | xargs kill -9 & +ps aux | grep -ie simple | awk '{print $2}' | xargs kill -9 & diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/__init__.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/__init__.py diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/readme.txt b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/readme.txt new file mode 100644 index 000000000..1e8792f5b --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/component-test/suites/readme.txt @@ -0,0 +1,19 @@ +The description of each case in the test suites, should add descriptions in this file when new cases created in the future. + +suite 01-life-cycle: +case 01-install: + install or uninstall apps for times and query apps to see if the app list is expected. +case 02-request: + send request to an app, the app will respond specific attribute objects, host side should get them. +case 03-event: + register event to an app, the app will send event back periodically, host side should get some payload. +case 04-request_internal: + install 2 apps, host sends request to app2, then app2 sends request to app1, finally app1 respond specific payload to host, host side will check it. +case 05-event_internal: + install 2 apps, host sends request to app2, then app2 subscribe app1's event, finally app1 respond specific payload to host, host side will check it. +case 06-timer: + host send request to an app, the app then start a timer, when time goes by 2 seconds, app will respond specific payload to host, host side will check it. +case 07-sensor: + open sensor in app and then config the sensor in on_init, finally app will respond specific payload to host, host side will check it. +case 08-on_destroy: + open sensor in app in on_init, and close the sensor in on_destroy, host should install and uninstall the app successfully. diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/CMakeLists.txt b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/CMakeLists.txt new file mode 100644 index 000000000..932cf73bd --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/CMakeLists.txt @@ -0,0 +1,56 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +cmake_minimum_required (VERSION 2.9) +project (host-agent) + +if (NOT CMAKE_BUILD_TYPE) + SET(CMAKE_BUILD_TYPE Debug) +endif (NOT CMAKE_BUILD_TYPE) + +if (NOT WAMR_BUILD_PLATFORM) + set (WAMR_BUILD_PLATFORM "linux") +endif (NOT WAMR_BUILD_PLATFORM) + +message ("WAMR_BUILD_PLATFORM = " ${WAMR_BUILD_PLATFORM}) + +add_definitions(-DWA_MALLOC=malloc) +add_definitions(-DWA_FREE=free) + +set (REPO_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../..) +set (IWASM_DIR ${REPO_ROOT_DIR}/core/iwasm) +set (APP_MGR_DIR ${REPO_ROOT_DIR}/core/app-mgr) +set (SHARED_DIR ${REPO_ROOT_DIR}/core/shared) +set (APP_FRAMEWORK_DIR ${REPO_ROOT_DIR}/core/app-framework) +#TODO: use soft-plc/tools/iec-runtime/external/cJSON instead +set (CJSON_DIR ${CMAKE_CURRENT_LIST_DIR}/external/cJSON) + +include (${APP_FRAMEWORK_DIR}/app-native-shared/native_interface.cmake) +include (${APP_MGR_DIR}/app-mgr-shared/app_mgr_shared.cmake) +include (${SHARED_DIR}/platform/${WAMR_BUILD_PLATFORM}/shared_platform.cmake) +include (${SHARED_DIR}/utils/shared_utils.cmake) +include (${SHARED_DIR}/mem-alloc/mem_alloc.cmake) +include (${CJSON_DIR}/cjson.cmake) +include (${SHARED_DIR}/coap/lib_coap.cmake) + +add_definitions(-Wall -Wno-pointer-sign) + +include_directories( + ${CMAKE_CURRENT_LIST_DIR}/src + ${IWASM_DIR}/include +) + +file (GLOB_RECURSE HOST_TOOL_SRC src/*.c) + +SET(SOURCES + ${HOST_TOOL_SRC} + ${PLATFORM_SHARED_SOURCE} + ${UTILS_SHARED_SOURCE} + ${NATIVE_INTERFACE_SOURCE} + ${CJSON_SOURCE} + ${LIB_HOST_AGENT_SOURCE} + ) + +add_executable(host_tool ${SOURCES}) +target_link_libraries(host_tool pthread) diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/LICENSE b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/LICENSE new file mode 100644 index 000000000..78deb0406 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/cJSON.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/cJSON.c new file mode 100644 index 000000000..2e35351db --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/cJSON.c @@ -0,0 +1,2817 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning(push) +/* disable warning about single line comments in system headers */ +#pragma warning(disable : 4001) +#endif + +#include <string.h> +#include <stdio.h> +#include <math.h> +#include <stdlib.h> +#include <limits.h> +#include <ctype.h> + +#ifdef ENABLE_LOCALES +#include <locale.h> +#endif + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#define true ((cJSON_bool)1) +#define false ((cJSON_bool)0) + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char *)(global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item) +{ + if (!cJSON_IsString(item)) { + return NULL; + } + + return item->valuestring; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and + * header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) \ + || (CJSON_VERSION_PATCH != 10) +#error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char *) cJSON_Version(void) +{ + static char version[15]; + snprintf(version, sizeof(version), "%i.%i.%i", CJSON_VERSION_MAJOR, + CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal + * though */ +static int +case_insensitive_strcmp(const unsigned char *string1, + const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) { + return 1; + } + + if (string1 == string2) { + return 0; + } + + for (; tolower(*string1) == tolower(*string2); (void)string1++, string2++) { + if (*string1 == '\0') { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks { + void *(CJSON_CDECL *allocate)(size_t size); + void(CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dillimport '...' + is not static */ +static void *CJSON_CDECL +internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL +internal_free(void *pointer) +{ + free(pointer); +} +static void *CJSON_CDECL +internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* clang-format off */ +static internal_hooks global_hooks = { + internal_malloc, + internal_free, + internal_realloc +}; +/* clang-format on */ + +static unsigned char * +cJSON_strdup(const unsigned char *string, const internal_hooks *const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) { + return NULL; + } + + length = strlen((const char *)string) + sizeof(""); + copy = (unsigned char *)hooks->allocate(length); + if (copy == NULL) { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks *hooks) +{ + if (hooks == NULL) { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) + && (global_hooks.deallocate == free)) { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON * +cJSON_New_Item(const internal_hooks *const hooks) +{ + cJSON *node = (cJSON *)hooks->allocate(sizeof(cJSON)); + if (node) { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) { + global_hooks.deallocate(item->valuestring); + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) { + global_hooks.deallocate(item->string); + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char +get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char)lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct { + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the + current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting + * with 1) */ +#define can_read(buffer, size) \ + ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) \ + ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) \ + (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result + into item. */ +static cJSON_bool +parse_number(cJSON *const item, parse_buffer *const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char number_c_string[64]; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal + * point of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking + * the end of the input */ + for (i = 0; (i < (sizeof(number_c_string) - 1)) + && can_access_at_index(input_buffer, i); + i++) { + switch (buffer_at_offset(input_buffer)[i]) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_c_string[i] = buffer_at_offset(input_buffer)[i]; + break; + + case '.': + number_c_string[i] = decimal_point; + break; + + default: + goto loop_end; + } + } +loop_end: + number_c_string[i] = '\0'; + + number = strtod((const char *)number_c_string, (char **)&after_end); + if (number_c_string == after_end) { + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) { + item->valueint = INT_MIN; + } + else { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or + * double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) { + object->valueint = INT_MIN; + } + else { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +typedef struct { + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char * +ensure(printbuffer *const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) { + newsize = INT_MAX; + } + else { + return NULL; + } + } + else { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) { + /* reallocate with realloc if available */ + newbuffer = (unsigned char *)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else { + /* otherwise reallocate manually */ + newbuffer = (unsigned char *)p->hooks.allocate(newsize); + if (!newbuffer) { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + if (newbuffer) { + memcpy(newbuffer, p->buffer, p->offset + 1); + } + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset + */ +static void +update_offset(printbuffer *const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char *)buffer_pointer); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool +print_number(const cJSON *const item, printbuffer *const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char + number_buffer[26]; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test; + + if (output_buffer == NULL) { + return false; + } + + /* This checks for NaN and Infinity */ + if ((d * 0) != 0) { + length = snprintf((char *)number_buffer, sizeof(number_buffer), "null"); + } + else { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero + * digits */ + length = + snprintf((char *)number_buffer, sizeof(number_buffer), "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char *)number_buffer, "%lg", &test) != 1) + || ((double)test != d)) { + /* If not, print with 17 decimal places of precision */ + length = snprintf((char *)number_buffer, sizeof(number_buffer), + "%1.17g", d); + } + } + + /* snprintf failed or buffer overrun occured */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) { + if (number_buffer[i] == decimal_point) { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned +parse_hex4(const unsigned char *const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) { + h += (unsigned int)input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) { + h += (unsigned int)10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) { + h += (unsigned int)10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char +utf16_literal_to_utf8(const unsigned char *const input_pointer, + const unsigned char *const input_end, + unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) { + /* invalid second half of the surrogate pair */ + goto fail; + } + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = + 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; + utf8_position--) { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = + (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) { + (*output_pointer)[0] = + (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool +parse_string(cJSON *const item, parse_buffer *const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while ( + ((size_t)(input_end - input_buffer->content) < input_buffer->length) + && (*input_end != '\"')) { + /* is escape sequence */ + if (input_end[0] == '\\') { + if ((size_t)(input_end + 1 - input_buffer->content) + >= input_buffer->length) { + /* prevent buffer overflow when last input character is a + * backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) + >= input_buffer->length) + || (*input_end != '\"')) { + goto fail; + /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t)(input_end - buffer_at_offset(input_buffer)) + - skipped_bytes; + output = (unsigned char *)input_buffer->hooks.allocate(allocation_length + + sizeof("")); + if (output == NULL) { + goto fail; + /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) { + if (*input_pointer != '\\') { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) { + goto fail; + } + + switch (input_pointer[1]) { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8( + input_pointer, input_end, &output_pointer); + if (sequence_length == 0) { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char *)output; + + input_buffer->offset = (size_t)(input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) { + input_buffer->hooks.deallocate(output); + } + + if (input_pointer != NULL) { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool +print_string_ptr(const unsigned char *const input, + printbuffer *const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL, *output_end; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) { + return false; + } + + /* empty string */ + if (input == NULL) { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) { + return false; + } + strcpy((char *)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) { + switch (*input_pointer) { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) { + return false; + } + output_end = output + output_length + sizeof("\"\""); + + /* no characters have to be escaped */ + if (escape_characters == 0) { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; + (void)input_pointer++, output_pointer++) { + if ((*input_pointer > 31) && (*input_pointer != '\"') + && (*input_pointer != '\\')) { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + snprintf((char *)output_pointer, + output_end - output_pointer, "u%04x", + *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool +print_string(const cJSON *const item, printbuffer *const p) +{ + return print_string_ptr((unsigned char *)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool +parse_value(cJSON *const item, parse_buffer *const input_buffer); +static cJSON_bool +print_value(const cJSON *const item, printbuffer *const output_buffer); +static cJSON_bool +parse_array(cJSON *const item, parse_buffer *const input_buffer); +static cJSON_bool +print_array(const cJSON *const item, printbuffer *const output_buffer); +static cJSON_bool +parse_object(cJSON *const item, parse_buffer *const input_buffer); +static cJSON_bool +print_object(const cJSON *const item, printbuffer *const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer * +buffer_skip_whitespace(parse_buffer *const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) { + return NULL; + } + + while (can_access_at_index(buffer, 0) + && (buffer_at_offset(buffer)[0] <= 32)) { + buffer->offset++; + } + + if (buffer->offset == buffer->length) { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer * +skip_utf8_bom(parse_buffer *const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) + || (buffer->offset != 0)) { + return NULL; + } + + if (can_access_at_index(buffer, 4) + && (strncmp((const char *)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) + == 0)) { + buffer->offset += 3; + } + + return buffer; +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) +cJSON_ParseWithOpts(const char *value, const char **return_parse_end, + cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL) { + goto fail; + } + + buffer.content = (const unsigned char *)value; + buffer.length = strlen((const char *)value) + sizeof(""); + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and + * then check for a null terminator */ + if (require_null_terminated) { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) + || buffer_at_offset(&buffer)[0] != '\0') { + goto fail; + } + } + if (return_parse_end) { + *return_parse_end = (const char *)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) { + cJSON_Delete(item); + } + + if (value != NULL) { + error local_error; + local_error.json = (const unsigned char *)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) { + *return_parse_end = + (const char *)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +#define cjson_min(a, b) ((a < b) ? a : b) + +static unsigned char * +print(const cJSON *const item, cJSON_bool format, + const internal_hooks *const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char *)hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) { + printed = (unsigned char *)hooks->reallocate(buffer->buffer, + buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char *)hooks->allocate(buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + memcpy(printed, buffer->buffer, + cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + } + + return printed; + +fail: + if (buffer->buffer != NULL) { + hooks->deallocate(buffer->buffer); + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char *)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char *)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) +cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) { + return NULL; + } + + p.buffer = (unsigned char *)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) { + global_hooks.deallocate(p.buffer); + return NULL; + } + + return (char *)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) +cJSON_PrintPreallocated(cJSON *item, char *buf, const int len, + const cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((len < 0) || (buf == NULL)) { + return false; + } + + p.buffer = (unsigned char *)buf; + p.length = (size_t)len; + p.offset = 0; + p.noalloc = true; + p.format = fmt; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool +parse_value(cJSON *const item, parse_buffer *const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) + && (strncmp((const char *)buffer_at_offset(input_buffer), "null", 4) + == 0)) { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) + && (strncmp((const char *)buffer_at_offset(input_buffer), "false", 5) + == 0)) { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) + && (strncmp((const char *)buffer_at_offset(input_buffer), "true", 4) + == 0)) { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) + && (buffer_at_offset(input_buffer)[0] == '\"')) { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) + && ((buffer_at_offset(input_buffer)[0] == '-') + || ((buffer_at_offset(input_buffer)[0] >= '0') + && (buffer_at_offset(input_buffer)[0] <= '9')))) { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) + && (buffer_at_offset(input_buffer)[0] == '[')) { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) + && (buffer_at_offset(input_buffer)[0] == '{')) { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool +print_value(const cJSON *const item, printbuffer *const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) { + return false; + } + + switch ((item->type) & 0xFF) { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) { + return false; + } + strcpy((char *)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) { + return false; + } + strcpy((char *)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) { + return false; + } + strcpy((char *)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool +parse_array(cJSON *const item, parse_buffer *const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) + && (buffer_at_offset(input_buffer)[0] == ']')) { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) { + goto fail; + /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) { + /* start the linked list */ + current_item = head = new_item; + } + else { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) { + goto fail; + /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } while (can_access_at_index(input_buffer, 0) + && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) + || buffer_at_offset(input_buffer)[0] != ']') { + goto fail; + /* expected end of array */ + } + +success: + input_buffer->depth--; + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool +print_array(const cJSON *const item, printbuffer *const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) { + if (!print_value(current_element, output_buffer)) { + return false; + } + update_offset(output_buffer); + if (current_element->next) { + length = (size_t)(output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) { + return false; + } + *output_pointer++ = ','; + if (output_buffer->format) { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool +parse_object(cJSON *const item, parse_buffer *const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) + || (buffer_at_offset(input_buffer)[0] != '{')) { + goto fail; + /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) + && (buffer_at_offset(input_buffer)[0] == '}')) { + goto success; + /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) { + goto fail; + /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) { + /* start the linked list */ + current_item = head = new_item; + } + else { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) { + goto fail; + /* faile to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) + || (buffer_at_offset(input_buffer)[0] != ':')) { + goto fail; + /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) { + goto fail; + /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } while (can_access_at_index(input_buffer, 0) + && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) + || (buffer_at_offset(input_buffer)[0] != '}')) { + goto fail; + /* expected end of object */ + } + +success: + input_buffer->depth--; + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool +print_object(const cJSON *const item, printbuffer *const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) { + return false; + } + + /* Compose the output: */ + length = (size_t)(output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) { + if (output_buffer->format) { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) { + return false; + } + for (i = 0; i < output_buffer->depth; i++) { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char *)current_item->string, + output_buffer)) { + return false; + } + update_offset(output_buffer); + + length = (size_t)(output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) { + return false; + } + if (current_item->next) { + *output_pointer++ = ','; + } + + if (output_buffer->format) { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure( + output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) { + return false; + } + if (output_buffer->format) { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) { + return 0; + } + + child = array->child; + + while (child != NULL) { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON * +get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON * +get_object_item(const cJSON *const object, const char *const name, + const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) { + return NULL; + } + + current_element = object->child; + if (case_sensitive) { + while ((current_element != NULL) && (current_element->string != NULL) + && (strcmp(name, current_element->string) != 0)) { + current_element = current_element->next; + } + } + else { + while ((current_element != NULL) + && (case_insensitive_strcmp( + (const unsigned char *)name, + (const unsigned char *)(current_element->string)) + != 0)) { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItem(const cJSON *const object, const char *const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItemCaseSensitive(const cJSON *const object, + const char *const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) +cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void +suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON * +create_reference(const cJSON *item, const internal_hooks *const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool +add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL)) { + return false; + } + + child = array->child; + + if (child == NULL) { + /* list is empty, start new one */ + array->child = item; + } + else { + /* append to the end */ + while (child->next) { + child = child->next; + } + suffix_object(child, item); + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) \ + || (defined(__GNUC__) \ + && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) +#pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void * +cast_away_const(const void *string) +{ + return (void *)string; +} +#if defined(__clang__) \ + || (defined(__GNUC__) \ + && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) +#pragma GCC diagnostic pop +#endif + +static cJSON_bool +add_item_to_object(cJSON *const object, const char *const string, + cJSON *const item, const internal_hooks *const hooks, + const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL)) { + return false; + } + + if (constant_key) { + new_key = (char *)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else { + new_key = (char *)cJSON_strdup((const unsigned char *)string, hooks); + if (new_key == NULL) { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) { + return false; + } + + return add_item_to_object(object, string, + create_reference(item, &global_hooks), + &global_hooks, false); +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddNullToObject(cJSON *const object, const char *const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddTrueToObject(cJSON *const object, const char *const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddFalseToObject(cJSON *const object, const char *const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddBoolToObject(cJSON *const object, const char *const name, + const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddNumberToObject(cJSON *const object, const char *const name, + const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddStringToObject(cJSON *const object, const char *const name, + const char *const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddRawToObject(cJSON *const object, const char *const name, + const char *const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddObjectToObject(cJSON *const object, const char *const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddArrayToObject(cJSON *const object, const char *const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemViaPointer(cJSON *parent, cJSON *const item) +{ + if ((parent == NULL) || (item == NULL)) { + return NULL; + } + + if (item->prev != NULL) { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) { + /* first element */ + parent->child = item->next; + } + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, + get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) +cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) +cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0) { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) { + return add_item_to_array(array, newitem); + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) { + array->child = newitem; + } + else { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemViaPointer(cJSON *const parent, cJSON *const item, + cJSON *replacement) +{ + if ((parent == NULL) || (replacement == NULL) || (item == NULL)) { + return false; + } + + if (replacement == item) { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) { + replacement->next->prev = replacement; + } + if (replacement->prev != NULL) { + replacement->prev->next = replacement; + } + if (parent->child == item) { + parent->child = replacement; + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(void) +cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) { + return; + } + + cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), + newitem); +} + +static cJSON_bool +replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, + cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) + && (replacement->string != NULL)) { + cJSON_free(replacement->string); + } + replacement->string = + (char *)cJSON_strdup((const unsigned char *)string, &global_hooks); + replacement->type &= ~cJSON_StringIsConst; + + cJSON_ReplaceItemViaPointer( + object, get_object_item(object, string, case_sensitive), replacement); + + return true; +} + +CJSON_PUBLIC(void) +cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(void) +cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, + cJSON *newitem) +{ + replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool b) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = b ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) { + item->valueint = INT_MIN; + } + else { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_String; + item->valuestring = + (char *)cJSON_strdup((const unsigned char *)string, &global_hooks); + if (!item->valuestring) { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char *)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON *)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON *)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_Raw; + item->valuestring = + (char *)cJSON_strdup((const unsigned char *)raw, &global_hooks); + if (!item->valuestring) { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) { + return NULL; + } + + a = cJSON_CreateArray(); + for (i = 0; a && (i < (size_t)count); i++) { + n = cJSON_CreateNumber(numbers[i]); + if (!n) { + cJSON_Delete(a); + return NULL; + } + if (!i) { + a->child = n; + } + else { + suffix_object(p, n); + } + p = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) { + n = cJSON_CreateNumber((double)numbers[i]); + if (!n) { + cJSON_Delete(a); + return NULL; + } + if (!i) { + a->child = n; + } + else { + suffix_object(p, n); + } + p = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) { + n = cJSON_CreateNumber(numbers[i]); + if (!n) { + cJSON_Delete(a); + return NULL; + } + if (!i) { + a->child = n; + } + else { + suffix_object(p, n); + } + p = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) { + n = cJSON_CreateString(strings[i]); + if (!n) { + cJSON_Delete(a); + return NULL; + } + if (!i) { + a->child = n; + } + else { + suffix_object(p, n); + } + p = n; + } + + return a; +} + +/* Duplication */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) { + newitem->valuestring = (char *)cJSON_strdup( + (unsigned char *)item->valuestring, &global_hooks); + if (!newitem->valuestring) { + goto fail; + } + } + if (item->string) { + newitem->string = (item->type & cJSON_StringIsConst) + ? item->string + : (char *)cJSON_strdup( + (unsigned char *)item->string, &global_hooks); + if (!newitem->string) { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) { + newchild = cJSON_Duplicate( + child, + true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) { + goto fail; + } + if (next != NULL) { + /* If newitem->child already set, then crosswire ->prev and ->next + * and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + + return newitem; + +fail: + if (newitem != NULL) { + cJSON_Delete(newitem); + } + + return NULL; +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + unsigned char *into = (unsigned char *)json; + + if (json == NULL) { + return; + } + + while (*json) { + if (*json == ' ') { + json++; + } + else if (*json == '\t') { + /* Whitespace characters. */ + json++; + } + else if (*json == '\r') { + json++; + } + else if (*json == '\n') { + json++; + } + else if ((*json == '/') && (json[1] == '/')) { + /* double-slash comments, to end of line. */ + while (*json && (*json != '\n')) { + json++; + } + } + else if ((*json == '/') && (json[1] == '*')) { + /* multiline comments. */ + while (*json && !((*json == '*') && (json[1] == '/'))) { + json++; + } + json += 2; + } + else if (*json == '\"') { + /* string literals, which are \" sensitive. */ + *into++ = (unsigned char)*json++; + while (*json && (*json != '\"')) { + if (*json == '\\') { + *into++ = (unsigned char)*json++; + } + *into++ = (unsigned char)*json++; + } + *into++ = (unsigned char)*json++; + } + else { + /* All other characters. */ + *into++ = (unsigned char)*json++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON *const item) +{ + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON *const item) +{ + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON *const item) +{ + if (item == NULL) { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON *const item) +{ + if (item == NULL) { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON *const item) +{ + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON *const item) +{ + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON *const item) +{ + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON *const item) +{ + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON *const item) +{ + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON *const item) +{ + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) +cJSON_Compare(const cJSON *const a, const cJSON *const b, + const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) + || cJSON_IsInvalid(a)) { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) { + return true; + } + + switch (a->type & 0xFF) { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (a->valuedouble == b->valuedouble) { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = + get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a + * subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = + get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/cJSON.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/cJSON.h new file mode 100644 index 000000000..d437196a3 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/cJSON.h @@ -0,0 +1,363 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(__WINDOWS__) \ + && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) \ + || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/** + * When compiling for windows, we specify a specific calling convention to avoid + * issues where we are being called from a project with a different default + * calling convention. For windows you have 3 define options: + * CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever + * dllexport symbols + * CJSON_EXPORT_SYMBOLS - Define this on library build when you want to + * dllexport symbols (default) + * CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + * + * For *nix builds that support visibility attribute, you can define similar + * behavior by setting default visibility to hidden by adding + * -fvisibility=hidden (for gcc) + * or + * -xldscope=hidden (for sun cc) + * to CFLAGS, then using the CJSON_API_VISIBILITY flag to "export" the same + * symbols the way CJSON_EXPORT_SYMBOLS does + */ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and + header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) \ + && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined(__SUNPRO_C)) \ + && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 10 + +#include <stddef.h> + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON { + /* next/prev allow you to walk array/object chains. Alternatively, use + GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of + the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list + of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks { + /* malloc/free are CDECL on Windows regardless of the default calling + * convention of the compiler, so ensure the hooks allow passing those + * functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void(CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse + them. This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char *) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks *hooks); + +/* Memory Management: the caller is always responsible to free the results from + * all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib + * free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is + * cJSON_PrintPreallocated, where the caller has full responsibility of the + * buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. + */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +/* ParseWithOpts allows you to require (and check) that the JSON is null + * terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then + * return_parse_end will contain a pointer to the error so will match + * cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) +cJSON_ParseWithOpts(const char *value, const char **return_parse_end, + cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess + * at the final size. guessing well reduces reallocation. fmt=0 gives + * unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) +cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with + * given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will + * use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) +cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, + const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *c); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if + * unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItem(const cJSON *const object, const char *const string); +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItemCaseSensitive(const cJSON *const object, + const char *const string); +CJSON_PUBLIC(cJSON_bool) +cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. + * You'll probably need to look a few chars back to make sense of it. Defined + * when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check if the item is a string and return its valuestring */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON *const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/arrray that only references it's elements so + they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and + * will definitely survive the cJSON object. WARNING: When this function was + * used, make sure to always check that (item->type & cJSON_StringIsConst) is + * zero before writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you + * want to add an existing cJSON to a new cJSON, but don't want to corrupt your + * existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detatch items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemViaPointer(cJSON *parent, cJSON *const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) +cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) +cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) +cJSON_InsertItemInArray( + cJSON *array, int which, + cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemViaPointer(cJSON *const parent, cJSON *const item, + cJSON *replacement); +CJSON_PUBLIC(void) +cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(void) +cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem); +CJSON_PUBLIC(void) +cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, + cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new + memory that will need to be released. With recurse!=0, it will duplicate any + children connected to the item. The item->next and ->prev pointers are always + zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or + * invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or + * case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) +cJSON_Compare(const cJSON *const a, const cJSON *const b, + const cJSON_bool case_sensitive); + +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON *) +cJSON_AddNullToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddTrueToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddFalseToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddBoolToObject(cJSON *const object, const char *const name, + const cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) +cJSON_AddNumberToObject(cJSON *const object, const char *const name, + const double number); +CJSON_PUBLIC(cJSON *) +cJSON_AddStringToObject(cJSON *const object, const char *const name, + const char *const string); +CJSON_PUBLIC(cJSON *) +cJSON_AddRawToObject(cJSON *const object, const char *const name, + const char *const raw); +CJSON_PUBLIC(cJSON *) +cJSON_AddObjectToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddArrayToObject(cJSON *const object, const char *const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble + too. */ +#define cJSON_SetIntValue(object, number) \ + ((object) ? (object)->valueint = (object)->valuedouble = (number) \ + : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) \ + ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) \ + : (number)) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) \ + for (element = (array != NULL) ? (array)->child : NULL; element != NULL; \ + element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with + cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/cjson.cmake b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/cjson.cmake new file mode 100644 index 000000000..af1a9d8a1 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/external/cJSON/cjson.cmake @@ -0,0 +1,10 @@ + +set (CJSON_DIR ${CMAKE_CURRENT_LIST_DIR}) + +include_directories(${CJSON_DIR}) + + +file (GLOB_RECURSE source_all ${CJSON_DIR}/*.c) + +set (CJSON_SOURCE ${source_all}) + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/host_tool_utils.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/host_tool_utils.c new file mode 100644 index 000000000..9ea3d6ca9 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/host_tool_utils.c @@ -0,0 +1,336 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include "host_tool_utils.h" +#include "bi-inc/shared_utils.h" +#include "bh_platform.h" + +#include <time.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <unistd.h> +#include <stdlib.h> + +typedef union jvalue { + bool z; + int8_t i8; + uint8_t u8; + int16_t i16; + uint16_t u16; + int32_t i32; + uint32_t u32; + int64_t i64; + uint64_t u64; + float f; + double d; +} jvalue; + +static inline int16_t +get_int16(const char *buf) +{ + int16_t ret; + bh_memcpy_s(&ret, sizeof(int16_t), buf, sizeof(int16_t)); + return ret; +} + +static inline uint16_t +get_uint16(const char *buf) +{ + return get_int16(buf); +} + +static inline int32_t +get_int32(const char *buf) +{ + int32_t ret; + bh_memcpy_s(&ret, sizeof(int32_t), buf, sizeof(int32_t)); + return ret; +} + +static inline uint32_t +get_uint32(const char *buf) +{ + return get_int32(buf); +} + +char * +attr_container_get_attr_begin(const attr_container_t *attr_cont, + uint32_t *p_total_length, uint16_t *p_attr_num); + +cJSON * +attr2json(const attr_container_t *attr_cont) +{ + uint32_t total_length; + uint16_t attr_num, i, j, type; + const char *p, *tag, *key; + jvalue value; + cJSON *root; + + if (!attr_cont) + return NULL; + + root = cJSON_CreateObject(); + if (!root) + return NULL; + + /* TODO: how to convert the tag? */ + tag = attr_container_get_tag(attr_cont); + if (!tag) + goto fail; + + p = attr_container_get_attr_begin(attr_cont, &total_length, &attr_num); + if (!p) + goto fail; + + for (i = 0; i < attr_num; i++) { + cJSON *obj; + + key = p + 2; + /* Skip key len and key */ + p += 2 + get_uint16(p); + type = *p++; + + switch (type) { + case ATTR_TYPE_BYTE: /* = ATTR_TYPE_INT8 */ + bh_memcpy_s(&value.i8, 1, p, 1); + if (NULL == (obj = cJSON_CreateNumber(value.i8))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p++; + break; + case ATTR_TYPE_SHORT: /* = ATTR_TYPE_INT16 */ + bh_memcpy_s(&value.i16, sizeof(int16_t), p, sizeof(int16_t)); + if (NULL == (obj = cJSON_CreateNumber(value.i16))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + /* another approach: cJSON_AddNumberToObject(root, key, value.s) + */ + p += 2; + break; + case ATTR_TYPE_INT: /* = ATTR_TYPE_INT32 */ + bh_memcpy_s(&value.i32, sizeof(int32_t), p, sizeof(int32_t)); + if (NULL == (obj = cJSON_CreateNumber(value.i32))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 4; + break; + case ATTR_TYPE_INT64: + bh_memcpy_s(&value.i64, sizeof(int64_t), p, sizeof(int64_t)); + if (NULL == (obj = cJSON_CreateNumber(value.i64))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 8; + break; + case ATTR_TYPE_UINT8: + bh_memcpy_s(&value.u8, 1, p, 1); + if (NULL == (obj = cJSON_CreateNumber(value.u8))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p++; + break; + case ATTR_TYPE_UINT16: + bh_memcpy_s(&value.u16, sizeof(uint16_t), p, sizeof(uint16_t)); + if (NULL == (obj = cJSON_CreateNumber(value.u16))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 2; + break; + case ATTR_TYPE_UINT32: + bh_memcpy_s(&value.u32, sizeof(uint32_t), p, sizeof(uint32_t)); + if (NULL == (obj = cJSON_CreateNumber(value.u32))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 4; + break; + case ATTR_TYPE_UINT64: + bh_memcpy_s(&value.u64, sizeof(uint64_t), p, sizeof(uint64_t)); + if (NULL == (obj = cJSON_CreateNumber(value.u64))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 8; + break; + case ATTR_TYPE_FLOAT: + bh_memcpy_s(&value.f, sizeof(float), p, sizeof(float)); + if (NULL == (obj = cJSON_CreateNumber(value.f))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 4; + break; + case ATTR_TYPE_DOUBLE: + bh_memcpy_s(&value.d, sizeof(double), p, sizeof(double)); + if (NULL == (obj = cJSON_CreateNumber(value.d))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += 8; + break; + case ATTR_TYPE_BOOLEAN: + bh_memcpy_s(&value.z, 1, p, 1); + if (NULL == (obj = cJSON_CreateBool(value.z))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p++; + break; + case ATTR_TYPE_STRING: + if (NULL == (obj = cJSON_CreateString(p + sizeof(uint16_t)))) + goto fail; + cJSON_AddItemToObject(root, key, obj); + p += sizeof(uint16_t) + get_uint16(p); + break; + case ATTR_TYPE_BYTEARRAY: + if (NULL == (obj = cJSON_CreateArray())) + goto fail; + cJSON_AddItemToObject(root, key, obj); + for (j = 0; j < get_uint32(p); j++) { + cJSON *item = + cJSON_CreateNumber(*(p + sizeof(uint32_t) + j)); + if (item == NULL) + goto fail; + cJSON_AddItemToArray(obj, item); + } + p += sizeof(uint32_t) + get_uint32(p); + break; + } + } + + return root; + +fail: + cJSON_Delete(root); + return NULL; +} + +attr_container_t * +json2attr(const cJSON *json_obj) +{ + attr_container_t *attr_cont; + cJSON *item; + + if (NULL == (attr_cont = attr_container_create(""))) + return NULL; + + if (!cJSON_IsObject(json_obj)) + goto fail; + + cJSON_ArrayForEach(item, json_obj) + { + + if (cJSON_IsNumber(item)) { + attr_container_set_double(&attr_cont, item->string, + item->valuedouble); + } + else if (cJSON_IsTrue(item)) { + attr_container_set_bool(&attr_cont, item->string, true); + } + else if (cJSON_IsFalse(item)) { + attr_container_set_bool(&attr_cont, item->string, false); + } + else if (cJSON_IsString(item)) { + attr_container_set_string(&attr_cont, item->string, + item->valuestring); + } + else if (cJSON_IsArray(item)) { + int8_t *array; + int i = 0, len = sizeof(int8_t) * cJSON_GetArraySize(item); + cJSON *array_item; + + if (0 == len || NULL == (array = (int8_t *)malloc(len))) + goto fail; + memset(array, 0, len); + + cJSON_ArrayForEach(array_item, item) + { + /* must be number array */ + if (!cJSON_IsNumber(array_item)) + break; + /* TODO: if array_item->valuedouble > 127 or < -128 */ + array[i++] = (int8_t)array_item->valuedouble; + } + if (i > 0) + attr_container_set_bytearray(&attr_cont, item->string, array, + i); + free(array); + } + } + + return attr_cont; + +fail: + attr_container_destroy(attr_cont); + return NULL; +} + +int g_mid = 0; + +int +gen_random_id() +{ + static bool init = false; + int r; + + if (!init) { + srand(time(NULL)); + init = true; + } + + r = rand(); + g_mid = r; + + return r; +} + +char * +read_file_to_buffer(const char *filename, int *ret_size) +{ + char *buffer; + int file; + int file_size, read_size; + struct stat stat_buf; + + if (!filename || !ret_size) { + return NULL; + } + + if ((file = open(filename, O_RDONLY, 0)) == -1) { + return NULL; + } + + if (fstat(file, &stat_buf) != 0) { + close(file); + return NULL; + } + + file_size = stat_buf.st_size; + + if (!(buffer = malloc(file_size))) { + close(file); + return NULL; + } + + read_size = read(file, buffer, file_size); + close(file); + + if (read_size < file_size) { + free(buffer); + return NULL; + } + + *ret_size = file_size; + return buffer; +} + +int +wirte_buffer_to_file(const char *filename, const char *buffer, int size) +{ + int file, ret; + + if ((file = open(filename, O_RDWR | O_CREAT | O_APPEND, 0644)) == -1) + return -1; + + ret = write(file, buffer, size); + + close(file); + + return ret; +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/host_tool_utils.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/host_tool_utils.h new file mode 100644 index 000000000..9b30b41ab --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/host_tool_utils.h @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _HOST_TOOL_UTILS_H_ +#define _HOST_TOOL_UTILS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "bi-inc/attr_container.h" +#include "cJSON.h" + +/** + * @brief Convert attribute container object to cJSON object. + * + * @param attr the attribute container object to be converted + * + * @return the created cJSON object if not NULL, NULL means fail + * + * @warning the return object should be deleted with cJSON_Delete by caller + */ +cJSON * +attr2json(const attr_container_t *attr); + +/** + * @brief Convert cJSON object to attribute container object. + * + * @param json the cJSON object to be converted + * + * @return the created attribute container object if not NULL, NULL means fail + * + * @warning the return object should be deleted with attr_container_destroy + */ +attr_container_t * +json2attr(const cJSON *json); + +/** + * @brief Generate a random 32 bit integer. + * + * @return the generated random integer + */ +int +gen_random_id(); + +/** + * @brief Read file content to buffer. + * + * @param filename the file name to read + * @param ret_size pointer of integer to save file size once return success + * + * @return the created buffer which contains file content if not NULL, NULL + * means fail + * + * @warning the return buffer should be deleted with free by caller + */ +char * +read_file_to_buffer(const char *filename, int *ret_size); + +/** + * @brief Write buffer content to file. + * + * @param filename name the file name to be written + * @param buffer the buffer + * @param size size of the buffer to be written + * + * @return < 0 means fail, > 0 means the number of bytes actually written + */ +int +wirte_buffer_to_file(const char *filename, const char *buffer, int size); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/main.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/main.c new file mode 100644 index 000000000..dbddbf81b --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/main.c @@ -0,0 +1,887 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <getopt.h> +#include <termios.h> +#include <unistd.h> + +#include "host_tool_utils.h" +#include "bi-inc/shared_utils.h" +#include "bi-inc/attr_container.h" +#include "coap_ext.h" +#include "cJSON.h" +#include "app_manager_export.h" /* for Module_WASM_App */ +#include "host_link.h" /* for REQUEST_PACKET */ +#include "transport.h" + +#define BUF_SIZE 1024 +#define TIMEOUT_EXIT_CODE 2 +#define URL_MAX_LEN 256 +#define DEFAULT_TIMEOUT_MS 5000 +#define DEFAULT_ALIVE_TIME_MS 0 + +#define CONNECTION_MODE_TCP 1 +#define CONNECTION_MODE_UART 2 + +typedef enum { + INSTALL, + UNINSTALL, + QUERY, + REQUEST, + REGISTER, + UNREGISTER +} op_type; + +typedef struct { + const char *file; + const char *name; + const char *module_type; + int heap_size; + /* max timers number */ + int timers; + int watchdog_interval; +} inst_info; + +typedef struct { + const char *name; + const char *module_type; +} uninst_info; + +typedef struct { + const char *name; +} query_info; + +typedef struct { + const char *url; + int action; + const char *json_payload_file; +} req_info; + +typedef struct { + const char *urls; +} reg_info; + +typedef struct { + const char *urls; +} unreg_info; + +typedef union operation_info { + inst_info inst; + uninst_info uinst; + query_info query; + req_info req; + reg_info reg; + unreg_info unreg; +} operation_info; + +typedef struct { + op_type type; + operation_info info; +} operation; + +typedef enum REPLY_PACKET_TYPE { + REPLY_TYPE_EVENT = 0, + REPLY_TYPE_RESPONSE = 1 +} REPLY_PACKET_TYPE; + +static uint32_t g_timeout_ms = DEFAULT_TIMEOUT_MS; +static uint32_t g_alive_time_ms = DEFAULT_ALIVE_TIME_MS; +static char *g_redirect_file_name = NULL; +static int g_redirect_udp_port = -1; +static int g_conn_fd; /* may be tcp or uart */ +static char *g_server_addr = "127.0.0.1"; +static int g_server_port = 8888; +static char *g_uart_dev = "/dev/ttyS2"; +static int g_baudrate = B115200; +static int g_connection_mode = CONNECTION_MODE_TCP; + +extern int g_mid; +extern unsigned char leading[2]; + +/* -1 fail, 0 success */ +static int +send_request(request_t *request, uint16_t msg_type) +{ + char *req_p; + int req_size, req_size_n, ret = -1; + + if ((req_p = pack_request(request, &req_size)) == NULL) + return -1; + + /* leading bytes */ + if (!host_tool_send_data(g_conn_fd, leading, sizeof(leading))) + goto ret; + + /* message type */ + msg_type = htons(msg_type); + if (!host_tool_send_data(g_conn_fd, (char *)&msg_type, sizeof(msg_type))) + goto ret; + + /* payload length */ + req_size_n = htonl(req_size); + if (!host_tool_send_data(g_conn_fd, (char *)&req_size_n, + sizeof(req_size_n))) + goto ret; + + /* payload */ + if (!host_tool_send_data(g_conn_fd, req_p, req_size)) + goto ret; + + ret = 0; + +ret: + free_req_resp_packet(req_p); + return ret; +} + +#define url_remain_space (sizeof(url) - strlen(url)) + +/** + * return: 0: success, others: fail + */ +static int +install(inst_info *info) +{ + request_t request[1] = { 0 }; + char *app_file_buf; + char url[URL_MAX_LEN] = { 0 }; + int ret = -1, app_size; + + snprintf(url, sizeof(url) - 1, "/applet?name=%s", info->name); + + if (info->module_type != NULL && url_remain_space > 0) + snprintf(url + strlen(url), url_remain_space, "&type=%s", + info->module_type); + + if (info->heap_size > 0 && url_remain_space > 0) + snprintf(url + strlen(url), url_remain_space, "&heap=%d", + info->heap_size); + + if (info->timers > 0 && url_remain_space > 0) + snprintf(url + strlen(url), url_remain_space, "&timers=%d", + info->timers); + + if (info->watchdog_interval > 0 && url_remain_space > 0) + snprintf(url + strlen(url), url_remain_space, "&wd=%d", + info->watchdog_interval); + + if ((app_file_buf = read_file_to_buffer(info->file, &app_size)) == NULL) + return -1; + + init_request(request, url, COAP_PUT, FMT_APP_RAW_BINARY, app_file_buf, + app_size); + request->mid = gen_random_id(); + + if (info->module_type == NULL || strcmp(info->module_type, "wasm") == 0) + ret = send_request(request, INSTALL_WASM_APP); + else + ret = send_request(request, REQUEST_PACKET); + + free(app_file_buf); + + return ret; +} + +static int +uninstall(uninst_info *info) +{ + request_t request[1] = { 0 }; + char url[URL_MAX_LEN] = { 0 }; + + snprintf(url, sizeof(url) - 1, "/applet?name=%s", info->name); + + if (info->module_type != NULL && url_remain_space > 0) + snprintf(url + strlen(url), url_remain_space, "&type=%s", + info->module_type); + + init_request(request, url, COAP_DELETE, FMT_ATTR_CONTAINER, NULL, 0); + request->mid = gen_random_id(); + + return send_request(request, REQUEST_PACKET); +} + +static int +query(query_info *info) +{ + request_t request[1] = { 0 }; + char url[URL_MAX_LEN] = { 0 }; + + if (info->name != NULL) + snprintf(url, sizeof(url) - 1, "/applet?name=%s", info->name); + else + snprintf(url, sizeof(url) - 1, "/applet"); + + init_request(request, url, COAP_GET, FMT_ATTR_CONTAINER, NULL, 0); + request->mid = gen_random_id(); + + return send_request(request, REQUEST_PACKET); +} + +static int +request(req_info *info) +{ + request_t request[1] = { 0 }; + attr_container_t *payload = NULL; + int ret = -1, payload_len = 0; + + if (info->json_payload_file != NULL) { + char *payload_file; + cJSON *json; + int payload_file_size; + + if ((payload_file = read_file_to_buffer(info->json_payload_file, + &payload_file_size)) + == NULL) + return -1; + + if (NULL == (json = cJSON_Parse(payload_file))) { + free(payload_file); + goto fail; + } + + if (NULL == (payload = json2attr(json))) { + cJSON_Delete(json); + free(payload_file); + goto fail; + } + payload_len = attr_container_get_serialize_length(payload); + + cJSON_Delete(json); + free(payload_file); + } + + init_request(request, (char *)info->url, info->action, FMT_ATTR_CONTAINER, + payload, payload_len); + request->mid = gen_random_id(); + + ret = send_request(request, REQUEST_PACKET); + + if (info->json_payload_file != NULL && payload != NULL) + attr_container_destroy(payload); + +fail: + return ret; +} + +/** + * TODO: currently only support 1 url. + * how to handle multiple responses and set process's exit code? + */ +static int +subscribe(reg_info *info) +{ + request_t request[1] = { 0 }; + int ret = -1; +#if 0 + char *p; + + p = strtok(info->urls, ","); + while(p != NULL) { + char url[URL_MAX_LEN] = {0}; + snprintf(url, URL_MAX_LEN, "%s%s", "/event/", p); + init_request(request, + url, + COAP_PUT, + FMT_ATTR_CONTAINER, + NULL, + 0); + request->mid = gen_random_id(); + ret = send_request(request, false); + p = strtok (NULL, ","); + } +#else + char url[URL_MAX_LEN] = { 0 }; + char *prefix = info->urls[0] == '/' ? "/event" : "/event/"; + snprintf(url, URL_MAX_LEN, "%s%s", prefix, info->urls); + init_request(request, url, COAP_PUT, FMT_ATTR_CONTAINER, NULL, 0); + request->mid = gen_random_id(); + ret = send_request(request, REQUEST_PACKET); +#endif + return ret; +} + +static int +unsubscribe(unreg_info *info) +{ + request_t request[1] = { 0 }; + int ret = -1; +#if 0 + char *p; + + p = strtok(info->urls, ","); + while(p != NULL) { + char url[URL_MAX_LEN] = {0}; + snprintf(url, URL_MAX_LEN, "%s%s", "/event/", p); + init_request(request, + url, + COAP_DELETE, + FMT_ATTR_CONTAINER, + NULL, + 0); + request->mid = gen_random_id(); + ret = send_request(request, false); + p = strtok (NULL, ","); + } +#else + char url[URL_MAX_LEN] = { 0 }; + snprintf(url, URL_MAX_LEN, "%s%s", "/event/", info->urls); + init_request(request, url, COAP_DELETE, FMT_ATTR_CONTAINER, NULL, 0); + request->mid = gen_random_id(); + ret = send_request(request, REQUEST_PACKET); +#endif + return ret; +} + +static int +init() +{ + if (g_connection_mode == CONNECTION_MODE_TCP) { + int fd; + if (!tcp_init(g_server_addr, g_server_port, &fd)) + return -1; + g_conn_fd = fd; + return 0; + } + else if (g_connection_mode == CONNECTION_MODE_UART) { + int fd; + if (!uart_init(g_uart_dev, g_baudrate, &fd)) + return -1; + g_conn_fd = fd; + return 0; + } + + return -1; +} + +static void +deinit() +{ + close(g_conn_fd); +} + +static int +parse_action(const char *str) +{ + if (strcasecmp(str, "PUT") == 0) + return COAP_PUT; + if (strcasecmp(str, "GET") == 0) + return COAP_GET; + if (strcasecmp(str, "DELETE") == 0) + return COAP_DELETE; + if (strcasecmp(str, "POST") == 0) + return COAP_POST; + return -1; +} + +/* clang-format off */ +static void showUsage() +{ + printf("Usages:\n"); + printf(" host_tool -i|-u|-q|-r|-s|-d ...\n"); + printf(" host_tool -i <App Name> -f <App File>\n" + " [--type=<App Type>]\n" + " [--heap=<Heap Size>]\n" + " [--timers=<Timers Number>]\n" + " [--watchdog=<Watchdog Interval>]\n" + " [<Control Options> ...] \n"); + printf(" host_tool -u <App Name> [<Control Options> ...]\n"); + printf(" host_tool -q[<App Name>] [<Control Options> ...]\n"); + printf(" host_tool -r <Resource URL> -A <Action> [-p <Payload File>] [<Control Options> ...]\n"); + printf(" host_tool -s <Event URLs> [<Control Options> ...]\n"); + printf(" host_tool -d <Event URLs> [<Control Options> ...]\n"); + + printf("\nGeneral Options:\n"); + printf(" -i, --install Install an application\n"); + printf(" -u, --uninstall Uninstall an application\n"); + printf(" -q, --query Query all applications\n"); + printf(" -r, --request Send a request\n"); + printf(" -s, --register Register event(s)\n"); + printf(" -d, --deregister De-register event(s)\n"); + printf(" -f, --file Specify app binary file path\n"); + printf(" -A, --action Specify action of the request\n"); + printf(" -p, --payload Specify payload of the request\n"); + + printf("\nControl Options:\n"); + printf(" -S <Address>|--address=<Address> Set server address, default to 127.0.0.1\n"); + printf(" -P <Port>|--port=<Port> Set server port, default to 8888\n"); + printf(" -D <Device>|--uart=<Device> Set uart device, default to /dev/ttyS2\n"); + printf(" -B <Baudrate>|--baudrate=<Baudrate> Set uart device baudrate, default to 115200\n"); + printf(" -t <timeout>|--timeout=<timeout> Operation timeout in ms, default to 5000\n"); + printf(" -a <alive_time>|--alive=<alive_time> Alive time in ms after last operation done, default to 0\n"); + printf(" -o <output_file>|--output=<output_file> Redirect the output to output a file\n"); + printf(" -U <udp_port>|--udp=<udp_port> Redirect the output to an UDP port in local machine\n"); + + printf("\nNotes:\n"); + printf(" <App Name>=name of the application\n"); + printf(" <App File>=path of the application binary file in wasm format\n"); + printf(" <Resource URL>=resource descriptor, such as /app/<App Name>/res1 or /res1\n"); + printf(" <Event URLs>=event url list separated by ',', such as /event1,/event2,/event3\n"); + printf(" <Action>=action of the request, can be PUT, GET, DELETE or POST (case insensitive)\n"); + printf(" <Payload File>=path of the payload file in json format\n"); + printf(" <App Type>=Type of app. Can be 'wasm'(default) or 'jeff'\n"); + printf(" <Heap Size>=Heap size of app.\n"); + printf(" <Timers Number>=Max timers number app can use.\n"); + printf(" <Watchdog Interval>=Watchdog interval in ms.\n"); +} + +#define CHECK_DUPLICATE_OPERATION do { \ + if (operation_parsed) { \ + showUsage(); \ + return false; \ + } \ +} while(0) + +#define ERROR_RETURN do { \ + showUsage(); \ + return false; \ +} while(0) + +#define CHECK_ARGS_UNMATCH_OPERATION(op_type) do { \ + if (!operation_parsed || op->type != op_type) { \ + showUsage(); \ + return false; \ + } \ +} while(0) + +static bool parse_args(int argc, char *argv[], operation *op) +{ + int c; + bool operation_parsed = false; + bool conn_mode_parsed = false; + + while (1) { + int optIndex = 0; + static struct option longOpts[] = { + { "install", required_argument, NULL, 'i' }, + { "uninstall", required_argument, NULL, 'u' }, + { "query", optional_argument, NULL, 'q' }, + { "request", required_argument, NULL, 'r' }, + { "register", required_argument, NULL, 's' }, + { "deregister", required_argument, NULL, 'd' }, + { "timeout", required_argument, NULL, 't' }, + { "alive", required_argument, NULL, 'a' }, + { "output", required_argument, NULL, 'o' }, + { "udp", required_argument, NULL, 'U' }, + { "action", required_argument, NULL, 'A' }, + { "file", required_argument, NULL, 'f' }, + { "payload", required_argument, NULL, 'p' }, + { "type", required_argument, NULL, 0 }, + { "heap", required_argument, NULL, 1 }, + { "timers", required_argument, NULL, 2 }, + { "watchdog", required_argument, NULL, 3 }, + { "address", required_argument, NULL, 'S' }, + { "port", required_argument, NULL, 'P' }, + { "uart_device",required_argument, NULL, 'D' }, + { "baudrate", required_argument, NULL, 'B' }, + { "help", required_argument, NULL, 'h' }, + { 0, 0, 0, 0 } + }; + + c = getopt_long(argc, argv, "i:u:q::r:s:d:t:a:o:U:A:f:p:S:P:D:B:h", + longOpts, &optIndex); + if (c == -1) + break; + + switch (c) { + case 'i': + CHECK_DUPLICATE_OPERATION; + op->type = INSTALL; + op->info.inst.name = optarg; + operation_parsed = true; + break; + case 'u': + CHECK_DUPLICATE_OPERATION; + op->type = UNINSTALL; + op->info.uinst.name = optarg; + operation_parsed = true; + break; + case 'q': + CHECK_DUPLICATE_OPERATION; + op->type = QUERY; + op->info.query.name = optarg; + break; + case 'r': + CHECK_DUPLICATE_OPERATION; + op->type = REQUEST; + op->info.req.url = optarg; + operation_parsed = true; + break; + case 's': + CHECK_DUPLICATE_OPERATION; + op->type = REGISTER; + op->info.reg.urls = optarg; + operation_parsed = true; + break; + case 'd': + CHECK_DUPLICATE_OPERATION; + op->type = UNREGISTER; + op->info.unreg.urls = optarg; + operation_parsed = true; + break; + case 't': + g_timeout_ms = atoi(optarg); + break; + case 'a': + g_alive_time_ms = atoi(optarg); + break; + case 'o': + g_redirect_file_name = optarg; + break; + case 'U': + g_redirect_udp_port = atoi(optarg); + break; + case 'A': + CHECK_ARGS_UNMATCH_OPERATION(REQUEST); + op->info.req.action = parse_action(optarg); + break; + case 'f': + CHECK_ARGS_UNMATCH_OPERATION(INSTALL); + op->info.inst.file = optarg; + break; + case 'p': + CHECK_ARGS_UNMATCH_OPERATION(REQUEST); + op->info.req.json_payload_file = optarg; + break; + /* module type */ + case 0: + /* TODO: use bit mask */ + /* CHECK_ARGS_UNMATCH_OPERATION(INSTALL | UNINSTALL); */ + if (op->type == INSTALL) + op->info.inst.module_type = optarg; + else if (op->type == UNINSTALL) + op->info.uinst.module_type = optarg; + break; + /* heap */ + case 1: + CHECK_ARGS_UNMATCH_OPERATION(INSTALL); + op->info.inst.heap_size = atoi(optarg); + break; + /* timers */ + case 2: + CHECK_ARGS_UNMATCH_OPERATION(INSTALL); + op->info.inst.timers = atoi(optarg); + break; + /* watchdog */ + case 3: + CHECK_ARGS_UNMATCH_OPERATION(INSTALL); + op->info.inst.watchdog_interval = atoi(optarg); + break; + case 'S': + if (conn_mode_parsed) { + showUsage(); + return false; + } + g_connection_mode = CONNECTION_MODE_TCP; + g_server_addr = optarg; + conn_mode_parsed = true; + break; + case 'P': + g_server_port = atoi(optarg); + break; + case 'D': + if (conn_mode_parsed) { + showUsage(); + return false; + } + g_connection_mode = CONNECTION_MODE_UART; + g_uart_dev = optarg; + conn_mode_parsed = true; + break; + case 'B': + g_baudrate = parse_baudrate(atoi(optarg)); + break; + case 'h': + showUsage(); + return false; + default: + showUsage(); + return false; + } + } + + /* check mandatory options for the operation */ + switch (op->type) { + case INSTALL: + if (NULL == op->info.inst.file || NULL == op->info.inst.name) + ERROR_RETURN; + break; + case UNINSTALL: + if (NULL == op->info.uinst.name) + ERROR_RETURN; + break; + case QUERY: + break; + case REQUEST: + if (NULL == op->info.req.url || op->info.req.action <= 0) + ERROR_RETURN; + break; + case REGISTER: + if (NULL == op->info.reg.urls) + ERROR_RETURN; + break; + case UNREGISTER: + if (NULL == op->info.unreg.urls) + ERROR_RETURN; + break; + default: + return false; + } + + return true; +} + +/** + * return value: < 0: not complete message + * REPLY_TYPE_EVENT: event(request) + * REPLY_TYPE_RESPONSE: response + */ +static int process_reply_data(const char *buf, int len, + imrt_link_recv_context_t *ctx) +{ + int result = -1; + const char *pos = buf; + +#if DEBUG + int i = 0; + for (; i < len; i++) { + printf(" 0x%02x", buf[i]); + } + printf("\n"); +#endif + + while (len-- > 0) { + result = on_imrt_link_byte_arrive((unsigned char) *pos++, ctx); + switch (result) { + case 0: { + imrt_link_message_t *message = &ctx->message; + if (message->message_type == RESPONSE_PACKET) + return REPLY_TYPE_RESPONSE; + if (message->message_type == REQUEST_PACKET) + return REPLY_TYPE_EVENT; + break; + } + default: + break; + } + } + + return -1; +} + +static response_t * +parse_response_from_imrtlink(imrt_link_message_t *message, response_t *response) +{ + if (!unpack_response(message->payload, message->payload_size, response)) + return NULL; + + return response; +} + +static request_t * +parse_event_from_imrtlink(imrt_link_message_t *message, request_t *request) +{ + if (!unpack_request(message->payload, message->payload_size, request)) + return NULL; + + return request; +} + +static void output(const char *header, attr_container_t *payload, + int foramt, int payload_len) +{ + cJSON *json = NULL; + char *json_str = NULL; + + /* output the header */ + printf("%s", header); + if (g_redirect_file_name != NULL) + wirte_buffer_to_file(g_redirect_file_name, header, strlen(header)); + if (g_redirect_udp_port > 0 && g_redirect_udp_port < 65535) + udp_send("127.0.0.1", g_redirect_udp_port, header, strlen(header)); + + if (foramt != FMT_ATTR_CONTAINER || payload == NULL || payload_len <= 0) + return; + + if ((json = attr2json(payload)) == NULL) + return; + + if ((json_str = cJSON_Print(json)) == NULL) { + cJSON_Delete(json); + return; + } + + /* output the payload as json format */ + printf("%s", json_str); + if (g_redirect_file_name != NULL) + wirte_buffer_to_file(g_redirect_file_name, json_str, strlen(json_str)); + if (g_redirect_udp_port > 0 && g_redirect_udp_port < 65535) + udp_send("127.0.0.1", g_redirect_udp_port, json_str, strlen(json_str)); + + free(json_str); + cJSON_Delete(json); +} + +static void output_response(response_t *obj) +{ + char header[32] = { 0 }; + snprintf(header, sizeof(header), "\nresponse status %d\n", obj->status); + output(header, obj->payload, obj->fmt, obj->payload_len); +} + +static void output_event(request_t *obj) +{ + char header[256] = { 0 }; + snprintf(header, sizeof(header), "\nreceived an event %s\n", obj->url); + output(header, obj->payload, obj->fmt, obj->payload_len); +} + +int main(int argc, char *argv[]) +{ + int ret = -1; + imrt_link_recv_context_t recv_ctx = { 0 }; + char buffer[BUF_SIZE] = { 0 }; + uint32_t last_check = 0, total_elpased_ms = 0; + bool is_responsed = false; + operation op; + + memset(&op, 0, sizeof(op)); + + if (!parse_args(argc, argv, &op)) + return -1; + + /* TODO: reconnect 3 times */ + if (init() != 0) + return -1; + + switch (op.type) { + case INSTALL: + ret = install((inst_info *) &op.info.inst); + break; + case UNINSTALL: + ret = uninstall((uninst_info *) &op.info.uinst); + break; + case QUERY: + ret = query((query_info *) &op.info.query); + break; + case REQUEST: + ret = request((req_info *) &op.info.req); + break; + case REGISTER: + ret = subscribe((reg_info *) &op.info.reg); + break; + case UNREGISTER: + ret = unsubscribe((unreg_info *) &op.info.unreg); + break; + default: + goto ret; + } + + if (ret != 0) + goto ret; + + bh_get_elpased_ms(&last_check); + + while (1) { + int result = 0; + fd_set readfds; + struct timeval tv; + + total_elpased_ms += bh_get_elpased_ms(&last_check); + + if (!is_responsed) { + if (total_elpased_ms >= g_timeout_ms) { + output("operation timeout\n", NULL, 0, 0); + ret = TIMEOUT_EXIT_CODE; + goto ret; + } + } else { + if (total_elpased_ms >= g_alive_time_ms) { + /*ret = 0;*/ + goto ret; + } + } + + if (g_conn_fd == -1) { + if ((init() != 0) + || (g_conn_fd == -1)) { + sleep(1); + continue; + } + } + + FD_ZERO(&readfds); + FD_SET(g_conn_fd, &readfds); + + tv.tv_sec = 1; + tv.tv_usec = 0; + + result = select(FD_SETSIZE, &readfds, NULL, NULL, &tv); + + if (result < 0) { + if (errno != EINTR) { + printf("Error in select, errno: 0x%x\n", errno); + ret = -1; + goto ret; + } + } + else if (result == 0) { /* select timeout */ + } + else if (result > 0) { + int n; + if (FD_ISSET(g_conn_fd, &readfds)) { + int reply_type = -1; + + n = read(g_conn_fd, buffer, BUF_SIZE); + if (n <= 0) { + g_conn_fd = -1; + continue; + } + + reply_type = process_reply_data((char *) buffer, n, &recv_ctx); + + if (reply_type == REPLY_TYPE_RESPONSE) { + response_t response[1] = { 0 }; + + parse_response_from_imrtlink(&recv_ctx.message, response); + + if (response->mid != g_mid) { + /* ignore invalid response */ + continue; + } + + is_responsed = true; + ret = response->status; + output_response(response); + + if (op.type == REGISTER || op.type == UNREGISTER) { + /* alive time start */ + total_elpased_ms = 0; + bh_get_elpased_ms(&last_check); + } + } + else if (reply_type == REPLY_TYPE_EVENT) { + request_t event[1] = { 0 }; + + parse_event_from_imrtlink(&recv_ctx.message, event); + + if (op.type == REGISTER || op.type == UNREGISTER) { + output_event(event); + } + } + } + } + } /* end of while(1) */ + +ret: + if (recv_ctx.message.payload != NULL) + free(recv_ctx.message.payload); + + deinit(); + return ret; +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/transport.c b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/transport.c new file mode 100644 index 000000000..d4edf4f1d --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/transport.c @@ -0,0 +1,263 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#include <stdbool.h> +#include <errno.h> +#include <stdlib.h> +#include <sys/socket.h> +#include <sys/types.h> +#include <string.h> +#include <unistd.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <netinet/in.h> +#include <termios.h> +#include <fcntl.h> + +#include "transport.h" + +#define SA struct sockaddr + +unsigned char leading[2] = { 0x12, 0x34 }; + +bool +tcp_init(const char *address, uint16_t port, int *fd) +{ + int sock; + struct sockaddr_in servaddr; + + if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) + return false; + + bzero(&servaddr, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = inet_addr(address); + servaddr.sin_port = htons(port); + + if (connect(sock, (SA *)&servaddr, sizeof(servaddr)) != 0) { + close(sock); + return false; + } + + *fd = sock; + return true; +} + +int +parse_baudrate(int baud) +{ + switch (baud) { + case 9600: + return B9600; + case 19200: + return B19200; + case 38400: + return B38400; + case 57600: + return B57600; + case 115200: + return B115200; + case 230400: + return B230400; + case 460800: + return B460800; + case 500000: + return B500000; + case 576000: + return B576000; + case 921600: + return B921600; + case 1000000: + return B1000000; + case 1152000: + return B1152000; + case 1500000: + return B1500000; + case 2000000: + return B2000000; + case 2500000: + return B2500000; + case 3000000: + return B3000000; + case 3500000: + return B3500000; + case 4000000: + return B4000000; + default: + return -1; + } +} + +bool +uart_init(const char *device, int baudrate, int *fd) +{ + int uart_fd; + struct termios uart_term; + + uart_fd = open(device, O_RDWR | O_NOCTTY); + + if (uart_fd < 0) + return false; + + memset(&uart_term, 0, sizeof(uart_term)); + uart_term.c_cflag = baudrate | CS8 | CLOCAL | CREAD; + uart_term.c_iflag = IGNPAR; + uart_term.c_oflag = 0; + + /* set noncanonical mode */ + uart_term.c_lflag = 0; + uart_term.c_cc[VTIME] = 30; + uart_term.c_cc[VMIN] = 1; + tcflush(uart_fd, TCIFLUSH); + + if (tcsetattr(uart_fd, TCSANOW, &uart_term) != 0) { + close(uart_fd); + return false; + } + + *fd = uart_fd; + return true; +} + +bool +udp_send(const char *address, int port, const char *buf, int len) +{ + int sockfd; + ssize_t size_sent; + struct sockaddr_in servaddr; + + if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) + return false; + + memset(&servaddr, 0, sizeof(servaddr)); + + servaddr.sin_family = AF_INET; + servaddr.sin_port = htons(port); + servaddr.sin_addr.s_addr = INADDR_ANY; + + size_sent = sendto(sockfd, buf, len, MSG_CONFIRM, + (const struct sockaddr *)&servaddr, sizeof(servaddr)); + + close(sockfd); + return (size_sent != -1) ? true : false; +} + +bool +host_tool_send_data(int fd, const char *buf, unsigned int len) +{ + int cnt = 0; + ssize_t ret; + + if (fd == -1 || buf == NULL || len <= 0) { + return false; + } + +resend: + ret = write(fd, buf, len); + + if (ret == -1) { + if (errno == ECONNRESET) { + close(fd); + } + + // repeat sending if the outbuffer is full + if (errno == EAGAIN || errno == EWOULDBLOCK) { + if (++cnt > 10) { + close(fd); + return false; + } + sleep(1); + goto resend; + } + } + + return (ret == len); +} + +#define SET_RECV_PHASE(ctx, new_phase) \ + do { \ + ctx->phase = new_phase; \ + ctx->size_in_phase = 0; \ + } while (0) + +/* + * input: 1 byte from remote + * output: parse result + * return: -1 invalid sync byte + * 1 byte added to buffer, waiting more for complete packet + * 0 completed packet + * 2 in receiving payload + */ +int +on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx) +{ + if (ctx->phase == Phase_Non_Start) { + if (ctx->message.payload) { + free(ctx->message.payload); + ctx->message.payload = NULL; + ctx->message.payload_size = 0; + } + + if (leading[0] == ch) { + ctx->phase = Phase_Leading; + } + else { + return -1; + } + } + else if (ctx->phase == Phase_Leading) { + if (leading[1] == ch) { + SET_RECV_PHASE(ctx, Phase_Type); + } + else { + ctx->phase = Phase_Non_Start; + return -1; + } + } + else if (ctx->phase == Phase_Type) { + unsigned char *p = (unsigned char *)&ctx->message.message_type; + p[ctx->size_in_phase++] = ch; + + if (ctx->size_in_phase == sizeof(ctx->message.message_type)) { + ctx->message.message_type = ntohs(ctx->message.message_type); + SET_RECV_PHASE(ctx, Phase_Size); + } + } + else if (ctx->phase == Phase_Size) { + unsigned char *p = (unsigned char *)&ctx->message.payload_size; + p[ctx->size_in_phase++] = ch; + + if (ctx->size_in_phase == sizeof(ctx->message.payload_size)) { + ctx->message.payload_size = ntohl(ctx->message.payload_size); + SET_RECV_PHASE(ctx, Phase_Payload); + + if (ctx->message.payload) { + free(ctx->message.payload); + ctx->message.payload = NULL; + } + + /* no payload */ + if (ctx->message.payload_size == 0) { + SET_RECV_PHASE(ctx, Phase_Non_Start); + return 0; + } + + ctx->message.payload = (char *)malloc(ctx->message.payload_size); + SET_RECV_PHASE(ctx, Phase_Payload); + } + } + else if (ctx->phase == Phase_Payload) { + ctx->message.payload[ctx->size_in_phase++] = ch; + + if (ctx->size_in_phase == ctx->message.payload_size) { + SET_RECV_PHASE(ctx, Phase_Non_Start); + return 0; + } + + return 2; + } + + return 1; +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/transport.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/transport.h new file mode 100644 index 000000000..449f438f8 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/host-tool/src/transport.h @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef DEPS_APP_MGR_HOST_TOOL_SRC_TRANSPORT_H_ +#define DEPS_APP_MGR_HOST_TOOL_SRC_TRANSPORT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* IMRT link message between host and WAMR */ +typedef struct { + unsigned short message_type; + unsigned int payload_size; + char *payload; +} imrt_link_message_t; + +/* The receive phase of IMRT link message */ +typedef enum { + Phase_Non_Start, + Phase_Leading, + Phase_Type, + Phase_Size, + Phase_Payload +} recv_phase_t; + +/* The receive context of IMRT link message */ +typedef struct { + recv_phase_t phase; + int size_in_phase; + imrt_link_message_t message; +} imrt_link_recv_context_t; + +/** + * @brief Send data to WAMR. + * + * @param fd the connection fd to WAMR + * @param buf the buffer that contains content to be sent + * @param len size of the buffer to be sent + * + * @return true if success, false if fail + */ +bool +host_tool_send_data(int fd, const char *buf, unsigned int len); + +/** + * @brief Handle one byte of IMRT link message + * + * @param ch the one byte from WAMR to be handled + * @param ctx the receive context + * + * @return -1 invalid sync byte + * 1 byte added to buffer, waiting more for complete packet + * 0 completed packet + * 2 in receiving payload + */ +int +on_imrt_link_byte_arrive(unsigned char ch, imrt_link_recv_context_t *ctx); + +/** + * @brief Initialize TCP connection with remote server. + * + * @param address the network address of peer + * @param port the network port of peer + * @param fd pointer of integer to save the socket fd once return success + * + * @return true if success, false if fail + */ +bool +tcp_init(const char *address, uint16_t port, int *fd); + +/** + * @brief Initialize UART connection with remote. + * + * @param device name of the UART device + * @param baudrate baudrate of the device + * @param fd pointer of integer to save the uart fd once return success + * + * @return true if success, false if fail + */ +bool +uart_init(const char *device, int baudrate, int *fd); + +/** + * @brief Parse UART baudrate from an integer + * + * @param the baudrate interger to be parsed + * + * @return true if success, false if fail + * + * @par + * @code + * int baudrate = parse_baudrate(9600); + * ... + * uart_term.c_cflag = baudrate; + * ... + * @endcode + */ +int +parse_baudrate(int baud); + +/** + * @brief Send data over UDP. + * + * @param address network address of the remote + * @param port network port of the remote + * @param buf the buffer that contains content to be sent + * @param len size of the buffer to be sent + * + * @return true if success, false if fail + */ +bool +udp_send(const char *address, int port, const char *buf, int len); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* DEPS_APP_MGR_HOST_TOOL_SRC_TRANSPORT_H_ */ diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/pick-up-emscripten-headers/collect_files.py b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/pick-up-emscripten-headers/collect_files.py new file mode 100755 index 000000000..7e832145f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/pick-up-emscripten-headers/collect_files.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# + +""" +The script operates on such directories and files +|-- core +| `-- deps +| |-- emscripten +|-- samples +| `-- workloads +| |-- include +`-- test-tools + |-- pick-up-emscripten_headers + | |-- collect_files.py +""" + +import argparse +import hashlib +import logging +import os +import pathlib +import shutil +import sys +import tarfile +import tempfile +import urllib +import urllib.request + +logger = logging.getLogger("pick-up-emscripten-headers") + +external_repos = { + "emscripten": { + "sha256": "c5524755b785d8f4b83eb3214fdd3ac4b2e1b1a4644df4c63f06e5968f48f90e", + "store_dir": "core/deps/emscripten", + "strip_prefix": "emscripten-3.0.0", + "url": "https://github.com/emscripten-core/emscripten/archive/refs/tags/3.0.0.tar.gz", + } +} + +# TOOD: can we use headers from wasi-libc and clang directly ? +emscripten_headers_src_dst = [ + ("include/compat/emmintrin.h", "sse/emmintrin.h"), + ("include/compat/immintrin.h", "sse/immintrin.h"), + ("include/compat/smmintrin.h", "sse/smmintrin.h"), + ("include/compat/xmmintrin.h", "sse/xmmintrin.h"), + ("lib/libc/musl/include/pthread.h", "libc/musl/pthread.h"), + ("lib/libc/musl/include/signal.h", "libc/musl/signal.h"), + ("lib/libc/musl/include/netdb.h", "libc/musl/netdb.h"), + ("lib/libc/musl/include/sys/wait.h", "libc/musl/sys/wait.h"), + ("lib/libc/musl/include/sys/socket.h", "libc/musl/sys/socket.h"), + ("lib/libc/musl/include/setjmp.h", "libc/musl/setjmp.h"), + ("lib/libc/musl/arch/emscripten/bits/setjmp.h", "libc/musl/bits/setjmp.h"), +] + + +def checksum(name, local_file): + sha256 = hashlib.sha256() + with open(local_file, "rb") as f: + bytes = f.read(4096) + while bytes: + sha256.update(bytes) + bytes = f.read(4096) + + return sha256.hexdigest() == external_repos[name]["sha256"] + + +def download(url, local_file): + logger.debug(f"download from {url}") + urllib.request.urlretrieve(url, local_file) + return local_file.exists() + + +def unpack(tar_file, strip_prefix, dest_dir): + # extract .tar.gz to /tmp, then move back without strippred prefix directories + with tempfile.TemporaryDirectory() as tmp: + with tarfile.open(tar_file) as tar: + logger.debug(f"extract to {tmp}") + + def is_within_directory(directory, target): + + abs_directory = os.path.abspath(directory) + abs_target = os.path.abspath(target) + + prefix = os.path.commonprefix([abs_directory, abs_target]) + + return prefix == abs_directory + + def safe_extract(tar, path=".", members=None, *, numeric_owner=False): + + for member in tar.getmembers(): + member_path = os.path.join(path, member.name) + if not is_within_directory(path, member_path): + raise Exception("Attempted Path Traversal in Tar File") + + tar.extractall(path, members, numeric_owner=numeric_owner) + + safe_extract(tar, tmp) + + strip_prefix_dir = ( + pathlib.Path(tmp).joinpath(strip_prefix + os.path.sep).resolve() + ) + if not strip_prefix_dir.exists(): + logger.error(f"extract {tar_file.name} failed") + return False + + # mv /tmp/${strip_prefix} dest_dir/* + logger.debug(f"move {strip_prefix_dir} to {dest_dir}") + shutil.copytree( + str(strip_prefix_dir), + str(dest_dir), + copy_function=shutil.move, + dirs_exist_ok=True, + ) + + return True + + +def download_repo(name, root): + if not name in external_repos: + logger.error(f"{name} is not a known repository") + return False + + store_dir = root.joinpath(f'{external_repos[name]["store_dir"]}').resolve() + download_flag = store_dir.joinpath("DOWNLOADED") + if store_dir.exists() and download_flag.exists(): + logger.info( + f"bypass downloading '{store_dir.relative_to(root)}'. Or to remove it and try again if needs a new release" + ) + return True + + # download only when the target is neither existed nor broken + download_dir = pathlib.Path("/tmp/pick-up-emscripten-headers/") + download_dir.mkdir(exist_ok=True) + + tar_name = pathlib.Path(external_repos[name]["url"]).name + tar_file = download_dir.joinpath(tar_name) + if tar_file.exists(): + if checksum(name, tar_file): + logger.debug(f"use pre-downloaded {tar_file}") + else: + logger.debug(f"{tar_file} is broken, remove it") + tar_file.unlink() + + if not tar_file.exists(): + if not download(external_repos[name]["url"], tar_file) or not checksum( + name, tar_file + ): + logger.error(f"download {name} failed") + return False + + # unpack and removing *strip_prefix* + if not unpack(tar_file, external_repos[name]["strip_prefix"], store_dir): + return False + + # leave a FLAG + download_flag.touch() + + # leave download files in /tmp + logger.info(f"Has downloaed and stored in {store_dir.relative_to(root)}") + return True + + +def collect_headers(root, install_location): + if not install_location.exists(): + logger.error(f"{install_location} does not found") + return False + + install_flag = install_location.joinpath("INSTALLED").resolve() + if install_flag.exists(): + logger.info( + f"bypass downloading '{install_location}'. Or to remove it and try again if needs a new one" + ) + return True + + emscripten_home = root.joinpath( + f'{external_repos["emscripten"]["store_dir"]}' + ).resolve() + if not emscripten_home.exists(): + logger.error(f"{emscripten_home} does not found") + return False + + emscripten_headers = emscripten_home.joinpath("system").resolve() + for (src, dst) in emscripten_headers_src_dst: + src = emscripten_headers.joinpath(src) + dst = install_location.joinpath(dst) + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(src, dst) + + install_flag.touch() + logger.info(f"Has installed in {install_location}") + return True + + +def main(): + parser = argparse.ArgumentParser( + description="collect headers from emscripten for workload compilation" + ) + parser.add_argument( + "--install", + type=str, + required=True, + help="identify installation location", + ) + parser.add_argument( + "--loglevel", + type=str, + default="INFO", + choices=[ + "ERROR", + "WARNING", + "INFO", + ], + help="the logging level", + ) + options = parser.parse_args() + + console = logging.StreamHandler() + console.setFormatter(logging.Formatter("%(asctime)s - %(message)s")) + logger.setLevel(getattr(logging, options.loglevel)) + logger.addHandler(console) + logger.propagate = False + + # locate the root of WAMR + current_file = pathlib.Path(__file__) + if current_file.is_symlink(): + current_file = pathlib.Path(os.readlink(current_file)) + root = current_file.parent.joinpath("../..").resolve() + logger.info(f"The root of WAMR is {root}") + + # download repos + for repo in external_repos.keys(): + if not download_repo(repo, root): + return False + + if not collect_headers(root, pathlib.Path(options.install)): + return False + + return True + + +if __name__ == "__main__": + sys.exit(0 if main() else 1) diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/.gitattributes b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/.gitattributes new file mode 100644 index 000000000..dcd444fbe --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/.gitattributes @@ -0,0 +1,2 @@ +# Convert to LF line endings on checkout. +*.sh text eol=lf
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/Config_building_target.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/Config_building_target.png Binary files differnew file mode 100644 index 000000000..a1270007f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/Config_building_target.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/build_folder.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/build_folder.png Binary files differnew file mode 100644 index 000000000..0ca05ff16 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/build_folder.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/build_terminal.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/build_terminal.png Binary files differnew file mode 100644 index 000000000..24fe26eeb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/build_terminal.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/change_workspace_dialog.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/change_workspace_dialog.png Binary files differnew file mode 100644 index 000000000..9f6a61428 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/change_workspace_dialog.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/compilation_config.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/compilation_config.png Binary files differnew file mode 100644 index 000000000..43c60a21f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/compilation_config.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/compilation_config_2.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/compilation_config_2.png Binary files differnew file mode 100644 index 000000000..c16bb09ec --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/compilation_config_2.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/debug.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/debug.png Binary files differnew file mode 100644 index 000000000..1d8636da7 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/debug.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/decoration_for_files.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/decoration_for_files.png Binary files differnew file mode 100644 index 000000000..dd5c0bd74 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/decoration_for_files.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/docker_config.jpg b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/docker_config.jpg Binary files differnew file mode 100644 index 000000000..50cea7192 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/docker_config.jpg diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/docker_engine_config.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/docker_engine_config.png Binary files differnew file mode 100644 index 000000000..c3757075e --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/docker_engine_config.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/docker_images.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/docker_images.png Binary files differnew file mode 100644 index 000000000..67d38e714 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/docker_images.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/install_from_vsix.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/install_from_vsix.png Binary files differnew file mode 100644 index 000000000..f313ec590 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/install_from_vsix.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/new_project_page.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/new_project_page.png Binary files differnew file mode 100644 index 000000000..b498aca4b --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/new_project_page.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/open_project_page.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/open_project_page.png Binary files differnew file mode 100644 index 000000000..d4e534307 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/open_project_page.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/project_template.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/project_template.png Binary files differnew file mode 100644 index 000000000..e10b102ec --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/project_template.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/right_click_menus_1.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/right_click_menus_1.png Binary files differnew file mode 100644 index 000000000..0649f2f49 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/right_click_menus_1.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/right_click_menus_2.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/right_click_menus_2.png Binary files differnew file mode 100644 index 000000000..9d8e32216 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/right_click_menus_2.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/run.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/run.png Binary files differnew file mode 100644 index 000000000..0213dcab3 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/run.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/save_configuration.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/save_configuration.png Binary files differnew file mode 100644 index 000000000..39a5c1c4a --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/save_configuration.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/set_up_workspace_message.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/set_up_workspace_message.png Binary files differnew file mode 100644 index 000000000..c812a59a4 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/set_up_workspace_message.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/wamr_ide_main_menu.png b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/wamr_ide_main_menu.png Binary files differnew file mode 100644 index 000000000..89c56fa92 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Media/wamr_ide_main_menu.png diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/README.md b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/README.md new file mode 100644 index 000000000..8a6e1509f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/README.md @@ -0,0 +1,303 @@ +# WAMR-IDE (Experimental) + +## Introduction + +The WAMR-IDE is an Integrated Development Environment to develop WebAssembly application with coding, compiling and source debugging support. It contains 3 components: `VSCode extension`, `wasm-toolchain docker image` and `wasm-debug-server docker image`. + +- `VSCode extension` is an `vscode` extension, with which user can build and manage projects, develop `wasm application`, including `building`, `running` and `debugging`. + +- `WASM-toolchain` is a docker image which provides building environment for wasm. + +- `WASM source debug server` is a docker image which provides running and source debugging environment for wasm application. + +--- + +## How to setup WAMR IDE + +Now, we have same version tagged docker images, lldb binaries and VS Code installation file(.vsix file) packed for each GitHub release. So if you simply want to use WAMR debugging features in VS Code, the ideal(and effortless) way is following the tutorial in [this section](#21-download-wamr-vs-code-extension-from-the-github-releaserecommended-approach). + +Alternatively, if you want to build lldb, docker images, or .vsix file locally so that you can try the effect of your modification, you could refer to the tutorial in [this section](#22-build-wamr-vs-code-extension-locallyalternative-approach). + +### 1. Preparation + +#### 1.1. Install `VSCode` on host + +- make sure the version of [vscode](https://code.visualstudio.com/Download) you installed is at least _1.59.0_ + +#### 1.2. Install `Docker` on host + + 1. [Windows: Docker Desktop](https://docs.docker.com/desktop/windows/install/) + 2. [Ubuntu: Docker Engine](https://docs.docker.com/engine/install/ubuntu) + ```xml + OS requirements: + To install Docker Engine, you need the 64-bit version of one of these Ubuntu versions: + - Ubuntu Impish 21.10 + - Ubuntu Hirsute 21.04 + - Ubuntu Focal 20.04(LTS) + - Ubuntu Bionic 18.04(LTS) + ``` + +### 2. WAMR VS Code extension: download from the GitHub release or build locally + +#### 2.1 Download WAMR VS Code extension from the GitHub release(Recommended approach) + +##### 2.1.1 Load docker images from the GitHub release tar file + +From now on, for each GitHub release, we have the same version tagged docker image saved as a tar file, which you can find and download in the GitHub release. + +You could download the tar archive files for docker images from the release, and then load them using the following commands: + +```sh +# download the zip or tar.gz from release depending on your platform +# decompress and get the tar file + +# on Linux/MacOS, you could use tar +tar xf wasm-toolchain-{version number}.tar.gz +tar xf wasm-debug-server-{version number}.tar.gz +# or you could use unzip +unzip wasm-toolchain-{version number}.zip +unzip wasm-debug-server-{version number}.zip +# load wasm-toolchain +docker load --input wasm-toolchain.tar +# load wasm-debug-server +docker load --input wasm-debug-server.tar + +# on Windows, you could use any unzip software you like +# then loading docker images using powershell or git bash +# load wasm-toolchain +docker load --input ./wasm-toolchain.tar +# load wasm-debug-server +docker load --input ./wasm-debug-server.tar +``` + +##### 2.1.2 Download the VS Code extension installation file from the GitHub release + +From now on, for each GitHub release, we have the same version tagged zip/tar.gz file. For example, in release version 1.1.2, you can easily download and decompress `wamr-ide-1.1.2.tar.gz` `wamr-ide-1.1.2.zip`, which contains `wamr-ide.vsix` VS Code extension installation file. As you can imagine, in the future, when new releases are available, you can freely choose whichever version(for example, 1.2.0, 1.3.0, etc.) you prefer. It should work as long as you download the same version tagged docker image and .vsix file. + +##### 2.1.3 Install extension from vsix + +![install_from_vsix](./Media/install_from_vsix.png "install wamr-ide from vsix") + +select `wamr-ide.vsix` which you have decompressed from `.tar.gz` or `.zip` file. + +#### 2.2 Build WAMR VS Code extension locally(Alternative approach) + +You could also build the VS Code extension locally, the following instruction provides a thorough tutorial. It's worth noting that in the local build tutorial we use hard-coded tag version 1.0 other than the semantic version of WAMR. + +Note: Please ensure that the scripts under `resource` directories have execution permission. While on git they have x bits, you might have dropped them eg. by copying them from Windows. Similarly, do not drop execution permission when copying `lldb` binaries under `resource/debug/bin`. + +##### 2.2.1 Build docker images on host + +We have 2 docker images which should be built or loaded on your host, `wasm-toolchain` and `wasm-debug-server`. To build these 2 images, please enter the `WASM-Debug-Server/Docker` & `WASM-Toolchain/Docker`, then execute the `build_docker_image` script respectively. + +Windows (powershell): + +```batch +$ cd .\WASM-Toolchain\Docker +$ .\build_docker_image.bat +$ cd .\WASM-Debug-Server\Docker +$ .\build_docker_image.bat +``` + +Linux: + +```shell +$ cd ./WASM-Toolchain/Docker +$ ./build_docker_image.sh +$ cd ./WASM-Debug-Server/Docker +$ ./build_docker_image.sh +``` + +##### 2.2.2 After building, you can find `wasm-toolchain` and `wasm-debug-server` docker images on your local + +![docker-images](./Media/docker_images.png) + +##### 2.2.3 If building docker images fail during the process + +Sometimes building the Docker images may fail due to bad network conditions. If the `wasm-toolchain` and `wasm-debug-server` images do not exist after building, please build them manually. Fix the proxy setting if needed and execute the following command to build docker images. + +![docker-engine-config](./Media/docker_config.jpg) + +> Note: please correctly replace example proxy address with your own before you run manually. + +```xml +$ cd .\docker_images\wasm-debug-server +$ docker build --no-cache --build-arg http_proxy=http://proxy.example.com:1234 +--build-arg https_proxy=http://proxy.example.com:1234 -t wasm-debug-server:1.0 . +``` + +```xml +$ cd .\docker_images\wasm-toolchain +$ docker build --no-cache --build-arg http_proxy=http://proxy.example.com:1234 +--build-arg https_proxy=http://proxy.example.com:1234 -t wasm-toolchain:1.0 . +``` + +##### 2.2.4 If you encounter the problem `failed to solve with frontend dockerfile.v0: failed to create LLB definition`, please config your docker desktop + +![docker-engine-config](./Media/docker_engine_config.png) + +##### 2.2.5 Points To Remember + +- Make sure that the `wasm-toolchain:1.0` and `wasm-debug-server:1.0` docker images are both successfully built before using `WAMR IDE`, otherwise `Build`, `Run` and `Debug` will not work. + +##### 2.2.6 Generate wamride extension package file + +`wamride-1.0.0.vsix` can be packaged by [`npm vsce`](https://code.visualstudio.com/api/working-with-extensions/publishing-extension). + +```shell +$ npm install -g vsce +$ cd VSCode-Extension +$ rm -rf node_modules +$ npm install +$ vsce package +``` + +##### 2.2.7 Enable VS Code debugging feature + +By default, when you build .vsix locally, the debugging feature is off. Suppose you want to enable the source debugging feature. In that case, you could download `lldb` binaries from our GitHub release (for example, `wamr-lldb-1.1.2-x86_64-ubuntu-20.04.tar.gz`), decompress and put every subdirectory and file to the installed directory of your VS Code extension. + +For example, let's say you are on an Ubuntu 20.04 machine. You first download and decompress `wamr-lldb-1.1.2-x86_64-ubuntu-20.04.tar.gz`, and you will get a `wamr-lldb` folder (or `inst` folder in our earlier release). Then, you can simply copy the files and directory inside that folder to the relative path `resource/debug/linux/` under your VS Code extension installation directory. + +Example commands on an Ubuntu 20.04 machine: + +```shell +# decompress .tar.gz file and get the folder +$ ls wamr-lldb +bin lib package.json syntaxes +# copy everything to the vscode extension installation path(in this case, it's /home/{usrname}/.vscode-server/extensions/wamr.wamride-1.0.0/) +$ cp inst/* /home/{usrname}/.vscode-server/extensions/wamr.wamride-1.0.0/resource/debug/linux/ +``` + +If you want to use your own patched `lldb`, you could follow this [instruction](../../doc/source_debugging.md#debugging-with-interpreter) to build `lldb`. And follow this [instruction](./VSCode-Extension/resource/debug/README.md) +to copy the binaries to replace the existing ones. + + +> **You can also debug the extension directly follow this [instruction](./VSCode-Extension/README.md) without packing the extension.** + +##### 2.2.7 Install extension from vsix + +![install_from_vsix](./Media/install_from_vsix.png "install wamr-ide from vsix") + +select `wamride-1.0.0.vsix` which you have packed on your host. + +--- + +## How to use `wamr-ide` + +#### `WAMR-IDE` extension contains 2 components as following picture showing. `WAMR IDE` for workspace and project management and `Current Project` for project's execution. + +![wamr_ide_main_menu](./Media/wamr_ide_main_menu.png "wamr-ide main menu") + +### Project Execution + +#### 1. New project + +When you click `New project` button, the extension will pop up a message box at the bottom right of the screen as following: + +![set-up-workspace-message](./Media/set_up_workspace_message.png "set up workspace message box") + +You can click `Set up now` and select the target folder to create project workspace, or you click `Maybe later` to close the message box. + +> Note that your selected workspace folder should be **empty** or the folder you have set up as workspace. + +After setting up workspace, extension will prompt successful message: + +```xml +Workspace has been set up successfully! +``` + +Then click `New project` button again, a new page will show as following. + +![new-project-page](./Media/new_project_page.png "new project page") + +Enter the `Project name` and select the `Template`, then click `Create` button. A new project will be generated and opened in your current `VS Code window` or in a new `VS Code window`. + +> Opening in current windows or a new one depends on whether your `vscode's explorer` is empty or not. If empty, open in current window, or open in the new vscode window. + +A new initialized project is as following picture shows. + +![project-template](./Media/project_template.png "default project template") + +`.wamr` is the project configuration folder which contains 3 files, `CMakeLists.txt`, `project.cmake`, and `compilation_config.json`. `CMakeLists.txt` is used to build `wasm target` and the `project.cmake` is included in `CMakeLists.txt`. `compilation_config.json` includes the user's customized configuration such as folders which should be added in the include path. + +#### 2. Open project + +Click `Open project` button, `quick-pick-box` will show as following. All projects under your current workspace will be shown and can be selected. + +![configuration file](./Media/open_project_page.png "configuration file") + +#### 3. Change workspace + +Click `Change workspace` button, a dialog will show as following. You can select 1 folder in file system as workspace, and the new workspace path will override previous workspace, and all new created projects will be generated in the new workspace. + +![change workspace ](./Media/change_workspace_dialog.png "change workspace dialog") + +#### 4. Customize `include paths` and `exclude source files` + + Extension supports adding header file folder to `include path` and excluding source file from build. + +- `Add to include path` + + - Move the cursor to the `folder` and right click, then `menus` will be shown as following. Click `Toggle state of path including`. + + ![right click menus](./Media/right_click_menus_1.png "right click menus") + +- `Exclude source file from build` + + - Move the cursor to the `source file` and right click, then `menus` will be shown as following. Click `Toggle state of excluding`. + + ![right click menus](./Media/right_click_menus_2.png "right click menus") + +#### After setting up `include path` and `exclude files`, the corresponding folder and files will be decorated with color and icon as following picture shows + + ![decoration for files](./Media/decoration_for_files.png "decoration for files") + + At the same time, all added `include path` and `exclude files` will be saved in `.wamr/compilation_config.json` as json array. + + ![compilation config](./Media/compilation_config_2.png "compilation config") + +> `Toggle state of path including` just shows when selecting `folder` and hides with other resources. +> +> `Toggle state of excluding` just shows when selecting `[.c | .cpp | .cxx] source files` and hides with other resources. + +### Current Project Management + +#### 1. Configuration + +Click `Configuration` button, a new page will be shown as following. You can config building target with `Include paths`, `Initial & Max linear memory`, `stack size`, `exported_symbols` and `include paths`, `exclude files`. + +![config building target](./Media/Config_building_target.png "config building target") + +Then click `Modify` button to confirm, if configurations are modified successfully and following message will pop. Click `OK`, the page will be auto closed. + +![save configuration](./Media/save_configuration.png "save configuration") + +And all configuration will be saved in `.wamr/compilation_config.json`. + +![configuration file](./Media/compilation_config.png "configuration file") + +#### 2. `Build` + +When you have completed coding and ready to build target, click `build` button and the `wasm-toolchain` will auto start a container and execute the building process. + +![build terminal output](./Media/build_terminal.png "build terminal output") + +After successful building execution, `build` folder will be generated in `explorer`, in which `${output_file_name}.wasm` is exist. + +![build folder](./Media/build_folder.png "build folder") + +> Note that to start `docker service` firstly. + +#### 3. Run + +Click `Run` button and `wasm-debug-server` docker image will auto start a container and execute the running process. + +![run](./Media/run.png "run wasm") + +#### 4. Debug + +Click `Debug` button will trigger start ip `wamr-debug-server` docker image, and boot up `lldb debug server` inside of iwasm. Then start a debugging session with configuration to connect. Tap `F11` or click `step into` to start debugging. + +![debug](./Media/debug.png "source debugging") + +> Docker containers will be auto stopped and removed after the execution. diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Script/build.bat b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Script/build.bat new file mode 100644 index 000000000..5274dad46 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Script/build.bat @@ -0,0 +1,41 @@ +@REM Copyright (C) 2019 Intel Corporation. All rights reserved. +@REM SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +@echo off +set DIR_ROOT=%cd%\.. + +echo "=== Verify the vscode status ===" +call code --version +IF %ERRORLEVEL%==0 ( + echo "vscode is ready." +) ELSE ( + echo "VSCode is not installed, please install firstly." + exit /b 1 +) + +echo "=== Verify the docker status ===" +call docker --version +IF %ERRORLEVEL%==0 ( + echo "docker is ready." +) ELSE ( + echo "Docker is not installed, please install firstly." + exit /b 1 +) + +cd %DIR_ROOT%\WASM-Debug-Server\Docker +call docker build -t wasm-debug-server:1.0 . +IF %ERRORLEVEL%==0 ( + echo "wasm-debug-server image is ready." +) ELSE ( + echo "build wasm-debug-server image failed." + exit /b 1 +) + +cd %DIR_ROOT%\WASM-Toolchain\Docker +call docker build -t wasm-toolchain:1.0 . +IF %ERRORLEVEL%==0 ( + echo "wasm-toolchain image is ready." +) ELSE ( + echo "build wasm-toolchain image failed." + exit /b 1 +)
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Script/build.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Script/build.sh new file mode 100755 index 000000000..c30cb5af2 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/Script/build.sh @@ -0,0 +1,46 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#!/bin/bash + +# 1. verify the environment: vscode & docker +# 1.1 if docker is installed, config docker command execution without sudo, promp if not installed and exit. +# 1.2 if vscode is not installed, promp and exit. +# 2. build wasm-toolchain & wasm-debug-server docker image + +DIR_ROOT=$(pwd)/.. + +echo "=== Verify the vscode status ===" +if [ "$(code --version)" ]; then + echo "VSCode is ready." +else + echo "VSCode is not installed, please install firstly." + exit 1 +fi + +echo "=== Verify the docker status ===" +if [ "$(docker --version)" ]; then + echo "Docker is ready." +else + echo "Docker is not installed, please install firstly." + exit 1 +fi + +# setup docker command exectuion without sudo permission +sudo groupadd docker +sudo gpasswd -a ${USER} docker +sudo service docker restart + +# create new group and execute the rest commands +newgrp - docker << REST + +# 2. build wasm-debug-server docker image +cd ${DIR_ROOT}/WASM-Debug-Server/Docker +docker build -t wasm-debug-server:1.0 . + +# 3. build wasm-toolchain docker image +cd ${DIR_ROOT}/WASM-Toolchain/Docker +docker pull ubuntu:20.04 +docker build -t wasm-toolchain:1.0 . + +REST
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.eslintrc.json b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.eslintrc.json new file mode 100644 index 000000000..5c1fd464c --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.eslintrc.json @@ -0,0 +1,19 @@ +{ + "root": true, + "parser": "@typescript-eslint/parser", + "extends": ["plugin:@typescript-eslint/recommended"], + "parserOptions": { + "ecmaVersion": "latest", + "sourceType": "module" + }, + "plugins": ["@typescript-eslint"], + "rules": { + "@typescript-eslint/naming-convention": "warn", + "@typescript-eslint/semi": "warn", + "curly": "warn", + "eqeqeq": "warn", + "no-throw-literal": "warn", + "semi": "off" + }, + "ignorePatterns": ["out", "dist", "**/*.d.ts"] +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.gitignore b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.gitignore new file mode 100644 index 000000000..417c854d2 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.gitignore @@ -0,0 +1,7 @@ +out +dist +node_modules +.vscode-test/ +*.vsix +package-lock.json +src/test
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.prettierrc.json b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.prettierrc.json new file mode 100644 index 000000000..b2b00da56 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.prettierrc.json @@ -0,0 +1,12 @@ +{ + "printWidth": 80, + "tabWidth": 4, + "useTabs": false, + "semi": true, + "singleQuote": true, + "trailingComma": "es5", + "bracketSpacing": true, + "jsxBracketSameLine": false, + "arrowParens": "avoid", + "proseWrap": "always" +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscode/extensions.json b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscode/extensions.json new file mode 100644 index 000000000..b1a2d99f0 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscode/extensions.json @@ -0,0 +1,5 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": ["dbaeumer.vscode-eslint"] +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscode/launch.json b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscode/launch.json new file mode 100644 index 000000000..4e9ccc24b --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscode/launch.json @@ -0,0 +1,15 @@ +// A launch configuration that compiles the extension and then opens it inside a new window + +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Extension", + "type": "extensionHost", + "request": "launch", + "args": ["--extensionDevelopmentPath=${workspaceFolder}"], + "outFiles": ["${workspaceFolder}/out/**/*.js"], + "preLaunchTask": "${defaultBuildTask}" + } + ] +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscode/tasks.json b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscode/tasks.json new file mode 100644 index 000000000..5deb2bccd --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscode/tasks.json @@ -0,0 +1,20 @@ +// See https://go.microsoft.com/fwlink/?LinkId=733558 +// for the documentation about the tasks.json format +{ + "version": "2.0.0", + "tasks": [ + { + "type": "npm", + "script": "watch", + "problemMatcher": "$tsc-watch", + "isBackground": true, + "presentation": { + "reveal": "never" + }, + "group": { + "kind": "build", + "isDefault": true + } + } + ] +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscodeignore b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscodeignore new file mode 100644 index 000000000..b2d2b4787 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/.vscodeignore @@ -0,0 +1,11 @@ +.gitignore +.yarnrc + +.vscode/** +.vscode-test/** +out/test/** + +**/tsconfig.json +**/.eslintrc.json +**/*.map +**/*.ts diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/CONTRIBUTING.md b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/CONTRIBUTING.md new file mode 100644 index 000000000..f70a959eb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/CONTRIBUTING.md @@ -0,0 +1,34 @@ +# CONTRIBUTING + +## Pull requests + +To submit your change: + +- Make sure your code is in line with our + [coding conventions](##Coding-conventions). +- Create an [issue] describing the bug the PR fixes or the feature you intend + to implement. +- Submit a [pull request] into the main branch. + +## Coding conventions + +#### Format + +The codebase is formatted by `Prettier` and the `.prettierrc.json` has been +configured. + +- VSCode along with `Format on Save` configuration could easily format your + code during development. +- You can run `prettier-format-check` and `prettier-format-apply` to check and + format your codebase with `prettier` in terminal. + +#### Lint + +`ESlint` is used as linter for the codebase and the `.eslintrc.json` has been +configured. + +- It's suggested to run `npm run lint` then fix errors and warnings before + committing. + +[issue]: https://github.com/bytecodealliance/wasm-micro-runtime/issues +[pull request]: https://github.com/bytecodealliance/wasm-micro-runtime/pulls diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/LICENSE b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/LICENSE new file mode 100644 index 000000000..c6bd7e0c5 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/LICENSE @@ -0,0 +1,219 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/README.md b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/README.md new file mode 100644 index 000000000..739e39a72 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/README.md @@ -0,0 +1,40 @@ +# Introduction + +### An integrated development environment for WASM. + +# How to debug this extension +> Note that when you download and +> decompress to get .vsix file from [our release](https://github.com/bytecodealliance/wasm-micro-runtime/releases). +> It's by default that the `source debugging` feature is not enabled. +> If you want to enable the `source debugging` feature of this extension, +> you could download `lldb` from [our release](https://github.com/bytecodealliance/wasm-micro-runtime/releases) +> (This is the recommended way, and you could do it with a single click in VS Code). +> Then if you want to use your customized lldb patch, +> you could build your own version of `lldb` +> and then follow this [instruction](./resource/debug/README.md) +> to put them in the correct path + +### 1. open `VSCode_Extension` directory with the `vscode` + +```xml +File -> Open Folder -> select `VSCode_Extension` +``` + +### 2. run `npm install` in `terminal` to install necessary dependencies. + +### 3. click `F5` or `ctrl+shift+D` switch to `Run and Debug` panel and click `Run Extension` to boot. + +# Code Format + +`prettier` is recommended and `.prettierrc.json` has been provided in workspace. +More details and usage guidance please refer [prettier](https://prettier.io/docs/en/install.html) + +You can run following commands in current extension directory to check and apply +```shell +# install prettier firstly +npm install --save-dev prettier +# check format +npm run prettier-format-check +# apply +npm run prettier-format-apply +```
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/package.json b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/package.json new file mode 100644 index 000000000..dfe37961b --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/package.json @@ -0,0 +1,258 @@ +{ + "name": "wamride", + "publisher": "wamr-ide", + "repository": { + "url": "https://github.com/bytecodealliance/wasm-micro-runtime/tree/main/test-tools/wamr-ide" + }, + "displayName": "WAMR-IDE", + "description": "An Integrated Development Environment for WASM", + "version": "1.2.1", + "engines": { + "vscode": "^1.59.0" + }, + "categories": [ + "Other" + ], + "activationEvents": [ + "onStartupFinished" + ], + "main": "./out/extension.js", + "contributes": { + "commands": [ + { + "command": "wamride.newProject", + "title": "Create new project", + "category": "New project" + }, + { + "command": "wamride.changeWorkspace", + "title": "Change workspace", + "category": "Change Workspace" + }, + { + "command": "wamride.build", + "title": "WAMRIDE:Build Wasm" + }, + { + "command": "wamride.run", + "title": "WAMRIDE:Run Wasm" + }, + { + "command": "wamride.debug", + "title": "WAMRIDE:Source Debug" + }, + { + "command": "wamride.openFolder", + "title": "WAMRIDE:openWorkspace" + }, + { + "command": "wamride.build.toggleStateIncludePath", + "title": "Toggle state of path including" + }, + { + "command": "wamride.build.toggleStateExclude", + "title": "Toggle state of excluding" + }, + { + "command": "wamride.targetConfig", + "title": "Target Configuration" + } + ], + "viewsContainers": { + "activitybar": [ + { + "id": "wamride", + "title": "WAMRIDE", + "icon": "$(star)" + } + ] + }, + "views": { + "wamride": [ + { + "id": "wamride.views.welcome", + "name": "Quick Access" + } + ] + }, + "viewsWelcome": [ + { + "view": "wamride.views.welcome", + "contents": "[ WAMR IDE ]\n[$(project)New project](command:wamride.newProject)\n[$(files)Open project](command:wamride.openFolder)\n[$(book)Change workspace](command:wamride.changeWorkspace)" + }, + { + "view": "wamride.views.welcome", + "contents": "[ Current Project ]\n[$(pencil)Configuration](command:wamride.targetConfig)\n[$(gear)Build](command:wamride.build)\n[$(run)Run](command:wamride.run)\n[$(debug-alt) Debug](command:wamride.debug)", + "enablement": "ext.isWasmProject" + } + ], + "menus": { + "explorer/context": [ + { + "command": "wamride.build.toggleStateIncludePath", + "alt": "wamride.build.toggleStateIncludePath", + "group": "config", + "when": "explorerResourceIsFolder" + }, + { + "command": "wamride.build.toggleStateExclude", + "alt": "wamride.build.toggleStateExclude", + "group": "config", + "when": "!explorerResourceIsFolder && resourceExtname in ext.supportedFileType" + } + ] + }, + "debuggers": [ + { + "type": "wamr-debug", + "label": "WAMR lldb debugger", + "enableBreakpointsFor": { + "languageIds": [ + "ada", + "arm", + "asm", + "c", + "cpp", + "crystal", + "d", + "fortan", + "fortran-modern", + "nim", + "objective-c", + "objectpascal", + "pascal", + "rust", + "swift" + ] + }, + "windows": { + "program": "./resource/debug/windows/bin/lldb-vscode.exe" + }, + "osx": { + "program": "./resource/debug/darwin/bin/lldb-vscode" + }, + "linux": { + "program": "./resource/debug/linux/bin/lldb-vscode" + }, + "configurationAttributes": { + "attach": { + "properties": { + "sourcePath": { + "type": "string", + "description": "Specify a source path to remap \"./\" to allow full paths to be used when setting breakpoints in binaries that have relative source paths." + }, + "sourceMap": { + "type": "array", + "description": "Specify an array of path remappings; each element must itself be a two element array containing a source and destination pathname. Overrides sourcePath.", + "default": [] + }, + "debuggerRoot": { + "type": "string", + "description": "Specify a working directory to set the debug adaptor to so relative object files can be located." + }, + "attachCommands": { + "type": "array", + "description": "Custom commands that are executed instead of attaching to a process ID or to a process by name. These commands may optionally create a new target and must perform an attach. A valid process must exist after these commands complete or the \"attach\" will fail.", + "default": [] + }, + "initCommands": { + "type": "array", + "description": "Initialization commands executed upon debugger startup.", + "default": [] + }, + "preRunCommands": { + "type": "array", + "description": "Commands executed just before the program is attached to.", + "default": [] + }, + "stopCommands": { + "type": "array", + "description": "Commands executed each time the program stops.", + "default": [] + }, + "exitCommands": { + "type": "array", + "description": "Commands executed at the end of debugging session.", + "default": [] + } + } + } + }, + "initialConfigurations": [ + { + "type": "wamr-debug", + "request": "attach", + "name": "Debug", + "stopOnEntry": true, + "attachCommands": [ + "process connect -p wasm connect://127.0.0.1:1234" + ] + } + ], + "configurationSnippets": [ + { + "label": "WAMR: Attach", + "description": "", + "body": { + "type": "wamr-debug", + "request": "attach", + "name": "${2:Attach}", + "stopOnEntry": true, + "attachCommands": [ + "process connect -p wasm connect://${3:127.0.0.1}:${4:1234}" + ] + } + } + ] + } + ], + "configuration": [ + { + "title": "WAMR-IDE", + "properties": { + "WAMR-IDE.configWorkspace": { + "type": "string", + "description": "Config the workspace for WebAssembly project." + } + } + } + ], + "taskDefinitions": [ + { + "type": "wasm" + } + ] + }, + "scripts": { + "vscode:prepublish": "npm run compile", + "compile": "tsc -p ./", + "watch": "tsc -watch -p ./", + "pretest": "npm run compile && npm run lint", + "lint": "eslint src --ext ts", + "lint-fix": "eslint --fix src --ext ts", + "test": "node ./out/test/runTest.js", + "prettier-format-check": "prettier --config .prettierrc.json 'src/**/*.ts' --check", + "prettier-format-apply": "prettier --config .prettierrc.json 'src/**/*.ts' --write" + }, + "devDependencies": { + "@types/glob": "^7.1.3", + "@types/mocha": "^8.2.2", + "@types/node": "14.x", + "@types/request": "^2.48.8", + "@types/vscode": "^1.54.0", + "@types/yauzl": "^2.10.0", + "@typescript-eslint/eslint-plugin": "^4.26.0", + "@typescript-eslint/parser": "^4.26.0", + "eslint": "^7.32.0", + "glob": "^7.1.7", + "mocha": "^8.4.0", + "prettier": "2.5.1", + "typescript": "^4.3.2", + "vscode-test": "^1.5.2" + }, + "dependencies": { + "@vscode/webview-ui-toolkit": "^0.8.4", + "request": "^2.88.2", + "yauzl": "^2.10.0" + } +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/README.md b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/README.md new file mode 100644 index 000000000..403e35ae9 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/README.md @@ -0,0 +1,15 @@ +### If you want to enable `source debugging` for this extension and use your own patched `lldb`, please build `lldb` firstly following this [instruction](../../../../../doc/source_debugging.md#debugging-with-interpreter) + +### After building(`linux` for example), create `bin` folder and `lib` folder respectively in `linux` directory, add following necessary target files into the folders + +```shell +/llvm/build-lldb/bin/lldb # move this file to {VS Code directory}/resource/debug/linux/bin/ +/llvm/build-lldb/bin/lldb-vscode # move this file to {VS Code directory}/resource/debug/linux/bin/ +/llvm/build-lldb/lib/liblldb.so.13 # move this file to {VS Code directory}/resource/debug/linux/lib/ +``` + +> If you are debugging this extension following this [tutorial](../../README.md), {VS Code directory} will be `{WAMR root directory}/test-tools/wamr-ide/VSCode-Extension`. If you want to replace the current lldb with your own patched version so that you can use your patched lldb in VS Code, {VS Code directory} will be `~/.vscode/extensions/wamr.wamride-1.1.2` or `~/.vscode-server/extensions/wamr.wamride-1.1.2`. + +Note: For macOS, the library is named like `liblldb.13.0.1.dylib`. + +### Then you can start the extension and run the execute source debugging by clicking the `debug` button in the extension panel. diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/darwin/.placeholder b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/darwin/.placeholder new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/darwin/.placeholder diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/linux/.placeholder b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/linux/.placeholder new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/linux/.placeholder diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/windows/.placeholder b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/windows/.placeholder new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/debug/windows/.placeholder diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/CMakeLists.txt b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/CMakeLists.txt new file mode 100644 index 000000000..81d998bc8 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/CMakeLists.txt @@ -0,0 +1,32 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +cmake_minimum_required (VERSION 2.9) + +project(Main) + +include(${CMAKE_CURRENT_SOURCE_DIR}/project.cmake) + +set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -Wno-unused-command-line-argument " CACHE INTERNAL "") + +set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -z stack-size=${STACK_SIZE}") + +set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fdebug-prefix-map=/mnt='$ENV{PROJ_PATH}'") + +set (CMAKE_EXE_LINKER_FLAGS + "${CMAKE_EXE_LINKER_FLAGS} -Wl,--initial-memory=${INIT_MEM_SIZE},--max-memory=${MAX_MEM_SIZE},") + +set (CMAKE_EXE_LINKER_FLAGS + "${CMAKE_EXE_LINKER_FLAGS} \ + ${EXPORTED_SYMBOLS},") + +set (SRC_LIST + ${PROJECT_SRC_LIST}) + +set (HEADER_LIST + ${CMAKE_CURRENT_SOURCE_DIR}/../include + ${PROJECT_INCLUDES}) + +include_directories(${HEADER_LIST}) + +add_executable (${OUTPUT_FILE_NAME} ${SRC_LIST})
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.bat b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.bat new file mode 100644 index 000000000..7fd1f024a --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.bat @@ -0,0 +1,10 @@ +@REM Copyright (C) 2019 Intel Corporation. All rights reserved. +@REM SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +@echo off + +docker run --rm -it --name=wasm-debug-server-ctr ^ + -v "%cd%":/mnt ^ + -p 1234:1234 ^ + wasm-debug-server:%2 ^ + /bin/bash -c "./debug.sh %1" diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.sh new file mode 100755 index 000000000..169fb7e5f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/boot_debugger_server.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +set -e + +docker run --rm -it --name=wasm-debug-server-ctr \ + -v "$(pwd)":/mnt \ + -p 1234:1234 \ + wasm-debug-server:$2 \ + /bin/bash -c "./debug.sh $1" diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/build.bat b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/build.bat new file mode 100644 index 000000000..de415107a --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/build.bat @@ -0,0 +1,11 @@ +@REM Copyright (C) 2019 Intel Corporation. All rights reserved. +@REM SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +@echo off + +@REM start a container, mount current project path to container/mnt +docker run --rm --name=wasm-toolchain-ctr ^ + -it -v "%cd%":/mnt ^ + --env=PROJ_PATH="%cd%" ^ + wasm-toolchain:%2 ^ + /bin/bash -c "./build_wasm.sh %1" diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/build.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/build.sh new file mode 100755 index 000000000..a8a42cc89 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/build.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +set -e + +docker run --rm --name=wasm-toolchain-ctr \ + -it -v "$(pwd)":/mnt \ + --env=PROJ_PATH="$(pwd)" \ + wasm-toolchain:$2 \ + /bin/bash -c "./build_wasm.sh $1" diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/destroy.bat b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/destroy.bat new file mode 100644 index 000000000..faf316ab3 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/destroy.bat @@ -0,0 +1,36 @@ +@REM Copyright (C) 2019 Intel Corporation. All rights reserved. +@REM SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +@echo off + +call docker --version>nul 2>nul +IF %ERRORLEVEL% GTR 0 ( + echo "Docker is not installed, please install docker desktop firstly." + echo + exit /b 1 +) + +call docker images>nul 2>nul +IF %ERRORLEVEL% GTR 0 ( + echo "Docker is not ready, please lanuch docker desktop firstly." + echo + exit /b 2 +) + +echo "Prepare to clean up the docker containers..." + +call docker inspect wasm-toolchain-ctr>nul 2>nul +IF %ERRORLEVEL% EQU 0 ( + echo "Stopping and removing wasm-toolchain-ctr container..." + docker rm -f wasm-toolchain-ctr>nul 2>nul + echo "Done." +) + +call docker inspect wasm-debug-server-ctr>nul 2>nul +IF %ERRORLEVEL% EQU 0 ( + echo "Stopping and removing wasm-debug-server-ctr container..." + docker rm -f wasm-debug-server-ctr>nul 2>nul + echo "Done." +) + +echo "Clean up docker containers successfully." diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/destroy.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/destroy.sh new file mode 100755 index 000000000..41faf3eaf --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/destroy.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +set -e + +docker -v>/dev/null +if [ $? -ne 0 ]; then + echo "\nDocker is not installed, please install docker firstly.\n" + exit 1 +fi + +docker images>/dev/null +if [ $? -ne 0 ]; then + echo "\nDocker service is not running, please start your docker service firstly.\n" + exit 2 +fi + +echo "Prepare to clean up the docker containers..." + +if test ! -z "$(docker ps -a | grep wasm-toolchain-ctr)"; then + echo "Stopping and removing wasm-toolchain-ctr container..." + docker rm -f wasm-toolchain-ctr>/dev/null + echo "Done." +fi + +if test ! -z "$(docker ps -a | grep wasm-debug-server-ctr)"; then + echo "Stopping and removing wasm-debug-server-ctr container..." + docker rm -f wasm-debug-server-ctr>/dev/null + echo "Done." +fi + +echo "Clean up docker containers successfully." diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/project.cmake b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/project.cmake new file mode 100644 index 000000000..20b080e0c --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/project.cmake @@ -0,0 +1,17 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +set (OUTPUT_FILE_NAME) + +set (INIT_MEM_SIZE) + +set (MAX_MEM_SIZE) + +set (STACK_SIZE) + +set (EXPORTED_SYMBOLS) + +set (PROJECT_SRC_LIST) + +set (PROJECT_INCLUDES) + diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.bat b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.bat new file mode 100644 index 000000000..af47f35ba --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.bat @@ -0,0 +1,9 @@ +@REM Copyright (C) 2019 Intel Corporation. All rights reserved. +@REM SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +@echo off + +docker run --rm -it --name=wasm-debug-server-ctr ^ + -v "%cd%":/mnt ^ + wasm-debug-server:%2 ^ + /bin/bash -c "./run.sh %1" diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.sh new file mode 100755 index 000000000..670e57c1e --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/scripts/run.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +set -e + +docker run --rm -it --name=wasm-debug-server-ctr \ + -v "$(pwd)":/mnt \ + wasm-debug-server:$2 \ + /bin/bash -c "./run.sh $1" diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/assert.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/assert.h new file mode 100644 index 000000000..86fdefe61 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/assert.h @@ -0,0 +1,17 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_ASSERT_H +#define _WAMR_LIBC_ASSERT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/ctype.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/ctype.h new file mode 100644 index 000000000..846e7c8f6 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/ctype.h @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_CTYPE_H +#define _WAMR_LIBC_CTYPE_H + +#ifdef __cplusplus +extern "C" { +#endif + +int +isupper(int c); +int +isalpha(int c); +int +isspace(int c); +int +isgraph(int c); +int +isprint(int c); +int +isdigit(int c); +int +isxdigit(int c); +int +tolower(int c); +int +toupper(int c); +int +isalnum(int c); + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/errno.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/errno.h new file mode 100644 index 000000000..8883bf806 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/errno.h @@ -0,0 +1,17 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_ERRNO_H +#define _WAMR_LIBC_ERRNO_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/fcntl.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/fcntl.h new file mode 100644 index 000000000..b7e292f22 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/fcntl.h @@ -0,0 +1,17 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_FCNTL_H +#define _WAMR_LIBC_FCNTL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/inttypes.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/inttypes.h new file mode 100644 index 000000000..2e59ca38d --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/inttypes.h @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_INTTYPES_H +#define _WAMR_LIBC_INTTYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include <stdint.h> + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/limits.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/limits.h new file mode 100644 index 000000000..3859b050b --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/limits.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_LIMITS_H +#define _WAMR_LIBC_LIMITS_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define CHAR_BIT 8 +#define SCHAR_MIN -128 +#define SCHAR_MAX 127 +#define UCHAR_MAX 255 +#define CHAR_MIN 0 +#define CHAR_MAX 127 +#define MB_LEN_MAX 1 +#define SHRT_MIN -32768 +#define SHRT_MAX +32767 +#define USHRT_MAX 65535 +#define INT_MIN -32768 +#define INT_MAX +32767 +#define UINT_MAX 65535 +#define LONG_MIN -2147483648 +#define LONG_MAX +2147483647 +#define ULONG_MAX 4294967295 + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/pthread.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/pthread.h new file mode 100644 index 000000000..10b3978e9 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/pthread.h @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIB_PTHREAD_H +#define _WAMR_LIB_PTHREAD_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include <stdint.h> + +/* Data type define of pthread, mutex, cond and key */ +typedef unsigned int pthread_t; +typedef unsigned int pthread_mutex_t; +typedef unsigned int pthread_cond_t; +typedef unsigned int pthread_key_t; + +/* Thread APIs */ +int +pthread_create(pthread_t *thread, const void *attr, + void *(*start_routine)(void *), void *arg); + +int +pthread_join(pthread_t thread, void **retval); + +int +pthread_detach(pthread_t thread); + +int +pthread_cancel(pthread_t thread); + +pthread_t +pthread_self(void); + +void +pthread_exit(void *retval); + +/* Mutex APIs */ +int +pthread_mutex_init(pthread_mutex_t *mutex, const void *attr); + +int +pthread_mutex_lock(pthread_mutex_t *mutex); + +int +pthread_mutex_unlock(pthread_mutex_t *mutex); + +int +pthread_mutex_destroy(pthread_mutex_t *mutex); + +/* Cond APIs */ +int +pthread_cond_init(pthread_cond_t *cond, const void *attr); + +int +pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); + +int +pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, + uint64_t useconds); + +int +pthread_cond_signal(pthread_cond_t *cond); + +int +pthread_cond_broadcast(pthread_cond_t *cond); + +int +pthread_cond_destroy(pthread_cond_t *cond); + +/* Pthread key APIs */ +int +pthread_key_create(pthread_key_t *key, void (*destructor)(void *)); + +int +pthread_setspecific(pthread_key_t key, const void *value); + +void * +pthread_getspecific(pthread_key_t key); + +int +pthread_key_delete(pthread_key_t key); + +#ifdef __cplusplus +} +#endif + +#endif /* end of _WAMR_LIB_PTHREAD_H */ diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdarg.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdarg.h new file mode 100644 index 000000000..509595734 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdarg.h @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_STDARG_H +#define _WAMR_LIBC_STDARG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef _VA_LIST +typedef __builtin_va_list va_list; +#define _VA_LIST +#endif +#define va_start(ap, param) __builtin_va_start(ap, param) +#define va_end(ap) __builtin_va_end(ap) +#define va_arg(ap, type) __builtin_va_arg(ap, type) + +#define __va_copy(d, s) __builtin_va_copy(d, s) + +#ifdef __cplusplus +} +#endif + +#endif /* end of _WAMR_LIBC_STDARG_H */ diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdbool.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdbool.h new file mode 100644 index 000000000..2d1f8cd76 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdbool.h @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_STDBOOL_H +#define _WAMR_LIBC_STDBOOL_H + +#define __bool_true_false_are_defined 1 + +#ifndef __cplusplus + +#define bool _Bool +#define false 0 +#define true 1 + +#endif /* __cplusplus */ + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdint.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdint.h new file mode 100644 index 000000000..8c55bff50 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdint.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_STDINT_H +#define _WAMR_LIBC_STDINT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* clang-format off */ +typedef char int8_t; +typedef short int int16_t; +typedef int int32_t; +typedef long long int int64_t; + +/* Unsigned. */ +typedef unsigned char uint8_t; +typedef unsigned short int uint16_t; +typedef unsigned int uint32_t; +typedef unsigned long long int uint64_t; + +typedef __INTPTR_TYPE__ intptr_t; +typedef __UINTPTR_TYPE__ uintptr_t; + +/* Minimum of signed integral types. */ +# define INT8_MIN (-128) +# define INT16_MIN (-32767-1) +# define INT32_MIN (-2147483647-1) +# define INT64_MIN (-__INT64_C(9223372036854775807)-1) +/* Maximum of signed integral types. */ +# define INT8_MAX (127) +# define INT16_MAX (32767) +# define INT32_MAX (2147483647) +# define INT64_MAX (__INT64_C(9223372036854775807)) + +/* Maximum of unsigned integral types. */ +# define UINT8_MAX (255) +# define UINT16_MAX (65535) +# define UINT32_MAX (4294967295U) +# define UINT64_MAX (__UINT64_C(18446744073709551615)) +/* clang-format on */ + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdio.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdio.h new file mode 100644 index 000000000..f9f03660f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdio.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_STDIO_H +#define _WAMR_LIBC_STDIO_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef NULL +#define NULL ((void *)0) +#endif + +typedef unsigned long size_t; + +int +printf(const char *format, ...); +int +putchar(int c); +int +snprintf(char *str, size_t size, const char *format, ...); +int +sprintf(char *str, const char *format, ...); +int +puts(char *string); + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdlib.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdlib.h new file mode 100644 index 000000000..302c896c4 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/stdlib.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_STDLIB_H +#define _WAMR_LIBC_STDLIB_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef unsigned long size_t; + +int +atoi(const char *s); +void +exit(int status); +long +strtol(const char *nptr, char **endptr, register int base); +unsigned long +strtoul(const char *nptr, char **endptr, register int base); +void * +malloc(size_t size); +void * +calloc(size_t n, size_t size); +void +free(void *ptr); + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/string.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/string.h new file mode 100644 index 000000000..7a1a93dc4 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/string.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_STRING_H +#define _WAMR_LIBC_STRING_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef unsigned long size_t; + +int +memcmp(const void *s1, const void *s2, size_t n); +void * +memcpy(void *dest, const void *src, size_t n); +void * +memmove(void *dest, const void *src, size_t n); +void * +memset(void *s, int c, size_t n); +void * +memchr(const void *s, int c, size_t n); +int +strncasecmp(const char *s1, const char *s2, size_t n); +size_t +strspn(const char *s, const char *accept); +size_t +strcspn(const char *s, const char *reject); +char * +strstr(const char *s, const char *find); +char * +strchr(const char *s, int c); +int +strcmp(const char *s1, const char *s2); +char * +strcpy(char *dest, const char *src); +size_t +strlen(const char *s); +int +strncmp(const char *str1, const char *str2, size_t n); +char * +strncpy(char *dest, const char *src, unsigned long n); +char * +strdup(const char *s); + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/strings.h b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/strings.h new file mode 100644 index 000000000..3fe6ff63a --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/wamr-sdk/libc-builtin-sysroot/include/strings.h @@ -0,0 +1,17 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +#ifndef _WAMR_LIBC_STRINGS_H +#define _WAMR_LIBC_STRINGS_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif + +#endif
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/css/style.css b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/css/style.css new file mode 100644 index 000000000..bff10e5b4 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/css/style.css @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +.box_wrapper { + display: flex; + justify-content: center; + align-items: center; +} + +.form_heading { + text-align: left; +} + +.form_heading vscode-divider, +.config_form_heading vscode-divider, +.form_bottom vscode-divider, +.config_form_bottom vscode-divider { + padding-bottom: 0.5rem; +} + +.form_body, +.config_form_body { + display: grid; + grid-row-gap: 1rem; + padding-bottom: 0.5rem; +} + +.config_form_body div, +.config_submit_btn_wrapper { + display: grid; + grid-template-columns: 4fr 8fr; + grid-column-gap: 0.5rem; +} + +.form_heading, +.form_body, +.form_bottom { + width: 400px; +} + +.config_form_body, +.config_form_heading, +.config_form_bottom { + width: 550px; +} + +#btn_submit { + border-radius: 5px; +} + +#select_div, +#text_filed_div, +.proj_submit_btn_wrapper { + display: grid; + grid-template-columns: 3fr 9fr; + grid-column-gap: 0.5rem; +} + +#ipt_projName, +#select_dropdown, +.config_form_body vscode-text-field, +.config_form_body vscode-text-area { + width: 100%; +} + +#btn { + text-align: center; +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/js/configbuildtarget.js b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/js/configbuildtarget.js new file mode 100644 index 000000000..837f384bc --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/js/configbuildtarget.js @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +const vscode = acquireVsCodeApi(); + +document.getElementById('btn_submit').onclick = () => { + submitFunc(); +}; + +function submitFunc() { + let outputFileName = document.getElementById('output_file_name').value; + let initMemSize = document.getElementById('initial_mem_size').value; + let maxMemSize = document.getElementById('max_mem_size').value; + let stackSize = document.getElementById('stack_size').value; + let exportedSymbols = document.getElementById('exported_symbols').value; + + vscode.postMessage({ + command: 'config_build_target', + outputFileName: outputFileName, + initMemSize: initMemSize, + maxMemSize: maxMemSize, + stackSize: stackSize, + exportedSymbols: exportedSymbols, + }); +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/js/newproj.js b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/js/newproj.js new file mode 100644 index 000000000..30e169788 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/js/newproj.js @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +const vscode = acquireVsCodeApi(); + +document.getElementById('btn_submit').onclick = () => { + submitFunc(); +}; + +function submitFunc() { + let projectName = document.getElementById('ipt_projName').value; + let template = document.getElementById('select_dropdown').value; + + vscode.postMessage({ + command: 'create_new_project', + projectName: projectName, + template: template, + }); + + /* get msg from ext */ + window.addEventListener('message', event => { + const message = event.data; + switch (message.command) { + /* send command to open the project */ + case 'proj_creation_finish': + vscode.postMessage({ + command: 'open_project', + projectName: message.prjName, + }); + break; + default: + break; + } + }); +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/page/configBuildTarget.html b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/page/configBuildTarget.html new file mode 100644 index 000000000..b4c431511 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/page/configBuildTarget.html @@ -0,0 +1,63 @@ +<!-- + -- Copyright (C) 2019 Intel Corporation. All rights reserved. + -- SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + --> + +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <script type="module" src="${toolkitUri}"></script> + <script type="module" src="${mainUri}"></script> + <link rel="stylesheet" href="${styleUri}"> + <title>New project</title> +</head> + +<body> + <div class="box_wrapper"> + <div class="config_form_heading"> + <h2>Config building target</h2> + <vscode-divider></vscode-divider> + </div> + </div> + + <div class="box_wrapper"> + <div class="config_form_body"> + <div> + <label><b>Output file name: </b></label> + <vscode-text-field id="output_file_name" value=${output_file_val}></vscode-text-field> + </div> + <div> + <label><b>Initial linear memory size: </b></label> + <vscode-text-field id="initial_mem_size" value=${initial_mem_size_val}></vscode-text-field> + </div> + <div> + <label><b>Max linear memory size: </b></label> + <vscode-text-field id="max_mem_size" value=${max_mem_size_val}></vscode-text-field> + </div> + <div> + <label><b>Stack size: </b></label> + <vscode-text-field id="stack_size" value=${stack_size_val}></vscode-text-field> + </div> + <div> + <label><b>Exported symbols: </b></label> + <vscode-text-area rows="3" id="exported_symbols" placeholder="Please split each symbol with comma. Like 'app_main,on_init'" value=${exported_symbols_val}></vscode-text-area> + </div> + </div> + </div> + + <div class="box_wrapper"> + <div class="config_form_bottom"> + <vscode-divider></vscode-divider> + <div class="config_submit_btn_wrapper"> + <div></div> + <div id="btn"> + <vscode-button id="btn_submit"><b>Modify</b></vscode-buton> + </div> + </div> + </div> + </div> + +</body> +</html> diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/page/newProject.html b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/page/newProject.html new file mode 100644 index 000000000..71e67bd89 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/resource/webview/page/newProject.html @@ -0,0 +1,55 @@ +<!-- + -- Copyright (C) 2019 Intel Corporation. All rights reserved. + -- SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + --> + +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <script type="module" src="${toolkitUri}"></script> + <script type="module" src="${mainUri}"></script> + <link rel="stylesheet" href="${styleUri}"> + <title>Create project</title> +</head> + +<body> + <div class="box_wrapper"> + <div class="form_heading"> + <h2>Create project</h2> + <vscode-divider class="divider_wrapper"></vscode-divider> + </div> + </div> + + <div class="box_wrapper"> + <div class="form_body"> + <div id="text_filed_div"> + <label><b>Project Name: </b></label> + <vscode-text-field id="ipt_projName"></vscode-text-field> + </div> + + <div id="select_div"> + <label><b>Template:</b></label> + <vscode-dropdown id="select_dropdown"> + <vscode-option value="" selected:disabled style="display:none"></vscode-option> + <vscode-option value="default">default</vscode-option> + </vscode-dropdown> + </div> + </div> + </div> + + <div class="box_wrapper"> + <div class="form_bottom"> + <vscode-divider></vscode-divider> + <div class="proj_submit_btn_wrapper"> + <div></div> + <div id="btn"> + <vscode-button id="btn_submit"><b>Create</b></vscode-buton> + </div> + </div> + </div> + </div> + +</body> +</html> diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/constants.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/constants.ts new file mode 100644 index 000000000..cf8bb7103 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/constants.ts @@ -0,0 +1,7 @@ +export const enum SelectionOfPrompt { + skip = 'skip', + setUp = 'setup', +} +export const enum Status { + done = 'done', +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/debugConfigurationProvider.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/debugConfigurationProvider.ts new file mode 100644 index 000000000..e7b42bf03 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/debugConfigurationProvider.ts @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +import * as vscode from 'vscode'; +import * as os from 'os'; + +export class WasmDebugConfigurationProvider + implements vscode.DebugConfigurationProvider { + private wasmDebugConfig = { + type: 'wamr-debug', + name: 'Attach', + request: 'attach', + stopOnEntry: true, + initCommands: os.platform() === 'win32' || os.platform() === 'darwin' ? + /* linux and windows has different debug configuration */ + ['platform select remote-linux'] : + undefined, + attachCommands: [ + /* default port 1234 */ + 'process connect -p wasm connect://127.0.0.1:1234', + ] + }; + + public resolveDebugConfiguration( + _: vscode.WorkspaceFolder | undefined, + debugConfiguration: vscode.DebugConfiguration, + ): vscode.ProviderResult<vscode.DebugConfiguration> { + + this.wasmDebugConfig = { + ...this.wasmDebugConfig, + ...debugConfiguration + }; + + return this.wasmDebugConfig; + } + + public getDebugConfig(): vscode.DebugConfiguration { + return this.wasmDebugConfig; + } +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/decorationProvider.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/decorationProvider.ts new file mode 100644 index 000000000..46efcc90c --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/decorationProvider.ts @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +import * as vscode from 'vscode'; +import { readFromFile } from './utilities/directoryUtilities'; +import * as path from 'path'; +import * as os from 'os'; + +const DECORATION_INCLUDE_PATHS: vscode.FileDecoration = + new vscode.FileDecoration( + '✔', + 'Included', + new vscode.ThemeColor('list.highlightForeground') + ); +const DECORATION_EXCLUDE_FILES: vscode.FileDecoration = + new vscode.FileDecoration( + '✗', + 'Excluded', + new vscode.ThemeColor('list.errorForeground') + ); + +export class DecorationProvider implements vscode.FileDecorationProvider { + private disposables: vscode.Disposable[] = []; + public onDidChangeFileDecorations: vscode.Event< + vscode.Uri | vscode.Uri[] | undefined + >; + private eventEmitter: vscode.EventEmitter<vscode.Uri | vscode.Uri[]>; + + constructor() { + this.eventEmitter = new vscode.EventEmitter(); + this.onDidChangeFileDecorations = this.eventEmitter.event; + this.disposables.push( + vscode.window.registerFileDecorationProvider(this) + ); + } + + public provideFileDecoration( + uri: vscode.Uri + ): vscode.ProviderResult<vscode.FileDecoration> { + const currentPrjDir = + os.platform() === 'win32' + ? (vscode.workspace.workspaceFolders?.[0].uri.fsPath as string) + : os.platform() === 'linux' || os.platform() === 'darwin' + ? (vscode.workspace.workspaceFolders?.[0].uri.path as string) + : ''; + + const pathRelative = (uri.fsPath ? uri.fsPath : uri.toString()).replace( + currentPrjDir, + '..' + ); + + const prjConfigDir = path.join(currentPrjDir, '.wamr'); + const configFilePath = path.join( + prjConfigDir, + 'compilation_config.json' + ); + if (readFromFile(configFilePath) !== '') { + const configData = JSON.parse(readFromFile(configFilePath)); + const includePathArr = configData['includePaths']; + const excludeFileArr = configData['excludeFiles']; + + if (includePathArr.indexOf(pathRelative) > -1) { + return DECORATION_INCLUDE_PATHS; + } else if (excludeFileArr.indexOf(pathRelative) > -1) { + return DECORATION_EXCLUDE_FILES; + } + } + } + + public dispose(): void { + this.disposables.forEach(d => d.dispose()); + } + + public updateDecorationsForSource(uri: vscode.Uri): void { + this.eventEmitter.fire(uri); + } +} + +export const decorationProvider: DecorationProvider = new DecorationProvider(); diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/extension.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/extension.ts new file mode 100644 index 000000000..523b26b83 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/extension.ts @@ -0,0 +1,1027 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +import * as fileSystem from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as vscode from 'vscode'; + +import { WasmTaskProvider } from './taskProvider'; +import { TargetConfigPanel } from './view/TargetConfigPanel'; +import { NewProjectPanel } from './view/NewProjectPanel'; +import { + checkIfDirectoryExists, + writeIntoFile, + readFromFile, +} from './utilities/directoryUtilities'; +import { decorationProvider } from './decorationProvider'; +import { WasmDebugConfigurationProvider } from './debugConfigurationProvider'; +import { + isLLDBInstalled, + promptInstallLLDB, + getWAMRExtensionVersion, +} from './utilities/lldbUtilities'; + +import { + checkIfDockerStarted, + checkIfDockerImagesExist, + promptSetupDockerImages, +} from './utilities/dockerUtilities'; +import { SelectionOfPrompt } from './constants'; + +let wasmTaskProvider: WasmTaskProvider; +let wasmDebugConfigProvider: WasmDebugConfigurationProvider; +let currentPrjDir = ''; +let isWasmProject = false; + +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export async function activate(context: vscode.ExtensionContext) { + const extensionPath = context.extensionPath; + const osPlatform = os.platform(); + const wamrVersion = getWAMRExtensionVersion(context); + const typeMap = new Map<string, string>(); + const scriptMap = new Map<string, string>(); + /* set relative path of build.bat|sh script */ + const scriptPrefix = 'resource/scripts/'; + + let buildScript = '', + runScript = '', + debugScript = '', + destroyScript = '', + buildScriptFullPath = '', + runScriptFullPath = '', + debugScriptFullPath = '', + destroyScriptFullPath = '', + /* include paths array used for written into config file */ + includePathArr = new Array<string>(), + /* exclude files array used for written into config file */ + excludeFileArr = new Array<string>(); + + /** + * Provide Build & Run Task with Task Provider instead of "tasks.json" + */ + + if (osPlatform === 'win32') { + buildScript = scriptPrefix.concat('build.bat'); + runScript = scriptPrefix.concat('run.bat'); + debugScript = scriptPrefix.concat('boot_debugger_server.bat'); + destroyScript = scriptPrefix.concat('destroy.bat'); + } else if (osPlatform === 'linux' || osPlatform === 'darwin') { + buildScript = scriptPrefix.concat('build.sh'); + runScript = scriptPrefix.concat('run.sh'); + debugScript = scriptPrefix.concat('boot_debugger_server.sh'); + destroyScript = scriptPrefix.concat('destroy.sh'); + } + + buildScriptFullPath = path.join(extensionPath, buildScript); + runScriptFullPath = path.join(extensionPath, runScript); + debugScriptFullPath = path.join(extensionPath, debugScript); + destroyScriptFullPath = path.join(extensionPath, destroyScript); + + scriptMap.set('buildScript', buildScriptFullPath); + scriptMap.set('runScript', runScriptFullPath); + scriptMap.set('debugScript', debugScriptFullPath); + scriptMap.set('destroyScript', destroyScriptFullPath); + + typeMap.set('Build', 'Build'); + typeMap.set('Run', 'Run'); + typeMap.set('Debug', 'Debug'); + typeMap.set('Destroy', 'Destroy'); + + wasmTaskProvider = new WasmTaskProvider(typeMap, scriptMap, wamrVersion); + + vscode.tasks.registerTaskProvider('wasm', wasmTaskProvider); + + if (vscode.workspace.workspaceFolders?.[0]) { + if (osPlatform === 'win32') { + currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri + .fsPath as string; + } else if (osPlatform === 'linux' || osPlatform === 'darwin') { + currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri + .path as string; + } + + /** + * check whether current project opened in vscode workspace is wasm project + * it not, `build`, `run` and `debug` will be disabled + */ + if (currentPrjDir !== '') { + const wamrFolder = fileSystem + .readdirSync(currentPrjDir, { + withFileTypes: true, + }) + .filter( + folder => folder.isDirectory() && folder.name === '.wamr' + ); + + if (wamrFolder.length !== 0) { + isWasmProject = true; + vscode.commands.executeCommand( + 'setContext', + 'ext.isWasmProject', + isWasmProject + ); + if ( + vscode.workspace + .getConfiguration() + .has('C_Cpp.default.systemIncludePath') + ) { + let newIncludeInCppArr: string[] | undefined | null; + + newIncludeInCppArr = vscode.workspace + .getConfiguration() + .get('C_Cpp.default.systemIncludePath'); + + const libcBuiltinHeaderPath = path.join( + extensionPath, + 'resource/wamr-sdk/libc-builtin-sysroot/include' + ); + + if (newIncludeInCppArr !== undefined) { + /* in case the configuration has not been set up, push directly */ + if (newIncludeInCppArr === null) { + newIncludeInCppArr = []; + newIncludeInCppArr.push(libcBuiltinHeaderPath); + } else { + /* if the configuration has been set up, check the condition */ + if ( + /* include libc-builtin-sysroot */ + newIncludeInCppArr.indexOf( + libcBuiltinHeaderPath + ) < 0 + ) { + newIncludeInCppArr.push(libcBuiltinHeaderPath); + } + } + + vscode.workspace + .getConfiguration() + .update( + 'C_Cpp.default.systemIncludePath', + newIncludeInCppArr, + vscode.ConfigurationTarget.Workspace + ); + } + } + } + } + } + + /* register debug configuration */ + wasmDebugConfigProvider = new WasmDebugConfigurationProvider(); + + vscode.debug.registerDebugConfigurationProvider( + 'wamr-debug', + wasmDebugConfigProvider + ); + + /* update ext.includePaths to show or hide 'Remove' button in menus */ + vscode.commands.executeCommand('setContext', 'ext.supportedFileType', [ + '.c', + '.cpp', + '.cxx', + ]); + + if (readFromConfigFile() !== '') { + const configData = JSON.parse(readFromConfigFile()); + includePathArr = configData['includePaths']; + excludeFileArr = configData['excludeFiles']; + + if (Object.keys(configData['buildArgs']).length !== 0) { + TargetConfigPanel.buildArgs = configData['buildArgs']; + } + } + + const disposableNewProj = vscode.commands.registerCommand( + 'wamride.newProject', + () => { + const okStr = 'Set up now'; + const cancelStr = 'Maybe later'; + const curWorkspace = vscode.workspace + .getConfiguration() + .get('WAMR-IDE.configWorkspace'); + + /* if user has not set up workspace yet, prompt to set up */ + if (curWorkspace === '' || curWorkspace === undefined) { + vscode.window + .showWarningMessage( + 'Please setup your workspace firstly.', + okStr, + cancelStr + ) + .then(item => { + if (item === okStr) { + vscode.commands.executeCommand( + 'wamride.changeWorkspace' + ); + } else { + return; + } + }); + } else if (!checkIfDirectoryExists(curWorkspace as string)) { + vscode.window + .showWarningMessage( + 'Invalid workspace:', + { + modal: true, + detail: + '' + + vscode.workspace + .getConfiguration() + .get('WAMR-IDE.configWorkspace') + + '', + }, + okStr + ) + .then(item => { + if (item === okStr) { + vscode.commands.executeCommand( + 'wamride.changeWorkspace' + ); + } else { + return; + } + }); + } else { + NewProjectPanel.render(context); + } + } + ); + + const disposableTargetConfig = vscode.commands.registerCommand( + 'wamride.targetConfig', + () => { + if (currentPrjDir !== '') { + TargetConfigPanel.render(context); + } else { + vscode.window.showWarningMessage( + 'Please create and open project firstly.', + 'OK' + ); + } + } + ); + + const disposableChangeWorkspace = vscode.commands.registerCommand( + 'wamride.changeWorkspace', + async () => { + const options: vscode.OpenDialogOptions = { + canSelectFiles: false, + canSelectFolders: true, + openLabel: 'Select Workspace', + }; + + const workSpace = await vscode.window + .showOpenDialog(options) + .then(res => { + if (res) { + return res[0].fsPath as string; + } else { + return ''; + } + }); + + /* update workspace value to vscode global settings */ + if (workSpace !== '' && workSpace !== undefined) { + await vscode.workspace + .getConfiguration() + .update( + 'WAMR-IDE.configWorkspace', + workSpace.trim(), + vscode.ConfigurationTarget.Global + ) + .then( + () => { + vscode.window.showInformationMessage( + 'Workspace has been set up successfully!' + ); + }, + () => { + vscode.window.showErrorMessage( + 'Set up Workspace failed!' + ); + } + ); + } + } + ); + + const disposableBuild = vscode.commands.registerCommand( + 'wamride.build', + async () => { + if (!isWasmProject) { + vscode.window.showErrorMessage('Build failed', { + modal: true, + detail: 'Current project is not wasm project, please open wasm project and try again.', + }); + return; + } + + try { + /* check if docker images are ready before building */ + if ( + (await checkIfDockerStarted()) && + !(await checkIfDockerImagesExist(context)) + ) { + /**NOTE - if users select to skip install, + * we should return rather than continue + * the execution + */ + if ( + (await promptSetupDockerImages(context)) === + SelectionOfPrompt.skip + ) { + return; + } + } + } catch (e) { + vscode.window.showWarningMessage((e as Error).message); + return; + } + + generateCMakeFile(includePathArr, excludeFileArr); + /* destroy the wasm-toolchain-ctr if it exists */ + vscode.commands + .executeCommand( + 'workbench.action.tasks.runTask', + 'Destroy: Wasm-Container-Before-Build' + ) + .then(() => { + const disposable = vscode.tasks.onDidEndTaskProcess(t => { + if ( + t.execution.task.name === + 'Wasm-Container-Before-Build' + ) { + if (t.exitCode !== 0) { + disposable.dispose(); + return; + } + + /* execute the build task */ + vscode.commands + .executeCommand( + 'workbench.action.tasks.runTask', + 'Build: Wasm' + ) + .then(() => { + /* destroy the wasm-toolchain-ctr after building */ + const disposableAft = + vscode.tasks.onDidEndTask(a => { + if ( + a.execution.task.name === + 'Wasm' && + a.execution.task.source === + 'Build' + ) { + vscode.commands + .executeCommand( + 'workbench.action.tasks.runTask', + 'Destroy: Wasm-Container-After-Build' + ) + .then(() => { + /* dispose the event after this building process + */ + disposableAft.dispose(); + }); + } + }); + }); + /* dispose the event after this building process */ + disposable.dispose(); + } + }); + }); + } + ); + + const disposableDebug = vscode.commands.registerCommand( + 'wamride.debug', + async () => { + if (!isWasmProject) { + vscode.window.showErrorMessage('debug failed', { + modal: true, + detail: 'Current project is not wasm project, please open wasm project and try again.', + }); + return; + } + + /* we should check again whether the user installed lldb, as this can be skipped during activation */ + try { + if (!isLLDBInstalled(context)) { + /**NOTE - if users select to skip install, + * we should return rather than continue + * the execution + */ + if ( + (await promptInstallLLDB(context)) === + SelectionOfPrompt.skip + ) { + return; + } + } + + if ( + (await checkIfDockerStarted()) && + !(await checkIfDockerImagesExist(context)) + ) { + /**NOTE - save as above lldb, should return if + * users select to skip set up + */ + if ( + (await promptSetupDockerImages(context)) === + SelectionOfPrompt.skip + ) { + return; + } + } + } catch (e) { + vscode.window.showWarningMessage((e as Error).message); + return; + } + + /* refuse to debug if build process failed */ + if (!checkIfBuildSuccess()) { + vscode.window.showErrorMessage('Debug failed', { + modal: true, + detail: 'Can not find WASM binary, please build WASM firstly.', + }); + return; + } + + /* show debug view */ + vscode.commands.executeCommand('workbench.view.debug'); + + /* should destroy the wasm-debug-server-ctr before debugging */ + vscode.commands + .executeCommand( + 'workbench.action.tasks.runTask', + 'Destroy: Wasm-Container-Before-Debug' + ) + .then(() => { + /* execute the debug task when destroy task finish */ + const disposableBfr = vscode.tasks.onDidEndTask(t => { + if ( + t.execution.task.name === + 'Wasm-Container-Before-Debug' + ) { + vscode.commands + .executeCommand( + 'workbench.action.tasks.runTask', + 'Debug: Wasm' + ) + .then(() => { + vscode.debug + .startDebugging( + undefined, + wasmDebugConfigProvider.getDebugConfig() + ) + .then(() => { + /* register to listen debug session finish event */ + const disposableAft = + vscode.debug.onDidTerminateDebugSession( + s => { + if ( + s.type !== + 'wamr-debug' + ) { + return; + } + + /* execute the task to destroy + * wasm-debug-server-ctr */ + vscode.commands.executeCommand( + 'workbench.action.tasks.runTask', + 'Destroy: Wasm-Container-After-Debug' + ); + + /* execute the task to kill the terminal */ + vscode.commands.executeCommand( + 'workbench.action.terminal.kill', + 'Debug: Wasm' + ); + + disposableAft.dispose(); + } + ); + }); + }); + } + disposableBfr.dispose(); + }); + }); + } + ); + + const disposableRun = vscode.commands.registerCommand( + 'wamride.run', + async () => { + if (!isWasmProject) { + vscode.window.showErrorMessage('run failed', { + modal: true, + detail: 'Current project is not wasm project, please open wasm project and try again.', + }); + return; + } + + try { + /* check if docker images are set up before building */ + if ( + (await checkIfDockerStarted()) && + !(await checkIfDockerImagesExist(context)) + ) { + await promptSetupDockerImages(context); + } + } catch (e) { + vscode.window.showWarningMessage((e as Error).message); + return; + } + + /* refuse to debug if build process failed */ + if (!checkIfBuildSuccess()) { + vscode.window.showErrorMessage('Debug failed', { + modal: true, + detail: 'Can not find WASM binary, please build WASM firstly.', + }); + return; + } + + vscode.commands + .executeCommand( + 'workbench.action.tasks.runTask', + 'Destroy: Wasm-Container-Before-Run' + ) + .then(() => { + const disposableAft = vscode.tasks.onDidEndTaskProcess( + e => { + if ( + e.execution.task.name === + 'Wasm-Container-Before-Run' + ) { + /* make sure that run wasm task will be executed when destroy task finish */ + vscode.commands + .executeCommand( + 'workbench.action.tasks.runTask', + 'Run: Wasm' + ) + .then(() => { + if (e.exitCode !== 0) { + disposableAft.dispose(); + return; + } + }); + disposableAft.dispose(); + } + } + ); + }); + } + ); + + const disposableToggleIncludePath = vscode.commands.registerCommand( + 'wamride.build.toggleStateIncludePath', + fileUri => { + const path = + fileUri._fsPath !== null && fileUri._fsPath !== undefined + ? fileUri._fsPath + : vscode.Uri.parse(fileUri.path as string).fsPath; + const pathRelative = path.replace(currentPrjDir, '..'); + + if (includePathArr.indexOf(pathRelative) > -1) { + /* this folder has been added to include path, remove it */ + includePathArr = includePathArr.filter(value => { + return value !== pathRelative; + }); + } else { + includePathArr.push(pathRelative); + } + + writeIntoConfigFile( + includePathArr, + excludeFileArr, + TargetConfigPanel.buildArgs + ); + + decorationProvider.updateDecorationsForSource(fileUri); + } + ); + + const disposableToggleExcludeFile = vscode.commands.registerCommand( + 'wamride.build.toggleStateExclude', + fileUri => { + const path = + fileUri._fsPath !== null && fileUri._fsPath !== undefined + ? fileUri._fsPath + : vscode.Uri.parse(fileUri.path as string).fsPath; + + /* replace the current project absolute path with .. to change to relative path */ + const pathRelative = path.replace(currentPrjDir, '..'); + + if (excludeFileArr.indexOf(pathRelative) > -1) { + excludeFileArr = excludeFileArr.filter(val => { + return val !== pathRelative; + }); + } else { + excludeFileArr.push(pathRelative); + } + + writeIntoConfigFile( + includePathArr, + excludeFileArr, + TargetConfigPanel.buildArgs + ); + + /* update decoration for this source file */ + decorationProvider.updateDecorationsForSource(fileUri); + } + ); + + const disposableOpenFolder = vscode.commands.registerCommand( + 'wamride.openFolder', + () => { + /* get projects list under current workspace */ + const okStr = 'Set up now'; + const cancelStr = 'Maybe later'; + const createStr = 'Create now'; + const curWorkspace = vscode.workspace + .getConfiguration() + .get('WAMR-IDE.configWorkspace') as string; + + /* if user has not set up workspace yet, prompt to set up */ + if (curWorkspace === '' || curWorkspace === undefined) { + vscode.window + .showWarningMessage( + 'Please setup your workspace firstly.', + okStr, + cancelStr + ) + .then(item => { + if (item === okStr) { + vscode.commands.executeCommand( + 'wamride.changeWorkspace' + ); + } else { + return; + } + }); + } else if (!checkIfDirectoryExists(curWorkspace as string)) { + vscode.window + .showWarningMessage( + 'Invalid workspace:', + { + modal: true, + detail: + '' + + vscode.workspace + .getConfiguration() + .get('WAMR-IDE.configWorkspace') + + '', + }, + okStr + ) + .then(item => { + if (item === okStr) { + vscode.commands.executeCommand( + 'wamride.changeWorkspace' + ); + } else { + return; + } + }); + } else { + /* get all directories within directory, ignore files */ + let directoryArrDirent, directoryArr; + try { + directoryArrDirent = fileSystem.readdirSync(curWorkspace, { + withFileTypes: true, + }); + } catch (err) { + vscode.window.showErrorMessage( + 'Read projects from current workspace failed.' + ); + } + + if (directoryArrDirent !== undefined) { + directoryArr = directoryArrDirent + .filter(dirent => dirent.isDirectory()) + .map(dirent => dirent.name); + + const projFilesArr = directoryArr.filter(obj => { + if (checkIfWasmProj(path.join(curWorkspace, obj))) { + return true; + } + }); + + if (projFilesArr.length === 0) { + vscode.window + .showWarningMessage( + 'Current workspace is empty, please create your project firstly.', + createStr, + cancelStr + ) + .then(item => { + if (item === createStr) { + vscode.commands.executeCommand( + 'wamride.newProject' + ); + } else { + return; + } + }); + } else { + vscode.window + .showQuickPick(projFilesArr, { + title: 'Select project', + placeHolder: 'Please select project', + }) + .then(option => { + if (!option) { + return; + } + + const path = curWorkspace.concat( + osPlatform === 'win32' + ? '\\' + : osPlatform === 'linux' || + osPlatform === 'darwin' + ? '/' + : '', + option + ); + + /* open the selected wasm project */ + openWindowWithSituation(vscode.Uri.file(path)); + }); + } + } + } + } + ); + + context.subscriptions.push( + disposableNewProj, + disposableTargetConfig, + disposableChangeWorkspace, + disposableBuild, + disposableRun, + disposableToggleIncludePath, + disposableOpenFolder, + disposableToggleExcludeFile, + disposableDebug + ); + + try { + if (!isLLDBInstalled(context)) { + await promptInstallLLDB(context); + } + + if ( + (await checkIfDockerStarted()) && + !(await checkIfDockerImagesExist(context)) + ) { + await promptSetupDockerImages(context); + } + } catch (e) { + vscode.window.showWarningMessage((e as Error).message); + } +} + +function openWindowWithSituation(uri: vscode.Uri) { + /** + * check if the workspace folder is empty, + * if yes, open new window, else open in current window + */ + const isWorkspaceEmpty = !vscode.workspace.workspaceFolders?.[0] + ? true + : false; + + isWorkspaceEmpty === false + ? vscode.commands.executeCommand('vscode.openFolder', uri, { + forceNewWindow: true, + }) + : vscode.commands.executeCommand('vscode.openFolder', uri); + + return; +} + +interface BuildArgs { + outputFileName: string; + initMemorySize: string; + maxMemorySize: string; + stackSize: string; + exportedSymbols: string; +} + +/** + * @param: includePathArr + * @param: excludeFileArr + * Get current includePathArr and excludeFileArr from the json string that + * will be written into compilation_config.json + */ +export function writeIntoConfigFile( + includePathArr: string[], + excludeFileArr: string[], + buildArgs?: BuildArgs +): void { + const jsonStr = JSON.stringify( + { + includePaths: includePathArr, + excludeFiles: excludeFileArr, + buildArgs: buildArgs ? buildArgs : '{}', + }, + null, + '\t' + ); + + const prjConfigDir = path.join(currentPrjDir, '.wamr'); + const configFilePath = path.join(prjConfigDir, 'compilation_config.json'); + writeIntoFile(configFilePath, jsonStr); +} + +export function readFromConfigFile(): string { + const prjConfigDir = path.join(currentPrjDir, '.wamr'); + const configFilePath = path.join(prjConfigDir, 'compilation_config.json'); + return readFromFile(configFilePath); +} + +/** + * will be triggered when the user clicking `build` button + */ +function generateCMakeFile( + includePathArr: string[], + excludeFileArr: string[] +): void { + // -Wl,--export=${EXPORT_SYMBOLS} + const srcFilePath = path.join(currentPrjDir, 'src'); + const prjConfigDir = path.join(currentPrjDir, '.wamr'); + const cmakeFilePath = path.join(prjConfigDir, 'project.cmake'); + + let strIncludeList = 'set (PROJECT_INCLUDES'; + let strSrcList = 'set (PROJECT_SRC_LIST'; + + let strOutputFileName = 'set (OUTPUT_FILE_NAME'; + let strInitMemSize = 'set (INIT_MEM_SIZE'; + let strMaxMemSize = 'set (MAX_MEM_SIZE'; + let strStackSize = 'set (STACK_SIZE'; + let strExportedSymbols = 'set (EXPORTED_SYMBOLS'; + + let fullStr = ''; + let i, s, e: number; + + /* change the absolute path into relative path */ + const _re = currentPrjDir; + const _substr = '${CMAKE_CURRENT_SOURCE_DIR}/..'; + + /** + * set PROJECT_SRC_LIST + * default ADD every c OR c++ OR cpp under the src/ path + * except the files saved in the excludeFiles array + */ + + const srcPathArr = getAllSrcFiles(srcFilePath); + + if (srcPathArr === undefined) { + return; + } + + for (s = 0; s < srcPathArr.length; s++) { + if ( + excludeFileArr.indexOf( + srcPathArr[s].path.replace(currentPrjDir, '..') + ) === -1 + ) { + /* replace currentPrjDir with ${CMAKE_CURRENT_SOURCE_DIR} */ + const newStr = srcPathArr[s].path + .replace(_re, _substr) + .replace(/\\/g, '/'); + + strSrcList = strSrcList.concat(' ', newStr); + } + } + strSrcList = strSrcList.concat(' )'); + + for (i = 0; i < includePathArr.length; i++) { + const newStr = includePathArr[i] + .replace(/../, _substr) + .replace(/\\/g, '/'); + strIncludeList = strIncludeList.concat(' ', newStr); + } + strIncludeList = strIncludeList.concat(' )'); + + /* set up user customized input in configBuildArgs webview */ + strOutputFileName = strOutputFileName.concat( + ' ', + TargetConfigPanel.buildArgs.outputFileName + ')' + ); + + strInitMemSize = strInitMemSize.concat( + ' ', + TargetConfigPanel.buildArgs.initMemorySize + ')' + ); + + strMaxMemSize = strMaxMemSize.concat( + ' ', + TargetConfigPanel.buildArgs.maxMemorySize + ')' + ); + + strStackSize = strStackSize.concat( + ' ', + TargetConfigPanel.buildArgs.stackSize + ')' + ); + + const exportedSymbolArr = + TargetConfigPanel.buildArgs.exportedSymbols.split(','); + + strExportedSymbols = strExportedSymbols.concat(' "'); + + for (e = 0; e < exportedSymbolArr.length; e++) { + strExportedSymbols = strExportedSymbols.concat( + ' -Wl,', + '--export=', + exportedSymbolArr[e] + ); + } + + strExportedSymbols = strExportedSymbols.concat('")'); + + fullStr = strOutputFileName + .concat('\n', strInitMemSize) + .concat('\n', strMaxMemSize) + .concat('\n', strStackSize) + .concat('\n', strExportedSymbols) + .concat('\n', strSrcList) + .concat('\n', strIncludeList); + + writeIntoFile(cmakeFilePath, fullStr); +} + +function getAllSrcFiles(_path: string) { + try { + const entries = fileSystem.readdirSync(_path, { + withFileTypes: true, + }); + + const files = entries + .filter( + /* filter files mismatch .c |.cpp |.cxx */ + file => + !file.isDirectory() && file.name.match('(.c|.cpp|.cxx)$') + ) + .map(file => ({ + path: path.join(_path, file.name), + })); + + const folders = entries.filter(folder => folder.isDirectory()); + + for (const folder of folders) { + const fileArr = getAllSrcFiles(path.join(_path, folder.name)); + fileArr ? files.push(...fileArr) : ''; + } + + return files; + } catch (error) { + vscode.window.showErrorMessage(error as string); + } +} + +function checkIfBuildSuccess(): boolean { + try { + let wasmExist = false; + const entries = fileSystem.readdirSync( + path.join(currentPrjDir, 'build'), + { + withFileTypes: true, + } + ); + + entries.map(e => { + if (e.name.match('(.wasm)$')) { + wasmExist = true; + } + }); + + return wasmExist; + } catch { + return false; + } +} + +function checkIfWasmProj(path: string): boolean { + try { + let isWasmProj = false; + const entries = fileSystem.readdirSync(path, { + withFileTypes: true, + }); + + entries.map(e => { + if (e.isDirectory() && e.name === '.wamr') { + isWasmProj = true; + } + }); + + return isWasmProj; + } catch { + return false; + } +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/taskProvider.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/taskProvider.ts new file mode 100644 index 000000000..9b9b75f9a --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/taskProvider.ts @@ -0,0 +1,228 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +import * as vscode from 'vscode'; +import * as os from 'os'; +import { TargetConfigPanel } from './view/TargetConfigPanel'; + +export interface OwnShellOption { + cmd: string; + options: vscode.ShellExecutionOptions; +} + +export class WasmTaskProvider implements vscode.TaskProvider { + constructor( + public _type: Map<string, string>, + public _script: Map<string, string>, + public _wamrVersion: string + ) {} + + buildShellOption: OwnShellOption | undefined; + runShellOption: OwnShellOption | undefined; + debugShellOption: OwnShellOption | undefined; + destroyShellOption: OwnShellOption | undefined; + + private wasmPromise: Thenable<vscode.Task[]> | undefined = undefined; + + public provideTasks(): Thenable<vscode.Task[]> | undefined { + if (!this.wasmPromise) { + /* target name is used for generated aot target */ + const targetName = + TargetConfigPanel.buildArgs.outputFileName.split('.')[0]; + + if ( + os.platform() === 'linux' || + os.platform() === 'darwin' || + os.platform() === 'win32' + ) { + /* build */ + this.buildShellOption = { + cmd: + os.platform() === 'linux' || os.platform() === 'darwin' + ? 'bash' + : (this._script.get('buildScript') as string), + options: { + executable: this._script.get('buildScript'), + shellArgs: [targetName, this._wamrVersion], + }, + }; + + /* debug */ + this.debugShellOption = { + cmd: + os.platform() === 'linux' || os.platform() === 'darwin' + ? 'bash' + : (this._script.get('debugScript') as string), + options: { + executable: this._script.get('debugScript'), + shellArgs: [targetName, this._wamrVersion], + }, + }; + + /* run */ + this.runShellOption = { + cmd: + os.platform() === 'linux' || os.platform() === 'darwin' + ? 'bash' + : (this._script.get('runScript') as string), + options: { + executable: this._script.get('runScript'), + shellArgs: [targetName, this._wamrVersion], + }, + }; + + /* destroy */ + /* run */ + this.destroyShellOption = { + cmd: + os.platform() === 'linux' || os.platform() === 'darwin' + ? 'bash' + : (this._script.get('destroyScript') as string), + options: { + executable: this._script.get('destroyScript'), + shellArgs: [targetName], + }, + }; + } else { + this.buildShellOption = { + cmd: "echo 'os platform is not supported yet'", + options: {}, + }; + + this.debugShellOption = { + cmd: "echo 'os platform is not supported yet'", + options: {}, + }; + + this.runShellOption = { + cmd: "echo 'os platform is not supported yet'", + options: {}, + }; + + this.destroyShellOption = { + cmd: "echo 'os platform is not supported yet'", + options: {}, + }; + } + + this.wasmPromise = Promise.resolve([ + new vscode.Task( + { type: 'wasm' }, + vscode.TaskScope.Workspace, + 'Wasm', + this._type.get('Build') as string, + new vscode.ShellExecution( + this.buildShellOption.cmd, + this.buildShellOption.options + ) + ), + + new vscode.Task( + { type: 'wasm' }, + vscode.TaskScope.Workspace, + 'Wasm', + this._type.get('Run') as string, + new vscode.ShellExecution( + this.runShellOption.cmd, + this.runShellOption.options + ) + ), + + new vscode.Task( + { type: 'wasm' }, + vscode.TaskScope.Workspace, + 'Wasm', + this._type.get('Debug') as string, + new vscode.ShellExecution( + this.debugShellOption.cmd, + this.debugShellOption.options + ) + ), + + new vscode.Task( + { type: 'wasm' }, + vscode.TaskScope.Workspace, + 'Wasm-Container-Before-Build', + this._type.get('Destroy') as string, + new vscode.ShellExecution( + this.destroyShellOption.cmd, + this.destroyShellOption.options + ) + ), + + new vscode.Task( + { type: 'wasm' }, + vscode.TaskScope.Workspace, + 'Wasm-Container-Before-Debug', + this._type.get('Destroy') as string, + new vscode.ShellExecution( + this.destroyShellOption.cmd, + this.destroyShellOption.options + ) + ), + + new vscode.Task( + { type: 'wasm' }, + vscode.TaskScope.Workspace, + 'Wasm-Container-Before-Run', + this._type.get('Destroy') as string, + new vscode.ShellExecution( + this.destroyShellOption.cmd, + this.destroyShellOption.options + ) + ), + + new vscode.Task( + { type: 'wasm' }, + vscode.TaskScope.Workspace, + 'Wasm-Container-After-Build', + this._type.get('Destroy') as string, + new vscode.ShellExecution( + this.destroyShellOption.cmd, + this.destroyShellOption.options + ) + ), + + new vscode.Task( + { type: 'wasm' }, + vscode.TaskScope.Workspace, + 'Wasm-Container-After-Debug', + this._type.get('Destroy') as string, + new vscode.ShellExecution( + this.destroyShellOption.cmd, + this.destroyShellOption.options + ) + ), + + new vscode.Task( + { type: 'wasm' }, + vscode.TaskScope.Workspace, + 'Wasm-Container-After-Run', + this._type.get('Destroy') as string, + new vscode.ShellExecution( + this.destroyShellOption.cmd, + this.destroyShellOption.options + ) + ), + ]); + } + + return this.wasmPromise; + } + + /** + * if the task or task in tasks.json does not set command, ` + * resolveTask` will be invoked, + * otherwise, `provideTasks` will be invoked + * @param _task + * @returns + */ + public resolveTask(task: vscode.Task): vscode.Task | undefined { + if (task) { + return task; + } + return undefined; + } +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/directoryUtilities.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/directoryUtilities.ts new file mode 100644 index 000000000..0efbea5d9 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/directoryUtilities.ts @@ -0,0 +1,211 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +import fileSystem = require('fs'); +import vscode = require('vscode'); +import path = require('path'); +import os = require('os'); +import request = require('request'); +import yauzl = require('yauzl'); + +/** + * + * @param path destination path + */ +export function createDirectory( + dest: string, + mode: string | number | null | undefined = undefined +): boolean { + try { + if (fileSystem.existsSync(dest)) { + if (fileSystem.lstatSync(dest).isDirectory()) { + return true; + } else { + return false; + } + } + + if (!path) { + return false; + } + + const parent = path.dirname(dest); + if (!createDirectory(parent, mode)) { + return false; + } + + fileSystem.mkdirSync(dest, mode); + return true; + } catch (error) { + vscode.window.showErrorMessage(error as string); + return false; + } +} + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function copyFiles(src: string, dest: string, flags?: number): boolean { + try { + fileSystem.copyFileSync(src, dest); + return true; + } catch (error) { + vscode.window.showErrorMessage(error as string); + return false; + } +} + +export function writeIntoFile(path: string, data: string): void { + try { + fileSystem.writeFileSync(path, data, null); + } catch (err) { + vscode.window.showErrorMessage(err as string); + } +} + +export function readFromFile(path: string): string { + try { + const data = fileSystem.readFileSync(path, { encoding: 'utf-8' }); + return data as string; + } catch (err) { + vscode.window.showErrorMessage(err as string); + return ''; + } +} + +export function writeIntoFileAsync( + path: string, + data: string, + callback: fileSystem.NoParamCallback +): void { + try { + fileSystem.writeFile(path, data, callback); + } catch (err) { + vscode.window.showErrorMessage(err as string); + return; + } +} + +export function checkIfPathExists(path: string): boolean { + try { + if (fileSystem.existsSync(path)) { + return true; + } else { + return false; + } + } catch (err) { + vscode.window.showErrorMessage(err as string); + return false; + } +} + +export function checkIfDirectoryExists(path: string): boolean { + const doesPathExist = checkIfPathExists(path); + if (doesPathExist) { + return fileSystem.lstatSync(path).isDirectory(); + } + return false; +} + +export function checkIfFileExists(path: string): boolean { + const doesPathExist = checkIfPathExists(path); + if (doesPathExist) { + return fileSystem.lstatSync(path).isFile(); + } + return false; +} + +export function checkFolderName(folderName: string): boolean { + let invalidCharacterArr: string[] = []; + let valid = true; + + if (folderName.length > 255) { + valid = false; + } + + if (os.platform() === 'win32') { + invalidCharacterArr = ['\\', '/', ':', '?', '*', '"', '|', '<', '>']; + } else if (os.platform() === 'linux' || os.platform() === 'darwin') { + invalidCharacterArr = ['/']; + } + + invalidCharacterArr.forEach(function (c) { + if (folderName.indexOf(c) !== -1) { + valid = false; + } + }); + + return valid; +} + +export function downloadFile( + url: string, + destinationPath: string +): Promise<void> { + return new Promise((resolve, reject) => { + const file = fileSystem.createWriteStream(destinationPath); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const stream = request(url, undefined, (error, response, body) => { + if (response.statusCode !== 200) { + reject( + new Error( + `Download from ${url} failed with ${response.statusMessage}` + ) + ); + } + }).pipe(file); + stream.on('close', resolve); + stream.on('error', reject); + }); +} + +export function unzipFile( + sourcePath: string, + getDestinationFileName: (entryName: string) => string +): Promise<string[]> { + return new Promise((resolve, reject) => { + const unzippedFilePaths: string[] = []; + yauzl.open( + sourcePath, + { lazyEntries: true }, + function (error, zipfile) { + if (error) { + reject(error); + return; + } + zipfile.readEntry(); + zipfile.on('entry', function (entry) { + // This entry is a directory so skip it + if (/\/$/.test(entry.fileName)) { + zipfile.readEntry(); + return; + } + + zipfile.openReadStream(entry, function (error, readStream) { + if (error) { + reject(error); + return; + } + readStream.on('end', () => zipfile.readEntry()); + const destinationFileName = getDestinationFileName( + entry.fileName + ); + fileSystem.mkdirSync( + path.dirname(destinationFileName), + { recursive: true } + ); + + const file = + fileSystem.createWriteStream(destinationFileName); + readStream.pipe(file).on('error', reject); + unzippedFilePaths.push(destinationFileName); + }); + }); + zipfile.on('end', function () { + zipfile.close(); + resolve(unzippedFilePaths); + }); + } + ); + }); +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/dockerUtilities.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/dockerUtilities.ts new file mode 100644 index 000000000..0a749ba19 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/dockerUtilities.ts @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +import * as vscode from 'vscode'; +import * as cp from 'child_process'; +import * as path from 'path'; +import * as fs from 'fs'; +import { getWAMRExtensionVersion } from './lldbUtilities'; +import { downloadFile, unzipFile } from './directoryUtilities'; +import { SelectionOfPrompt, Status } from '../constants'; + +const DOCKER_IMAGES_TEM_FOLDER_NAME = 'docker-resource'; + +type SelectionStatus = SelectionOfPrompt | Status; + +const execShell = (cmd: string) => + new Promise<string>((resolve, reject) => { + cp.exec(cmd, (error, result) => { + if (error) { + return reject(error); + } + return resolve(result); + }); + }); + +export async function promptSetupDockerImages( + context: vscode.ExtensionContext +): Promise<SelectionStatus> { + const extensionPath = context.extensionPath; + const response = await vscode.window.showWarningMessage( + 'Necessary docker images are not found. Setup now?', + SelectionOfPrompt.setUp, + SelectionOfPrompt.skip + ); + + if (response === SelectionOfPrompt.skip) { + return response; + } + + const downloadUrlArray = getDockerImagesDownloadUrl(context); + + const destinationFolder = path.resolve( + extensionPath, + 'resource', + DOCKER_IMAGES_TEM_FOLDER_NAME + ); + + if (!fs.existsSync(destinationFolder)) { + fs.mkdirSync(destinationFolder); + } + + vscode.window.showInformationMessage(`Downloading Docker Images...`); + + for (const url of downloadUrlArray) { + const imageZipName = path.basename(url); + const imageStorePath = path.join(destinationFolder, imageZipName); + await downloadFile(url, imageStorePath); + + /** + * extract docker image tar package to + * '${destinationFolder}' + */ + const dockerImageFile = await unzipFile(imageStorePath, filename => + path.join(destinationFolder, filename) + ); + /* give access before loading */ + dockerImageFile.forEach(file => fs.chmodSync(file, '0775')); + + /**NOTE - load docker image tar package to host + * right now there are just one file + * `docker-image-name.tar` inside so we can + * directly use files[0] here, should be modified + * if the package's files change + */ + await execShell(`docker load -i ${dockerImageFile[0]}`); + } + + /* remove the DOCKER_IMAGES_TEM_FOLDER */ + fs.rmSync(destinationFolder, { recursive: true, force: true }); + + vscode.window.showInformationMessage( + `Docker images are ready, please run '$docker images' to check.` + ); + + return Status.done; +} + +export async function checkIfDockerStarted(): Promise<boolean> { + try { + await execShell('docker images'); + return true; + } catch (e) { + vscode.window.showWarningMessage((e as Error).message); + return false; + } +} + +export async function checkIfDockerImagesExist( + context: vscode.ExtensionContext +): Promise<boolean> { + try { + /* the tag of images is equal to extension's version */ + const imageTag = getWAMRExtensionVersion(context); + await execShell( + `docker image inspect wasm-debug-server:${imageTag} wasm-toolchain:${imageTag}` + ); + return true; + } catch (e) { + return false; + } +} + +function getDockerImagesDownloadUrl( + context: vscode.ExtensionContext +): string[] { + const wamrVersion = getWAMRExtensionVersion(context); + const wamrReleaseUrl = `https://github.com/bytecodealliance/wasm-micro-runtime/releases/download/WAMR`; + + return [ + `${wamrReleaseUrl}-${wamrVersion}/wasm-debug-server-${wamrVersion}.zip`, + `${wamrReleaseUrl}-${wamrVersion}/wasm-toolchain-${wamrVersion}.zip`, + ]; +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/getUri.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/getUri.ts new file mode 100644 index 000000000..93a7eef30 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/getUri.ts @@ -0,0 +1,14 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +import { Uri, Webview } from 'vscode'; + +export function getUri( + webview: Webview, + extensionUri: Uri, + pathList: string[] +): Uri { + return webview.asWebviewUri(Uri.joinPath(extensionUri, ...pathList)); +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/lldbUtilities.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/lldbUtilities.ts new file mode 100644 index 000000000..9170a75d3 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/utilities/lldbUtilities.ts @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2022 Amazon.com Inc. or its affiliates. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +import * as vscode from 'vscode'; +import * as os from 'os'; +import * as path from 'path'; +import * as fs from 'fs'; +import { + checkIfFileExists, + downloadFile, + unzipFile, +} from './directoryUtilities'; +import { SelectionOfPrompt } from '../constants'; + +const LLDB_RESOURCE_DIR = 'resource/debug'; +const LLDB_OS_DOWNLOAD_URL_SUFFIX_MAP: Partial< + Record<NodeJS.Platform, string> +> = { + linux: 'x86_64-ubuntu-20.04', + darwin: 'universal-macos-latest', +}; + +const WAMR_LLDB_NOT_SUPPORTED_ERROR = new Error( + 'WAMR LLDB is not supported on this platform' +); + +function getLLDBUnzipFilePath(destinationFolder: string, filename: string) { + const dirs = filename.split('/'); + if (dirs[0] === 'wamr-lldb') { + dirs.shift(); + } + + return path.join(destinationFolder, ...dirs); +} + +export function getWAMRExtensionVersion( + context: vscode.ExtensionContext +): string { + // eslint-disable-next-line @typescript-eslint/no-var-requires + return require(path.join(context.extensionPath, 'package.json')).version; +} + +function getLLDBDownloadUrl(context: vscode.ExtensionContext): string { + const wamrVersion = getWAMRExtensionVersion(context); + const lldbOsUrlSuffix = LLDB_OS_DOWNLOAD_URL_SUFFIX_MAP[os.platform()]; + + if (!lldbOsUrlSuffix) { + throw WAMR_LLDB_NOT_SUPPORTED_ERROR; + } + + return `https://github.com/bytecodealliance/wasm-micro-runtime/releases/download/WAMR-${wamrVersion}/wamr-lldb-${wamrVersion}-${lldbOsUrlSuffix}.zip`; +} + +export function isLLDBInstalled(context: vscode.ExtensionContext): boolean { + const extensionPath = context.extensionPath; + const lldbOSDir = os.platform(); + const lldbBinaryPath = path.join( + extensionPath, + LLDB_RESOURCE_DIR, + lldbOSDir, + 'bin', + 'lldb' + ); + return checkIfFileExists(lldbBinaryPath); +} + +export async function promptInstallLLDB( + context: vscode.ExtensionContext +): Promise<SelectionOfPrompt> { + const extensionPath = context.extensionPath; + + const response = await vscode.window.showWarningMessage( + 'No LLDB instance found. Setup now?', + SelectionOfPrompt.setUp, + SelectionOfPrompt.skip + ); + + if (response === SelectionOfPrompt.skip) { + return response; + } + + const downloadUrl = getLLDBDownloadUrl(context); + const destinationDir = os.platform(); + + if (!downloadUrl) { + throw WAMR_LLDB_NOT_SUPPORTED_ERROR; + } + + const lldbDestinationFolder = path.join( + extensionPath, + LLDB_RESOURCE_DIR, + destinationDir + ); + const lldbZipPath = path.join(lldbDestinationFolder, 'bundle.zip'); + + vscode.window.showInformationMessage(`Downloading LLDB...`); + + await downloadFile(downloadUrl, lldbZipPath); + + vscode.window.showInformationMessage( + `LLDB downloaded to ${lldbZipPath}. Installing...` + ); + + const lldbFiles = await unzipFile(lldbZipPath, filename => + getLLDBUnzipFilePath(lldbDestinationFolder, filename) + ); + // Allow execution of lldb + lldbFiles.forEach(file => fs.chmodSync(file, '0775')); + + vscode.window.showInformationMessage( + `LLDB installed at ${lldbDestinationFolder}` + ); + + // Remove the bundle.zip + fs.unlinkSync(lldbZipPath); + return SelectionOfPrompt.setUp; +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/view/NewProjectPanel.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/view/NewProjectPanel.ts new file mode 100644 index 000000000..79671f68c --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/view/NewProjectPanel.ts @@ -0,0 +1,260 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +import * as vscode from 'vscode'; +import * as path from 'path'; +import * as fs from 'fs'; +import * as os from 'os'; +import { + createDirectory, + copyFiles, + checkFolderName, +} from '../utilities/directoryUtilities'; +import { getUri } from '../utilities/getUri'; + +export class NewProjectPanel { + public static userSetWorkSpace: string; + public static currentPanel: NewProjectPanel | undefined; + private readonly viewPanel: vscode.WebviewPanel; + private disposableArr: vscode.Disposable[] = []; + + private static readonly executionSuccess = 0; + private static readonly dirExistedError = -1; + private static readonly userInputError = -2; + private static readonly dirPathInvalidError = -3; + + constructor(extensionUri: vscode.Uri, panel: vscode.WebviewPanel) { + this.viewPanel = panel; + this.viewPanel.webview.html = this.getHtmlForWebview( + this.viewPanel.webview, + extensionUri, + 'resource/webview/page/newProject.html' + ); + this._setWebviewMessageListener(this.viewPanel.webview, extensionUri); + this.viewPanel.onDidDispose(this.dispose, null, this.disposableArr); + } + + public static render(context: vscode.ExtensionContext): void { + NewProjectPanel.userSetWorkSpace = vscode.workspace + .getConfiguration() + .get('WAMR-IDE.configWorkspace') as string; + + /* check if current panel is initialized */ + if (NewProjectPanel.currentPanel) { + NewProjectPanel.currentPanel.viewPanel.reveal( + vscode.ViewColumn.One + ); + } else { + const panel = vscode.window.createWebviewPanel( + 'newProject', + 'Create project', + vscode.ViewColumn.One, + { + enableScripts: true, + retainContextWhenHidden: true, + } + ); + + NewProjectPanel.currentPanel = new NewProjectPanel( + context.extensionUri, + panel + ); + } + } + + private createNewProject( + projName: string, + template: string, + extensionUri: vscode.Uri + ): number { + if (projName === '' || template === '') { + return NewProjectPanel.userInputError; + } + + if (!checkFolderName(projName)) { + return NewProjectPanel.dirPathInvalidError; + } + + const ROOT_PATH = path.join(NewProjectPanel.userSetWorkSpace, projName); + const EXT_PATH = extensionUri.fsPath; + + if (fs.existsSync(ROOT_PATH)) { + if (fs.lstatSync(ROOT_PATH).isDirectory()) { + return NewProjectPanel.dirExistedError; + } + } + + createDirectory(path.join(ROOT_PATH, '.wamr')); + createDirectory(path.join(ROOT_PATH, 'include')); + createDirectory(path.join(ROOT_PATH, 'src')); + + copyFiles( + path.join(EXT_PATH, 'resource/scripts/CMakeLists.txt'), + path.join(ROOT_PATH, '.wamr/CMakeLists.txt') + ); + + copyFiles( + path.join(EXT_PATH, 'resource/scripts/project.cmake'), + path.join(ROOT_PATH, '.wamr/project.cmake') + ); + + return NewProjectPanel.executionSuccess; + } + + public getHtmlForWebview( + webview: vscode.Webview, + extensionUri: vscode.Uri, + templatePath: string + ): string { + const toolkitUri = getUri(webview, extensionUri, [ + 'node_modules', + '@vscode', + 'webview-ui-toolkit', + 'dist', + 'toolkit.js', + ]); + + const styleUri = getUri(webview, extensionUri, [ + 'resource', + 'webview', + 'css', + 'style.css', + ]); + + const mainUri = getUri(webview, extensionUri, [ + 'resource', + 'webview', + 'js', + 'newproj.js', + ]); + + const resourcePath = path.join(extensionUri.fsPath, templatePath); + let html = fs.readFileSync(resourcePath, 'utf-8'); + html = html + .replace(/(\${toolkitUri})/, toolkitUri.toString()) + .replace(/(\${mainUri})/, mainUri.toString()) + .replace(/(\${styleUri})/, styleUri.toString()); + + return html; + } + + private _setWebviewMessageListener( + webview: vscode.Webview, + extensionUri: vscode.Uri + ) { + webview.onDidReceiveMessage( + message => { + switch (message.command) { + case 'create_new_project': + const createNewProjectStatus = this.createNewProject( + message.projectName, + message.template, + extensionUri + ); + if ( + createNewProjectStatus === + NewProjectPanel.executionSuccess + ) { + webview.postMessage({ + command: 'proj_creation_finish', + prjName: message.projectName, + }); + } else if ( + createNewProjectStatus === + NewProjectPanel.dirExistedError + ) { + vscode.window.showErrorMessage( + 'Project : ' + + message.projectName + + ' exists in your current root path, please change project name or root path!' + ); + return; + } else if ( + createNewProjectStatus === + NewProjectPanel.userInputError + ) { + vscode.window.showErrorMessage( + 'Please fill chart before your submit!' + ); + return; + } else if ( + createNewProjectStatus === + NewProjectPanel.dirPathInvalidError + ) { + if (os.platform() === 'win32') { + vscode.window.showErrorMessage( + "A file name can't contain any of the following characters: ' / \\ : * ? < > | ' and the length should be less than 255" + ); + } else if ( + os.platform() === 'linux' || + os.platform() === 'darwin' + ) { + vscode.window.showErrorMessage( + "A file name can't contain following characters: '/' and the length should be less than 255" + ); + } + return; + } + return; + + case 'open_project': + vscode.window.showInformationMessage( + 'Project : ' + + message.projectName + + ' will be opened!' + ); + + const projPath = path.join( + NewProjectPanel.userSetWorkSpace, + message.projectName + ); + const uri = vscode.Uri.file(projPath); + + /** + * check if the vscode workspace folder is empty, + * if yes, open new window, else open in current window + */ + const isWorkspaceEmpty = !vscode.workspace + .workspaceFolders?.[0] + ? true + : false; + isWorkspaceEmpty === false + ? vscode.commands.executeCommand( + 'vscode.openFolder', + uri, + { + forceNewWindow: true, + } + ) + : vscode.commands.executeCommand( + 'vscode.openFolder', + uri + ); + + case 'close_webview': + this.viewPanel.dispose(); + return; + + default: + break; + } + }, + undefined, + this.disposableArr + ); + } + + private dispose() { + NewProjectPanel.currentPanel = undefined; + this.viewPanel.dispose(); + + while (this.disposableArr.length) { + const disposable = this.disposableArr.pop(); + if (disposable) { + disposable.dispose(); + } + } + } +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/view/TargetConfigPanel.ts b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/view/TargetConfigPanel.ts new file mode 100644 index 000000000..f2e1343a5 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/src/view/TargetConfigPanel.ts @@ -0,0 +1,238 @@ +/* + * Copyright (C) 2019 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + */ + +import * as vscode from 'vscode'; +import * as path from 'path'; +import * as fs from 'fs'; +import { readFromConfigFile, writeIntoConfigFile } from '../extension'; +import { getUri } from '../utilities/getUri'; + +export class TargetConfigPanel { + public static currentPanel: TargetConfigPanel | undefined; + private readonly viewPanel: vscode.WebviewPanel; + + private _disposables: vscode.Disposable[] = []; + public static buildArgs = { + outputFileName: 'main.wasm', + initMemorySize: '131072', + maxMemorySize: '131072', + stackSize: '4096', + exportedSymbols: 'main', + }; + + private static readonly userInputError: number = -2; + private static readonly executionSuccess: number = 0; + + /** + * + * @param context extension context from extension.ts active func + * @param panelName + */ + constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) { + this.viewPanel = panel; + this.viewPanel.webview.html = this._getHtmlForWebview( + this.viewPanel.webview, + extensionUri, + 'resource/webview/page/configBuildTarget.html' + ); + this.viewPanel.onDidDispose(this.dispose, null, this._disposables); + this._setWebviewMessageListener(this.viewPanel.webview); + } + + /** + * + * @param context + */ + public static render(context: vscode.ExtensionContext): void { + /* check if current panel is initialized */ + if (TargetConfigPanel.currentPanel) { + TargetConfigPanel.currentPanel.viewPanel.reveal( + vscode.ViewColumn.One + ); + } else { + const panel = vscode.window.createWebviewPanel( + 'targetConfig', + 'Config building target', + vscode.ViewColumn.One, + { + enableScripts: true, + retainContextWhenHidden: true, + } + ); + + TargetConfigPanel.currentPanel = new TargetConfigPanel( + panel, + context.extensionUri + ); + } + } + + private configBuildArgs( + outputFileName: string, + initMemSize: string, + maxMemSize: string, + stackSize: string, + exportedSymbols: string + ): number { + if ( + outputFileName === '' || + initMemSize === '' || + maxMemSize === '' || + stackSize === '' || + exportedSymbols === '' + ) { + return TargetConfigPanel.userInputError; + } + + let includePathArr = []; + let excludeFileArr = []; + + const configObj = { + outputFileName: outputFileName, + initMemorySize: initMemSize, + maxMemorySize: maxMemSize, + stackSize: stackSize, + exportedSymbols: exportedSymbols, + }; + const configStr = readFromConfigFile(); + + TargetConfigPanel.buildArgs = configObj; + + if (configStr !== '' && configStr !== undefined) { + const configJson = JSON.parse(configStr); + includePathArr = + configJson['includePaths'] === undefined + ? [] + : configJson['includePaths']; + excludeFileArr = + configJson['excludeFiles'] === undefined + ? [] + : configJson['excludeFiles']; + } + + writeIntoConfigFile( + includePathArr, + excludeFileArr, + TargetConfigPanel.buildArgs + ); + + return TargetConfigPanel.executionSuccess; + } + + private _getHtmlForWebview( + webview: vscode.Webview, + extensionUri: vscode.Uri, + templatePath: string + ) { + /* get toolkit uri */ + const toolkitUri = getUri(webview, extensionUri, [ + 'node_modules', + '@vscode', + 'webview-ui-toolkit', + 'dist', + 'toolkit.js', + ]); + + const styleUri = getUri(webview, extensionUri, [ + 'resource', + 'webview', + 'css', + 'style.css', + ]); + + const mainUri = getUri(webview, extensionUri, [ + 'resource', + 'webview', + 'js', + 'configbuildtarget.js', + ]); + + const resourcePath = path.join(extensionUri.fsPath, templatePath); + let html = fs.readFileSync(resourcePath, 'utf-8'); + html = html + .replace(/(\${toolkitUri})/, toolkitUri.toString()) + .replace(/(\${mainUri})/, mainUri.toString()) + .replace(/(\${styleUri})/, styleUri.toString()) + .replace( + /(\${output_file_val})/, + TargetConfigPanel.buildArgs.outputFileName + ) + .replace( + /(\${initial_mem_size_val})/, + TargetConfigPanel.buildArgs.initMemorySize + ) + .replace( + /(\${max_mem_size_val})/, + TargetConfigPanel.buildArgs.maxMemorySize + ) + .replace( + /(\${stack_size_val})/, + TargetConfigPanel.buildArgs.stackSize + ) + .replace( + /(\${exported_symbols_val})/, + TargetConfigPanel.buildArgs.exportedSymbols + ); + + return html; + } + + private _setWebviewMessageListener(webview: vscode.Webview) { + webview.onDidReceiveMessage( + message => { + switch (message.command) { + case 'config_build_target': + if ( + message.outputFileName === '' || + message.initMemSize === '' || + message.maxMemSize === '' || + message.stackSize === '' || + message.exportedSymbols === '' + ) { + vscode.window.showErrorMessage( + 'Please fill chart before your submit!' + ); + return; + } else if ( + this.configBuildArgs( + message.outputFileName, + message.initMemSize, + message.maxMemSize, + message.stackSize, + message.exportedSymbols + ) === TargetConfigPanel.executionSuccess + ) { + vscode.window + .showInformationMessage( + 'Configurations have been saved!', + 'OK' + ) + .then(() => { + this.viewPanel.dispose(); + return; + }); + } + + default: + break; + } + }, + undefined, + this._disposables + ); + } + + private dispose() { + TargetConfigPanel.currentPanel = undefined; + this.viewPanel.dispose(); + + while (this._disposables.length) { + const disposable = this._disposables.pop(); + if (disposable) { + disposable.dispose(); + } + } + } +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/tsconfig.json b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/tsconfig.json new file mode 100644 index 000000000..c75039eee --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/VSCode-Extension/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "outDir": "out", + "lib": ["es6"], + "sourceMap": true, + "rootDir": "src", + "strict": true /* enable all strict type-checking options */ + /* Additional Checks */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + }, + "exclude": ["node_modules", ".vscode-test"] +} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/Dockerfile b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/Dockerfile new file mode 100644 index 000000000..8165bd5f5 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/Dockerfile @@ -0,0 +1,30 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +FROM gcc:12.2.0 AS BASE + +## set work directory +WORKDIR /root/ +COPY resource /root/ + +# hadolint ignore=DL3008 +RUN apt-get update \ + && apt-get -y install make cmake --no-install-recommends + +## -clone wamr-repo and build iwasm +RUN git clone -b main --depth=1 https://github.com/bytecodealliance/wasm-micro-runtime.git \ + && mkdir -p /root/wasm-micro-runtime/product-mini/platforms/linux/build + +WORKDIR /root/wasm-micro-runtime/product-mini/platforms/linux/build +RUN cmake .. -DWAMR_BUILD_DEBUG_INTERP=1 \ + && make \ + && cp /root/wasm-micro-runtime/product-mini/platforms/linux/build/iwasm /root/iwasm \ + && rm -fr /root/wasm-micro-runtime + +FROM ubuntu:22.04 +# COPY files from BASE image +COPY --from=BASE /root/iwasm /root +COPY --from=BASE /root/debug.sh /root +COPY --from=BASE /root/run.sh /root + +WORKDIR /root/
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/README.md b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/README.md new file mode 100644 index 000000000..b4738e867 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/README.md @@ -0,0 +1,20 @@ +### Build Docker Image + +- Linux + + ```shell + ./build_docker_image.sh + ``` + +- Windows + + ```shell + ./build_docker_image.bat + ``` + + +### Resource Details + +- `Dockerflie` is the source file to build `wasm-debug-server` docker image +- `resource/debug.sh` is the script to execute the wasm app in debug mod, will start up the debugger server inside of the `iwasm` and hold to wait for connecting. +- `resource/run.sh` is the script to execute the wasm app directly. diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/build_docker_image.bat b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/build_docker_image.bat new file mode 100644 index 000000000..2861105bd --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/build_docker_image.bat @@ -0,0 +1,8 @@ +@REM Copyright (C) 2019 Intel Corporation. All rights reserved. +@REM SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +@echo off +docker build -t wasm-debug-server:1.0 . + +@REM delete intermediate docker image +docker image prune -f
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/build_docker_image.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/build_docker_image.sh new file mode 100755 index 000000000..6beedd6df --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/build_docker_image.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +docker build -t wasm-debug-server:1.0 . + +# delete intermediate docker image +docker image prune -f diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/debug.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/debug.sh new file mode 100755 index 000000000..48458870f --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/debug.sh @@ -0,0 +1,6 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#!/bin/bash +TARGET=$1 +./iwasm -g=0.0.0.0:1234 /mnt/build/${TARGET}.wasm
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/run.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/run.sh new file mode 100755 index 000000000..4e3acecba --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Debug-Server/Docker/resource/run.sh @@ -0,0 +1,6 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#!/bin/bash +TARGET=$1 +./iwasm /mnt/build/${TARGET}.wasm
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/.dockerignore b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/.dockerignore new file mode 100644 index 000000000..920e09905 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/.dockerignore @@ -0,0 +1,4 @@ +# remove unnecessary files here to save build time cost and image size +*.md +*.sh +*.bat
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/Dockerfile b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/Dockerfile new file mode 100644 index 000000000..cd8da38d9 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/Dockerfile @@ -0,0 +1,71 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +## Build docker image that consists of gcc, cmake, wasi-sdk & zephyr sdk +FROM gcc:12.2.0 AS BASE + +## set work directory +WORKDIR /root/ + +COPY resource /root/ + +# - download cmake with wget and set up +# hadolint ignore=DL3008 +RUN apt-get update \ + && apt-get -y install ccache ninja-build make cmake python3-pip --no-install-recommends + +# set compilation environment for wamrc +# - wamr repo +# - cmake +# - wasi-sdk +# - wamr-sdk + +# - download wasi-sdk with wget and set up to /opt/wasi-sdk +RUN wget --progress=dot:giga https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-19/wasi-sdk-19.0-linux.tar.gz \ + && tar -zxf wasi-sdk-*-linux.tar.gz \ + && mv wasi-sdk-19.0 /opt/wasi-sdk/ \ + && rm -f wasi-sdk-*-linux.tar.gz + +## - clone wamr repo +RUN git clone -b main --depth=1 https://github.com/bytecodealliance/wasm-micro-runtime.git + +WORKDIR /root/wasm-micro-runtime/build-scripts +RUN pip3 install --no-cache-dir --user -r requirements.txt + +WORKDIR /root/wasm-micro-runtime/wamr-compiler +RUN ./build_llvm.sh \ + && mkdir build + +WORKDIR /root/wasm-micro-runtime/wamr-compiler/build +RUN cmake .. \ + && make \ + # - copy the wamrc to /root + && cp /root/wasm-micro-runtime/wamr-compiler/build/wamrc /root/wamrc \ + && mkdir -p /opt/wamr-sdk \ + && cp -r /root/wasm-micro-runtime/wamr-sdk/app /opt/wamr-sdk/ \ + && mv /root/wamr_toolchain.cmake /opt/wamr-sdk/app \ + # - remove the wamr repo to save the size + && rm -fr /root/wasm-micro-runtime + +# ## STAGE 2 +FROM ubuntu:22.04 +ENV HOME_DIR=/home/wasm-toolchain + +RUN mkdir -p /opt/wasi-sdk \ + && mkdir -p /opt/wamr-sdk/app \ + && mkdir -p /home/wasm-toolchain + +# COPY files from BASE image +COPY --from=BASE /opt/wamr-sdk/app/ /opt/wamr-sdk/app/ +COPY --from=BASE /opt/wasi-sdk /opt/wasi-sdk/ +COPY --from=BASE /root/wamrc ${HOME_DIR} +COPY --from=BASE /root/build_wasm.sh ${HOME_DIR} + +RUN ln -s ${HOME_DIR}/wamrc /usr/bin/wamrc + +# hadolint ignore=DL3008 +RUN apt-get update && apt-get install -y cmake make --no-install-recommends \ + && apt-get clean -y \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR ${HOME_DIR} diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/README.md b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/README.md new file mode 100644 index 000000000..f5ecb957e --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/README.md @@ -0,0 +1,18 @@ +### Build Docker Image + +- Linux + + ```shell + ./build_docker_image.sh + ``` + +- Windows + + ```shell + ./build_docker_image.bat + ``` + +### Resource Details + +- `Dockerflie` is the source file to build `wasm-debug-server` docker image. +- `resource/build_wasm.sh` is the script to compile the wasm app with `wasi-sdk`. diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/build_docker_image.bat b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/build_docker_image.bat new file mode 100644 index 000000000..96fb02879 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/build_docker_image.bat @@ -0,0 +1,9 @@ +@REM Copyright (C) 2019 Intel Corporation. All rights reserved. +@REM SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +@echo off + +docker build -t wasm-toolchain:1.0 . + +@REM delete intermediate docker image +docker image prune -f diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/build_docker_image.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/build_docker_image.sh new file mode 100755 index 000000000..aa1e2f5e4 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/build_docker_image.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +docker build -t wasm-toolchain:1.0 . + +# delete intermediate docker image +docker image prune -f diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/resource/build_wasm.sh b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/resource/build_wasm.sh new file mode 100755 index 000000000..3d8c06c4d --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/resource/build_wasm.sh @@ -0,0 +1,25 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#!/bin/bash +export CC=/opt/wasi-sdk/bin/clang +export CXX=/opt/wasi-sdk/bin/clang++ + +cd /mnt +if [ -d build ];then + rm -fr build +fi + +mkdir -p build && cd build +echo "========> compile wasm with wasi-sdk" +cmake -DWASI_SDK_DIR=/opt/wasi-sdk -DCMAKE_TOOLCHAIN_FILE=/opt/wamr-sdk/app/wamr_toolchain.cmake ../.wamr && make + +if [ $? -eq 0 ]; then + echo "========> compile wasm to AoT with wamrc" + # target name will be provided: + # - user input the target name in IDE + # - generated wasm binary name will be set as user's input target name + # - aot binary name should be the same as wasm binary name + # - target name will be provided through 1st parameter + wamrc -o $1.aot $1.wasm +fi
\ No newline at end of file diff --git a/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/resource/wamr_toolchain.cmake b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/resource/wamr_toolchain.cmake new file mode 100755 index 000000000..97b82cc90 --- /dev/null +++ b/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/test-tools/wamr-ide/WASM-Toolchain/Docker/resource/wamr_toolchain.cmake @@ -0,0 +1,33 @@ +# Copyright (C) 2019 Intel Corporation. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +SET (CMAKE_SYSTEM_NAME Linux) +SET (CMAKE_SYSTEM_PROCESSOR wasm32) +SET (CMAKE_SYSROOT ${CMAKE_CURRENT_LIST_DIR}/libc-builtin-sysroot) + +IF (NOT (DEFINED WASI_SDK_DIR OR DEFINED CACHE{WASI_SDK_DIR})) + SET (WASI_SDK_DIR "/opt/wasi-sdk") +ELSE () + MESSAGE (STATUS "WASI_SDK_DIR=${WASI_SDK_DIR}") + LIST (APPEND CMAKE_TRY_COMPILE_PLATFORM_VARIABLES "WASI_SDK_DIR") +ENDIF () + + +SET (CMAKE_C_FLAGS "-nostdlib" CACHE INTERNAL "") +SET (CMAKE_C_COMPILER_TARGET "wasm32") +SET (CMAKE_C_COMPILER "${WASI_SDK_DIR}/bin/clang") + +SET (CMAKE_CXX_FLAGS "-nostdlib" CACHE INTERNAL "") +SET (CMAKE_CXX_COMPILER_TARGET "wasm32") +SET (CMAKE_CXX_COMPILER "${WASI_SDK_DIR}/bin/clang++") + +SET (CMAKE_EXE_LINKER_FLAGS + "-Wl,--no-entry,--fatal-warnings" CACHE INTERNAL "") + +SET (CMAKE_LINKER "${WASI_SDK_DIR}/bin/wasm-ld" CACHE INTERNAL "") +SET (CMAKE_AR "${WASI_SDK_DIR}/bin/llvm-ar" CACHE INTERNAL "") +SET (CMAKE_NM "${WASI_SDK_DIR}/bin/llvm-nm" CACHE INTERNAL "") +SET (CMAKE_OBJDUMP "${WASI_SDK_DIR}/bin/llvm-dwarfdump" CACHE INTERNAL "") +SET (CMAKE_RANLIB "${WASI_SDK_DIR}/bin/llvm-ranlib" CACHE INTERNAL "") +SET (CMAKE_EXE_LINKER_FLAGS + "${CMAKE_EXE_LINKER_FLAGS},--allow-undefined-file=${CMAKE_SYSROOT}/share/defined-symbols.txt" CACHE INTERNAL "")
\ No newline at end of file |