├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CONTRIBUTING.md ├── Cargo.lock ├── Cargo.toml ├── Dockerfile ├── LICENSE ├── README.md ├── build.rs ├── build.sh ├── sp-wasm-engine ├── Cargo.toml ├── LICENSE ├── README.md └── src │ ├── error.rs │ ├── lib.rs │ └── sandbox │ ├── engine.rs │ ├── mod.rs │ └── vfs.rs ├── sp-wasm-memfs ├── Cargo.toml ├── LICENSE ├── README.md └── src │ ├── error.rs │ ├── file.rs │ ├── lib.rs │ ├── memfs.rs │ └── node.rs ├── src └── main.rs └── tests ├── assets ├── aaa.txt ├── bbb.txt ├── gettimeofday.c ├── gettimeofday.js ├── gettimeofday.wasm ├── test.js └── test.wasm ├── common.rs ├── date_test.rs ├── gettimeofday_test.rs ├── random_device_determinism_test.rs ├── random_device_emulation_test.rs ├── sandbox_test.rs ├── vfs_js_security_test.rs └── vfs_test.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Continuous Integration 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | tags: 8 | - v* 9 | pull_request: 10 | branches: 11 | - master 12 | 13 | jobs: 14 | build_debug: 15 | name: Build debug 16 | runs-on: ${{ matrix.os }}-latest 17 | strategy: 18 | fail-fast: false 19 | matrix: 20 | os: [ubuntu, macOS] 21 | 22 | steps: 23 | - name: Checkout 24 | uses: actions/checkout@v1 25 | - name: Install Rust 26 | uses: actions-rs/toolchain@v1 27 | with: 28 | profile: minimal 29 | toolchain: 1.38.0 30 | override: true 31 | components: rustfmt 32 | - name: Install preqrequisites (ubuntu) 33 | if: matrix.os == 'ubuntu' 34 | run: | 35 | sudo apt-get install -y --no-install-recommends autoconf2.13 36 | - name: Install preqrequisites (macOS) 37 | if: matrix.os == 'macOS' 38 | run: | 39 | brew install yasm autoconf@2.13 40 | - name: Check formatting 41 | uses: actions-rs/cargo@v1 42 | with: 43 | command: fmt 44 | args: --all -- --check 45 | - name: Build 46 | env: 47 | SHELL: ${{ '/bin/bash' }} 48 | uses: actions-rs/cargo@v1 49 | with: 50 | command: build 51 | 52 | build_release: 53 | name: Build release 54 | needs: [build_debug, test] 55 | runs-on: ${{ matrix.os }}-latest 56 | strategy: 57 | matrix: 58 | os: [ubuntu, macOS] 59 | 60 | steps: 61 | - name: Checkout 62 | uses: actions/checkout@v1 63 | - name: Install Rust 64 | uses: actions-rs/toolchain@v1 65 | with: 66 | profile: minimal 67 | toolchain: 1.38.0 68 | override: true 69 | - name: Install preqrequisites (ubuntu) 70 | if: matrix.os == 'ubuntu' 71 | run: | 72 | sudo apt-get install -y --no-install-recommends autoconf2.13 73 | - name: Install preqrequisites (macOS) 74 | if: matrix.os == 'macOS' 75 | run: | 76 | brew install yasm autoconf@2.13 77 | - name: Build 78 | env: 79 | SHELL: ${{ '/bin/bash' }} 80 | uses: actions-rs/cargo@v1 81 | with: 82 | command: build 83 | args: --release 84 | - name: Prepare archive 85 | run: | 86 | tar -czvf sp-wasm.tar.gz target/release/wasm-sandbox 87 | - name: Upload asset 88 | uses: actions/upload-artifact@v1 89 | with: 90 | name: ${{ matrix.os }}-asset 91 | path: sp-wasm.tar.gz 92 | 93 | test: 94 | name: Test 95 | runs-on: ${{ matrix.os }}-latest 96 | strategy: 97 | fail-fast: false 98 | matrix: 99 | os: [ubuntu, macOS] 100 | 101 | steps: 102 | - name: Checkout 103 | uses: actions/checkout@v1 104 | - name: Install Rust 105 | uses: actions-rs/toolchain@v1 106 | with: 107 | profile: minimal 108 | toolchain: 1.38.0 109 | override: true 110 | - name: Install preqrequisites (ubuntu) 111 | if: matrix.os == 'ubuntu' 112 | run: | 113 | sudo apt-get install -y --no-install-recommends autoconf2.13 114 | - name: Install preqrequisites (macOS) 115 | if: matrix.os == 'macOS' 116 | run: | 117 | brew install yasm autoconf@2.13 118 | - name: Run tests 119 | env: 120 | SHELL: ${{ '/bin/bash' }} 121 | uses: actions-rs/cargo@v1 122 | with: 123 | command: test 124 | args: --all 125 | 126 | publish: 127 | name: Publish release 128 | needs: [build_release] 129 | if: startsWith(github.ref, 'refs/tags/v') 130 | runs-on: macOS-latest 131 | 132 | steps: 133 | - name: Prepare tag 134 | id: tag_name 135 | uses: olegtarasov/get-tag@v1 136 | with: 137 | tagname: ${{ steps.tag_name.outputs.tag }} 138 | - name: Create release 139 | id: create_release 140 | uses: actions/create-release@v1.0.0 141 | env: 142 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 143 | with: 144 | tag_name: ${{ steps.tag_name.outputs.tag }} 145 | release_name: sp-wasm-${{ steps.tag_name.outputs.tag }} 146 | draft: true 147 | prerelease: false 148 | - name: Download asset (linux) 149 | uses: actions/download-artifact@v1 150 | with: 151 | name: ubuntu-asset 152 | - name: Download asset (macOS) 153 | uses: actions/download-artifact@v1 154 | with: 155 | name: macOS-asset 156 | - name: Upload artifact (linux) 157 | uses: actions/upload-release-asset@v1.0.1 158 | env: 159 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 160 | with: 161 | upload_url: ${{ steps.create_release.outputs.upload_url }} 162 | asset_path: ubuntu-asset/sp-wasm.tar.gz 163 | asset_name: sp-wasm-${{ steps.tag_name.outputs.tag }}-linux.tar.gz 164 | asset_content_type: application/gzip 165 | - name: Upload artifact (macOS) 166 | uses: actions/upload-release-asset@v1.0.1 167 | env: 168 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 169 | with: 170 | upload_url: ${{ steps.create_release.outputs.upload_url }} 171 | asset_path: macOS-asset/sp-wasm.tar.gz 172 | asset_name: sp-wasm-${{ steps.tag_name.outputs.tag }}-macos.tar.gz 173 | asset_content_type: application/gzip 174 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | .DS_Store -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to sp-wasm 2 | We welcome all issues and pull requests! 3 | 4 | When submitting a pull request, please make sure to run unit tests: 5 | 6 | ``` 7 | $ cargo test 8 | ``` 9 | 10 | and integration tests: 11 | 12 | ``` 13 | $ cargo build && ./target/debug/sp-wasm-tests 14 | ``` -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sp-wasm" 3 | version = "0.5.1" 4 | authors = ["Jakub Konka "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | sp-wasm-engine = { path = "sp-wasm-engine", version = "0.4.0" } 9 | serde = { version = "1", features = ["derive"] } 10 | env_logger = "0.6" 11 | log = "0.4" 12 | structopt = "0.3" 13 | 14 | [dev-dependencies] 15 | tempfile = "3" 16 | 17 | [features] 18 | debugmozjs = ["sp-wasm-engine/debugmozjs"] 19 | 20 | [[bin]] 21 | name = "wasm-sandbox" 22 | path = "src/main.rs" 23 | 24 | [workspace] 25 | members = [ 26 | 'sp-wasm-engine', 27 | 'sp-wasm-memfs' 28 | ] 29 | 30 | [profile.release] 31 | lto = true 32 | 33 | [build-dependencies] 34 | version_check = "0.9.1" 35 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM rust:1.38 2 | 3 | RUN echo "deb http://deb.debian.org/debian stretch-backports main" >> /etc/apt/sources.list 4 | RUN apt -y update && apt -y install autoconf2.13 clang-6.0 --no-install-recommends && rm -rf /var/lib/apt/lists/* 5 | 6 | WORKDIR /sp-wasm 7 | COPY . . 8 | ENV SHELL=/bin/bash 9 | ENV CC=clang-6.0 10 | ENV CPP="clang-6.0 -E" 11 | ENV CXX=clang++-6.0 12 | RUN cargo install --path . 13 | RUN cargo clean 14 | 15 | ENTRYPOINT ["wasm-sandbox"] 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpiderMonkey-based WebAssembly Sandbox 2 | [![Build Status]][build] 3 | 4 | [Build Status]: https://github.com/golemfactory/sp-wasm/workflows/Continuous%20Integration/badge.svg 5 | [build]: https://github.com/golemfactory/sp-wasm/actions 6 | 7 | A WebAssembly sandbox using standalone SpiderMonkey engine. For `v8` version, 8 | see [golemfactory/v8-wasm](https://github.com/golemfactory/v8-wasm). 9 | 10 | This WebAssembly sandbox is used in current development version of 11 | Golem: [golem/apps/wasm](https://github.com/golemfactory/golem/tree/develop/apps/wasm). 12 | If you would like to launch a gWASM task in Golem, see 13 | [here](https://docs.golem.network/#/About/Use-Cases?id=wasm). 14 | 15 | - [SpiderMonkey-based WebAssembly Sandbox](#spidermonkey-based-webassembly-sandbox) 16 | - [Quick start guide](#quick-start-guide) 17 | - [1. Create and cross-compile simple program](#1-create-and-cross-compile-simple-program) 18 | - [1.1 C/C++](#11-cc) 19 | - [1.2 Rust](#12-rust) 20 | - [2. Create input and output dirs and files](#2-create-input-and-output-dirs-and-files) 21 | - [3. Run!](#3-run) 22 | - [Build instructions](#build-instructions) 23 | - [Using Docker (recommended)](#using-docker-recommended) 24 | - [Natively on Linux](#natively-on-linux) 25 | - [Natively on other OSes](#natively-on-other-oses) 26 | - [CLI arguments explained](#cli-arguments-explained) 27 | - [Caveats](#caveats) 28 | - [Wasm store](#wasm-store) 29 | - [Contributing](#contributing) 30 | - [License](#license) 31 | 32 | ## Quick start guide 33 | This guide assumes you have successfully built the `wasm-sandbox` binary; for build instructions, see section 34 | [Build instructions](#build-instructions) below. If you are running Linux, then you can also use the prebuilt 35 | binaries from [here](https://github.com/golemfactory/sp-wasm/releases). 36 | 37 | ### 1. Create and cross-compile simple program 38 | Let us create a simple `hello world` style program which will read in 39 | some text from `in.txt` text file, read your name from the command line, 40 | and save the resultant text in `out.txt`. We'll demonstrate how to 41 | cross-compile apps to Wasm for use in Golem in two languages of choice: 42 | C and Rust. 43 | 44 | #### 1.1 C/C++ 45 | ```c 46 | #include 47 | 48 | int main(int argc, char** argv) { 49 | char* name = argc >= 2 ? argv[1] : "anonymous"; 50 | size_t len = 0; 51 | char* line = NULL; 52 | ssize_t read; 53 | 54 | FILE* f_in = fopen("in.txt", "r"); 55 | FILE* f_out = fopen("out.txt", "w"); 56 | 57 | while ((read = getline(&line, &len, f_in)) != -1) 58 | fprintf(f_out, "%s\n", line); 59 | 60 | fprintf(f_out, "%s\n", name); 61 | 62 | fclose(f_out); 63 | fclose(f_in); 64 | 65 | return 0; 66 | } 67 | ``` 68 | 69 | There is one important thing to notice here. The sandbox communicates 70 | the results of computation by reading and writing to files. Thus, every 71 | Wasm program is required to at the very least create an output file. 72 | If your code does not include file manipulation in its main body, 73 | then the Emscripten compiler, by default, will not initialise 74 | JavaScript `FS` library, and will trip the sandbox. This will also be true 75 | for programs cross-compiled [from Rust](#12-rust). 76 | 77 | Now, we can try and compile the program with Emscripten. 78 | In order to do that you need Emscripten SDK installed on your 79 | system. For instructions on how to do it, see 80 | [here](https://emscripten.org/docs/getting_started/downloads.html). 81 | 82 | ``` 83 | $ emcc -o simple.js simple.c 84 | ``` 85 | 86 | Emscripten will then produce two files: `simple.js` and `simple.wasm`. 87 | The produced JavaScript file acts as glue code and sets up all of 88 | the rudimentary syscalls in JavaScript such as `MemFS` (in-memory 89 | filesystem), etc., while the `simple.wasm` is our C program 90 | cross-compiled to Wasm. 91 | 92 | #### 1.2 Rust 93 | With Rust, firstly go ahead and create a new binary with `cargo` 94 | ``` 95 | $ cargo new --bin simple 96 | ``` 97 | 98 | Then go ahead and paste the following to `simple/src/main.rs` 99 | file 100 | ```rust 101 | use std::env; 102 | use std::fs; 103 | use std::io::{self, Read, Write}; 104 | 105 | fn main() -> io::Result<()> { 106 | let args = env::args().collect::>(); 107 | let name = args.get(1).map_or("anonymous".to_owned(), |x| x.clone()); 108 | 109 | let mut in_file = fs::File::open("in.txt")?; 110 | let mut contents = String::new(); 111 | in_file.read_to_string(&mut contents)?; 112 | 113 | let mut out_file = fs::File::create("out.txt")?; 114 | out_file.write_all(&contents.as_bytes())?; 115 | out_file.write_all(&name.as_bytes())?; 116 | 117 | Ok(()) 118 | } 119 | ``` 120 | 121 | As was the case with [C program](#11-c/c++), it is important to notice 122 | here that the sandbox communicates 123 | the results of computation by reading and writing to files. Thus, every 124 | Wasm program is required to at the very least create an output file. 125 | If your code does not include file manipulation in its main body, 126 | then the Emscripten compiler, by default, will not initialise 127 | JavaScript `FS` library, and will trip the sandbox. 128 | 129 | In order to cross-compile Rust to Wasm compatible with Golem's 130 | sandbox, firstly we need to install rustc 1.38.0 toolchain which 131 | includes fastcomp backend for `wasm32-unknown-emscripten` target 132 | 133 | ``` 134 | $ rustup toolchain add 1.38.0 135 | ``` 136 | 137 | Then, we need to install the required target which 138 | is `wasm32-unknown-emscripten`. The easiest way of doing so, as well 139 | as generally managing your Rust installations, is to use 140 | [rustup](https://rustup.rs/) 141 | ``` 142 | $ rustup target add wasm32-unknown-emscripten --toolchain 1.38.0 143 | ``` 144 | 145 | Note that cross-compiling Rust to this target still requires that you 146 | have Emscripten SDK installed on your 147 | system. For instructions on how to do it, see 148 | [here](https://emscripten.org/docs/getting_started/downloads.html). 149 | 150 | Now, we can compile our Rust program to Wasm. Make sure you are in 151 | the root of your Rust crate, i.e., at the top of `simple` 152 | if you didn't change the name of your crate, and run 153 | ``` 154 | $ cargo +1.38.0 build --target=wasm32-unknown-emscripten --release 155 | ``` 156 | 157 | If everything went OK, you should now see two files: 158 | `simple.js` and `simple.wasm` in `simple/target/wasm32-unknown-emscripten/release`. 159 | Just like in [C program](#11-cc++)'s case, the produced JavaScript 160 | file acts as glue code and sets up all of 161 | the rudimentary syscalls in JavaScript such as `MemFS` (in-memory 162 | filesystem), etc., while the `simple.wasm` is our Rust program 163 | cross-compiled to Wasm. 164 | 165 | ### 2. Create input and output dirs and files 166 | The sandbox will require us to specify input and output paths together 167 | with output filenames to create, and any additional arguments (see 168 | [CLI arguments explained](#cli-arguments-explained) section below 169 | for detailed specification 170 | of the required arguments). Suppose we have the following file 171 | structure locally 172 | 173 | ``` 174 | |-- in/ 175 | | | 176 | | |-- in.txt 177 | | 178 | |-- out/ 179 | ``` 180 | 181 | Paste the following text in the `in.txt` file 182 | 183 | ``` 184 | // in.txt 185 | You are running Wasm! 186 | ``` 187 | 188 | ### 3. Run! 189 | After you have successfully run all of the above steps up to now, you should have the following file structure locally 190 | 191 | ``` 192 | |-- simple.js 193 | |-- simple.wasm 194 | | 195 | |-- in/ 196 | | | 197 | | |-- in.txt 198 | | 199 | |-- out/ 200 | ``` 201 | 202 | We can now run our Wasm binary inside the sandbox 203 | 204 | 1. using Docker (if you've followed [Using Docker (recommended)](#using-docker-recommended) 205 | build instructions) 206 | 207 | ``` 208 | docker run --mount type=bind,source=$PWD,target=/workdir --workdir /workdir \ 209 | wasm-sandbox:latest -I in/ -O out/ -j simple.js -w simple.wasm \ 210 | -o out.txt -- "" 211 | ``` 212 | 213 | 2. natively (if you're using the prebuilt binaries, or you've built natively following 214 | [Natively on Linux](#natively-on-linux) build instructions) 215 | 216 | ``` 217 | $ wasm-sandbox -I in/ -O out/ -j simple.js -w simple.wasm \ 218 | -o out.txt -- "" 219 | ``` 220 | 221 | Here, `-I` maps the input dir with *all* its contents (files and 222 | subdirs) directly to the root `/` in `MemFS`. The output files, 223 | on the other hand, will be saved in `out/` local dir. The names of 224 | the expected output files have to match those specified with `-o` 225 | flags. Thus, in this case, our Wasm bin is expected to create an 226 | output file `/out.txt` in `MemFS` which will then be saved in 227 | `out/out.txt` locally. 228 | 229 | After you execute Wasm bin in the sandbox, `out.txt` should be 230 | created in `out/` dir 231 | 232 | ``` 233 | |-- simple.js 234 | |-- simple.wasm 235 | | 236 | |-- in/ 237 | | | 238 | | |-- in.txt 239 | | 240 | |-- out/ 241 | | | 242 | | |-- out.txt 243 | ``` 244 | 245 | with the contents similar to the following 246 | 247 | ``` 248 | // out.txt 249 | You are running Wasm! 250 | 251 | ``` 252 | 253 | ## Build instructions 254 | ### Using Docker (recommended) 255 | To build using Docker, simply run 256 | 257 | ``` 258 | $ ./build.sh 259 | ``` 260 | 261 | If you are running Windows, then you can invoke the command in the shell script manually 262 | in the command line as follows 263 | 264 | ``` 265 | docker build -t wasm-sandbox:latest . 266 | ``` 267 | 268 | ### Natively on Linux 269 | **NOTE: Building the sandbox from source requires rustc 1.38.0 due to fastcomp backend 270 | compability for `wasm32-unknown-emscripten` target, and other changes that are 271 | incompatible with SpiderMonkey Rust wrappers.** 272 | 273 | To build natively on Linux, first install rustc `1.38.0` toolchain 274 | 275 | ``` 276 | $ rustup toolchain add 1.38.0 277 | ``` 278 | 279 | Next, you need to follow the installation instructions of 280 | [servo/rust-mozjs](https://github.com/servo/rust-mozjs) and 281 | [servo/mozjs](https://github.com/servo/mozjs). The latter is Mozilla's Servo's SpiderMonkey fork and low-level 282 | Rust bindings, and as such, requires C/C++ compiler and Autoconf 2.13. See [servo/mozjs/README.md](https://github.com/servo/mozjs) 283 | for detailed building instructions. 284 | 285 | After following the aforementioned instructions, to build the sandbox, run 286 | 287 | ``` 288 | $ cargo +1.38.0 build --release 289 | ``` 290 | 291 | If you would like to build with SpiderMonkey's debug symbols and extensive logging, run instead 292 | 293 | ``` 294 | $ cargo +1.38.0 build --release --features "debugmozjs" 295 | ``` 296 | 297 | ### Natively on other OSes 298 | We currently do not offer any support for building the sandbox natively on other OSes. 299 | 300 | ## CLI arguments explained 301 | ``` 302 | wasm-sandbox -I -O -j -w -o ... -- ... 303 | ``` 304 | 305 | where 306 | * `-I` path to the input dir 307 | * `-O` path to the output dir 308 | * `-j` path to the Emscripten JS glue script 309 | * `-w` path to the Emscripten WASM binary 310 | * `-o` paths to expected output files 311 | * `--` anything after this will be passed to the WASM binary as arguments 312 | 313 | By default, basic logging is enabled. If you would like to enable more comprehensive logging, export 314 | the following variable 315 | 316 | ``` 317 | RUST_LOG=debug 318 | ``` 319 | 320 | ## Caveats 321 | * Building the sandbox from source requires rustc 1.38.0 due to fastcomp backend 322 | compability for `wasm32-unknown-emscripten` target, and other changes that are 323 | incompatible with SpiderMonkey Rust wrappers. 324 | * Sometimes, if the binary you are cross-compiling is of substantial 325 | size, you might encounter a `asm2wasm` validation error stating 326 | that there is not enough memory assigned to Wasm. In this case, 327 | you can circumvent the problem by adding `-s TOTAL_MEMORY=value` 328 | flag. The value has to be an integer multiple of 1 Wasm memory page 329 | which is currently set at `65,536` bytes. 330 | * When running your Wasm binary you encounter an `OOM` error at 331 | runtime, it usually means that the sandbox has run out-of-memory. 332 | To alleviate the problem, recompile your program with 333 | `-s ALLOW_MEMORY_GROWTH=1`. 334 | * Emscripten, by default, doesn't support `/dev/(u)random` emulation 335 | targets different than either browser or `nodejs`. Therefore, we 336 | have added basic emulation of the random device that is *fully* 337 | deterministic. For details, see [#5](https://github.com/golemfactory/sp-wasm/pull/5). 338 | 339 | ## Wasm store 340 | More examples of precompiled Wasm binaries can be found in [golemfactory/wasm-store](https://github.com/golemfactory/wasm-store) repo. 341 | 342 | ## Contributing 343 | All contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for pointers. 344 | 345 | ## License 346 | Licensed under [GNU General Public License v3.0](LICENSE). 347 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use version_check; 2 | 3 | fn main() { 4 | match version_check::is_max_version("1.38.0") { 5 | None => println!("cargo:warning=sp-wasm: error querying Rust version"), 6 | Some(false) => panic!("sp-wasm: only Rust <= 1.38.0 is supported, build aborted"), 7 | Some(true) => {} 8 | }; 9 | } 10 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | set -e 3 | docker build -t wasm-sandbox:latest . -------------------------------------------------------------------------------- /sp-wasm-engine/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sp-wasm-engine" 3 | version = "0.4.0" 4 | authors = ["Jakub Konka "] 5 | edition = "2018" 6 | license = "GPL-3.0" 7 | readme = "README.md" 8 | repository = "https://github.com/golemfactory/sp-wasm" 9 | homepage = "https://github.com/golemfactory/sp-wasm" 10 | documentation = "https://docs.rs/sp-wasm-engine" 11 | description = "Runtime/engine of Golem's sp-wasm sandbox" 12 | 13 | [dependencies] 14 | sp-wasm-memfs = { path = "../sp-wasm-memfs", version = "0.2.0" } 15 | libc = "0.2" 16 | mozjs = "0.10" 17 | log = "0.4" 18 | lazy_static = "1.3" 19 | itertools = "0.8" 20 | path-clean = "0.1" 21 | thiserror = "1" 22 | 23 | [features] 24 | debugmozjs = ["mozjs/debugmozjs"] 25 | -------------------------------------------------------------------------------- /sp-wasm-engine/LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /sp-wasm-engine/README.md: -------------------------------------------------------------------------------- 1 | # sp-wasm-engine 2 | 3 | Runtime/engine of Golem's sp-wasm sandbox 4 | -------------------------------------------------------------------------------- /sp-wasm-engine/src/error.rs: -------------------------------------------------------------------------------- 1 | use super::sandbox::engine::error::Error as EngineError; 2 | use sp_wasm_memfs::error::Error as MemFSError; 3 | use std::io::Error as IoError; 4 | use std::path::{Path, PathBuf, StripPrefixError}; 5 | use std::string::FromUtf8Error; 6 | 7 | #[derive(Debug, thiserror::Error)] 8 | pub enum Error { 9 | #[error("invalid path: {0}")] 10 | InvalidPath(String), 11 | #[error("{1}: {0}")] 12 | FileError(IoError, PathBuf), 13 | #[error("{0}")] 14 | StripPrefix(#[from] StripPrefixError), 15 | #[error("{0}")] 16 | FromUtf8(#[from] FromUtf8Error), 17 | #[error("{0}")] 18 | MemFS(#[from] MemFSError), 19 | #[error("{0}")] 20 | Io(#[from] IoError), 21 | #[error("{0}")] 22 | Engine(#[from] EngineError), 23 | } 24 | 25 | pub type Result = std::result::Result; 26 | 27 | pub(crate) trait FileContext { 28 | fn file_context(self, path: P) -> Result; 29 | } 30 | 31 | impl> FileContext for std::io::Result { 32 | fn file_context(self, path: P) -> Result { 33 | self.map_err(|e| Error::FileError(e, path.as_ref().to_owned())) 34 | } 35 | } 36 | 37 | impl PartialEq for Error { 38 | fn eq(&self, other: &Error) -> bool { 39 | match (self, other) { 40 | (&Error::InvalidPath(ref p_left), &Error::InvalidPath(ref p_right)) => { 41 | p_left == p_right 42 | } 43 | (&Error::StripPrefix(ref left), &Error::StripPrefix(ref right)) => left == right, 44 | (&Error::FromUtf8(ref left), &Error::FromUtf8(ref right)) => { 45 | left.utf8_error() == right.utf8_error() 46 | } 47 | (&Error::MemFS(ref left), &Error::MemFS(ref right)) => left == right, 48 | (&Error::Io(ref left), &Error::Io(ref right)) => left.kind() == right.kind(), 49 | (&Error::Engine(ref left), &Error::Engine(ref right)) => left == right, 50 | (_, _) => false, 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /sp-wasm-engine/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate mozjs; 3 | 4 | pub mod error; 5 | pub mod sandbox; 6 | 7 | pub use error::{Error, Result}; 8 | 9 | pub mod prelude { 10 | pub use super::sandbox::engine::{Engine, Runtime}; 11 | pub use super::sandbox::vfs::VirtualFS; 12 | pub use super::sandbox::Sandbox; 13 | } 14 | -------------------------------------------------------------------------------- /sp-wasm-engine/src/sandbox/engine.rs: -------------------------------------------------------------------------------- 1 | use super::VFS; 2 | use crate::Result; 3 | use mozjs::{ 4 | glue::SetBuildId, 5 | jsapi::{ 6 | BuildIdCharVector, CallArgs, CompartmentOptions, ContextOptionsRef, InitSelfHostedCode, 7 | JSAutoCompartment, JSContext, JSGCParamKey, JSObject, JSString, JS_BeginRequest, 8 | JS_DefineFunction, JS_DestroyContext, JS_EncodeStringToUTF8, JS_EndRequest, JS_NewContext, 9 | JS_NewGlobalObject, JS_ReportErrorASCII, JS_SetGCParameter, JS_SetNativeStackQuota, 10 | OnNewGlobalHookOption, RunJobs, SetBuildIdOp, UseInternalJobQueues, Value, JS, 11 | }, 12 | jsval::{ObjectValue, UndefinedValue}, 13 | panic::maybe_resume_unwind, 14 | rust::{ 15 | CompileOptionsWrapper, Handle, HandleObject, JSEngine, MutableHandleValue, ToString, 16 | ToUint64, SIMPLE_GLOBAL_CLASS, 17 | }, 18 | typedarray::{ArrayBuffer, CreateWith}, 19 | }; 20 | use std::{ 21 | ffi, 22 | ops::Deref, 23 | os::raw::c_uint, 24 | ptr::{self, NonNull}, 25 | sync::Arc, 26 | }; 27 | 28 | const STACK_QUOTA: usize = 128 * 8 * 1024; 29 | const SYSTEM_CODE_BUFFER: usize = 10 * 1024; 30 | const TRUSTED_SCRIPT_BUFFER: usize = 8 * 12800; 31 | 32 | unsafe fn new_root_context() -> Result> { 33 | let ctx = match NonNull::new(JS_NewContext( 34 | 32_u32 * 1024_u32 * 1024_u32, 35 | 1 << 20 as u32, 36 | ptr::null_mut(), 37 | )) { 38 | Some(ctx) => ctx, 39 | None => return Err(error::Error::SMNullPtr.into()), 40 | }; 41 | let ctx_ptr = ctx.as_ptr(); 42 | 43 | JS_SetGCParameter(ctx_ptr, JSGCParamKey::JSGC_MAX_BYTES, std::u32::MAX); 44 | JS_SetNativeStackQuota( 45 | ctx_ptr, 46 | STACK_QUOTA, 47 | STACK_QUOTA - SYSTEM_CODE_BUFFER, 48 | STACK_QUOTA - SYSTEM_CODE_BUFFER - TRUSTED_SCRIPT_BUFFER, 49 | ); 50 | UseInternalJobQueues(ctx_ptr, false); 51 | InitSelfHostedCode(ctx_ptr); 52 | let contextopts = ContextOptionsRef(ctx_ptr); 53 | (*contextopts).set_baseline_(true); 54 | (*contextopts).set_ion_(true); 55 | (*contextopts).set_nativeRegExp_(true); 56 | (*contextopts).set_wasm_(true); 57 | (*contextopts).set_wasmBaseline_(true); 58 | (*contextopts).set_wasmIon_(true); 59 | JS_BeginRequest(ctx_ptr); 60 | 61 | Ok(ctx) 62 | } 63 | 64 | pub fn evaluate_script( 65 | ctx: NonNull, 66 | glob: HandleObject, 67 | script: &str, 68 | filename: &str, 69 | line_num: u32, 70 | rval: MutableHandleValue, 71 | ) -> Option<()> { 72 | let script_utf16: Vec = script.encode_utf16().collect(); 73 | let filename_cstr = ffi::CString::new(filename.as_bytes()).unwrap(); 74 | log::debug!( 75 | "Evaluating script from {} with content {}", 76 | filename, 77 | script 78 | ); 79 | // SpiderMonkey does not approve of null pointers. 80 | let (ptr, len) = if script_utf16.len() == 0 { 81 | static EMPTY: &'static [u16] = &[]; 82 | (EMPTY.as_ptr(), 0) 83 | } else { 84 | (script_utf16.as_ptr(), script_utf16.len() as c_uint) 85 | }; 86 | assert!(!ptr.is_null()); 87 | 88 | let ctx = ctx.as_ptr(); 89 | let _ac = JSAutoCompartment::new(ctx, glob.get()); 90 | let options = CompileOptionsWrapper::new(ctx, filename_cstr.as_ptr(), line_num); 91 | 92 | unsafe { 93 | if !JS::Evaluate2( 94 | ctx, 95 | options.ptr, 96 | ptr as *const u16, 97 | len as libc::size_t, 98 | rval.into(), 99 | ) { 100 | log::debug!("...err!"); 101 | maybe_resume_unwind(); 102 | None 103 | } else { 104 | // we could return the script result but then we'd have 105 | // to root it and so forth and, really, who cares? 106 | log::debug!("...ok!"); 107 | Some(()) 108 | } 109 | } 110 | } 111 | 112 | #[derive(Clone)] 113 | pub struct Engine(Arc); 114 | 115 | impl Engine { 116 | pub fn new() -> Result { 117 | log::info!("Initializing SpiderMonkey engine"); 118 | let engine = JSEngine::init().map_err(error::Error::from)?; 119 | Ok(Self(engine)) 120 | } 121 | } 122 | 123 | impl Deref for Engine { 124 | type Target = Arc; 125 | 126 | fn deref(&self) -> &Self::Target { 127 | &self.0 128 | } 129 | } 130 | 131 | pub struct Runtime { 132 | ctx: NonNull, 133 | global: NonNull, 134 | } 135 | 136 | impl Drop for Runtime { 137 | fn drop(&mut self) { 138 | let ctx = self.ctx.as_ptr(); 139 | unsafe { 140 | JS_EndRequest(ctx); 141 | JS_DestroyContext(ctx); 142 | } 143 | } 144 | } 145 | 146 | impl Runtime { 147 | pub fn new(_engine: &Engine) -> Result { 148 | log::info!("Creating new Runtime instance"); 149 | unsafe { 150 | let ctx = new_root_context()?; 151 | let rt = Self::create_with(ctx)?; 152 | Ok(rt) 153 | } 154 | } 155 | 156 | unsafe fn create_with(ctx: NonNull) -> Result { 157 | let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook; 158 | let c_option = CompartmentOptions::default(); 159 | let ctx_ptr = ctx.as_ptr(); 160 | 161 | let global = match NonNull::new(JS_NewGlobalObject( 162 | ctx_ptr, 163 | &SIMPLE_GLOBAL_CLASS, 164 | ptr::null_mut(), 165 | h_option, 166 | &c_option, 167 | )) { 168 | Some(global) => global, 169 | None => return Err(error::Error::SMNullPtr.into()), 170 | }; 171 | 172 | SetBuildIdOp(ctx_ptr, Some(Self::sp_build_id)); 173 | 174 | // callbacks 175 | let global_ptr = global.as_ptr(); 176 | rooted!(in(ctx_ptr) let global_root = global_ptr); 177 | let gl = global_root.handle(); 178 | let _ac = JSAutoCompartment::new(ctx_ptr, gl.get()); 179 | 180 | JS_DefineFunction( 181 | ctx_ptr, 182 | gl.into(), 183 | b"print\0".as_ptr() as *const libc::c_char, 184 | Some(Self::print), 185 | 0, 186 | 0, 187 | ); 188 | 189 | JS_DefineFunction( 190 | ctx_ptr, 191 | gl.into(), 192 | b"usleep\0".as_ptr() as *const libc::c_char, 193 | Some(Self::usleep), 194 | 0, 195 | 0, 196 | ); 197 | 198 | JS_DefineFunction( 199 | ctx_ptr, 200 | gl.into(), 201 | b"readFile\0".as_ptr() as *const libc::c_char, 202 | Some(Self::read_file), 203 | 0, 204 | 0, 205 | ); 206 | 207 | JS_DefineFunction( 208 | ctx_ptr, 209 | gl.into(), 210 | b"writeFile\0".as_ptr() as *const libc::c_char, 211 | Some(Self::write_file), 212 | 0, 213 | 0, 214 | ); 215 | 216 | // init print funcs 217 | Self::eval( 218 | ctx, 219 | global, 220 | "var Module = { 221 | 'printErr': print, 222 | 'print': print, 223 | };", 224 | )?; 225 | 226 | // init /dev/random emulation 227 | Self::eval( 228 | ctx, 229 | global, 230 | "var golem_MAGIC = 0; 231 | golem_randEmu = function() { 232 | golem_MAGIC = Math.pow(golem_MAGIC + 1.8912, 3) % 1; 233 | return golem_MAGIC; 234 | }; 235 | var crypto = { 236 | getRandomValues: function(array) { 237 | for (var i = 0; i < array.length; i++) 238 | array[i] = (golem_randEmu() * 256) | 0 239 | } 240 | };", 241 | )?; 242 | 243 | // make time ops fully deterministic 244 | Self::eval( 245 | ctx, 246 | global, 247 | " 248 | var date = new Date(0); 249 | var timestamp = date.getTime(); 250 | Date.now = function() { return timestamp; } 251 | ", 252 | )?; 253 | 254 | Ok(Self { ctx, global }) 255 | } 256 | 257 | unsafe fn eval( 258 | ctx: NonNull, 259 | global: NonNull, 260 | script: S, 261 | ) -> Result 262 | where 263 | S: AsRef, 264 | { 265 | let ctx_ptr = ctx.as_ptr(); 266 | let global = global.as_ptr(); 267 | 268 | rooted!(in(ctx_ptr) let global_root = global); 269 | let global = global_root.handle(); 270 | let _ac = JSAutoCompartment::new(ctx_ptr, global.get()); 271 | 272 | rooted!(in(ctx_ptr) let mut rval = UndefinedValue()); 273 | 274 | if let None = evaluate_script(ctx, global, script.as_ref(), "noname", 0, rval.handle_mut()) 275 | { 276 | return Err(error::Error::SMJS(error::JSError::new(ctx_ptr)).into()); 277 | } 278 | 279 | RunJobs(ctx_ptr); 280 | 281 | Ok(rval.get()) 282 | } 283 | 284 | pub fn evaluate_script(&self, script: S) -> Result 285 | where 286 | S: AsRef, 287 | { 288 | log::debug!("Evaluating script {}", script.as_ref()); 289 | unsafe { Self::eval(self.ctx, self.global, script) } 290 | } 291 | 292 | unsafe extern "C" fn sp_build_id(build_id: *mut BuildIdCharVector) -> bool { 293 | let sp_id = b"SP\0"; 294 | SetBuildId(build_id, &sp_id[0], sp_id.len()) 295 | } 296 | 297 | unsafe extern "C" fn read_file(ctx: *mut JSContext, argc: u32, vp: *mut Value) -> bool { 298 | let args = CallArgs::from_vp(vp, argc); 299 | 300 | if args.argc_ != 1 { 301 | JS_ReportErrorASCII( 302 | ctx, 303 | b"readFile(filename) requires exactly 1 argument\0".as_ptr() as *const libc::c_char, 304 | ); 305 | return false; 306 | } 307 | 308 | let arg = Handle::from_raw(args.get(0)); 309 | let filename = js_string_to_utf8(ctx, ToString(ctx, arg)); 310 | 311 | if let Err(err) = (|| -> Result<()> { 312 | let contents = VFS.lock().unwrap().read_file(&filename)?; 313 | 314 | rooted!(in(ctx) let mut rval = ptr::null_mut::()); 315 | ArrayBuffer::create(ctx, CreateWith::Slice(&contents), rval.handle_mut()) 316 | .map_err(|_| error::Error::SliceToUint8ArrayConversion)?; 317 | 318 | args.rval().set(ObjectValue(rval.get())); 319 | Ok(()) 320 | })() { 321 | JS_ReportErrorASCII( 322 | ctx, 323 | format!("failed to read file '{}' with error: {}\0", &filename, err) 324 | .as_bytes() 325 | .as_ptr() as *const libc::c_char, 326 | ); 327 | return false; 328 | } 329 | 330 | true 331 | } 332 | 333 | unsafe extern "C" fn write_file(ctx: *mut JSContext, argc: u32, vp: *mut Value) -> bool { 334 | let args = CallArgs::from_vp(vp, argc); 335 | 336 | if args.argc_ != 2 { 337 | JS_ReportErrorASCII( 338 | ctx, 339 | b"writeFile(filename, data) requires exactly 2 arguments\0".as_ptr() 340 | as *const libc::c_char, 341 | ); 342 | return false; 343 | } 344 | 345 | let arg = Handle::from_raw(args.get(0)); 346 | let filename = js_string_to_utf8(ctx, ToString(ctx, arg)); 347 | 348 | if let Err(err) = (|| -> Result<()> { 349 | typedarray!(in(ctx) let contents: ArrayBufferView = args.get(1).to_object()); 350 | let contents: Vec = contents 351 | .map_err(|_| error::Error::Uint8ArrayToVecConversion)? 352 | .to_vec(); 353 | 354 | VFS.lock().unwrap().write_file(&filename, &contents)?; 355 | 356 | Ok(()) 357 | })() { 358 | JS_ReportErrorASCII( 359 | ctx, 360 | format!("failed to write file '{}' with error: {}\0", &filename, err) 361 | .as_bytes() 362 | .as_ptr() as *const libc::c_char, 363 | ); 364 | return false; 365 | } 366 | 367 | args.rval().set(UndefinedValue()); 368 | true 369 | } 370 | 371 | unsafe extern "C" fn print(ctx: *mut JSContext, argc: u32, vp: *mut Value) -> bool { 372 | let args = CallArgs::from_vp(vp, argc); 373 | 374 | if args.argc_ > 1 { 375 | JS_ReportErrorASCII( 376 | ctx, 377 | b"print(msg=\"\") requires 0 or 1 arguments\0".as_ptr() as *const libc::c_char, 378 | ); 379 | return false; 380 | } 381 | 382 | let message = if args.argc_ == 0 { 383 | "".to_string() 384 | } else { 385 | let arg = Handle::from_raw(args.get(0)); 386 | js_string_to_utf8(ctx, ToString(ctx, arg)) 387 | }; 388 | 389 | println!("{}", message); 390 | 391 | args.rval().set(UndefinedValue()); 392 | true 393 | } 394 | 395 | unsafe extern "C" fn usleep(ctx: *mut JSContext, argc: u32, vp: *mut Value) -> bool { 396 | use std::{thread::sleep, time::Duration}; 397 | 398 | let args = CallArgs::from_vp(vp, argc); 399 | 400 | if args.argc_ != 1 { 401 | JS_ReportErrorASCII( 402 | ctx, 403 | b"usleep(useconds) requires exactly 1 argument\0".as_ptr() as *const libc::c_char, 404 | ); 405 | return false; 406 | } 407 | 408 | let arg = Handle::from_raw(args.get(0)); 409 | let useconds = match ToUint64(ctx, arg) { 410 | Ok(useconds) => useconds, 411 | Err(()) => { 412 | JS_ReportErrorASCII( 413 | ctx, 414 | b"couldn't extract value from input arg 'useconds'\0".as_ptr() 415 | as *const libc::c_char, 416 | ); 417 | return false; 418 | } 419 | }; 420 | 421 | // sleep 422 | sleep(Duration::from_micros(useconds)); 423 | 424 | args.rval().set(UndefinedValue()); 425 | true 426 | } 427 | } 428 | 429 | unsafe fn js_string_to_utf8(ctx: *mut JSContext, js_string: *mut JSString) -> String { 430 | rooted!(in(ctx) let string_root = js_string); 431 | let string = JS_EncodeStringToUTF8(ctx, string_root.handle().into()); 432 | let string = std::ffi::CStr::from_ptr(string); 433 | String::from_utf8_lossy(string.to_bytes()).into_owned() 434 | } 435 | 436 | pub mod error { 437 | use super::js_string_to_utf8; 438 | use super::JSContext; 439 | use super::UndefinedValue; 440 | use mozjs::jsapi::JS_ClearPendingException; 441 | use mozjs::jsapi::JS_IsExceptionPending; 442 | use mozjs::rust::jsapi_wrapped::JS_Stringify; 443 | use mozjs::rust::wrappers::{JS_ErrorFromException, JS_GetPendingException}; 444 | use mozjs::rust::HandleObject; 445 | use mozjs::rust::HandleValue; 446 | use mozjs::rust::JSEngineError; 447 | use std::slice; 448 | 449 | #[derive(Debug, thiserror::Error, PartialEq)] 450 | pub enum Error { 451 | #[error("couldn't convert &[u8] to Uint8Array")] 452 | SliceToUint8ArrayConversion, 453 | #[error("couldn't convert Uint8Array to Vec")] 454 | Uint8ArrayToVecConversion, 455 | #[error("SpiderMonkey internal error")] 456 | SMInternal, 457 | #[error("Null pointer exception")] 458 | SMNullPtr, 459 | #[error("{0}")] 460 | SMJS(#[from] JSError), 461 | } 462 | 463 | impl From for Error { 464 | fn from(_err: JSEngineError) -> Self { 465 | Error::SMInternal 466 | } 467 | } 468 | 469 | #[derive(Debug, PartialEq, thiserror::Error)] 470 | #[error("JavaScript error: {message}")] 471 | pub struct JSError { 472 | pub message: String, 473 | } 474 | 475 | impl JSError { 476 | const MAX_JSON_STRINGIFY: usize = 1024; 477 | 478 | pub unsafe fn new(ctx: *mut JSContext) -> Self { 479 | Self::create_with(ctx) 480 | } 481 | 482 | unsafe fn create_with(ctx: *mut JSContext) -> Self { 483 | if !JS_IsExceptionPending(ctx) { 484 | return Self { 485 | message: "Uncaught exception: exception reported but not pending".to_string(), 486 | }; 487 | } 488 | 489 | rooted!(in(ctx) let mut value = UndefinedValue()); 490 | 491 | if !JS_GetPendingException(ctx, value.handle_mut()) { 492 | JS_ClearPendingException(ctx); 493 | return Self { 494 | message: "Uncaught exception: JS_GetPendingException failed".to_string(), 495 | }; 496 | } 497 | 498 | JS_ClearPendingException(ctx); 499 | 500 | if value.is_object() { 501 | rooted!(in(ctx) let object = value.to_object()); 502 | Self::from_native_error(ctx, object.handle()).unwrap_or_else(|| { 503 | // try serializing to JSON 504 | let mut data = vec![0; Self::MAX_JSON_STRINGIFY]; 505 | if !JS_Stringify( 506 | ctx, 507 | &mut value.handle_mut(), 508 | HandleObject::null(), 509 | HandleValue::null(), 510 | Some(Self::stringify_cb), 511 | data.as_mut_ptr() as *mut libc::c_void, 512 | ) { 513 | return Self { 514 | message: "Uncaught exception: unknown (can't convert to string)" 515 | .to_string(), 516 | }; 517 | } 518 | 519 | if let Ok(data) = std::ffi::CString::from_vec_unchecked(data).into_string() { 520 | Self { message: data } 521 | } else { 522 | Self { 523 | message: "Uncaught exception: unknown (can't convert to string)" 524 | .to_string(), 525 | } 526 | } 527 | }) 528 | } else if value.is_string() { 529 | let message = js_string_to_utf8(ctx, value.to_string()); 530 | Self { message } 531 | } else { 532 | Self { 533 | message: "Uncaught exception: failed to stringify primitive".to_string(), 534 | } 535 | } 536 | } 537 | 538 | unsafe fn from_native_error(ctx: *mut JSContext, obj: HandleObject) -> Option { 539 | let report = JS_ErrorFromException(ctx, obj); 540 | if report.is_null() { 541 | return None; 542 | } 543 | 544 | let message = { 545 | let message = (*report)._base.message_.data_ as *const u8; 546 | let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap(); 547 | let message = slice::from_raw_parts(message, length as usize); 548 | String::from_utf8_lossy(message).into_owned() 549 | }; 550 | 551 | Some(Self { message }) 552 | } 553 | 554 | unsafe extern "C" fn stringify_cb( 555 | bytes: *const u16, 556 | len: u32, 557 | data: *mut libc::c_void, 558 | ) -> bool { 559 | let data = std::slice::from_raw_parts_mut(data as *mut u8, Self::MAX_JSON_STRINGIFY); 560 | let bytes = std::slice::from_raw_parts(bytes, len as usize); 561 | for i in 0..len as usize { 562 | // TODO substitute UTF16 chars with unknown symbol in UTF8 563 | data[i] = bytes[i].to_le_bytes()[0]; 564 | } 565 | true 566 | } 567 | } 568 | } 569 | -------------------------------------------------------------------------------- /sp-wasm-engine/src/sandbox/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod engine; 2 | pub mod vfs; 3 | 4 | use self::engine::*; 5 | use self::vfs::*; 6 | use super::Result; 7 | 8 | use std::path::{self, Path}; 9 | use std::sync::Mutex; 10 | 11 | use itertools::Itertools; 12 | use lazy_static::lazy_static; 13 | 14 | lazy_static! { 15 | static ref VFS: Mutex = Mutex::new(VirtualFS::default()); 16 | } 17 | 18 | pub struct Sandbox { 19 | runtime: Runtime, 20 | } 21 | 22 | impl Sandbox { 23 | pub fn new(engine: &Engine) -> Result { 24 | let runtime = Runtime::new(engine)?; 25 | Ok(Self { runtime }) 26 | } 27 | 28 | pub fn set_exec_args(self, exec_args: It) -> Result 29 | where 30 | It: IntoIterator, 31 | It::Item: AsRef, 32 | { 33 | let exec_args = exec_args 34 | .into_iter() 35 | .map(|s| format!("'{}'", s.as_ref())) 36 | .join(", "); 37 | log::info!("Setting exec args [ {} ]", exec_args); 38 | 39 | let js = format!("Module['arguments'] = [ {} ];", exec_args); 40 | self.runtime.evaluate_script(&js)?; 41 | 42 | Ok(self) 43 | } 44 | 45 | pub fn load_input_files(self, input_path: S) -> Result 46 | where 47 | S: AsRef, 48 | { 49 | log::info!("Loading input files at {}", input_path.as_ref().display()); 50 | 51 | // Include our version of '_usleep' function 52 | let mut js = " 53 | Module['preRun'] = function() { 54 | _usleep = usleep; 55 | " 56 | .to_string(); 57 | 58 | VFS.lock() 59 | .unwrap() 60 | .map_path(input_path.as_ref(), "/", &mut |source_path, dest_path| { 61 | let dest_path_s: String = dest_path.to_string_lossy().into(); 62 | if source_path.is_dir() { 63 | // create dir 64 | js += &format!("FS.mkdir('{}');", dest_path_s); 65 | } else { 66 | // create file 67 | js += &format!( 68 | "\n\tFS.writeFile('{}', new Uint8Array(readFile('{}')));", 69 | dest_path_s, dest_path_s 70 | ); 71 | } 72 | })?; 73 | 74 | js += "\n};"; 75 | self.runtime.evaluate_script(&js)?; 76 | 77 | Ok(self) 78 | } 79 | 80 | pub fn run(self, wasm_js: S, wasm_bin: S) -> Result 81 | where 82 | S: AsRef, 83 | { 84 | log::info!("Running WASM {}", wasm_bin.as_ref().display()); 85 | 86 | VFS.lock() 87 | .unwrap() 88 | .map_file(wasm_bin.as_ref(), Path::new("/main.wasm"))?; 89 | 90 | let mut js = "Module['wasmBinary'] = readFile('/main.wasm');".to_string(); 91 | let wasm_js = hostfs::read_file(wasm_js.as_ref())?; 92 | let wasm_js = String::from_utf8(wasm_js)?; 93 | js += &wasm_js; 94 | self.runtime.evaluate_script(&js)?; 95 | 96 | Ok(self) 97 | } 98 | 99 | pub fn save_output_files(self, output_path: S, output_files: It) -> Result<()> 100 | where 101 | S: AsRef, 102 | It: IntoIterator, 103 | It::Item: AsRef, 104 | { 105 | for output_file in output_files { 106 | // sanitize output file path (may contain subdirs) 107 | let output_file = hostfs::sanitize_path(output_file.as_ref())?; 108 | 109 | // create subdirs if they don't exist 110 | let mut output_vfs_path = path::PathBuf::from("/"); 111 | output_vfs_path.push(output_file.as_path()); 112 | 113 | if let Some(p) = output_vfs_path.parent() { 114 | VFS.lock().unwrap().create_dir_all(p)?; 115 | } 116 | 117 | // copy files from JS_FS to MemFS 118 | let output_vfs_path_str: String = output_vfs_path.as_path().to_string_lossy().into(); 119 | self.runtime.evaluate_script(&format!( 120 | " 121 | try {{ 122 | writeFile('{}', FS.readFile('{}')); 123 | }} 124 | catch(error) {{ 125 | throw new Error(\"Error writing to file '{}': \" + error); 126 | }}", 127 | output_vfs_path_str, output_vfs_path_str, output_vfs_path_str 128 | ))?; 129 | 130 | // create files on the host 131 | let mut output_hostfs_path = path::PathBuf::from(output_path.as_ref()); 132 | 133 | if let Some(p) = output_file.parent() { 134 | log::debug!("Creating subdirs={:?}", output_hostfs_path.join(p)); 135 | hostfs::create_dir_all(output_hostfs_path.join(p))?; 136 | } 137 | 138 | output_hostfs_path.push(output_file.as_path()); 139 | 140 | log::info!( 141 | "Saving output at {}", 142 | output_hostfs_path.as_path().to_string_lossy() 143 | ); 144 | 145 | let contents = VFS.lock().unwrap().read_file(output_vfs_path)?; 146 | hostfs::write_file(output_hostfs_path, &contents)?; 147 | } 148 | 149 | Ok(()) 150 | } 151 | 152 | pub fn runtime(&self) -> &Runtime { 153 | &self.runtime 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /sp-wasm-engine/src/sandbox/vfs.rs: -------------------------------------------------------------------------------- 1 | use crate::error::FileContext; 2 | use crate::{Error, Result}; 3 | use sp_wasm_memfs::prelude::*; 4 | use std::collections::VecDeque; 5 | use std::fs; 6 | use std::io::{Read, Write}; 7 | use std::path; 8 | 9 | pub struct VirtualFS { 10 | backend: MemFS, 11 | } 12 | 13 | impl VirtualFS { 14 | pub fn new() -> Self { 15 | Self::default() 16 | } 17 | 18 | pub fn read_file

(&mut self, path: P) -> Result> 19 | where 20 | P: AsRef, 21 | { 22 | let mut file = self.backend.open_file(path.as_ref())?; 23 | let mut contents = Vec::new(); 24 | file.read_to_end(&mut contents).file_context(&path)?; 25 | 26 | Ok(contents) 27 | } 28 | 29 | pub fn write_file

(&mut self, path: P, contents: &[u8]) -> Result<()> 30 | where 31 | P: AsRef, 32 | { 33 | log::debug!("Writing file={:?}", path.as_ref()); 34 | let mut file = self.backend.create_file(path.as_ref())?; 35 | file.write_all(contents).file_context(&path)?; 36 | 37 | Ok(()) 38 | } 39 | 40 | pub fn create_dir_all

(&mut self, path: P) -> Result<()> 41 | where 42 | P: AsRef, 43 | { 44 | log::debug!("Creating subdirs={:?}", path.as_ref()); 45 | self.backend.create_dir_all(path)?; 46 | 47 | Ok(()) 48 | } 49 | 50 | pub fn map_file

(&mut self, source_path: P, dest_path: P) -> Result<()> 51 | where 52 | P: AsRef, 53 | { 54 | let contents = hostfs::read_file(source_path.as_ref())?; 55 | self.write_file(dest_path.as_ref(), &contents)?; 56 | 57 | Ok(()) 58 | } 59 | 60 | pub fn map_path( 61 | &mut self, 62 | source_path: P1, 63 | dest_path: P2, 64 | cb: &mut dyn FnMut(&path::Path, &path::Path), 65 | ) -> Result<()> 66 | where 67 | P1: AsRef, 68 | P2: AsRef, 69 | { 70 | let dest_path = dest_path.as_ref().to_owned(); 71 | let source_path = source_path.as_ref().to_owned(); 72 | let mut fifo = VecDeque::new(); 73 | 74 | for entry in fs::read_dir(&source_path).file_context(&source_path)? { 75 | let entry = entry.file_context(&source_path)?; 76 | let source_path = entry.path(); 77 | 78 | let mut dest_path = dest_path.clone(); 79 | dest_path.push( 80 | source_path 81 | .file_name() 82 | .ok_or_else(|| Error::InvalidPath(source_path.to_string_lossy().to_string()))?, 83 | ); 84 | 85 | fifo.push_back((source_path, dest_path)); 86 | } 87 | 88 | while let Some((source_path, dest_path)) = fifo.pop_front() { 89 | log::debug!( 90 | "source_path = {:?}, dest_path = {:?}", 91 | source_path, 92 | dest_path 93 | ); 94 | cb(&source_path, &dest_path); 95 | 96 | if source_path.is_dir() { 97 | self.backend.create_dir(dest_path.as_path())?; 98 | log::debug!("mapped dir = {:?}", dest_path); 99 | 100 | for entry in fs::read_dir(&source_path).file_context(&source_path)? { 101 | let entry = entry.file_context(&source_path)?; 102 | let source_path = entry.path(); 103 | 104 | let mut dest_path = dest_path.clone(); 105 | dest_path.push(source_path.file_name().ok_or_else(|| { 106 | Error::InvalidPath(source_path.to_string_lossy().to_string()) 107 | })?); 108 | 109 | fifo.push_back((source_path, dest_path)); 110 | } 111 | } else { 112 | self.map_file(source_path.as_path(), dest_path.as_path())?; 113 | log::debug!("mapped file {:?} => {:?}", source_path, dest_path); 114 | } 115 | } 116 | 117 | Ok(()) 118 | } 119 | } 120 | 121 | impl Default for VirtualFS { 122 | fn default() -> Self { 123 | Self { 124 | backend: MemFS::default(), 125 | } 126 | } 127 | } 128 | 129 | pub mod hostfs { 130 | use crate::error::FileContext; 131 | use crate::Result; 132 | 133 | use std::fs; 134 | use std::io::{Read, Write}; 135 | use std::path; 136 | 137 | use path_clean::PathClean; 138 | 139 | pub fn read_file

(path: P) -> Result> 140 | where 141 | P: AsRef, 142 | { 143 | let mut file = fs::File::open(&path).file_context(&path)?; 144 | let mut contents = Vec::new(); 145 | file.read_to_end(&mut contents).file_context(&path)?; 146 | 147 | Ok(contents) 148 | } 149 | 150 | pub fn write_file

(path: P, contents: &[u8]) -> Result<()> 151 | where 152 | P: AsRef, 153 | { 154 | let mut file = fs::File::create(path.as_ref()).file_context(&path)?; 155 | file.write_all(contents).file_context(&path)?; 156 | 157 | Ok(()) 158 | } 159 | 160 | pub fn create_dir_all

(path: P) -> Result<()> 161 | where 162 | P: AsRef, 163 | { 164 | fs::create_dir_all(&path).file_context(&path)?; 165 | 166 | Ok(()) 167 | } 168 | 169 | pub fn sanitize_path

(path: P) -> Result 170 | where 171 | P: AsRef, 172 | { 173 | let mut sanitized = path::PathBuf::from("/"); 174 | sanitized.push(path.as_ref()); 175 | let sanitized = sanitized.clean(); 176 | let path = sanitized.strip_prefix("/").map(path::PathBuf::from)?; 177 | 178 | Ok(path) 179 | } 180 | } 181 | 182 | #[cfg(test)] 183 | mod test { 184 | use std::path::PathBuf; 185 | 186 | #[test] 187 | fn sanitize_path() { 188 | assert_eq!( 189 | Ok(PathBuf::from("out.txt")), 190 | super::hostfs::sanitize_path("../../../out.txt") 191 | ); 192 | 193 | assert_eq!( 194 | Ok(PathBuf::from("out.txt")), 195 | super::hostfs::sanitize_path("out/../../../out.txt") 196 | ); 197 | 198 | assert_eq!( 199 | Ok(PathBuf::from("out/out.txt")), 200 | super::hostfs::sanitize_path("out/../out/../out/../out/out.txt") 201 | ); 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /sp-wasm-memfs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sp-wasm-memfs" 3 | version = "0.2.0" 4 | authors = ["Jakub Konka "] 5 | edition = "2018" 6 | license = "GPL-3.0" 7 | readme = "README.md" 8 | repository = "https://github.com/golemfactory/sp-wasm" 9 | homepage = "https://github.com/golemfactory/sp-wasm" 10 | documentation = "https://docs.rs/sp-wasm-memfs" 11 | description = "Memory FS for Golem's sp-wasm sandbox" 12 | 13 | [dependencies] 14 | path-clean = "0.1" 15 | tool = "0.2" 16 | thiserror = "1" 17 | -------------------------------------------------------------------------------- /sp-wasm-memfs/LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /sp-wasm-memfs/README.md: -------------------------------------------------------------------------------- 1 | # sp-wasm-memfs 2 | 3 | Memory FS for Golem's sp-wasm sandbox 4 | -------------------------------------------------------------------------------- /sp-wasm-memfs/src/error.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | #[derive(Debug, thiserror::Error)] 4 | pub enum Error { 5 | #[error("file '{0}' already exists")] 6 | AlreadyExists(String), 7 | #[error("file '{0}' not found")] 8 | NotFound(String), 9 | #[error("invalid path: '{0}'")] 10 | InvalidPath(String), 11 | #[error("file is root")] 12 | IsRoot, 13 | #[error("{0}")] 14 | Io(#[from] io::Error), 15 | } 16 | 17 | impl PartialEq for Error { 18 | fn eq(&self, other: &Error) -> bool { 19 | match (self, other) { 20 | (&Error::AlreadyExists(ref left), &Error::AlreadyExists(ref right)) => left == right, 21 | (&Error::NotFound(ref left), &Error::NotFound(ref right)) => left == right, 22 | (&Error::InvalidPath(ref left), &Error::InvalidPath(ref right)) => left == right, 23 | (&Error::IsRoot, &Error::IsRoot) => true, 24 | (&Error::Io(ref left), &Error::Io(ref right)) => left.kind() == right.kind(), 25 | (_, _) => false, 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /sp-wasm-memfs/src/file.rs: -------------------------------------------------------------------------------- 1 | use super::node::*; 2 | use std::io::{self, Read, Write}; 3 | use std::sync::{Arc, Mutex}; 4 | 5 | #[derive(Debug)] 6 | pub struct File { 7 | node: Arc>, 8 | rdr_pos: usize, 9 | } 10 | 11 | impl File { 12 | pub(crate) fn new(node: Arc>) -> Self { 13 | Self { node, rdr_pos: 0 } 14 | } 15 | 16 | pub fn reset(&mut self) { 17 | self.rdr_pos = 0; 18 | } 19 | } 20 | 21 | impl Read for File { 22 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 23 | if self.rdr_pos == self.node.lock().unwrap().contents.len() { 24 | return Ok(0); 25 | } 26 | 27 | let result = (&self.node.lock().unwrap().contents[self.rdr_pos..]).read(buf); 28 | result.map(|count| { 29 | self.rdr_pos += count; 30 | count 31 | }) 32 | } 33 | } 34 | 35 | impl Write for File { 36 | fn write(&mut self, buf: &[u8]) -> io::Result { 37 | self.node.lock().unwrap().contents.write(buf) 38 | } 39 | 40 | fn flush(&mut self) -> io::Result<()> { 41 | self.node.lock().unwrap().contents.flush() 42 | } 43 | } 44 | 45 | #[cfg(test)] 46 | mod test { 47 | use super::*; 48 | 49 | #[test] 50 | fn read() { 51 | let mut file = File::new(new_file_node("test.txt")); 52 | file.node 53 | .lock() 54 | .unwrap() 55 | .contents 56 | .write_all(b"Hello world!") 57 | .unwrap(); 58 | 59 | let mut contents = Vec::new(); 60 | file.read_to_end(&mut contents).unwrap(); 61 | assert_eq!(file.node.lock().unwrap().contents, contents); 62 | 63 | // once read, need to reset to read again 64 | let mut contents = Vec::new(); 65 | file.read_to_end(&mut contents).unwrap(); 66 | assert!(contents.is_empty()); 67 | 68 | file.reset(); 69 | let mut contents = Vec::new(); 70 | file.read_to_end(&mut contents).unwrap(); 71 | assert_eq!(file.node.lock().unwrap().contents, contents); 72 | } 73 | 74 | #[test] 75 | fn write() { 76 | let mut file = File::new(new_file_node("test.txt")); 77 | 78 | let contents = b"Hello world!"; 79 | file.write_all(contents).unwrap(); 80 | assert_eq!(file.node.lock().unwrap().contents, b"Hello world!"); 81 | 82 | let contents = b" This is a test..."; 83 | file.write_all(contents).unwrap(); 84 | assert_eq!( 85 | file.node.lock().unwrap().contents, 86 | b"Hello world! This is a test..." 87 | ); 88 | 89 | assert!(file.flush().is_ok()); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /sp-wasm-memfs/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod error; 2 | pub mod file; 3 | pub mod memfs; 4 | mod node; 5 | 6 | pub type Result = std::result::Result; 7 | 8 | pub mod prelude { 9 | pub use super::file::File; 10 | pub use super::memfs::MemFS; 11 | } 12 | -------------------------------------------------------------------------------- /sp-wasm-memfs/src/memfs.rs: -------------------------------------------------------------------------------- 1 | use super::error::*; 2 | use super::file::*; 3 | use super::node::*; 4 | use super::Result; 5 | use path_clean::PathClean; 6 | use std::path::{Path, PathBuf}; 7 | use std::sync::{Arc, Mutex}; 8 | use tool::prelude::*; 9 | 10 | #[derive(Debug)] 11 | pub struct MemFS { 12 | root: Arc>, 13 | } 14 | 15 | impl MemFS { 16 | pub fn new() -> Self { 17 | Self::default() 18 | } 19 | 20 | fn walk

(&self, path: P, node: Arc>) -> Result>> 21 | where 22 | P: AsRef, 23 | { 24 | let mut components = path.as_ref().components(); 25 | components.next(); // skip first 26 | let path = components.as_path(); 27 | 28 | let name: String = match components.next() { 29 | Some(component) => component 30 | .as_os_str() 31 | .to_str() 32 | .ok_or(Error::InvalidPath( 33 | component.as_os_str().to_string_lossy().to_string(), 34 | ))? 35 | .to_owned(), 36 | None => return Ok(node), 37 | }; 38 | 39 | if node.lock().unwrap().is_file() { 40 | if node.lock().unwrap().name == name { 41 | return Ok(Arc::clone(&node)); 42 | } 43 | } else { 44 | if let Some(next) = node.lock().unwrap().children.get(&name) { 45 | return self.walk(path, Arc::clone(&next)); 46 | } 47 | } 48 | 49 | Err(Error::NotFound(name)) 50 | } 51 | 52 | fn normalize_path

(path: P) -> Result 53 | where 54 | P: AsRef, 55 | { 56 | if !path.as_ref().has_root() { 57 | return Err(Error::InvalidPath( 58 | path.as_ref().to_string_lossy().to_string(), 59 | )); 60 | } 61 | 62 | Ok(PathBuf::from(path.as_ref()).clean()) 63 | } 64 | 65 | fn resolve_parent

(path: P) -> Result<(PathBuf, String)> 66 | where 67 | P: AsRef, 68 | { 69 | let path = Self::normalize_path(path)?; 70 | let parent = path.parent().ok_or(Error::IsRoot)?; 71 | let filename = path 72 | .file_name() 73 | .and_then(|s| s.to_str()) 74 | .ok_or(Error::InvalidPath(path.to_string_lossy().to_string()))?; 75 | 76 | Ok((parent.to_owned(), filename.to_owned())) 77 | } 78 | 79 | pub fn create_dir

(&self, path: P) -> Result<()> 80 | where 81 | P: AsRef, 82 | { 83 | let (parent, filename) = Self::resolve_parent(path)?; 84 | let node = self.walk(parent, Arc::clone(&self.root))?; 85 | node.lock() 86 | .unwrap() 87 | .children 88 | .insert(filename.clone(), new_dir_node(filename)); 89 | 90 | Ok(()) 91 | } 92 | 93 | pub fn create_dir_all

(&self, path: P) -> Result<()> 94 | where 95 | P: AsRef, 96 | { 97 | let walk_create = fix(|f, path: PathBuf| -> Result>> { 98 | let (parent, filename) = Self::resolve_parent(path)?; 99 | 100 | let node = if self.is_dir(parent.as_path())? { 101 | self.walk(parent, Arc::clone(&self.root))? 102 | } else { 103 | f(parent)? 104 | }; 105 | 106 | let new_child = new_dir_node(filename.clone()); 107 | node.lock() 108 | .unwrap() 109 | .children 110 | .insert(filename.clone(), Arc::clone(&new_child)); 111 | 112 | Ok(new_child) 113 | }); 114 | 115 | if let Err(err) = walk_create(path.as_ref().to_owned()) { 116 | match err { 117 | Error::IsRoot => Ok(()), 118 | _ => Err(err), 119 | } 120 | } else { 121 | Ok(()) 122 | } 123 | } 124 | 125 | pub fn create_file

(&self, path: P) -> Result 126 | where 127 | P: AsRef, 128 | { 129 | let (parent, filename) = Self::resolve_parent(path)?; 130 | let node = self.walk(parent, Arc::clone(&self.root))?; 131 | let file_node = new_file_node(filename.clone()); 132 | node.lock() 133 | .unwrap() 134 | .children 135 | .insert(filename, Arc::clone(&file_node)); 136 | 137 | Ok(File::new(file_node)) 138 | } 139 | 140 | pub fn open_file

(&self, path: P) -> Result 141 | where 142 | P: AsRef, 143 | { 144 | let (parent, filename) = Self::resolve_parent(path)?; 145 | self.walk(parent.join(filename), Arc::clone(&self.root)) 146 | .map(|node| File::new(node)) 147 | } 148 | 149 | pub fn is_dir

(&self, path: P) -> Result 150 | where 151 | P: AsRef, 152 | { 153 | let path = Self::normalize_path(path)?; 154 | match self.walk(path, Arc::clone(&self.root)) { 155 | Ok(node) => Ok(node.lock().unwrap().is_dir()), 156 | _ => Ok(false), 157 | } 158 | } 159 | 160 | pub fn is_file

(&self, path: P) -> Result 161 | where 162 | P: AsRef, 163 | { 164 | let path = Self::normalize_path(path)?; 165 | match self.walk(path, Arc::clone(&self.root)) { 166 | Ok(node) => Ok(node.lock().unwrap().is_file()), 167 | _ => Ok(false), 168 | } 169 | } 170 | } 171 | 172 | impl Default for MemFS { 173 | fn default() -> Self { 174 | Self { 175 | root: Arc::new(Mutex::new(Node::new("/", FileType::Dir))), 176 | } 177 | } 178 | } 179 | 180 | #[cfg(test)] 181 | mod test { 182 | use super::*; 183 | use std::path::PathBuf; 184 | 185 | #[test] 186 | fn normalize_path() -> Result<()> { 187 | assert!(MemFS::normalize_path("tmp/").is_err()); 188 | assert!(MemFS::normalize_path("a.txt").is_err()); 189 | assert!(MemFS::normalize_path(".").is_err()); 190 | assert!(MemFS::normalize_path("").is_err()); 191 | assert!(MemFS::normalize_path(" ").is_err()); 192 | 193 | assert_eq!(MemFS::normalize_path("/")?, PathBuf::from("/")); 194 | assert_eq!(MemFS::normalize_path("//")?, PathBuf::from("/")); 195 | assert_eq!(MemFS::normalize_path("/../")?, PathBuf::from("/")); 196 | assert_eq!(MemFS::normalize_path("/./")?, PathBuf::from("/")); 197 | assert_eq!(MemFS::normalize_path("/.././")?, PathBuf::from("/")); 198 | assert_eq!(MemFS::normalize_path("/tmp/../")?, PathBuf::from("/")); 199 | assert_eq!(MemFS::normalize_path("/tmp/a/../")?, PathBuf::from("/tmp")); 200 | 201 | Ok(()) 202 | } 203 | 204 | #[test] 205 | fn resolve_parent() -> Result<()> { 206 | assert_eq!(MemFS::resolve_parent("/").unwrap_err(), Error::IsRoot); 207 | assert_eq!( 208 | MemFS::resolve_parent("tmp").unwrap_err(), 209 | Error::InvalidPath("tmp".to_owned()) 210 | ); 211 | 212 | assert_eq!( 213 | MemFS::resolve_parent("/tmp")?, 214 | (PathBuf::from("/"), "tmp".to_owned()) 215 | ); 216 | assert_eq!( 217 | MemFS::resolve_parent("/tmp/a/b/c")?, 218 | (PathBuf::from("/tmp/a/b"), "c".to_owned()) 219 | ); 220 | 221 | Ok(()) 222 | } 223 | 224 | #[test] 225 | fn create_dir() -> Result<()> { 226 | let fs = MemFS::new(); 227 | fs.create_dir("/tmp")?; 228 | fs.create_dir("/tmp/a")?; 229 | fs.create_dir("/tmp/a/b")?; 230 | fs.create_dir("/dev")?; 231 | 232 | assert!(fs.is_dir("/tmp")?); 233 | assert!(fs.is_dir("/tmp/a")?); 234 | assert!(fs.is_dir("/tmp/a/b")?); 235 | assert!(fs.is_dir("/dev")?); 236 | 237 | assert_eq!( 238 | fs.create_dir("/tmp/c/d").unwrap_err(), 239 | Error::NotFound("c".to_owned()) 240 | ); 241 | assert_eq!(fs.create_dir("/").unwrap_err(), Error::IsRoot); 242 | assert_eq!( 243 | fs.create_dir("tmp/a/c").unwrap_err(), 244 | Error::InvalidPath("tmp/a/c".to_owned()) 245 | ); 246 | 247 | Ok(()) 248 | } 249 | 250 | #[test] 251 | fn create_dir_all() -> Result<()> { 252 | let fs = MemFS::new(); 253 | fs.create_dir_all("/tmp/a/b/c")?; 254 | 255 | assert!(fs.is_dir("/tmp")?); 256 | assert!(fs.is_dir("/tmp/a")?); 257 | assert!(fs.is_dir("/tmp/a/b")?); 258 | assert!(fs.is_dir("/tmp/a/b/c")?); 259 | 260 | assert!(fs.create_dir_all("/").is_ok()); 261 | 262 | Ok(()) 263 | } 264 | 265 | #[test] 266 | fn create_file() -> Result<()> { 267 | let fs = MemFS::new(); 268 | fs.create_dir("/tmp")?; 269 | fs.create_file("/tmp/a")?; 270 | fs.create_file("/b")?; 271 | fs.create_dir("/dev")?; 272 | fs.create_file("/dev/random")?; 273 | 274 | assert!(fs.is_file("/tmp/a")?); 275 | assert!(fs.is_file("/b")?); 276 | assert!(fs.is_file("/dev/random")?); 277 | 278 | assert_eq!(fs.create_file("/").unwrap_err(), Error::IsRoot); 279 | assert_eq!( 280 | fs.create_file("c").unwrap_err(), 281 | Error::InvalidPath("c".to_owned()) 282 | ); 283 | assert_eq!( 284 | fs.create_file("/d/c").unwrap_err(), 285 | Error::NotFound("d".to_owned()) 286 | ); 287 | 288 | Ok(()) 289 | } 290 | 291 | #[test] 292 | fn open_file() -> Result<()> { 293 | let fs = MemFS::new(); 294 | fs.create_file("/test")?; 295 | 296 | assert!(fs.is_file("/test")?); 297 | assert!(fs.open_file("/test").is_ok()); 298 | 299 | assert_eq!(fs.open_file("/").unwrap_err(), Error::IsRoot); 300 | assert_eq!( 301 | fs.open_file("/bbb").unwrap_err(), 302 | Error::NotFound("bbb".to_owned()) 303 | ); 304 | assert_eq!( 305 | fs.open_file("bbb").unwrap_err(), 306 | Error::InvalidPath("bbb".to_owned()) 307 | ); 308 | 309 | Ok(()) 310 | } 311 | } 312 | -------------------------------------------------------------------------------- /sp-wasm-memfs/src/node.rs: -------------------------------------------------------------------------------- 1 | use std::collections::BTreeMap; 2 | use std::sync::{Arc, Mutex}; 3 | 4 | #[derive(Debug, PartialEq)] 5 | pub(crate) enum FileType { 6 | Dir, 7 | File, 8 | } 9 | 10 | #[derive(Debug)] 11 | pub(crate) struct Node { 12 | pub name: String, 13 | pub file_type: FileType, 14 | pub children: BTreeMap>>, 15 | pub contents: Vec, 16 | } 17 | 18 | impl Node { 19 | pub fn new(name: S, file_type: FileType) -> Self 20 | where 21 | S: Into, 22 | { 23 | Self { 24 | name: name.into(), 25 | file_type, 26 | children: BTreeMap::new(), 27 | contents: Vec::new(), 28 | } 29 | } 30 | 31 | pub fn is_file(&self) -> bool { 32 | self.file_type == FileType::File 33 | } 34 | 35 | pub fn is_dir(&self) -> bool { 36 | self.file_type == FileType::Dir 37 | } 38 | } 39 | 40 | pub(crate) fn new_file_node(name: S) -> Arc> 41 | where 42 | S: Into, 43 | { 44 | Arc::new(Mutex::new(Node::new(name, FileType::File))) 45 | } 46 | 47 | pub(crate) fn new_dir_node(name: S) -> Arc> 48 | where 49 | S: Into, 50 | { 51 | Arc::new(Mutex::new(Node::new(name, FileType::Dir))) 52 | } 53 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use sp_wasm_engine::prelude::*; 2 | use std::path::PathBuf; 3 | use structopt::StructOpt; 4 | 5 | /// Standalone SpiderMonkey instance that can be used to run Emscripten 6 | /// generated Wasm according to the Golem calling convention. 7 | #[derive(StructOpt, Debug)] 8 | #[structopt(name = "wasm-sandbox", version = env!("CARGO_PKG_VERSION"))] 9 | struct Opts { 10 | /// Path to input dir 11 | #[structopt(short = "I", long = "input_dir", parse(from_os_str))] 12 | input_dir: PathBuf, 13 | /// Path to output dir 14 | #[structopt(short = "O", long = "output_dir", parse(from_os_str))] 15 | output_dir: PathBuf, 16 | /// Path to Emscripten JavaScript glue code 17 | #[structopt(short = "j", long = "wasm_js", parse(from_os_str))] 18 | wasm_js: PathBuf, 19 | /// Path to Emscripten Wasm binary 20 | #[structopt(short = "w", long = "wasm_bin", parse(from_os_str))] 21 | wasm_bin: PathBuf, 22 | /// Paths to expected output files 23 | #[structopt( 24 | short = "o", 25 | long = "output_file", 26 | parse(from_os_str), 27 | number_of_values = 1 28 | )] 29 | output_files: Vec, 30 | /// The args to pass to Wasm module 31 | #[structopt()] 32 | args: Vec, 33 | } 34 | 35 | fn main() { 36 | let opts = Opts::from_args(); 37 | env_logger::init_from_env(env_logger::Env::default().default_filter_or("info")); 38 | 39 | let engine = Engine::new().unwrap_or_else(|err| { 40 | eprintln!("{}", err); 41 | std::process::exit(1) 42 | }); 43 | 44 | Sandbox::new(&engine) 45 | .and_then(|sandbox| sandbox.set_exec_args(opts.args.iter())) 46 | .and_then(|sandbox| sandbox.load_input_files(&opts.input_dir)) 47 | .and_then(|sandbox| sandbox.run(&opts.wasm_js, &opts.wasm_bin)) 48 | .and_then(|sandbox| sandbox.save_output_files(&opts.output_dir, opts.output_files.iter())) 49 | .unwrap_or_else(|err| { 50 | eprintln!("{}", err); 51 | std::process::exit(1) 52 | }); 53 | } 54 | -------------------------------------------------------------------------------- /tests/assets/aaa.txt: -------------------------------------------------------------------------------- 1 | test -------------------------------------------------------------------------------- /tests/assets/bbb.txt: -------------------------------------------------------------------------------- 1 | input -------------------------------------------------------------------------------- /tests/assets/gettimeofday.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main(int argc, const char *argv[]) { 7 | FILE* fout = fopen("out.txt", "w"); 8 | struct timeval tv; 9 | gettimeofday(&tv, NULL); 10 | 11 | struct timeval prev_tv = tv; 12 | sleep(1); 13 | gettimeofday(&tv, NULL); 14 | 15 | if (prev_tv.tv_sec == tv.tv_sec || prev_tv.tv_usec == tv.tv_usec) { 16 | fprintf(fout, "%d\n", 0); 17 | } else { 18 | fprintf(fout, "%d\n", 1); 19 | } 20 | 21 | fclose(fout); 22 | 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /tests/assets/gettimeofday.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/golemfactory/sp-wasm/09811ad0ebf1cf2aa3ccf723ed220664ee9b19bc/tests/assets/gettimeofday.wasm -------------------------------------------------------------------------------- /tests/assets/test.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/golemfactory/sp-wasm/09811ad0ebf1cf2aa3ccf723ed220664ee9b19bc/tests/assets/test.wasm -------------------------------------------------------------------------------- /tests/common.rs: -------------------------------------------------------------------------------- 1 | pub use tempfile::TempDir; 2 | 3 | pub fn create_workspace() -> Result { 4 | use tempfile::Builder; 5 | 6 | Builder::new() 7 | .prefix("sp-wasm") 8 | .tempdir() 9 | .map_err(|err| format!("couldn't create temp dir with error: {}", err)) 10 | } 11 | -------------------------------------------------------------------------------- /tests/date_test.rs: -------------------------------------------------------------------------------- 1 | use sp_wasm_engine::prelude::*; 2 | 3 | #[test] 4 | fn date() { 5 | let engine = Engine::new().unwrap(); 6 | let runtime = Runtime::new(&engine).unwrap(); 7 | let v1 = runtime.evaluate_script("Date.now()").unwrap().to_number(); 8 | assert_eq!(v1 as u64, 0); 9 | let v2 = runtime.evaluate_script("Date.now()").unwrap().to_number(); 10 | assert_eq!(v1, v2); 11 | } 12 | -------------------------------------------------------------------------------- /tests/gettimeofday_test.rs: -------------------------------------------------------------------------------- 1 | mod common; 2 | 3 | use common::*; 4 | use sp_wasm_engine::prelude::*; 5 | use std::{ 6 | fs::{self, File}, 7 | io::{Read, Write}, 8 | path::PathBuf, 9 | }; 10 | 11 | const EM_JS: &'static [u8] = include_bytes!("assets/gettimeofday.js"); 12 | const EM_WASM: &'static [u8] = include_bytes!("assets/gettimeofday.wasm"); 13 | 14 | fn gettimeofday_impl() -> Result<(), String> { 15 | let test_dir = create_workspace()?; 16 | let mut input_dir = PathBuf::from(test_dir.path()); 17 | input_dir.push("in/"); 18 | fs::create_dir(input_dir.as_path()).map_err(|err| err.to_string())?; 19 | 20 | let mut js = PathBuf::from(test_dir.path()); 21 | js.push("gettimeofday.js"); 22 | let mut f = File::create(js.as_path()).map_err(|err| err.to_string())?; 23 | f.write_all(EM_JS).map_err(|err| err.to_string())?; 24 | 25 | let mut wasm = PathBuf::from(test_dir.path()); 26 | wasm.push("gettimeofday.wasm"); 27 | let mut f = File::create(wasm.as_path()).map_err(|err| err.to_string())?; 28 | f.write_all(EM_WASM).map_err(|err| err.to_string())?; 29 | 30 | let mut output_dir = PathBuf::from(test_dir.path()); 31 | output_dir.push("out/"); 32 | fs::create_dir(output_dir.as_path()).map_err(|err| err.to_string())?; 33 | 34 | let engine = Engine::new().map_err(|err| err.to_string())?; 35 | Sandbox::new(&engine) 36 | .and_then(|sandbox| sandbox.load_input_files(input_dir.to_str().unwrap())) 37 | .and_then(|sandbox| sandbox.run(js.to_str().unwrap(), wasm.to_str().unwrap())) 38 | .and_then(|sandbox| { 39 | sandbox.save_output_files(output_dir.to_str().unwrap(), vec!["out.txt"]) 40 | }) 41 | .map_err(|err| err.to_string())?; 42 | 43 | let mut file = File::open(output_dir.join("out.txt")).map_err(|err| err.to_string())?; 44 | let mut contents = String::new(); 45 | file.read_to_string(&mut contents) 46 | .map_err(|err| err.to_string())?; 47 | 48 | assert_eq!("0\n".to_owned(), contents); 49 | 50 | Ok(()) 51 | } 52 | 53 | #[test] 54 | fn gettimeofday() { 55 | if let Err(e) = gettimeofday_impl() { 56 | eprintln!("unexpected error occurred: {}", e) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /tests/random_device_determinism_test.rs: -------------------------------------------------------------------------------- 1 | use sp_wasm_engine::prelude::*; 2 | 3 | #[test] 4 | fn random_device_determinism() { 5 | let engine = Engine::new().unwrap(); 6 | let start = Runtime::new(&engine) 7 | .unwrap() 8 | .evaluate_script("golem_randEmu()") 9 | .unwrap() 10 | .to_number(); 11 | let expected = 0.7641367265279992; 12 | 13 | assert_eq!(expected, start); 14 | } 15 | -------------------------------------------------------------------------------- /tests/random_device_emulation_test.rs: -------------------------------------------------------------------------------- 1 | use sp_wasm_engine::prelude::*; 2 | 3 | #[test] 4 | fn random_device_emulation() { 5 | let engine = Engine::new().unwrap(); 6 | let runtime = Runtime::new(&engine).unwrap(); 7 | let v1 = runtime 8 | .evaluate_script("golem_randEmu()") 9 | .unwrap() 10 | .to_number(); 11 | let v2 = runtime 12 | .evaluate_script("golem_randEmu()") 13 | .unwrap() 14 | .to_number(); 15 | let v3 = runtime 16 | .evaluate_script("golem_randEmu()") 17 | .unwrap() 18 | .to_number(); 19 | 20 | assert_ne!(v1, v2); 21 | assert_ne!(v2, v3); 22 | } 23 | -------------------------------------------------------------------------------- /tests/sandbox_test.rs: -------------------------------------------------------------------------------- 1 | mod common; 2 | 3 | use common::*; 4 | use sp_wasm_engine::prelude::*; 5 | use std::{ 6 | fs::{self, File}, 7 | io::{Read, Write}, 8 | path::PathBuf, 9 | }; 10 | 11 | const INPUT_PART1: &'static [u8] = include_bytes!("assets/aaa.txt"); 12 | const INPUT_PART2: &'static [u8] = include_bytes!("assets/bbb.txt"); 13 | const EM_JS: &'static [u8] = include_bytes!("assets/test.js"); 14 | const EM_WASM: &'static [u8] = include_bytes!("assets/test.wasm"); 15 | 16 | fn sandbox_impl() -> Result<(), String> { 17 | let test_dir = create_workspace()?; 18 | let mut input_dir = PathBuf::from(test_dir.path()); 19 | input_dir.push("in/"); 20 | fs::create_dir(input_dir.as_path()).map_err(|err| err.to_string())?; 21 | let mut f = File::create(input_dir.join("aaa.txt")).map_err(|err| err.to_string())?; 22 | f.write_all(INPUT_PART1).map_err(|err| err.to_string())?; 23 | 24 | let mut input_subdir = PathBuf::from(input_dir.as_path()); 25 | input_subdir.push("a/"); 26 | fs::create_dir(input_subdir.as_path()).map_err(|err| err.to_string())?; 27 | let mut f = File::create(input_subdir.join("bbb.txt")).map_err(|err| err.to_string())?; 28 | f.write_all(INPUT_PART2).map_err(|err| err.to_string())?; 29 | 30 | let mut js = PathBuf::from(test_dir.path()); 31 | js.push("test.js"); 32 | let mut f = File::create(js.as_path()).map_err(|err| err.to_string())?; 33 | f.write_all(EM_JS).map_err(|err| err.to_string())?; 34 | 35 | let mut wasm = PathBuf::from(test_dir.path()); 36 | wasm.push("test.wasm"); 37 | let mut f = File::create(wasm.as_path()).map_err(|err| err.to_string())?; 38 | f.write_all(EM_WASM).map_err(|err| err.to_string())?; 39 | 40 | let mut output_dir = PathBuf::from(test_dir.path()); 41 | output_dir.push("out/"); 42 | fs::create_dir(output_dir.as_path()).map_err(|err| err.to_string())?; 43 | 44 | let engine = Engine::new().map_err(|err| err.to_string())?; 45 | Sandbox::new(&engine) 46 | .and_then(|sandbox| sandbox.set_exec_args(vec!["test"])) 47 | .and_then(|sandbox| sandbox.load_input_files(input_dir.to_str().unwrap())) 48 | .and_then(|sandbox| sandbox.run(js.to_str().unwrap(), wasm.to_str().unwrap())) 49 | .and_then(|sandbox| { 50 | sandbox.save_output_files(output_dir.to_str().unwrap(), vec!["ccc.txt", "c/ddd.txt"]) 51 | }) 52 | .map_err(|err| err.to_string())?; 53 | 54 | let mut file = File::open(output_dir.join("ccc.txt")).map_err(|err| err.to_string())?; 55 | let mut contents = String::new(); 56 | file.read_to_string(&mut contents) 57 | .map_err(|err| err.to_string())?; 58 | 59 | assert_eq!("THIS IS PART1:\ntest\ntest\n".to_owned(), contents); 60 | 61 | let mut file = File::open(output_dir.join("c/ddd.txt")).map_err(|err| err.to_string())?; 62 | let mut contents = String::new(); 63 | file.read_to_string(&mut contents) 64 | .map_err(|err| err.to_string())?; 65 | 66 | assert_eq!("THIS IS PART2:\ninput\ntest\n".to_owned(), contents); 67 | 68 | Ok(()) 69 | } 70 | 71 | #[test] 72 | fn sandbox() { 73 | if let Err(e) = sandbox_impl() { 74 | eprintln!("unexpected error occurred: {}", e) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /tests/vfs_js_security_test.rs: -------------------------------------------------------------------------------- 1 | use sp_wasm_engine::error::Error; 2 | use sp_wasm_engine::prelude::*; 3 | use sp_wasm_engine::sandbox::engine::error::Error as EngineError; 4 | use std::path; 5 | 6 | #[test] 7 | fn vfs_js_security() { 8 | let engine = Engine::new().unwrap(); 9 | let runtime = Runtime::new(&engine).unwrap(); 10 | let result = runtime.evaluate_script("writeFile('/tmp/test.txt', new Uint8Array(2))"); 11 | 12 | assert!(result.is_err()); 13 | assert!(!path::Path::new("/tmp/test.txt").is_file()); 14 | 15 | match result { 16 | Err(Error::Engine(ref err)) => match err { 17 | EngineError::SMJS(ref err) => assert_eq!( 18 | err.message, 19 | "failed to write file '/tmp/test.txt' with error: file 'tmp' not found" 20 | ), 21 | _ => panic!("wrong error received"), 22 | }, 23 | _ => panic!("wrong error received"), 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/vfs_test.rs: -------------------------------------------------------------------------------- 1 | mod common; 2 | 3 | use common::*; 4 | use sp_wasm_engine::prelude::*; 5 | use std::{ 6 | fs::{self, File}, 7 | io::Write, 8 | path::PathBuf, 9 | }; 10 | 11 | fn vfs_impl() -> Result<(), String> { 12 | let test_dir = create_workspace()?; 13 | let mut dir = PathBuf::from(test_dir.path()); 14 | dir.push("a.txt"); 15 | let mut f = File::create(dir).map_err(|err| err.to_string())?; 16 | f.write_all(b"aaa").map_err(|err| err.to_string())?; 17 | 18 | let mut dir = PathBuf::from(test_dir.path()); 19 | dir.push("sub/"); 20 | fs::create_dir(dir.as_path()).map_err(|err| err.to_string())?; 21 | dir.push("b.txt"); 22 | let mut f = File::create(dir).map_err(|err| err.to_string())?; 23 | f.write_all(b"bbb").map_err(|err| err.to_string())?; 24 | 25 | // map into VFS 26 | let mut vfs = VirtualFS::new(); 27 | vfs.map_path(test_dir.path(), "/", &mut |_, _| {}) 28 | .map_err(|err| err.to_string())?; 29 | 30 | let contents = vfs.read_file("/a.txt").map_err(|err| err.to_string())?; 31 | assert_eq!(b"aaa".to_vec(), contents); 32 | 33 | let contents = vfs.read_file("/sub/b.txt").map_err(|err| err.to_string())?; 34 | assert_eq!(b"bbb".to_vec(), contents); 35 | 36 | // create file directly in VFS 37 | vfs.write_file("/sub/c.txt", b"ccc") 38 | .map_err(|err| err.to_string())?; 39 | 40 | let contents = vfs.read_file("/sub/c.txt").map_err(|err| err.to_string())?; 41 | assert_eq!(b"ccc".to_vec(), contents); 42 | 43 | // try & create file in subdir that doesn't exist 44 | let res = vfs.write_file("/sub/sub2/d.txt", b"ddd"); 45 | assert_eq!(res.is_err(), true); 46 | 47 | Ok(()) 48 | } 49 | 50 | #[test] 51 | fn vfs() { 52 | if let Err(e) = vfs_impl() { 53 | eprintln!("unexpected error occurred: {}", e) 54 | } 55 | } 56 | --------------------------------------------------------------------------------