|
| 1 | +/* |
| 2 | + * Copyright 2019 WebAssembly Community Group participants |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +// |
| 18 | +// Write the module to binary, and load it from there. This is useful in |
| 19 | +// testing to check for the effects of roundtripping in a single wasm-opt |
| 20 | +// parameter. |
| 21 | +// |
| 22 | + |
| 23 | +#ifdef _WIN32 |
| 24 | +#include <io.h> |
| 25 | +#endif |
| 26 | + |
| 27 | +#include <cstdlib> |
| 28 | +#include <vector> |
| 29 | + |
| 30 | +#include "ir/module-utils.h" |
| 31 | +#include "pass.h" |
| 32 | +#include "support/file.h" |
| 33 | +#include "wasm-io.h" |
| 34 | +#include "wasm.h" |
| 35 | + |
| 36 | +using namespace std; |
| 37 | + |
| 38 | +namespace wasm { |
| 39 | + |
| 40 | +struct RoundTrip : public Pass { |
| 41 | + void run(PassRunner* runner, Module* module) override { |
| 42 | + std::string templateName = "byn_round_trip_XXXXXX"; |
| 43 | + std::vector<char> buffer(templateName.begin(), templateName.end()); |
| 44 | + buffer.push_back(0); |
| 45 | +#ifndef _WIN32 |
| 46 | + auto fd = mkstemp(buffer.data()); |
| 47 | + WASM_UNUSED(fd); |
| 48 | + std::string tempName(buffer.begin(), buffer.end()); |
| 49 | +#else |
| 50 | + std::string tempName = _mktemp(buffer.data()); |
| 51 | +#endif |
| 52 | + // Write |
| 53 | + ModuleWriter writer; |
| 54 | + writer.setBinary(true); |
| 55 | + writer.setDebugInfo(runner->options.debugInfo); |
| 56 | + writer.write(*module, tempName); |
| 57 | + // Read |
| 58 | + Module newModule; |
| 59 | + ModuleReader reader; |
| 60 | + reader.read(tempName, newModule); |
| 61 | + // Clean up |
| 62 | + std::remove(tempName.c_str()); |
| 63 | + // Swap in |
| 64 | + ModuleUtils::clearModule(*module); |
| 65 | + ModuleUtils::copyModule(newModule, *module); |
| 66 | + } |
| 67 | +}; |
| 68 | + |
| 69 | +Pass* createRoundTripPass() { return new RoundTrip(); } |
| 70 | + |
| 71 | +} // namespace wasm |
0 commit comments