|
| 1 | +package build |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "os/exec" |
| 6 | + "path/filepath" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/xgo-dev/llgo/internal/crosscompile" |
| 11 | + "github.com/xgo-dev/llgo/internal/lto" |
| 12 | +) |
| 13 | + |
| 14 | +func TestEmscriptenLTOLateStdioLibcall(t *testing.T) { |
| 15 | + if testing.Short() { |
| 16 | + t.Skip("links and executes Emscripten LTO binaries") |
| 17 | + } |
| 18 | + for _, tool := range []string{"emcc", "node"} { |
| 19 | + if _, err := exec.LookPath(tool); err != nil { |
| 20 | + t.Skipf("%s is not installed", tool) |
| 21 | + } |
| 22 | + } |
| 23 | + dir := t.TempDir() |
| 24 | + source := filepath.Join(dir, "stdio.c") |
| 25 | + if err := os.WriteFile(source, []byte(`#include <stdio.h> |
| 26 | +__attribute__((noinline)) void byte(FILE *f) { fwrite("0", 1, 1, f); } |
| 27 | +int main(void) { byte(stderr); return 0; } |
| 28 | +`), 0600); err != nil { |
| 29 | + t.Fatal(err) |
| 30 | + } |
| 31 | + for _, target := range []struct { |
| 32 | + profile crosscompile.WasmProfile |
| 33 | + width string |
| 34 | + }{{crosscompile.WasmProfileJ32, "-m32"}, {crosscompile.WasmProfileJ64, "-m64"}} { |
| 35 | + for _, mode := range []lto.Mode{lto.Thin, lto.Full} { |
| 36 | + t.Run(string(target.profile)+"/"+mode.String(), func(t *testing.T) { |
| 37 | + ctx := &context{buildConf: &Config{LTO: mode}, crossCompile: crosscompile.Export{WasmProfile: target.profile}} |
| 38 | + out := filepath.Join(dir, string(target.profile)+"-"+mode.String()+".mjs") |
| 39 | + // Leave fwrite intact until link-time optimization, as happens |
| 40 | + // when LLVM specializes LLGo's runtime print buffers during LTO. |
| 41 | + args := []string{"-O2", "-flto=" + mode.String(), target.width, "-sEXIT_RUNTIME=1", "-sNODE_HOST_ENV=1", "-Xclang", "-disable-llvm-passes", source, "-o", out} |
| 42 | + args = append(args, emscriptenLTOLibcallArgs(ctx)...) |
| 43 | + if output, err := exec.CommandContext(t.Context(), "emcc", args...).CombinedOutput(); err != nil { |
| 44 | + t.Fatalf("link late stdio libcall: %v\n%s", err, output) |
| 45 | + } |
| 46 | + runner := `import {pathToFileURL} from 'node:url'; const m = await import(pathToFileURL(process.argv[1]).href); await m.default();` |
| 47 | + if output, err := exec.CommandContext(t.Context(), "node", "--input-type=module", "-e", runner, out).CombinedOutput(); err != nil || strings.TrimSpace(string(output)) != "0" { |
| 48 | + t.Fatalf("execute late stdio libcall: %v\n%s", err, output) |
| 49 | + } |
| 50 | + }) |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments