$ ./emsdk-portable/emscripten/incoming/emcc swift/hello.ll -o swift/hello.html warning: Linking two modules of different data layouts: '/Users/hiragram/.emscripten_cache/asmjs/dlmalloc.bc' is 'e-p:32:32-i64:64-v128:32:128-n32-S128' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmp4kw329/hello_0.o' is 'e-m:o-i64:64-f80:128-n8:16:32:64-S128' warning: Linking two modules of different target triples: /Users/hiragram/.emscripten_cache/asmjs/dlmalloc.bc' is 'asmjs-unknown-emscripten' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmp4kw329/hello_0.o' is 'x86_64-apple-macosx10.9' warning: Linking two modules of different data layouts: '/Users/hiragram/.emscripten_cache/asmjs/libc.bc' is 'e-p:32:32-i64:64-v128:32:128-n32-S128' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmp4kw329/hello_0.o' is 'e-m:o-i64:64-f80:128-n8:16:32:64-S128' warning: Linking two modules of different target triples: /Users/hiragram/.emscripten_cache/asmjs/libc.bc' is 'asmjs-unknown-emscripten' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmp4kw329/hello_0.o' is 'x86_64-apple-macosx10.9' error: Appending variables with different alignment need to be linked! ERROR:root:Failed to run llvm optimizations:print("Hello, Swift!") これだけ$ swiftc swift/hello.swift -emit-ir -o swift/hello.ll@convention(c) func a(x: Int) -> Int { return x * 2 }swift/hello.swift:1:2: error: attribute can only be applied to types, not declarations @convention(c) ^asmjs-unknown-emscripten で、swiftcはターゲットが x86_64-apple-macosx10.9 になってるっぽいwarning: Linking two modules of different data layouts: '/Users/hiragram/.emscripten_cache/asmjs/dlmalloc.bc' is 'e-p:32:32-i64:64-v128:32:128-n32-S128' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmpWhbLkq/hello_0.o' is 'e-m:o-i64:64-f80:128-n8:16:32:64-S128' warning: Linking two modules of different target triples: /Users/hiragram/.emscripten_cache/asmjs/dlmalloc.bc' is 'asmjs-unknown-emscripten' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmpWhbLkq/hello_0.o' is 'x86_64-apple-macosx10.9' warning: Linking two modules of different data layouts: '/Users/hiragram/.emscripten_cache/asmjs/libc.bc' is 'e-p:32:32-i64:64-v128:32:128-n32-S128' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmpWhbLkq/hello_0.o' is 'e-m:o-i64:64-f80:128-n8:16:32:64-S128' warning: Linking two modules of different target triples: /Users/hiragram/.emscripten_cache/asmjs/libc.bc' is 'asmjs-unknown-emscripten' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmpWhbLkq/hello_0.o' is 'x86_64-apple-macosx10.9'i32 みたいな型で記述されているから; ModuleID = 'swift/hello.ll' source_filename = "swift/hello.ll" target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-apple-macosx10.9" @__swift_reflection_version = linkonce_odr hidden constant i16 3 @llvm.used = appending global [1 x i8*] [i8* bitcast (i16* @__swift_reflection_version to i8*)], section "llvm.metadata", align 8 define i32 @main(i32, i8**) #0 { entry: %2 = bitcast i8** %1 to i8* ret i32 0 } attributes #0 = { "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "target-cpu"="core2" "target-features"="+cx16,+fxsr,+mmx,+sse,+sse2,+sse3,+ssse3,+x87" } !llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !9, !10} !0 = !{i32 1, !"Objective-C Version", i32 2} !1 = !{i32 1, !"Objective-C Image Info Version", i32 0} !2 = !{i32 1, !"Objective-C Image Info Section", !"__DATA, __objc_imageinfo, regular, no_dead_strip"} !3 = !{i32 4, !"Objective-C Garbage Collection", i32 1280} !4 = !{i32 1, !"Objective-C Class Properties", i32 64} !5 = !{i32 6, !"Linker Options", !6} !6 = !{!7, !8} !7 = !{!"-lswiftCore"} !8 = !{!"-lobjc"} !9 = !{i32 1, !"PIC Level", i32 2} !10 = !{i32 1, !"Swift Version", i32 5}@llvm.used = appending global [1 x i8*] [i8* bitcast (i16* @__swift_reflection_version to i8*)], section "llvm.metadata", align 8; ModuleID = 'swift/hello.ll' source_filename = "swift/hello.ll" target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-apple-macosx10.9" define i32 @main(i32, i8**) #0 { entry: %2 = bitcast i8** %1 to i8* ret i32 0 }main って名前の関数になってくれるかもしれんけど。Hello All, I tried using clang 3.9.0 to emit the llvm ir with -target wasm32-wasm32-wasm32, but end up getting warning for different data layout and target triple. The question is if llvm WebAssembly target is usable as is to generate llvm ir to be fed to emscripten ?
The warning is expected, but should not cause problems in practice. The important things are the same in those two triples. (Except perhaps for the size of long doubles, is that important in Swift?)warning: Linking two modules of different data layouts: '/Users/hiragram/.emscripten_cache/asmjs/dlmalloc.bc' is 'e-p:32:32-i64:64-v128:32:128-n32-S128' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmpWrnym7/hello_0.o' is 'e-m:o-i64:64-f80:128-n8:16:32:64-S128' warning: Linking two modules of different target triples: /Users/hiragram/.emscripten_cache/asmjs/dlmalloc.bc' is 'asmjs-unknown-emscripten' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmpWrnym7/hello_0.o' is 'x86_64-apple-macosx10.9' warning: Linking two modules of different data layouts: '/Users/hiragram/.emscripten_cache/asmjs/libc.bc' is 'e-p:32:32-i64:64-v128:32:128-n32-S128' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmpWrnym7/hello_0.o' is 'e-m:o-i64:64-f80:128-n8:16:32:64-S128' warning: Linking two modules of different target triples: /Users/hiragram/.emscripten_cache/asmjs/libc.bc' is 'asmjs-unknown-emscripten' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmpWrnym7/hello_0.o' is 'x86_64-apple-macosx10.9' warning: Linking two modules of different data layouts: '/Users/hiragram/.emscripten_cache/asmjs/wasm-libc.bc' is 'e-p:32:32-i64:64-v128:32:128-n32-S128' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmpWrnym7/hello_0.o' is 'e-m:o-i64:64-f80:128-n8:16:32:64-S128' warning: Linking two modules of different target triples: /Users/hiragram/.emscripten_cache/asmjs/wasm-libc.bc' is 'asmjs-unknown-emscripten' whereas '/var/folders/b6/shjk0l7j0mb0j9__n3w7z92w0000gn/T/tmpWrnym7/hello_0.o' is 'x86_64-apple-macosx10.9' warning: incorrect target triple 'x86_64-apple-macosx10.9' (did you use emcc/em++ on all source files and not clang directly?)$ swiftc -emit-ir -Xcc --target=wasm32 first.swift -o first.ll$ swiftc -emit-ir -Xcc --target=wasm32aaa first.swift -o first.ll <unknown>:0: warning: argument unused during compilation: '-mmacosx-version-min=10.9.0' <unknown>:0: error: -fobjc-arc is not supported on platforms using the legacy runtime <unknown>:0: error: unknown target triple 'wasm32aaa', please use -triple or -arch <unknown>:0: error: clang importer creation faileddefine hidden swiftcc i64 @_T01b3addS2i_SitF(i64, i64) #0 { entry: %2 = call { i64, i1 } @llvm.sadd.with.overflow.i64(i64 %0, i64 %1) %3 = extractvalue { i64, i1 } %2, 0 %4 = extractvalue { i64, i1 } %2, 1 br i1 %4, label %6, label %5 ; <label>:5: ; preds = %entry ret i64 %3 ; <label>:6: ; preds = %entry call void @llvm.trap() unreachable }swiftcc ってコンベンションになってて、 llc の wasm モードがそれをサポートしてないからダメっぽいswiftcc のサポートがバックポートされてるっぽくて.... + [origin/swift-4.1-branch~577] Canonicalize the spelling of RefDie (NFC) + [origin/swift-4.1-branch~578] dsymutil: strip unused types from imported DW_TAG_modules + [origin/swift-4.1-branch~579] Debug Info: Don't strip clang module skeleton CUs. ++ [llvm/master~5237] Recommit r274270, [CMake] Module builds depend on target intrinsics_gen to be built first.commit 18e8f9ef0645b15c777547d8655a17a315b0815d Author: NAKAMURA Takumi <geek4civic@gmail.com> Date: Wed Jul 19 11:27:31 2017 +0000 Recommit r274270, [CMake] Module builds depend on target intrinsics_gen to be built first. The builder clang-x86_64-linux-selfhost-modules-2 complains. Investigating. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@308439 91177308-0d34-0410-b5e6-96231b3b80d8xcrun clang で動くclangは-target=wasm32使えたけどそういうもん?.s を吐ければ、あとは Wasmのツールの管轄swiftcc などのSwift仕様が含まれていて、 llc が通らない。swiftc -emit-ir b.swift -o b.ll llc b.ll -o b.s libs=/Users/omochi/work/swift-source/build/Ninja-ReleaseAssert/swift-macosx-x86_64/lib/swift/macosx gcc -L$libs b.s -o b.out LD_LIBRARY_PATH=$libs ./b.out$ cat b.swift print("hello swift")_swift_retain とかも外部リンクされているので-static-stdlib の挙動について調べたけど、 /usr/bin/ld に -force_load_swift_libs を渡すようになっているだけで、/usr/bin/ld についてはオープンソースになってないから、何もわからんという結論になったupstream-with-swiftっていうブランチがあるけど、CIは通ってないぽい。 https://ci.swift.org/view/swift-master-next/$ kotlinc -target wasm32 hello.kt で hello.wasm が直接吐かれて超楽っぽい。The calling conventions are mostly for the backends, so it should be possible to just ignore it. That is, if swift didn't emit it, it should be ok, and for now you can strip it from the IR manually for testing. (There are exceptions like tail call optimizations that are done on IR and depend on the convention, but I don't think that would be an issue here.)avoid up-front load time costs がよくわからないな〜Relative..Pointer的なもの持つことをを検討する価値があるかも知れない」。uintptr_t とかタグポインタとか挟んで取り回してたら検出できないっしょ。~/Library/Developer/Toolchains に手でインストールすればXcodeからも切り替えられますexport TOOLCHAINS="org.swift.51220191107a" で$ swift が切り替わってれば他はいろいろと連動するはずってことね、OKEXAMPLES To check whether Mail.app is allowed to run on the local system: spctl -a /Applications/Mail.app To allow Frobozz.app to run on the local system: spctl --add --label "My Stuff" /Applications/Frobozz.app To forbid all code obtained from the Mac App Store from running: spctl --disable --label "Mac App Store"[omochi@omochi-iMacPro bin]$ sudo spctl --add --label swiftwasm $(pwd)/swift-demangle Password: [omochi@omochi-iMacPro bin]$ ./swift-demangle Killed: 9 [omochi@omochi-iMacPro bin]$ sudo spctl -a swift-demangle swift-demangle: rejected (the code is valid but does not seem to be an app)--master-disable でセキュリティ全解除する情報ばっかり出てくる/usr/local は聖域?$ codesign -dvvv /usr/local/bin/swiftlint /usr/local/bin/swiftlint: code object is not signed at all/usr/local/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/bin に動かしたけど駄目だなあ。 フォルダコピーするときにFinderが謎のダイアログを出して確認してきたからなんかいけそうな気がしたけど。[omochi@omochi-iMacPro wasm]$ spctl -a /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/bin/swift-frontend /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/bin/swift-frontend: rejected (the code is valid but does not seem to be an app)[omochi@omochi-iMacPro wasm]$ sil-opt Killed: 9 [omochi@omochi-iMacPro wasm]$ xattr sil-opt xattr: No such file: sil-opt [omochi@omochi-iMacPro wasm]$ which sil-opt /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/bin/sil-opt [omochi@omochi-iMacPro wasm]$ xattr $(which sil-opt) com.apple.quarantine [omochi@omochi-iMacPro wasm]$ sudo xattr -r -d com.apple.quarantine $(which sil-opt) Password: [omochi@omochi-iMacPro wasm]$ sil-opt --version LLVM (http://llvm.org/): LLVM version 10.0.0 Optimized build. Default target: x86_64-apple-darwin19.6.0 Host CPU: skylake-avx512find . -perm +111 -type f と xattr を組み合わせたらガッと浄化できそう。xattr -r -d com.apple.quarantine ディレクトリパス でディレクトリ内一気に消せますよ[omochi@omochi-iMacPro wasm]$ ls -alh total 20432 drwxr-xr-x 4 omochi staff 128B 10 7 01:32 . drwxr-xr-x 14 omochi staff 448B 10 7 01:07 .. -rw-r--r--@ 1 omochi staff 21B 10 7 01:08 a.swift -rwxr-xr-x 1 omochi staff 10M 10 7 01:32 a.wasm [omochi@omochi-iMacPro wasm]$ wasmer a.wasm hello world$ sudo codesign --force --deep --sign "Developer ID Application: Neko Chan (XXXXXXXXX)" --options runtime --deep-verify swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a.xctoolchain/ $ codesign -display swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a.xctoolchain/usr/bin/swift-package swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a.xctoolchain/usr/bin/swift-package: code object is not signed at all (edited)[omochi@omochi-iMacPro usr]$ tree | grep -i xctest │ │ │ ├── XCTest.swiftmodule │ │ │ │ ├── XCTest.opt.bitstream │ │ │ ├── libswiftXCTest.dylib │ │ │ ├── XCTestOverlayShims.h │ │ ├── XCTest.swiftdoc │ │ ├── XCTest.swiftmodule │ │ ├── XCTestOverlayShims.h │ ├── libXCTest.a │ └── swiftpm-xctest-helper[omochi@omochi-iMacPro SwiftDeclWeb]$ swift build --triple wasm32-unknown-wasi --sdk $TOOLCHAIN_PATH/share/wasi-sysroot <module-includes>:1:10: note: in file included from <module-includes>:1: #include "LibcOverlayShims.h" ^ /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/lib/swift/shims/LibcOverlayShims.h:31:10: error: 'semaphore.h' file not found #include <semaphore.h> ^ <unknown>:0: error: could not build C module 'SwiftOverlayShims' <module-includes>:1:10: note: in file included from <module-includes>:1: #include "../../../../share/wasi-sysroot/include/ctype.h" ^ <module-includes>:1:10: note: in file included from <module-includes>:1: #include "LibcOverlayShims.h" ^[omochi@omochi-iMacPro SwiftDeclWeb]$ swift test --triple wasm32-unknown-wasi --sdk $TOOLCHAIN_PATH/share/wasi-sysroot /Users/omochi/github/omochi/SwiftDeclWeb/Tests/SDWVDOMTests/VDOMTests.swift:1:8: error: could not find module 'XCTest' for target 'wasm32-unknown-wasi'; found: arm64e-apple-ios-macabi, x86_64-apple-ios-macabi, arm64, arm64-apple-macos, x86_64, arm64e-apple-macos, x86_64-apple-macos, arm64-apple-ios-macabi, arm64e import XCTest ^ /Users/omochi/github/omochi/SwiftDeclWeb/Tests/SDWVDOMTests/VDOMTests.swift:1:8: error: could not find module 'XCTest' for target 'wasm32-unknown-wasi'; found: arm64e-apple-ios-macabi, x86_64-apple-ios-macabi, arm64, arm64-apple-macos, x86_64, arm64e-apple-macos, x86_64-apple-macos, arm64-apple-ios-macabi, arm64e import XCTest ^ error: fatalErrorswift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a なんだけど。[omochi@omochi-iMacPro SwiftDeclWeb]$ swift build --triple wasm32-unknown-wasi --sdk $TOOLCHAIN_PATH/share/wasi-sysroot wasm-ld: error: /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/lib/swift_static/wasi/libFoundation.a(NSTimeZone.swift.obj): undefined symbol: CFHash wasm-ld: error: /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/lib/swift_static/wasi/libFoundation.a(NSDate.swift.obj): undefined symbol: _CFDeinit wasm-ld: error: /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/lib/swift_static/wasi/libFoundation.a(NSDate.swift.obj): undefined symbol: CFDateGetTypeID wasm-ld: error: /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/lib/swift_static/wasi/libFoundation.a(NSDate.swift.obj): undefined symbol: CFDateGetTypeID wasm-ld: error: /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/lib/swift_static/wasi/libFoundation.a(NSRegularExpression.swift.obj): undefined symbol: kCFAllocatorSystemDefault[omochi@omochi-iMacPro SwiftDeclWeb]$ tree -L 2 -d $TOOLCHAIN_PATH/share/wasi-sysroot /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/bin/../share/wasi-sysroot ├── include │ ├── arpa │ ├── bits │ ├── c++ │ ├── net │ ├── netinet │ ├── netpacket │ ├── scsi │ ├── sys │ └── wasi ├── lib │ ├── wasm32-wasi │ └── wasm32-wasi-unknown ├── share │ └── wasm32-wasi └── usr └── include 17 directories{ "extra-cc-flags" : [ "-I", "TOOLCHAIN_DIR/usr/lib/swift/wasi/wasm32" ], "extra-cpp-flags" : [ ], "target" : "wasm32-unknown-wasi", "version" : 1, "extra-swiftc-flags" : [ "-I", "TOOLCHAIN_DIR/usr/lib/swift/wasi/wasm32", "-Xlinker", "-lFoundation", "-Xlinker", "-lCoreFoundation", "-Xlinker", "-lBlocksRuntime", "-Xlinker", "-licui18n", "-Xlinker", "-luuid" ], "sdk" : "TOOLCHAIN_DIR/usr/share/wasi-syroot", "toolchain-bin-dir" : "TOOLCHAIN_DIR/usr/bin" }swift build -c debug --build-tests --destination wasm32-unknown-wasi.json--destination オプションに渡す[omochi@omochi-iMacPro SwiftDeclWeb]$ swift build -c debug --build-tests --destination /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/wasm32-unknown-wasi.json wasm-ld: error: /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/lib/swift_static/wasi/libFoundation.a(Data.swift.obj): undefined symbol: _withStackOrHeapBuffer clang-10: error: linker command failed with exit code 1 (use -v to see invocation) error: link command failed with exit code 1 (use -v to see invocation) [16/18] Linking SwiftDeclWebPackageTests.xctest[omochi@omochi-iMacPro wpkg]$ swift package init --type executable Creating executable package: wpkg Creating Package.swift Creating README.md Creating .gitignore Creating Sources/ Creating Sources/wpkg/main.swift Creating Tests/ Creating Tests/LinuxMain.swift Creating Tests/wpkgTests/ Creating Tests/wpkgTests/wpkgTests.swift Creating Tests/wpkgTests/XCTestManifests.swift [omochi@omochi-iMacPro wpkg]$ open . [omochi@omochi-iMacPro wpkg]$ swift build -c debug --build-tests --destination /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/wasm32-unknown-wasi.json /Users/omochi/temp/wpkg/Tests/wpkgTests/wpkgTests.swift:20:23: error: cannot find 'Process' in scope let process = Process() ^~~~~~~ /Users/omochi/temp/wpkg/Tests/wpkgTests/wpkgTests.swift:23:20: error: cannot find 'Pipe' in scope let pipe = Pipe() ^~~~ /Users/omochi/temp/wpkg/Tests/wpkgTests/wpkgTests.swift:44:28: error: value of type 'Bundle' has no member 'bundleURL' return Bundle.main.bundleURL ~~~~~~~~~~~ ^~~~~~~~~ [6/9] Compiling wpkgTests XCTestManifests.swiftimport XCTest final class wpkgTests: XCTestCase { func testExample() throws { XCTAssertTrue(true) } static var allTests = [ ("testExample", testExample), ] }[omochi@omochi-iMacPro wpkg]$ swift build -c debug --build-tests --destination /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/wasm32-unknown-wasi.json wasm-ld: error: /Users/omochi/swift/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a/usr/lib/swift_static/wasi/libFoundation.a(Data.swift.obj): undefined symbol: _withStackOrHeapBuffer clang-10: error: linker command failed with exit code 1 (use -v to see invocation) <unknown>:0: error: link command failed with exit code 1 (use -v to see invocation) [7/8] Linking wpkgPackageTests.xctest$ cat Tests/helloTests/helloTests.swift import XCTest final class helloTests: XCTestCase { func testExample() throws { XCTAssertTrue(true) } static var allTests = [ ("testExample", testExample), ] } $ ~/Downloads/swift-wasm-DEVELOPMENT-SNAPSHOT-2020-10-05-a.xctoolchain/usr/bin/swift build -c debug --build-tests --destination wasm-5.3-SNAPSHOT-2020-09-08-a.json [12/12] Linking helloPackageTests.xctest /var/folders/br/7sr_p7cj7v549x_gtkb33df00000gp/T/tmp.BSZU6PLa $ wasmer ./.build/debug/helloPackageTests.xctest Test Suite 'All tests' started at 2020-10-06 17:24:16.346 Test Suite 'testBundle.xctest' started at 2020-10-06 17:24:16.346 Test Suite 'helloTests' started at 2020-10-06 17:24:16.346 Test Case 'helloTests.testExample' started at 2020-10-06 17:24:16.346 Test Case 'helloTests.testExample' passed (0.0 seconds) Test Suite 'helloTests' passed at 2020-10-06 17:24:16.346 Executed 1 test, with 0 failures (0 unexpected) in 0.0 (0.0) seconds Test Suite 'testBundle.xctest' passed at 2020-10-06 17:24:16.347 Executed 1 test, with 0 failures (0 unexpected) in 0.0 (0.0) seconds Test Suite 'All tests' passed at 2020-10-06 17:24:16.347 Executed 1 test, with 0 failures (0 unexpected) in 0.0 (0.0) seconds.xctoolchain ?[omochi@omochi-iMacPro wpkg]$ swift build -c debug --build-tests --destination /Users/omochi/swift/swift-wasm-5.3-SNAPSHOT-2020-09-08-a/usr/wasm32-unknown-wasi.json wasm-ld: error: /Users/omochi/swift/swift-wasm-5.3-SNAPSHOT-2020-09-08-a/usr/share/wasi-sysroot/lib/wasm32-wasi/libc.a(__original_main.o): undefined symbol: main clang-10: error: linker command failed with exit code 1 (use -v to see invocation) <unknown>:0: error: link command failed with exit code 1 (use -v to see invocation) [8/9] Linking wpkgPackageTests.xctest[omochi@omochi-iMacPro wpkg]$ swift build -c debug --build-tests --destination /Users/omochi/swift/swift-wasm-5.3-SNAPSHOT-2020-10-02-a/usr/wasm32-unknown-wasi.json [12/12] Linking wpkgPackageTests.xctest (edited)[omochi@omochi-iMacPro wpkg]$ wasmer .build/debug/wpkgPackageTests.xctest Test Suite 'All tests' started at 2020-10-06 18:03:44.789 Test Suite 'testBundle.xctest' started at 2020-10-06 18:03:44.790 Test Suite 'wpkgTests' started at 2020-10-06 18:03:44.790 Test Case 'wpkgTests.testExample' started at 2020-10-06 18:03:44.790 Test Case 'wpkgTests.testExample' passed (0.0 seconds) Test Suite 'wpkgTests' passed at 2020-10-06 18:03:44.790 Executed 1 test, with 0 failures (0 unexpected) in 0.0 (0.0) seconds Test Suite 'testBundle.xctest' passed at 2020-10-06 18:03:44.790 Executed 1 test, with 0 failures (0 unexpected) in 0.0 (0.0) seconds Test Suite 'All tests' passed at 2020-10-06 18:03:44.790 Executed 1 test, with 0 failures (0 unexpected) in 0.0 (0.0) seconds.xctoolchainにしてexport TOOLCHAINS="org.swift.…"でツールチェインを切り替える仕組みは、SwiftPMがツールチェイン添付のXCTest.swiftmoduleを使ってくれないから、SwiftWasmには使えないんじゃないかな。 (edited)WebAssembly.instantiate でJS側の関数をWASM環境にいれるやつ// Output stdout and stderr to console const originalWriteSync = wasmFs.fs.writeSync; wasmFs.fs.writeSync = (fd, buffer, offset, length, position) => { const text = new TextDecoder("utf-8").decode(buffer); // Filter out standalone "\n" added by every `print`, `console.log` // always adds its own "\n" on top. if (text !== "\n") { switch (fd) { case 1: console.log(text); break; case 2: console.error(text); break; } } return originalWriteSync(fd, buffer, offset, length, position); };print って Swift.print のこと?Swift.print の末尾の改行が不要なのであれば、 print(str, terminator: "") って呼び出せばよくない?wasmFS.fs.writeSync の先に繋がってる console.log で勝手に改行されて改行が2つになることを気にしてそうなSwift.print("str", terminator: "") ってやっていたとしてもfflush() が呼ばれたら詰む。 (edited)/dev/stdout にファイルとして書き溜めてるだけなのね<pre> タグの中に流し込んでいくとかのほうがマシな挙動だと思う。 f2 = fopen(filename, mode); if (!f2) goto fail; if (f2->fd == f->fd) f2->fd = -1; /* avoid closing in fclose */ #ifdef __wasilibc_unmodified_upstream // WASI has no dup else if (__dup3(f2->fd, f->fd, fl&O_CLOEXEC)<0) goto fail2; #else // WASI doesn't have dup3, but does have a way to renumber // an existing file descriptor. else { if (__wasilibc_fd_renumber(f2->fd, f->fd)<0) goto fail2; f2->fd = -1; /* avoid closing in fclose */ } #endifopen の世界だったら pipe がそうfopen が返す FILE* は 生fd のラッパーpoll_oneoff(in: ConstPointer<subscription>, out: Pointer<event>, nsubscriptions: size) -> (errno, size) Concurrently poll for the occurrence of a set of events.void __wasi_fd_write(...) { // do redirect return original_fd_write(...); } void original_fd_write(...) __attribute__(( __import_module__("wasi_snapshot_preview1"), __import_name__("fd_write") )) (edited)> void __wasi_fd_write(...) { > // do redirect > return original_fd_write(...); > } > void original_fd_write(...) __attribute__(( > __import_module__("wasi_snapshot_preview1"), > __import_name__("fd_write") > )) (edited)__attribute__(( __import_module__("wasi_snapshot_preview1"), __import_name__("fd_write") )) __wasi_fd_write(...) ↑すでにこう書かれたヘッダーがビルドに含まれてるわけでしょ?original_fd_write と、 wasi関数を受け取ろうとしてるやつが2つできちゃうし__wasi_fd_write と 新たに作ろうとしてる、 もうひとつの fd_writeを本当につなぎたい original_fd_write と、__import_name__ は見ていなくて、C的なシンボルでルックアップしています__wasi_fd_write が別途存在すればそれはそこにつながるのか。__wasi_fd_write は実装が無いがユーザーが定義した __wasi_fd_write には実装があるので、この時点で __wasi_fd_write はundefinedなシンボルではなくなります__import_name__ は無視されますoriginal_fd_write は実装が無いのでundefinedなので、__import_name__ に基づいてimportエントリを発行します/dev/stdout を wasi で fopen して poll_oneoff 回せば良いんだ。 this.view.setUint32(nevents, eventc, true); while (bindings.hrtime() < waitEnd) { // nothing } return WASI_ESUCCESS;try とか await は前に書くし、前に書いちゃえば良さそう。 let x = try await jsTry(jsAwait(foo.bar.baz))jsTryAwait があってもいいか。let result = await jsAsync(fetch)("...")fetch は Promise 返すんだから、 await jsAsync(fetch("...")) でも良さそうな気も?JSValue に case error(JSValue) を追加すれば良い?indirect.error がネストしてほしくないから微妙だな・・・。)JSError が既にあるので case error(JSError) にできそうstring を throw したときは String になってるんですっけ?throw できるけど、オブジェクト化されてる可能性もあるのかなと。try { throw 1 } catch(e) { console.log(e) } // 1 (edited)typeof も試してみましたが、オブジェクトになってませんでした。string と出てきました。 <script> try { throw 'error'; } catch(e) { alert(typeof e); } </script>JSError っていうのは throw された値を格納するためのものじゃなくて、 JavaScript の Error に対応してるんですね。enum JSValue { case success(_JSValue) case failure(_JSValue) enum _JSValue { case boolean(Bool) case string(JSString) ... } }enum JSValue { case boolean(Bool) case string(JSString) ... case error(JSErroValue) } enum JSErrorValue { case boolean(Bool) case string(JSString) ... }jsTry がJS関数を受け取るようにすれば内部に隠蔽できるかもしれないthrow されることは普通にありそうな気がします。func jsTry(_ f: JSFunction) -> JSThrowingFunction みたいな?let result: JSValue = ... if case .error(let error) = result { // ... } // or if let error = result.error { // ... }
JSValue にエラー情報を埋め込んじゃって jsTry されたときにエラーを throw するというものだったので JSValue に埋め込まざるを得ませんでしたが、 JSThrowingFunction みたいなものに変換する方式なら JSValue はいじらずに済みそうですね。.throwing みたいに。JSValue に埋め込むなら jsTry と try が必ずセットになるから先頭に戻ってもいいけど、 JSThrowingFunction 方式だとそうは限らないですもんねー。JSThrowingFunction 化してから Swift で取り回すことを考えると、こっちの方がいい気もしますね。毎回 jsTry 噛まさなくてもいいし。let div = document.createElement!("div") これは let createElement = document.createElement.function! createElement("div") thisの扱いが違うんですよね。 (edited)jsTry / jsAwait よりも jsThrows / jsAsync が良さそうですね。this 問題。subscript(dynamicMember name: String) -> ((ConvertibleToJSValue...) -> JSValue)? が呼ばれて、thisがレシーバでバインドされるんですが https://github.com/swiftwasm/JavaScriptKit/blob/4b7981bc1b81a1f25e7aca851866d55913657d61/Sources/JavaScriptKit/FundamentalObjects/JSObject.swift#L34-L40 (edited)JSFunction になってしまって、JSFunctionのcallAsFunctionで実行されるのでthisがバインドされないんですよね https://github.com/swiftwasm/JavaScriptKit/blob/4b7981bc1b81a1f25e7aca851866d55913657d61/Sources/JavaScriptKit/FundamentalObjects/JSFunction.swift#L21 (edited)jsThrows 方式で行くと、レシーバのバインディングができないなと。(ConvertibleToJSValue...) -> JSValue) をjsThrowsの引数に取れば良いのか? (edited)func jsThrows(_: (ConvertibleToJSValue...) -> JSValue)) -> (ConvertibleToJSValue...) throws -> JSValue) func jsThrows(_: JSFunction) -> (ConvertibleToJSValue...) throws -> JSValue)jsAsync も実装できそうでいいですね。throws/try はどうしてるんでしょうね?throws は現状で identifier として使えないですけど、 async は使えてすでに使われてて、そう考えると throws も identifier として使えるようにするという変更があり得て、その上で throws と async を使うことで名前被りを避けることはできない?throws は JS で予約語だから、 throws さえ使えれば foo.throw がいけそう?struct Foo { func foo() async {} func async() {} } (edited)struct A { var `throws`: Int { 1 } } _ = A().throws (edited)throws にしちゃえば解決じゃないですか?a.import a['import'] a = { import: 'test' }.<script> const a = { throws: 'foo', }; console.log(a.throws); </script>var obj = { throws: 1 } これも書けるっぽい。。。 (edited)import のコードは上記ページのものだったんですね。jsThrows で外から被せる方式ですかねthrows はダメだったけど、 JS で使えない identifier にするって方法はないでしょうか?JSObject を @dynamicMemberLookup にするより、直接 JSValue を @dynamicMemberLoopup にして callAsFunction も持たせちゃった方が便利だったりしないでしょうか?どのみち JS 使ってる時点で安全じゃないですし。 (edited)! や .object, .function などを挟まないといけないのが気になってます。JSValue にメンバを生やさないで済むのならシャドーイングは問題にならないですか?jsTry とかと合わせるなら関数か static メソッド/プロパティにしちゃって、インスタンスメソッド/プロパティは @dynamicMemberLookup と callAsFunction のものという切り分けにできるなら、シャドーイングも避けられて切り分けも明快かなと。 (edited)JS. とかがあってもいいかもですね。JS.throws, JS.async
2swift-latest.xctoolchainではなくswift-latestになってる。swift-DEVELOPMENT-SNAPSHOT-2020-10-24-a-osx.pkgに入ってるpostinstallはこんな感じ。 #!/bin/bash INSTALLED_TOOLCHAIN=$2 rm -f "${INSTALLED_TOOLCHAIN%/*}/swift-latest.xctoolchain" ln -fs "${INSTALLED_TOOLCHAIN}" "${INSTALLED_TOOLCHAIN%/*}/swift-latest.xctoolchain" (edited).pkg作成を確認しようとしたら https://ci.swift.org 落ちてるぽい。 (edited)swift/utils/toolchain-installerは使ってないと思われる。 https://ci.swift.org/view/Packages/job/oss-swift-package-osx/5218/$ echo 'print("hello")'|swiftc -target wasm32-unknown-wasi - <unknown>:0: error: unable to load standard library for target 'wasm32-unknown-wasi'ghcr.io/swiftwasm/swift:latestのダウンロードが遅い…$ llc --version LLVM (http://llvm.org/): LLVM version 11.0.0 Optimized build. Default target: x86_64-apple-darwin19.6.0 Host CPU: skylake-avx512 Registered Targets: aarch64 - AArch64 (little endian) aarch64_32 - AArch64 (little endian ILP32) aarch64_be - AArch64 (big endian) ...$ echo 'print("hello")'|xcrun --toolchain org.swift.50320190830a swiftc -target arm64-apple-macos10.9 - -o /dev/null <unknown>:0: error: unable to load standard library for target 'arm64-apple-macos10.9' $ echo 'print("hello")'|xcrun --toolchain org.swift.531202011121a swiftc -target arm64-apple-macos10.9 - -o /dev/null で、同様にWasmをチェックしてみるとエラーになった。 $ echo 'print("hello")'|xcrun --toolchain org.swiftwasm.20201102 swiftc -target wasm32-unknown-wasi - -o /dev/null wasm-ld: error: cannot open crt1.o: No such file or directory wasm-ld: error: unable to find library -ldl wasm-ld: error: unable to find library -lc++ wasm-ld: error: unable to find library -lc++abi wasm-ld: error: unable to find library -lm wasm-ld: error: unable to find library -lwasi-emulated-mman wasm-ld: error: unable to find library -lc clang-10: error: linker command failed with exit code 1 (use -v to see invocation) <unknown>:0: error: link command failed with exit code 1 (use -v to see invocation) docker版はエラーにならない。 $ echo 'print("hello")'|docker run ghcr.io/swiftwasm/swift swiftc -target wasm32-unknown-wasi - -o /dev/null (edited)xcrunを使う方法は使えないということ?swiftcを使ったのは、swiftだとビルドに成功しても実行に失敗するから。.pkgによるswift-latest.xctoolchainシンボリックリンクの作成、既にシンボリックリンクが存在するとシンボリックリンクが指す先に新しいシンボリックリンクを作ってしまう。 https://github.com/swiftwasm/swift/blob/swiftwasm/utils/darwin-installer-scripts/postinstall#L16 これを避けるためにln -fhs …とかに変えるべき。 wasi_snapshot_preview1 モジュールの関数一式をimportしたがるwasmファイルが生成されるのですが、これって外せないのでしょうかね?Any trait, which enables dynamic typing of any 'static type through runtime reflection.wasmtime hello.wasm っていう形で動かせるんですね。
1release() は手動か〜となって、周辺コードみてたら発見しましたvar dic: [Int: CInt] = [0: 42] func getValue() -> CInt { dic[0] ?? -1 } この関数の返り値が-1 か 42 のランダムになるっていう不思議現象に遭遇したのですが、何か原因に心当たりありますか? 簡単な再現手順も用意しました https://github.com/sidepelican/SwiftWasmDicIssueSWIFT_DETERMINISTIC_HASHING=1でハッシュのシード固定して再現するか見てもらえますか?❯ swiftc -target wasm32-unknown-wasi Lib.swift -o Lib.wasm -Xlinker --export=get_value -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor <unknown>:0: error: unknown argument: '-Xswiftc' <unknown>:0: error: unknown argument: '-mexec-model=reactor'-Xswiftc を削って大丈夫ですー (edited)-Xclang-linker -mexec-model=reactor 足したら _start がいなくなってしまった_initialize を代わりに。_startじゃないと許してくれないっぽいですね_startくれって怒られちゃうんですよね-1 が返りますねw42 になりました.c経由して -Xlinker オプション使わずにexportしてても大丈夫?)_startのはずか_initializeにはmain入ってないからそうではないかcall 27 block (result i32) ;; label = @1 global.get 0 ... こういう呼び出しがあって (edited)(func (;27;) (type 20) (local i32 i32 i32 i32 i32 i32 i32 i32 i32 i64 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i64 f64) こう定義されてて、 type 20は(type (;20;) (func)) だったのでこれ関数型なのかな?とTSCUtility/Triple.swift:252: Fatal error: WebAssembly/WASI doesn't support dynamic library yetいわれるようになった・・・.dynamic なときも巻き込まれクラッシュするのが防げるという意味でした)stdio.h が見つからないという不可解なエラーが出ました。 [0/3] Compiling CWasmCallableKit XcodeSupport.c 836 In file included from /home/runner/work/CodableToTypeScript/CodableToTypeScript/demo/.build/checkouts/WasmCallableKit/Sources/CWasmCallableKit/CWasmCallableKit.c:1: 837 /home/runner/work/CodableToTypeScript/CodableToTypeScript/demo/.build/checkouts/WasmCallableKit/Sources/CWasmCallableKit/include/CWasmCallableKit.h:4:10: fatal error: 'stdio.h' file not found 838 #include <stdio.h> 839 ^~~~~~~~~/usr/include に stdio.h があることは確認できているので、+ which -a swift 98 /usr/local/bin/swift 99 + swift --version 100 Swift version 5.7.2 (swift-5.7.2-RELEASE) 101 Target: x86_64-unknown-linux-gnu+ which -a swift 392 /usr/local/bin/swift 393 /usr/bin/swift 394 + swift --version 395 /bin/swift 396 Swift version 5.7.2 (swift-5.7.2-RELEASE) 397 Target: x86_64-unknown-linux-gnu/usr/local/bin にあるのでそっちが使われてしまっていました・・・ 最初から入っていたのか〜/usr/bin に入れないで、別のところに置いてPATH通せばいいだけかtoolchainPath/usr/bin にインストールして addPath してるから自作したやつと原理は同じっぽいなllvm::compression namespaceLLVM_ENABLE_ZSTD with behavior mirroring that of LLVM_ENABLE_ZLIB
4
3preset=buildbot_linux_crosscompile_wasm @swift-ci Please test with preset Linux Platform と詠唱しないといけなかったのが楽になった
1
1Package.swift 内で wasm32-unknown-wasi 向けのビルド時だけ分岐させる方法をご存知の方がいればお聞きしたいです.(beginner-help でやるべき話かもしれないですが) 単純に #if os(WASI) だとうまくいかないですし,やりたいのが cSettings の .define を wasm32-unknown-wasi 以外の時だけ指定させたいので .define("HOGE", .when(platforms: [.wasi 以外を全部列挙])) みたいなのも試したんですが,.wasi 以外を全部列挙しないといけないのが微妙で....define("CMARK_THREADING", to: "0", .when(platforms: [.wasi])) で上書きすればいけるような気もしてきました.Foundation.URL.init(filePath:) のような新しいAPIは、 macOS 13以上、iOS16以上で提供されるわけですが、 こういった呼び出しが含まれるライブラリを持っていたとして、 SwiftPMにvisionOSが追加されたタイミングで、 「このAPIがvisionOSではいつから利用できるのか?」を調べて下限バージョンとして宣言するまでは、 このライブラリはvisionOSでは使えない、というのがデフォルト状態で正しいと思います。 (edited)condition: .when(platforms: [...]) とかの platforms のことじゃなくてもしかして .package の platforms の話をされてますか?そっちは .linux とかその辺がそもそも指定できないのでまた話が変わってくると思います..linux が書けるのに、 Package.platforms は宣言なしでlinuxが使えることになってますね。error: 'hoge': Invalid manifest (compiled with: ["/home/kebo/.local/share/swiftly/toolchains/main-snapshot-2024-03-01/usr/bin/swiftc", "-vfsoverlay", "/tmp/TemporaryDirectory.NMzSPB/vfs.yaml", "-L", "/home/kebo/.local/share/swiftly/toolchains/main-snapshot-2024-03-01/usr/lib/swift/pm/ManifestAPI", "-lPackageDescription", "-Xlinker", "-rpath", "-Xlinker", "/home/kebo/.local/share/swiftly/toolchains/main-snapshot-2024-03-01/usr/lib/swift/pm/ManifestAPI", "-swift-version", "5", "-I", "/home/kebo/.local/share/swiftly/toolchains/main-snapshot-2024-03-01/usr/lib/swift/pm/ManifestAPI", "-package-description-version", "6.0.0", "/home/kebo/hoge/Package.swift", "-Xfrontend", "-disable-implicit-concurrency-module-import", "-Xfrontend", "-disable-implicit-string-processing-module-import", "-o", "/tmp/TemporaryDirectory.OgHbDE/hoge-manifest"]) /home/kebo/hoge/Package.swift:8:18: error: type 'SupportedPlatform' has no member 'linux' 6 │ let package = Package( 7 │ name: "hoge", 8 │ platforms: [.linux], │ ╰─ error: type 'SupportedPlatform' has no member 'linux' 9 │ targets: [ 10 │ // Targets are the basic building blocks of a package, defining a module or a test suite.
1StaticMemberIterable がstdlibに入るのであれば一番楽だけどなかなか長そう❯ swift build --target FoundationEssentials --experimental-swift-sdk 5.9.2-RELEASE-wasm Building for debugging... /Users/iceman/Downloads/swift-foundation-main/.build/checkouts/swift-syntax/Sources/SwiftCompilerPlugin/CompilerPlugin.swift:103:19: error: cannot find 'dup' in scope let inputFD = dup(fileno(stdin)) ^~~ /Users/iceman/Downloads/swift-foundation-main/.build/checkouts/swift-syntax/Sources/SwiftCompilerPlugin/CompilerPlugin.swift:117:20: error: cannot find 'dup' in scope let outputFD = dup(fileno(stdout)) ^~~ /Users/iceman/Downloads/swift-foundation-main/.build/checkouts/swift-syntax/Sources/SwiftCompilerPlugin/CompilerPlugin.swift:124:11: error: cannot find 'dup2' in scope guard dup2(fileno(stderr), fileno(stdout)) >= 0 else { ^~~~❯ docker run -it --rm -v $(pwd):/$(basename $(pwd)) -t swift:5.9 /bin/bash root@5aaf21fbf0d1:/# swift experimental-sdk install https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip Swift SDK bundle successfully downloaded from `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip`. swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip is assumed to be an archive, unpacking... Swift SDK bundle at `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip` successfully installed. root@5aaf21fbf0d1:/# swift experimental-sdk list 5.9.2-RELEASE-wasm
❯ docker run -it --rm -v $(pwd):/$(basename $(pwd)) -t swift:5.10 /bin/bash root@59c43fdac52e:/# swift experimental-sdk install https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip Downloading a Swift SDK bundle archive from `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip`... Swift SDK bundle archive successfully downloaded from `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip`. Swift SDK bundle at `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip` is assumed to be an archive, unpacking... Error: gzip: stdin has more than one entry--rest ignored tar: Child returned status 2 tar: Error is not recoverable: exiting now❯ docker run -it --rm -v $(pwd):/$(basename $(pwd)) -t swift:5.9 /bin/bash root@5aaf21fbf0d1:/# swift experimental-sdk install https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip Swift SDK bundle successfully downloaded from `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip`. swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip is assumed to be an archive, unpacking... Swift SDK bundle at `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip` successfully installed. root@5aaf21fbf0d1:/# swift experimental-sdk list 5.9.2-RELEASE-wasm
❯ docker run -it --rm -v $(pwd):/$(basename $(pwd)) -t swift:5.10 /bin/bash root@59c43fdac52e:/# swift experimental-sdk install https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip Downloading a Swift SDK bundle archive from `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip`... Swift SDK bundle archive successfully downloaded from `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip`. Swift SDK bundle at `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-ubuntu22.04_x86_64.artifactbundle.zip` is assumed to be an archive, unpacking... Error: gzip: stdin has more than one entry--rest ignored tar: Child returned status 2 tar: Error is not recoverable: exiting now ❯ swift build --target FoundationEssentials --experimental-swift-sdk 5.9.2-RELEASE-wasm Building for debugging... /Users/iceman/Downloads/swift-foundation-main/.build/checkouts/swift-syntax/Sources/SwiftCompilerPlugin/CompilerPlugin.swift:103:19: error: cannot find 'dup' in scope let inputFD = dup(fileno(stdin)) ^~~ /Users/iceman/Downloads/swift-foundation-main/.build/checkouts/swift-syntax/Sources/SwiftCompilerPlugin/CompilerPlugin.swift:117:20: error: cannot find 'dup' in scope let outputFD = dup(fileno(stdout)) ^~~ /Users/iceman/Downloads/swift-foundation-main/.build/checkouts/swift-syntax/Sources/SwiftCompilerPlugin/CompilerPlugin.swift:124:11: error: cannot find 'dup2' in scope guard dup2(fileno(stderr), fileno(stdout)) >= 0 else { ^~~~ Clean (debug) + WasmKit > Clean (debug) + SwiftSyntax になってるのはWasmKit自体のデバッグビルドがSwiftSyntaxのビルドより時間かかってるということ何だと思います (edited)struct MyApp: ReactComponent { func render() -> ReactNode { h.div { h.h1 { "Hello My App" } h.p { "hello" } } } } SwiftにReactを提供するとしたらどんなAPIがいいんだろう HTML部分は Result Builder が便利だとは思うが、 div みたいな小文字キーワードを大量にネームスペースにばら撒くのは良くないと思ってて、 グローバルな h. にぶら下げたらマシかなあ (HTMLのh)condition: .when(platforms: [...])が使えます.object! とかで死んだら、どこかに何か出る?.wasm ファイルの中にsourcemapが埋め込まれてるの?public extension JSValue { /// An unsafe convenience method of `JSObject.subscript(_ name: String) -> ((ConvertibleToJSValue...) -> JSValue)?` /// - Precondition: `self` must be a JavaScript Object and specified member should be a callable object. subscript(dynamicMember name: String) -> ((ConvertibleToJSValue...) -> JSValue) { object![dynamicMember: name]! } これなんだけど、このsubscriptから返ってくる関数に @discardableResult 付ける方法ないよねえ?JSFunction が存在していたので、 クロージャからそれに置き換えるだけでよかった() が付いてることを起点に、dynamicMember subscriptをオーバーロードするの、テクいなあ@_disfavoredOverload ついてるからこれでクリアしたのかと思った_disfavoredOverload に慎重な傾向を感じる_disfavoredOverloadつけている_disfavoredOverloadにもランク付けをしたい<T: P1> と、 <T: P2> の2つのオーバーロードとは別に <T: P1 & P2> のオーバーロードを用意して、その中の実装で <T: P2> 版に転送すればいいですよpublic final class JSFunction { public convenience init< S: JSNativeObject, A0: ConstructibleFromJSValue, A1: ConstructibleFromJSValue >( _ selector: @escaping (S) -> (A0, A1) -> Void ) where A0.Constructed == A0, A1.Constructed == A1 { let impl = { (this: JSObject?, arguments: [JSValue]) -> JSValue in selector(this!.native as! S)( A0.construct(from: arguments[0])!, A1.construct(from: arguments[1])! ) return .undefined } print(S.self, A0.self, A1.self) self.init(impl: impl) } }public class WebNode { public func insertBefore(_ node: WebNode, _ ref: WebNode?) public func _get_property(_ name: String) -> JSValue { switch name { case "childNodes": childNodes.jsValue case "firstChild": firstChild.jsValue case "nextSibling": nextSibling.jsValue case "parentNode": parentNode.jsValue case "description": description.jsValue case "appendChild": JSFunction(Self.appendChild).jsValue case "insertBefore": JSFunction(Self.insertBefore).jsValue case "remove": JSFunction(Self.remove).jsValue case "removeChild": JSFunction(Self.removeChild).jsValue default: .undefined } } }(WebNode) -> (WebNode, WebNode?) -> Void がマッチしてS == WebNode, A0 == WebNode, A1 == WebNode? と解決されると思ったがS == WebNode, A0 == WebNode, A1 == WebNode と解決されてしまったA1 == WebNode として解決していても、 実際に渡すクロージャは (WebNode, WebNode?) -> Void で広く受けてるから問題ない、理論的には間違ってないA1 == WebNode? になってることだからnil がくると実行時クラッシュするextension Optional: ConvertibleToJSValue where Wrapped: ConvertibleToJSValue { public var jsValue: JSValue { self.map { $0.jsValue } ?? .null } }func foo<S, A0>(_ fn: (S) -> (A0) -> Void) { print(type(of: fn)) } struct Z { func method(_ arg: Int?) {} } foo(Z.method) // (Z) -> (Optional<Int>) -> () シンプルなコードだと望ましい挙動になるな。深いぞこれ・・・JSFunction(WebNode.insertBefore) であってますかねself が WebHTMLElement になっているから、 動的に確認すると (WebHTMLElement) -> (WebNode, WebNode?) -> Void を渡してる 静的にはコンパイル時に S = WebNode, A0 = WebNode, A1 = WebNode になっとるfunc foo<S, A0: CustomStringConvertible, B0: CustomStringConvertible>(_ fn: (S) -> (A0, B0) -> Void) { print(type(of: fn)) } struct Z { func method(_ arg1: Int, _ arg2: Int?) {} } foo(Z.method) 再現したよpublic protocol ConstructibleFromJSValue { associatedtype Constructed = Self static func construct(from value: JSValue) -> Constructed? } このassociatedtypeも関係あるかなあpublic protocol ConstructibleFromJSValue { associatedtype Constructed = Self static func construct(from value: JSValue) -> Constructed? } extension Optional: ConstructibleFromJSValue where Wrapped: ConstructibleFromJSValue { public static func construct(from value: JSValue) -> Wrapped.Constructed? { switch value { case .null, .undefined: return nil default: return Wrapped.construct(from: value) } } }case .null, .undefined: は .some(nil) を返したい?JSObject が ConstructibleFromJSValue に準拠できないんだよね public static func construct(from value: JSValue) -> Self? { value.object as? Self } これでいいんだねJSFunction のケースがあるんで case .object: と case .function:の両方のケースをここでチェックする必要があるんではないかな.object のなかの JSObject が 実際には JSFunction の可能性があるけど (edited)JSFunction を JSObject のサブクラスにしたのは相当後悔してる.object の中身が 実際にはJSFunctionの可能性はないですね.object の中身が 実際にはJSFunctionの可能性はないですね typeof objが function を返してくれるんでcase function が存在するのは問題ないのかclass MyFunc: JSFunction とやってから .object(MyFunc()) が通っちゃう。JSValue を enum にしたのがなぁJSObject(id: JavaScriptObjectRef) これに実際には function の値を渡す可能性はあるのか?JSObject(id: JavaScriptObjectRef) これに実際には function の値を渡す可能性はあるのか? .object(MyFunc()) これをやっても、 MyFunc の .jsValue は JSFunction のところでoverride されてるから、 .jsValue を使えば大丈夫か。 (edited)JSValue.object(function) が作れてしまうところだけではないかな。JSFunction から JSValue を作る場合普通の人は .jsValue を使うので問題が顕在化しないcase JSValue.object を呼び出した時に、内部でJS側の実体を調べて、 functionだったら case function になれば穴はなさそうだけど enum case constructor だからそういうフックが書けないのがダメなのか?case _object とかにして static func object() にしたら避けられるけど、switch-caseしたときにダサい名前が出てくるし・・・public enum にしたの本当にまずかったstatic funcで同名のオーバーロードを生やしつつそれをunavailableにマークすると一応できるんだけど、厳しすぎる…enum E { case c(Int) @available(*, unavailable) static func c(_: Int) -> E { fatalError() } } func check(e: E) { switch e { case .c(_): break } }enum E { case c(Int) @available(*, unavailable) static func c(_: Int) -> E { fatalError() } } func check(e: E) { switch e { case .c(_): break } } <stdin>:3:42: error: invalid redeclaration of 'c' 1 │ enum E { 2 │ case c(Int) 3 │ @available(*, unavailable) static func c(_: Int) -> E { fatalError() } │ ╰─ error: invalid redeclaration of 'c' 4 │ } 5 │ enum JSValue.Switcher とかにしておいて、 APIは struct JSValue で全部通す、とかかな。 var JSValue.switcher: JSValue.Switcher { get } (edited)switch foo.jsValue.switcher って書かないといけないのはダサいねw。JSFunction のケースがあるんで case .object: と case .function:の両方のケースをここでチェックする必要があるんではないかな public static func construct(from value: JSValue) -> Self? { switch value { case .object(let x): return x as? Self case .function(let x): return x as? Self default: return nil } }as? が不安になるんだけど考え中case .bigInt も必要だJSObject.construct に .object が渡る → as? JSObject でok 2. JSObject.construct に .function が渡る → x: JSFunction で取り出して as? JSObject は成功するから、動的にJSFunctionな静的なJSObjectが返る 3. JSFunction.construct に .object が渡る → x: JSObject で取り出して as? JSFunction に失敗して nil 4. JSFunction.construct に .function が渡る→ x: JSFunction で取り出して as? JSFunction で OK.jsValue を使う限り問題なし 3はダウンキャストの失敗だから失敗でok (edited)public final class JSBigInt: JSObject {JavaScript において、関数は第一級オブジェクトです。すなわち、関数はオブジェクトであり、他のあらゆるオブジェクトと同じように操作したり渡したりすることができます。具体的には、関数は Function オブジェクトです。const i = 1; i.__proto__; // Numbercase number(Double) になってると書き戻すときにNaNビットが変わる可能性があるのでUInt64のビットパターンで保持すべきだstruct JSString と同じように struct JSSymbol にしたら問題ある?JavaScriptObjectRef になってればSwift側でみた同値性をJS側でみた同一性で実装できる (edited)RawJSValue の時点では既にそういう表現になっているので問題はSwift API上での継承関係だなpublic struct JSHTMLElement: CustomStringConvertible { public init(jsObject: JSObject) { self.jsObject = jsObject } public let jsObject: JSObject public var jsValue: JSValue { .object(jsObject) } public func asNode() -> JSNode { JSNode(jsObject: jsObject) } } public struct JSNode: Equatable & Hashable & CustomStringConvertible { public init(jsObject: JSObject) { self.jsObject = jsObject } public let jsObject: JSObject public var jsValue: JSValue { .object(jsObject) } public func asHTMLElement() -> JSHTMLElement? { if jsObject.isInstanceOf(JSWindow.global.HTMLElement) { return JSHTMLElement(jsObject: jsObject) } else { return nil } } public func asText() -> JSText? { if jsObject.isInstanceOf(JSWindow.global.Text) { return JSText(jsObject: jsObject) } else { return nil } } }JSNode をコンストラクトするときに、値の真の型に応じたサブクラスで包むのが難しい(厳密にやろうとするとサブクラスが200種類とかある) (edited)JSValue」とどう違うの?JSObjectだけがあってJSなんちゃらクラスは存在しないJSObject に生えてるto_i, to_sとかを使う。root.render は ブラウザでも動くはずw$ swift build --triple wasm32-unknown-none-wasm -c release --product swift-audio ↑ -c release があるとビルドできる ないとできないerror: compile command failed due to signal 6 (use -v to see invocation) Assertion failed: (!f->isGeneric()), function addLazyFunction, file GenDecl.cpp, line 1589. Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the crash backtrace.dlmalloc が入ってるけどどこにも #include <malloc.h> がないposix_memalignシンボルを参照してるだけなんでユーザコードはdlmalloc直接使わないですね// dlmalloc.c int posix_memalign(void **memptr, size_t alignment, size_t size) { return dlposix_memalign(memptr, alignment, size); } これか.vult ファイルはビルドと関係なくて、生成された C++ ソースと一緒にコミットされてるだけかな@_extern(wasm) を使うアプローチなんだなconst { instance } = await WebAssembly.instantiateStreaming( fetch('.build/wasm32-unknown-none-wasm/release/swift-audio.wasm'), { ...importsObject, } ); instance.exports.main();instance のなかで継続してるのかな?@_expose(wasm, "onClick") func onClick { ... } みたいなことをやってinstance.onClick() とやればdimalloc/include/wasi_api.h はどこからきたんだ・・・wasi_api.h でめっちゃ色々書いてるけど、ほとんど使ってなさそうなswift build --triple wasm32-unknown-none-wasm -c release --product swift-audio-wasm なくても伝わりそうwasm32 って最初に言ってるし[omochi@omochi-mbp swift-for-wasm-examples (main =)]$ swift build --triple wasm32-unknown-none -c release --product swift-audio Building for production... error: emit-module command failed with exit code 1 (use -v to see invocation) <unknown>:0: error: could not find module 'Swift' for target 'wasm32-unknown-none'; found: riscv32-none-none-eabi, riscv64-none-none-eabi, i686-unknown-none-elf, armv7-apple-none-macho, armv6m-none-none-eabi, aarch64-none-none-elf, wasm64-unknown-none-wasm, arm64-apple-macos, i686-unknown-windows-msvc, x86_64-unknown-none-elf, x86_64-unknown-windows-msvc, arm64-apple-none-macho, armv7-none-none-eabi, armv7em-none-none-eabi, arm64e-apple-macos, x86_64-apple-macos, armv6-apple-none-macho, armv6m-apple-none-macho, wasm32-unknown-none-wasm, armv7em-apple-none-macho, armv6-none-none-eabi, at: /Users/omochi/Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2024-04-02-a.xctoolchain/usr/lib/swift/embedded/Swift.swiftmodule <unknown>:0: error: could not find module 'Swift' for target 'wasm32-unknown-none'; found: riscv32-none-none-eabi, riscv64-none-none-eabi, i686-unknown-none-elf, armv7-apple-none-macho, armv6m-none-none-eabi, aarch64-none-none-elf, wasm64-unknown-none-wasm, arm64-apple-macos, i686-unknown-windows-msvc, x86_64-unknown-none-elf, x86_64-unknown-windows-msvc, arm64-apple-none-macho, armv7-none-none-eabi, armv7em-none-none-eabi, arm64e-apple-macos, x86_64-apple-macos, armv6-apple-none-macho, armv6m-apple-none-macho, wasm32-unknown-none-wasm, armv7em-apple-none-macho, armv6-none-none-eabi, at: /Users/omochi/Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2024-04-02-a.xctoolchain/usr/lib/swift/embedded/Swift.swiftmodulewasm64-unknown-none-wasm wasm32-unknown-none-wasm ↑foundの中にはこの2つがあるな (edited)riscv32-none-none-eabi riscv64-none-none-eabi i686-unknown-none-elf armv7-apple-none-macho armv6m-none-none-eabi aarch64-none-none-elf wasm64-unknown-none-wasm arm64-apple-macos i686-unknown-windows-msvc x86_64-unknown-none-elf x86_64-unknown-windows-msvc arm64-apple-none-macho armv7-none-none-eabi armv7em-none-none-eabi arm64e-apple-macos x86_64-apple-macos armv6-apple-none-macho armv6m-apple-none-macho wasm32-unknown-none-wasm armv7em-apple-none-macho armv6-none-none-eabi/* Symbol marking the end of data, bss and explicit stack, provided by wasm-ld. */ extern char __heap_base; extern char __heap_end;__heap_base と __heap_end をリンクしてくれる、というのが、errno.c とかは別のディレクトリにおいてあるやつをかき集めてきたのか (edited)heap_end で全部あるわけじゃなくて、 /* Get memory from system using MORECORE or MMAP */ static void* sys_alloc(mstate m, size_t nb) { uintptr_t old = __builtin_wasm_memory_grow(0, (uintptr_t)increment / PAGESIZE);wasm_memory_grow が sbrk の実装になっててsbrk が MORECORE の実装になってるっぽいな #define MORECORE_DEFAULT sbrksys_alloc → malloc って感じで libc らしくなるのかsbrk のなかで sys_brk を呼んでいて、 それが return (void *)my_syscall1(__NR_brk, addr); している https://github.com/torvalds/linux/blob/3e92c1e6cd876754b64d1998ec0a01800ed954a6/tools/include/nolibc/sys.h#L87my_syscall はアセンブリを出すマクロになってる、これがシステムコールABIなのかwasi-libc は(LinuxのようなOSと比べると)小さいからこういうのがわかっていいな (edited)__builtin_wasm_memory_grow は関数としてリンクするんじゃなくてswift package cmd じゃなかったっけ? .executableTarget( name: "carton", dependencies: [ "SwiftToolchain", "CartonHelpers", ] ),carton って命名の由来ってどっかに説明ある?swift-tools-version バージョンチェックで死ぬのが直らない? (edited) --headless When running browser tests, run the browser in headless mode おーLaunch WebDriver executable: /System/Cryptexes/App/usr/bin/safaridriver Error: httpError("{\"value\":{\"error\":\"session not created\",\"message\":\"Could not create a session: You must enable the \'Allow Remote Automation\' option in Safari\'s Develop menu to control Safari via WebDriver.\",\"stacktrace\":\"\"}}") error: Plugin ended with exit code 1Error: bind(descriptor:ptr:bytes:): Address already in use (errno: 48) error: Plugin ended with exit code 1Error: bind(descriptor:ptr:bytes:): Address already in use (errno: 48) error: Plugin ended with exit code 1 - checking WebDriver endpoint: WEBDRIVER_REMOTE_URL - checking WebDriver executable: WEBDRIVER_PATH - checking WebDriver executable in PATH: chromedriver, geckodriver, safaridriver, msedgedriver Launch WebDriver executable: /System/Cryptexes/App/usr/bin/safaridriver Error: httpError("") error: Plugin ended with exit code 1- checking WebDriver executable in PATH: chromedriver, geckodriver, safaridriver, msedgedriverfor i in $(seq 1 100); do echo "$i'th try...."; swift run carton test --environment browser --headless; donekillall safaridriverとSafari.appのquiteで復活したcarton dev とか carton test が、 ツールチェインの選択とか、ビルドするときに走らせてるswiftのビルドコマンドがどうなってるかって、 どこでわかったり、コントロールできる?killall safaridriverとSafari.appのquiteで復活した swift package コマンドを swift package --verboseに変えて実行すると詳細なログ出てきますwebpack.config.js とか vite.config.js tsconfig.json みたいなものはないの?$ swift run carton bundle After stripping debug info the main binary size is 20.80 MB Running... wasm-opt -Os --enable-bulk-memory /Users/omochi/work/swiftwasm/MyApp/Bundle/main.wasm -o /Users/omochi/work/swiftwasm/MyApp/Bundle/main.wasm Process failed and produced following output: Warning: wasm-opt failed to optimize the binary, falling back to the original binary. If you don't have wasm-opt installed, you can install wasm-opt by running `brew install binaryen`, `apt-get install binaryen` or `npm install -g binaryen` Copying resources to /Users/omochi/work/swiftwasm/MyApp/Bundle/JavaScriptKit_JavaScriptKit.resources Bundle generation finished successfully could not find executable for 'wasm-opt' /** Infer `swift` binary path matching a given version if any is present, or infer the version from the `.swift-version` file. If neither version is installed, download it. */ public func inferSwiftPath( from versionSpec: String? = nil, _ terminal: InteractiveWriter ) async throws -> (AbsolutePath, String) { この辺だなVapor.Application が消えて、生の channel が生えてる。 (edited) let response: StaticResponse do { switch head.uri { case "/": response = try respondIndexPage(context: context) case "/main.wasm": response = StaticResponse( contentType: "application/wasm", body: try context.channel.allocator.buffer( bytes: localFileSystem.readFileContents(configuration.mainWasmPath).contents ) ) default: guard let staticResponse = try self.respond(context: context, head: head) else { self.respond404(context: context) return } response = staticResponse } } catch { configuration.logger.error("Failed to respond to \(head.uri): \(error)") response = StaticResponse( contentType: "text/plain", body: context.channel.allocator.buffer(string: "Internal server error") ) } self.responseBody = response.body ルーティングwentrypoint/bundle.js を加工して埋めてるわけじゃない?carton/package.json が居るのかimport ReconnectingWebSocket from "reconnecting-websocket"; // Base64 is not an efficient way, but too long byte array literal breaks type-checker let hashesFileContent = """ import CartonHelpers \(hashes.map { """ public let \($0)EntrypointSHA256 = ByteString([ \(arrayString(from: $1)) ]) """ }.joined(separator: "\n\n")) public let staticArchiveContents = "\(staticArchiveContents.withData { $0.base64EncodedString() })" """entrypoint/*.js に更新があったら開発者がコード生成してそのファイル更新するというとんでもない運用./Bundle に書き出すstaticArchiveContents はわかったぞ (edited)devEntrypointSHA256 は・・・? let staticArchiveContents = try localFileSystem.readFileContents( AbsolutePath( validating: "static.zip", relativeTo: localFileSystem.currentWorkingDirectory! ))staticArchiveContents に入ってて解凍して出てくる dev.js のハッシュをチェックする? (edited)$ shasum -a 256 dev.js a8967c30e28b7a862c3548beedd9c62ee742a564bc373893154c45d98bafe4c9 dev.js
public let devEntrypointSHA256 = ByteString([ 0xA8, 0x96, 0x7C, 0x30, 0xE2, 0x8B, 0x7A, 0x86, 0x2C, 0x35, 0x48, 0xBE, 0xED, 0xD9, 0xC6, 0x2E, 0xE7, 0x42, 0xA5, 0x64, 0xBC, 0x37, 0x38, 0x93, 0x15, 0x4C, 0x45, 0xD9, 0x8B, 0xAF, 0xE4, 0xC9 ])carton-release パッケージに入ってることに気付くのが遅かった。。index.html を置き換える、ぐらいしか多分カスタムがないから (edited)./Bundle/index.mjsがこんな感じになってると良いのかな import { SwiftRuntime } from "./JavaScriptKit_resource/index.mjs" export function init() { const importObject = { javascriptkit: SwiftRuntime.importObjects } const { instance } = await WebAssembly.instantiate(..., importObject) return instance.exports }#[wasm-bindgen]はマクロになっていて@_extern(wasm) てきなものになるWebAssembly.instantiate に alert を渡すJSグルーコードを生成する (edited)alert とかは JSのグローバルネームスペースが前提になってる?WebAssembly.instantiate に alert を渡すJSグルーコードを生成する (edited).wasm からメタデータを取り出すのちょっと面白いな./Bundle/index.mjsがこんな感じになってると良いのかな import { SwiftRuntime } from "./JavaScriptKit_resource/index.mjs" export function init() { const importObject = { javascriptkit: SwiftRuntime.importObjects } const { instance } = await WebAssembly.instantiate(..., importObject) return instance.exports } main で dispatchMain に自分で突入する?common.js がライブラリっぽくなっているねswift tool -p wasm-opt // パスが出る swift tool wasm-opt wasm-opt コマンドの代わりxcrun とかでもうそういう仕組みがあるか[omochi@omochi-mbp Toolchains]$ ls -al total 0 drwxr-xr-x 5 omochi staff 160 4 3 23:28 . drwxr-xr-x 8 omochi staff 256 4 3 20:52 .. drwxr-xr-x 7 omochi staff 224 4 3 20:52 swift-DEVELOPMENT-SNAPSHOT-2024-04-02-a.xctoolchain lrwxr-xr-x 1 omochi staff 79 4 3 23:28 swift-latest.xctoolchain -> /Users/omochi/Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain drwxr-xr-x 7 omochi staff 224 4 3 23:28 swift-wasm-5.9.2-RELEASE.xctoolchainswift-latest の向き先を変更された気がするcondition: .when(platforms: []) は、SwiftPMレベルでは、 条件なし と 空の条件が区別されるようになっているので、 空の条件 => いかなるOSでも false と設定できるような雰囲気があるが (edited)condition: .when(platforms: []) は、SwiftPMレベルでは、 条件なし と 空の条件が区別されるようになっているので、 空の条件 => いかなるOSでも false と設定できるような雰囲気があるが (edited) assignment.conditions = self.buildConditions(from: setting.condition) この左辺の型は non optional で区別できてなさそうなんだよねfalse」をしたい時は custom で絶対に来ないであろう String を指定するなど...? .when(platforms: [.custom("")]).target ごと消すのが良いと思います.custom("xxx") もいけそうですね.define("FOO", nil)FOO が定義されるんじゃ?let を読んでるだけなんだけどねPackage.swift では real target に [.wasi] と mock target に allPlatforms.except([.wasi]) を指定しておけば Bool のフラグなしで解決する話だったりはしないですか?(ビルド時のターゲット triple で切り替わる感じで) https://github.com/apple/swift-package-manager/issues/4479Package.swift では real target に [.wasi] と mock target に allPlatforms.except([.wasi]) を指定しておけば Bool のフラグなしで解決する話だったりはしないですか?(ビルド時のターゲット triple で切り替わる感じで) https://github.com/apple/swift-package-manager/issues/4479 .define でフラグ定義して #if FLAG で制御するようにしたらうまくいった。.build/release にパスを通して 手元の場所で $ carton test してみたら[omochi@omochi-mbp swift-react (main *=)]$ carton test - checking Swift compiler path: /Users/omochi/.carton/sdk/wasm-5.9.2-RELEASE/usr/bin/swift - checking Swift compiler path: /Users/omochi/.swiftenv/versions/wasm-5.9.2-RELEASE/usr/bin/swift - checking Swift compiler path: /Users/omochi/Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain/usr/bin/swift Inferring basic settings... - swift executable: /Users/omochi/Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain/usr/bin/swift SwiftWasm Swift version 5.9.2 (swift-5.9.2-RELEASE) Target: arm64-apple-darwin23.1.0 Running "/Users/omochi/Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain/usr/bin/swift" "package" "--triple" "wasm32-unknown-wasi" "--scratch-path" "/Users/omochi/github/omochi/swift-react/.build/carton" "plugin" "carton-test" "internal-get-build-command" "--output" "/var/folders/qw/myjd_8ld5lg9qg057bhm467c0000gn/T/carton-DfdnYH" error: Unknown subcommand or plugin name ‘carton-test’ Usage: swift package <options> <subcommand> See 'package -help' for more information.package carton-test を叩こうとして見つからないよとなってしまった$ CartonFrontend test Error: Missing expected argument '--prebuilt-test-bundle-path <prebuilt-test-bundle-path>' Help: --prebuilt-test-bundle-path <prebuilt-test-bundle-path> Use the given bundle instead of building the test target Usage: carton test [--release] [--list] [<test-cases> ...] [--environment <environment>] [--headless] [--sanitize <sanitize>] [--port <port>] [--host <host>] --prebuilt-test-bundle-path <prebuilt-test-bundle-path> See 'carton test --help' for more information. このエラーは、わかるぞRunning "/Users/omochi/Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain/usr/bin/swift" "build" "--product" "MyAppPackageTests" "-Xswiftc" "-static-stdlib" "-Xswiftc" "-Xclang-linker" "-Xswiftc" "-mexec-model=reactor" "-Xlinker" "--export-if-defined=main" "--disable-build-manifest-caching" "--triple" "wasm32-unknown-wasi" "--scratch-path" "/Users/omochi/work/swiftwasm/MyApp/.build/carton""--scratch-path" "/Users/omochi/work/swiftwasm/MyApp/.build/carton" これは何?要る? -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor[omochi@omochi-mbp swift-react (main *=)]$ swift build --triple wasm32-unknown-wasi --build-tests \ -Xswiftc -static-stdlib \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export-if-defined=main \ --disable-build-manifest-caching warning: 'swift-algorithms': found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /Users/omochi/github/omochi/swift-react/.build/checkouts/swift-algorithms/Sources/Algorithms/Documentation.docc Building for debugging... In file included from /Users/omochi/github/omochi/swift-react/.build/checkouts/JavaScriptKit/Sources/_CJavaScriptKit/_CJavaScriptKit.c:1: /Users/omochi/github/omochi/swift-react/.build/checkouts/JavaScriptKit/Sources/_CJavaScriptKit/include/_CJavaScriptKit.h:4:10: fatal error: 'stdlib.h' file not found 4 | #include <stdlib.h> | ^~~~~~~~~~ 1 error generated. [0/26] Write swift-version-37CF2ABA3CB73B3C.txt--build-tests はダメかな[omochi@omochi-mbp swift-react (main *=)]$ which swift /usr/bin/swift [omochi@omochi-mbp swift-react (main *=)]$ swift --version Apple Swift version 6.0-dev (LLVM 3dd3bce1adb5b65, Swift 1f09be97a890c3e) Target: arm64-apple-macosx14.0 [omochi@omochi-mbp swift-react (main *=)]$ env | grep TOOLCHAINS TOOLCHAINS=org.swift.59202404021aswift experimental-sdk install https://github.com/swiftwasm/swift/releases/download/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-04-03-a/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-04-03-a-macos_arm64.artifactbundle.zip[omochi@omochi-mbp swift-react (main *=)]$ swift experimental-sdk list DEVELOPMENT-SNAPSHOT-2024-04-03-a-wasm [omochi@omochi-mbp swift-react (main *=)]$ swift build --triple wasm32-unknown-wasi --build-tests \ -Xswiftc -static-stdlib \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export-if-defined=main \ --disable-build-manifest-caching warning: 'swift-algorithms': found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /Users/omochi/github/omochi/swift-react/.build/checkouts/swift-algorithms/Sources/Algorithms/Documentation.docc Building for debugging... In file included from /Users/omochi/github/omochi/swift-react/.build/checkouts/JavaScriptKit/Sources/_CJavaScriptKit/_CJavaScriptKit.c:1: /Users/omochi/github/omochi/swift-react/.build/checkouts/JavaScriptKit/Sources/_CJavaScriptKit/include/_CJavaScriptKit.h:4:10: fatal error: 'stdlib.h' file not found 4 | #include <stdlib.h> | ^~~~~~~~~~ 1 error generated. [0/26] Write swift-version-37CF2ABA3CB73B3C.txt--triple の代わりに --experimental-swift-sdk wasm32-unknown-wasiで[omochi@omochi-mbp swift-react (main *=)]$ swift experimental-sdk list DEVELOPMENT-SNAPSHOT-2024-04-03-a-wasm [omochi@omochi-mbp swift-react (main *=)]$ swift build --triple wasm32-unknown-wasi --build-tests \ -Xswiftc -static-stdlib \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export-if-defined=main \ --disable-build-manifest-caching warning: 'swift-algorithms': found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /Users/omochi/github/omochi/swift-react/.build/checkouts/swift-algorithms/Sources/Algorithms/Documentation.docc Building for debugging... In file included from /Users/omochi/github/omochi/swift-react/.build/checkouts/JavaScriptKit/Sources/_CJavaScriptKit/_CJavaScriptKit.c:1: /Users/omochi/github/omochi/swift-react/.build/checkouts/JavaScriptKit/Sources/_CJavaScriptKit/include/_CJavaScriptKit.h:4:10: fatal error: 'stdlib.h' file not found 4 | #include <stdlib.h> | ^~~~~~~~~~ 1 error generated. [0/26] Write swift-version-37CF2ABA3CB73B3C.txt [omochi@omochi-mbp debug (main *=)]$ CartonFrontend test --prebuilt-test-bundle-path .build/debug/swift-reactPackageTests.wasm --environment browser No prebuilt binary found at /Users/omochi/github/omochi/swift-react/.build/wasm32-unknown-wasi/debug/.build/debug/swift-reactPackageTests.wasm[omochi@omochi-mbp swift-react (main *=)]$ CartonFrontend test --prebuilt-test-bundle-path .build/debug/swift-reactPackageTests.wasm --environment browser 2024-04-05T00:31:29+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET / 2024-04-05T00:31:29+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /test.js 2024-04-05T00:31:29+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /main.wasm 2024-04-05T00:31:29+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /JavaScriptKit_JavaScriptKit.resources/Runtime/index.mjs 2024-04-05T00:32:20+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /apple-touch-icon.png 2024-04-05T00:32:20+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /favicon.ico 2024-04-05T00:32:20+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /apple-touch-icon-precomposed.png--product を指定してやり直してみるMyAppPackageTests ってなんだ?そんなproductないのに通るな <name>PackageTests なのかなswift-reactPackageTests.wasm だ。--build-tests の代わりに --product swift-reactPackageTests にしてみようBuild complete! (1.38s) 2024-04-05T00:52:04+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET / 2024-04-05T00:52:04+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /test.js 2024-04-05T00:52:04+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /JavaScriptKit_JavaScriptKit.resources/Runtime/index.mjs 2024-04-05T00:52:04+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /main.wasm An error occurred: NotFoundError: The object can not be found here. error: Plugin ended with exit code 1Running "/Users/katei/Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain/usr/bin/swift" "package" "--triple" "wasm32-unknown-wasi" "--scratch-path" "/Users/katei/ghq/github.com/swiftwasm/carton/Tests/Fixtures/TestApp/.build/carton" "--disable-sandbox" "plugin" "carton-test" こういう出力があると思うんでswift package の直後に --verbose つけると最後の方に CartonFrontend のコマンドが出てきますRunning "/Users/omochi/Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain/usr/bin/swift" "package" "--triple" "wasm32-unknown-wasi" "--scratch-path" "/Users/omochi/github/omochi/swift-react/.build/carton" "plugin" "carton-test" "internal-get-build-command" "--environment" "browser" "--output" "/var/folders/qw/myjd_8ld5lg9qg057bhm467c0000gn/T/carton-F2kqX9" Running "/Users/omochi/Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain/usr/bin/swift" "build" "--product" "swift-reactPackageTests" "-Xswiftc" "-static-stdlib" "-Xswiftc" "-Xclang-linker" "-Xswiftc" "-mexec-model=reactor" "-Xlinker" "--export-if-defined=main" "--disable-build-manifest-caching" "--triple" "wasm32-unknown-wasi" "--scratch-path" "/Users/omochi/github/omochi/swift-react/.build/carton" Running "/Users/omochi/Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain/usr/bin/swift" "package" "--triple" "wasm32-unknown-wasi" "--scratch-path" "/Users/omochi/github/omochi/swift-react/.build/carton" "--disable-sandbox" "plugin" "carton-test" "--environment" "browser"info: Running "/Users/omochi/github/omochi/swift-react/.build/carton/arm64-apple-macosx/debug/CartonFrontend" "test" "--prebuilt-test-bundle-path" "/Users/omochi/github/omochi/swift-react/.build/carton/wasm32-unknown-wasi/debug/swift-reactPackageTests.wasm" "--environment" "browser"swift run cartonを実行しない状態でもう一回CartonFrontend直でやってみるとどうでしょうexport TOOLCHAINS=org.swiftwasm.202439 swift build --triple wasm32-unknown-wasi \ --build-tests \ -Xswiftc -static-stdlib \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export-if-defined=main \ --disable-build-manifest-caching CartonFrontend test --prebuilt-test-bundle-path .build/debug/swift-reactPackageTests.wasm --environment browser これでテスト実行されたCartonFrontend がバージョン違う可能性があったけどそれは無くなったexport TOOLCHAINS=org.swift.59202404021a swift build --experimental-swift-sdk wasm32-unknown-wasi \ --build-tests \ -Xswiftc -static-stdlib \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export-if-defined=main \ --disable-build-manifest-caching CartonFrontend test --prebuilt-test-bundle-path .build/debug/swift-reactPackageTests.wasm --environment browser--triple を使うか --experimental-swift-sdk を使うか、だけ。--export-if-defined=__main_argc_argv にしてみてAn error occurred: RuntimeError: Unreachable code should not be executed (evaluating 'instance.exports.__main_argc_argv(0, 0)')#if compiler だと cartonのbuild time分岐だけどいいのか?選択してるツールチェインのバージョンではないのか (edited)diff --git a/Package.swift b/Package.swift index a57f2f3..5557ef3 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version: 5.10 +// swift-tools-version: 5.9 import PackageDescription @@ -41,6 +41,7 @@ let package = Package( dependencies: [ .package(url: "https://github.com/apple/swift-algorithms", from: "1.2.0"), .package(url: "https://github.com/swiftwasm/JavaScriptKit", from: "0.19.1"), + .package(url: "https://github.com/swiftwasm/carton", from: "1.0.0"), ], targets: [ .target( これだけswift_os が流れてきてみたことあったな2: wasm trap: wasm `unreachable` instruction executed これがwasmtimeで、ブラウザのやつも同じことかinsertBefore がコケるのとかも5.9.2wasmの時と同じpath モジュールをバインドしたことと、 /sandbox を作ってpreopenしたことはなんとなくわかる@wasmer/wasi のAPIを調べようとして迷ったnpm i @wasmer/wasi. There are 47 other projects in the npm registry using @wasmer/wasi."@wasmer/wasi": "^0.12.0", バージョン?path: any だけど Path モジュールを要求してるんやな.throws で変換するのめんどくさいなと思って無視したけど (edited).nothrowにするのは?.nothrowにするのは? throws な事自体はあまり違和感はないかな サーバサイドで普段から大量の async throws にまみれているから・・・ (edited)
1function catchCall(body) { try { return { type: "success", value: body() } } catch(error) { return { type: "failure", value: error } } }
let result = JSObject.global.catchCall(JSOneshotClosure { // do something })catchCallを被せて呼び出すみたいなのをイメージしてましたjsValue.createElement(tagName) これトリッキーに動いてるからjsValue.createElement.throws(tagName) こうするとうまくいかないんだ・・・.createElement に () が直結してないと callable type に返り値の推論がされないjsValue.createElement.aaaa(tagName) これなら、createElementは普通のオブジェクトアクセス扱いなんだけどthrows だと Ambiguous になるjsValue.object!.throwing.createElementが書けるjsValue.createElement.aaaa(tagName) これなら、createElementは普通のオブジェクトアクセス扱いなんだけど jsValue.object!.throwing.createElementが書ける throwing と throws で API揃ってないんfinal class JavaScriptKitTests: XCTestCase { func testClosureAsFunction() throws { let clo = JSClosure { (_) in return 7.jsValue } let obj = try JSObject.mustConstruct(from: clo.jsValue) XCTAssertFalse(obj is JSFunction) let fn = clo.asFunction() let ret = try Int.mustConstruct(from: try fn()) XCTAssertEqual(ret, 7) } } extension JSClosure { #if USES_JAVASCRIPT_KIT_MOCK public func asFunction() -> JSThrowingFunction { let fn = native as! JSNativeFunction return JSFunction(native: fn).throws } #else public func asFunction() -> JSThrowingFunction { var buffer: JSValue = Array<Int>([0]).jsValue buffer[0] = self.jsValue let fn = JSFunction.unsafeConstruct(from: buffer[0]) return fn.throws } #endif } hostFuncRef = JavaScriptHostFuncRef(bitPattern: ObjectIdentifier(self)) これがただのIDだから。button.onclick を書いたり読んだりすると起きえそうだJavaScriptHostFuncRef(bitPattern: ObjectIdentifier(self)) あとこれだけど、 #if JAVASCRIPTKIT_WITHOUT_WEAKREFS deinit { guard isReleased else { fatalError("release() must be called on JSClosure objects manually before they are deallocated") } } #endif } deinitは何もしてないから消えないんじゃ?#if JAVASCRIPTKIT_WITHOUT_WEAKREFS // MARK: - Legacy Closure Types extension JSClosure { public func release() { isReleased = true Self.sharedClosures[hostFuncRef] = nil } } @_cdecl("_free_host_function_impl") func _free_host_function_impl(_ hostFuncRef: JavaScriptHostFuncRef) {} #else extension JSClosure { @available(*, deprecated, message: "JSClosure.release() is no longer necessary") public func release() {} } @_cdecl("_free_host_function_impl") func _free_host_function_impl(_ hostFuncRef: JavaScriptHostFuncRef) { JSClosure.sharedClosures[hostFuncRef] = nil } #endif swjs_create_function: (host_func_id, line, file) => { var _a; const fileString = this.memory.getObject(file); const func = (...args) => this.callHostFunction(host_func_id, line, fileString, args); const func_ref = this.memory.retain(func); (_a = this.closureDeallocator) === null || _a === void 0 ? void 0 : _a.track(func, func_ref); return func_ref; },memory.retain を消せない気がしてきたswjs_call_new や swjs_create_function では retain してるけど// swiftで func inSwift() { // no retain let body = JSObject.construct(from: JSObject.global.document.body)! consume body // swjs_release } (edited) const writeRef = (kind) => { memory.writeUint32(payload1_ptr, memory.retain(value)); return exceptionBit | kind; }; あ、ほんとだis じゃなくても、明示的な変換でもいいし public func asFunction() -> JSThrowingFunction { var buffer: JSValue = Array<Int>([0]).jsValue buffer[0] = self.jsValue let fn = JSFunction.unsafeConstruct(from: buffer[0]) return fn.throws }WebMock を実装してて困った。 public class WebEventTarget: JSNativeObject { public init() { } private var listeners: [String: [JSFunction]] = [:] public func addEventListener(_ type: String, _ listener: JSFunction) { var lns = self.listeners[type] ?? [] if lns.contains(listener) { return } lns.append(listener) self.listeners[type] = lns } public func removeEventListener(_ type: String, _ listener: JSFunction) { guard var lns = self.listeners[type] else { return } lns.removeAll { $0 == listener } self.listeners[type] = lns } public func dispatchEvent(_ event: WebEvent) -> Bool { guard let lns = self.listeners[event.type] else { return true } for ln in lns { ln(event) } return true }stream.subscribe(on: button.onclick) とか。 // Note: Retain the closure object itself also to avoid funcRef conflicts fileprivate static var sharedClosures: [JavaScriptHostFuncRef: (object: JSObject, body: ([JSValue]) -> JSValue)] = [:]JavaScriptHostFuncRef を持ってるだけだから問題ないはず public func asFunction() -> JSThrowingFunction { var buffer: JSValue = Array<Int>([0]).jsValue buffer[0] = self.jsValue let fn = JSFunction.unsafeConstruct(from: buffer[0]) return fn.throws } ClosureEntry.object: AnyObject だからどちらにしても WeakBoxはclassにできないけどstrong を使う互換モードが要る?-DJAVASCRIPTKIT_WITHOUT_WEAKREFS を渡すかどうかで決まります$ swift build -swiftc -DJAVASC... ?Optional.construct の変更がもう一回入ってそう?[omochi@omochi-mbp IntegrationTests (fix-object-decode *=)]$ make test npm ci added 27 packages, and audited 31 packages in 313ms 1 package is looking for funding run `npm fund` for details found 0 vulnerabilities cd .. && npm run build > javascript-kit-swift@0.19.1 build > npm run build:clean && npm run build:ts > javascript-kit-swift@0.19.1 build:clean > rm -rf Runtime/lib > javascript-kit-swift@0.19.1 build:ts > cd Runtime; rollup -c sh: rollup: command not found make: *** [build_rt] Error 127rollup ってなんだっけ npm install はしたけどcreated lib/index.mjs, lib in 345ms swift build --package-path TestSuites \ --product ConcurrencyTests \ --triple wasm32-unknown-wasi \ --configuration debug \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export=main \ warning: 'testsuites': 'PrimaryTests' was identified as an executable target given the presence of a 'main.swift' file. Starting with tools version 5.4.0 executable targets should be declared as 'executableTarget()' warning: 'testsuites': 'ConcurrencyTests' was identified as an executable target given the presence of a 'main.swift' file. Starting with tools version 5.4.0 executable targets should be declared as 'executableTarget()' warning: 'testsuites': 'BenchmarkTests' was identified as an executable target given the presence of a 'main.swift' file. Starting with tools version 5.4.0 executable targets should be declared as 'executableTarget()' Building for debugging... In file included from /Users/omochi/github/swiftwasm/JavaScriptKit/Sources/_CJavaScriptKit/_CJavaScriptKit.c:1: /Users/omochi/github/swiftwasm/JavaScriptKit/Sources/_CJavaScriptKit/include/_CJavaScriptKit.h:4:10: fatal error: 'stdlib.h' file not found 4 | #include <stdlib.h> | ^~~~~~~~~~ 1 error generated. [4/12] Write swift-version-37CF2ABA3CB73B3C.txt make[1]: *** [TestSuites/.build/debug/ConcurrencyTests.wasm] Error 1 make: *** [test] Error 2 https://syzf23805k.execute-api.ap-northeast-1.amazonaws.com/prod/CompileSwiftWasm func testState() throws { struct Content: Component { @State var count = 0 func render() -> Node { return div { "\(count)" button( listeners: [ "click": Function { (ev) in count += 1 } ] ) } } } let body = try document.createElement("body") let root = ReactRoot(element: body) root.render( node: Content() ) XCTAssertPrint(body, """ <body> <div> 0 <button /> </div> </body> """) let btn: JSHTMLElement = try XCTUnwrap( root.root? .find { $0.tagElement?.tagName == "button" }? .dom?.asHTMLElement() ) try btn.click() XCTAssertPrint(body, """ <body> <div> 1 <button /> </div> </body> """) } ちょっとそれっぽくなってきた(↑このテストが通った) (edited)[omochi@omochi-mbp ReactTests (main =)]$ ls -1 CallbackHookTests.swift ContextHookTests.swift RefHookTests.swift RenderPlanTests.swift RenderTests.swift StateHookTests.swift VNodeTests.swiftVNodeTests RenderTests RenderPlanTests が含まれる時VNodeTests と RenderTests だけとか RenderTests と RenderPlanTests だけ、みたいな時は大丈夫なのに (edited)VNodeTests RenderTests RenderPlanTests の3つがあるとフリーズする (edited)-Xlinker -z -Xlinker stack-size=131072stack-size=65536 にしてみるね-Xlinker --stack-first を付けて、スタック領域をメモリ空間の最初に置いて、超えたときに負のアドレスをデリファレンスさせるようにして暗黙の破壊を防いでるんですけどswift build --experimental-swift-sdk wasm32-unknown-wasi \ --build-tests \ -Xswiftc -static-stdlib \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export-if-defined=__main_argc_argv \ --disable-build-manifest-caching \ -Xlinker -z -Xlinker stack-size=65536 CartonFrontend test \ --prebuilt-test-bundle-path .build/debug/swift-reactPackageTests.wasm \ --environment browsererror: link command failed with exit code 1 (use -v to see invocation) wasm-ld: error: --global-base cannot be less than stack size when --stack-first is used clang: error: linker command failed with exit code 1 (use -v to see invocation) [230/231] Linking swift-reactPackageTests.wasm ビルドできなくなったswift build --experimental-swift-sdk wasm32-unknown-wasi \ --build-tests \ -Xswiftc -static-stdlib \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export-if-defined=__main_argc_argv \ --disable-build-manifest-caching \ -Xlinker --stack-first \ -Xlinker -z -Xlinker stack-size=65536-Xlinker --global-base=65536 も一緒に付けると2024-04-13T22:44:40+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /JavaScriptKit_JavaScriptKit.resources/Runtime/index.mjs An error occurred: RuntimeError: memory access out of bounds お、なんか出たWEBDRIVER_PATHにchromedriverコマンドを指定すると+ swift build --experimental-swift-sdk wasm32-unknown-wasi --build-tests -Xswiftc -static-stdlib -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor -Xlinker --export-if-defined=__main_argc_argv --disable-build-manifest-caching -Xlinker --stack-first -Xlinker --global-base=65536 -Xlinker -z -Xlinker stack-size=65536 warning: 'swift-algorithms': found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /Users/omochi/github/omochi/swift-react/.build/checkouts/swift-algorithms/Sources/Algorithms/Documentation.docc Building for debugging... warning: Could not read SDKSettings.json for SDK at: /Users/omochi/Library/org.swift.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-04-03-a-macos_arm64.artifactbundle/DEVELOPMENT-SNAPSHOT-2024-04-03-a-wasm/wasm32-unknown-wasi/WASI.sdk <unknown>:0: warning: libc not found for 'wasm32-unknown-wasi'; C stdlib may be unavailable warning: Could not read SDKSettings.json for SDK at: /Users/omochi/Library/org.swift.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-04-03-a-macos_arm64.artifactbundle/DEVELOPMENT-SNAPSHOT-2024-04-03-a-wasm/wasm32-unknown-wasi/WASI.sdk <unknown>:0: warning: libc not found for 'wasm32-unknown-wasi'; C stdlib may be unavailable [5/5] Emitting module swift_reactPackageTests Build complete! (0.64s) + CartonFrontend test --prebuilt-test-bundle-path .build/debug/swift-reactPackageTests.wasm --environment browser 2024-04-13T22:56:33+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET / 2024-04-13T22:56:33+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /test.js 2024-04-13T22:56:33+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /main.wasm 2024-04-13T22:56:33+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /favicon.ico 2024-04-13T22:56:33+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /JavaScriptKit_JavaScriptKit.resources/Runtime/index.mjs An error occurred: RuntimeError: memory access out of bounds2024-04-13T22:58:03+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /main.wasm 2024-04-13T22:58:03+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /test.js 2024-04-13T22:58:03+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /main.wasm 2024-04-13T22:58:03+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /JavaScriptKit_JavaScriptKit.resources/Runtime/index.mjs これでサーバー継続してるRenderTests.swift ファイルを取り除いてリビルドしてたdefault: 0, data, stack, heap --stack-first: 0, stack, data, heap レイアウトによらず、スタックサイズの決め方は同じだね.wasm をロードした時に消費する初期メモリサイズがデカくなる、であってる? (edited)foo.wasm をロードした時点で数字がわかってるんだよね? 5,111,808 13,369,344 ちゃんと8MBぐらい増えているWebAssemblyクラスとメソッドを全てフックして、ブラウザからホストのwasminspectとRPCして、wasminspect上で実行してるswift build --experimental-swift-sdk wasm32-unknown-wasi \ --build-tests \ -Xswiftc -static-stdlib \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export-if-defined=__main_argc_argv \ --disable-build-manifest-caching \ -Xlinker --stack-first \ -Xlinker --global-base=1048576 \ -Xlinker -z -Xlinker stack-size=1048576 この辺のパラメータ、 -Xswiftc とか -Xlinker は Package.swift に書くことができるけど、 --experimental-swift-sdk wasm32-unknown-wasi は書けないですよね?$ swift build を使う人の責任、という設計は正しいんだろうか? これwasmというよりswiftpm cliの設計の話かなPackage.swift で宣言できるのが正しい気がする
1
1// @ts-ignore 外したいんだけどしばらく色々やったけどダメだったんだよなあ .mjs 周りとかはめんどくさい事になっとるなと思った (edited)load.ts が entrypoint/bundle.js だったものでWasmRunner.ts が entrypoint/common.js だったものねload.ts 経由で .wasm を渡して起動するbundle.js とかは .wasm の名前がコードに焼かれてるけど、そこをパラメータ化している) (edited).js (sourcemap付き) と .d.ts だったら本質的に同じはず (edited)foo.ts が foo.c + foo.h で、 foo.js が libfoo.a で、 foo.d.ts が foo.h という認識 (edited)libfoo.dylib と libfoo.swiftinterface もあった[omochi@omochi-mbp BrowserTests (add-brtest =)]$ echo $TOOLCHAINS org.swift.59202404021a 4/2.build/wasm32-unknown-wasi がどうのこうのと出る (edited)--disable-build-manifest-caching つけるとどうですか--disable-build-manifest-caching つけるとどうですか --disable-build-manifest-caching \ がついていた[omochi@omochi-mbp BrowserTests (add-brtest *=)]$ bin/build + swift build --experimental-swift-sdk wasm32-unknown-wasi -Xswiftc -static-stdlib -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor -Xlinker --export-if-defined=__main_argc_argv -Xlinker --stack-first -Xlinker --global-base=1048576 -Xlinker -z -Xlinker stack-size=1048576 warning: 'browsertests': found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /Users/omochi/github/omochi/swift-react/BrowserTests/Sources/QSDisplayingData/styles.css warning: 'swift-algorithms': found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /Users/omochi/github/omochi/swift-react/BrowserTests/.build/checkouts/swift-algorithms/Sources/Algorithms/Documentation.docc Building for debugging... [1/1] Write swift-version-37CF2ABA3CB73B3C.txt Build complete! (0.18s) + swift build warning: 'browsertests': found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /Users/omochi/github/omochi/swift-react/BrowserTests/Sources/QSDisplayingData/styles.css warning: 'swift-algorithms': found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /Users/omochi/github/omochi/swift-react/BrowserTests/.build/checkouts/swift-algorithms/Sources/Algorithms/Documentation.docc Building for debugging... [1/1] Write swift-version-37CF2ABA3CB73B3C.txt Build complete! (0.19s)Write swift-version-37CF2ABA3CB73B3C.txt がWrite swift-version-37CF2ABA3CB73B3C.txt ってメッセージがない--jobs 1 --verbose でログ取って比較してみてくださいswift build --experimental-swift-sdk wasm32-unknown-wasi \ --jobs 1 --verbose \ -Xswiftc -static-stdlib \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export-if-defined=__main_argc_argv \ -Xlinker --stack-first \ -Xlinker --global-base=1048576 \ -Xlinker -z -Xlinker stack-size=1048576Workaround: Add import _RegexParser in a Swift file.--verbose なのにほぼ何も出ないんだよな でも3週目で必ず死ぬから2週目で起きた副作用が問題っぽいけどWrite auxiliary file /Users/omochi/github/omochi/swift-react/BrowserTests/.build/arm64-apple-macosx/debug/swift-version-37CF2ABA3CB73B3C.txt こいつはいた[omochi@omochi-mbp BrowserTests (add-brtest *%=)]$ cat .build/debug/swift-version-37CF2ABA3CB73B3C.txt Apple Swift version 6.0-dev (LLVM 3dd3bce1adb5b65, Swift 1f09be97a890c3e) Target: arm64-apple-macosx14.0 中身ただのバージョンだったimport _RegexBuilder が書いてあっても大丈夫になったimport _RegexBuilder って普通にできてたと思う・・・--jobs 1 --verbose でログ取って比較してみてください [omochi@omochi-mbp BrowserTests (add-brtest *%=)]$ diff -r .build .build1 Binary files .build/arm64-apple-macosx/build.db and .build1/arm64-apple-macosx/build.db differ Binary files .build/wasm32-unknown-wasi/build.db and .build1/wasm32-unknown-wasi/build.db differPackageStructureCommand.getSignatureが呼ばれてないPackageStructureCommand signature: XXX bytes という行があればシグネチャが計算されてるfinal class PackageStructureCommand: CustomLLBuildCommand { override func getSignature(_: SPMLLBuild.Command) -> [UInt8] { let encoder = JSONEncoder.makeWithDefaults() // Include build parameters and process env in the signature. var hash = Data() hash += try! encoder.encode(self.context.productsBuildParameters) hash += try! encoder.encode(self.context.toolsBuildParameters) hash += try! encoder.encode(ProcessEnv.vars) return [UInt8](hash) }PackageStructure ターゲットのビルドがトリガーされないのでシグネチャがbuild.dbに記録されない。 (edited).build/debug.yml ファイルが存在するので PackageStructure ターゲットのビルドをトリガーしてビルドパラメータに更新があるかチェックする。ただし1回目でこのターゲットをビルドしてないので常に更新がある判定になるので .build/debug.ymlを作り直す。 (edited)build.db にシグネチャが記録される。.build/debug.yml ファイルが存在するのでPackageStructure ターゲットのビルドをトリガーして更新チェックする。 直前にhostビルドをしているので debug.ymlはhostの状態。ただしbuild.dbにはシグネチャが記録されておりビルド済み判定になり、debug.ymlを作り直さずにビルドを開始する。(本来は2回目のwasmビルドの時点のdebug.ymlに書き戻すべき。).build/debug.yml を参照するってこと?? (edited).build/debug.yml なんてものが存在しているのがおかしくて.build/arm64-apple-macosx/debug.yml と .build/wasm32-unknown-wasi/debug.yml で
1ExternalCommand というやつは自分でシグネチャを決めるのでそういうことが起きる.build/debug.yml を再利用していいかどうかの問合せロジックにおいて、 問い合わせる先のデータベースがパラメータによって変わって、 データベースは自分が使われた時の知識しか持ってないから、 再利用できるっていう結果を返すけど、 実際には別の構成のために書き換わった状態になってるので壊れる・・・?.build/debug.yml が書き換わるタイミングのシグネチャを常に記録してるシングルトンなデータベースがいないとやりたいことがやれないように思う-rw-r--r-- 1 katei katei 204800 Apr 18 14:53 .build/wasm32-unknown-wasi/build.db -rw-r--r-- 1 katei katei 172032 Apr 18 14:54 .build/x86_64-unknown-linux-gnu/build.db (edited)PackageStructure が起動しない問題、DBが別れててシグネチャ判定が役に立たない問題、並列数が1だと _RegexBuilder が見つからない問題key_id から key_name 引いたやつがN や C みたいなコマンド種別+ファイルパスとかで、そういうKVSになっていて、これがmakefileのターゲットみたいなもんで ただエントリの有効性を signature で保護している (edited)5.10-RELEASE は無い?ここは手動なのかな5.10.1 だよね? 5.9 は もう 5.9.2 まで出ているswift package --experimental-swift-sdk DEVELOPMENT-SNAPSHOT-2024-04-15-b-wasm32-unknown-wasi carton-dev これでswift package --experimental-swift-sdk DEVELOPMENT-SNAPSHOT-2024-04-15-b-wasm32-unknown-wasi carton-dev これで [omochi@omochi-mbp ~]$ swift sdk list DEVELOPMENT-SNAPSHOT-2024-04-03-a-wasm [omochi@omochi-mbp ~]$ swift sdk list DEVELOPMENT-SNAPSHOT-2024-04-03-a-wasm DEVELOPMENT-SNAPSHOT-2024-04-28-a-wasm32-unknown-wasi$ swift sdk が手元でもCIでも動いた。ドキュメントも更新した。 https://github.com/omochi/swift-react/pull/94 artifact bundle の選び方の説明文が変わった。 --global-baseってオプションは新しいんでしょうかね?
--stack-first と組み合わさって何か意味があるんだと思ってた --global-baseってオプションは新しいんでしょうかね?
--stack-firstを有効にしたとき明示的な--global-base が必要なのは6.0以降で、それ以前では必要ないのでおそらく大丈夫そう。const wrapWASI = (wasiObject: WASI, wasmModule: WebAssembly.Module): WebAssembly.ModuleImports => { あーこれが噛み合わないimport wasmUrl from 'foo.wasm?url' こっちの方式なら噛み合いそうだexport TOOLCHAINS=... してから $ npm run dev でdev serverが動く (edited)/ に全部置いてある想定で作ったんだけど、github pagesによって ディレクトリ名が付いたパスになってしまったがnpm run build -- --base=/swift-string-counter-web/ div( attributes: [ "style": """ display: flex; flex-direction: column; align-items: center; gap: 4px; """ ] ) {style アトリビュートに インラインスタイルを書こうとするとdiv(display: "flex", flex-direction: "column", align-items: "center", gap: "4px") って書ける事だけどclass → className, for → htmlFor などがある。(どちらもJSのキーワードと衝突している)Modifier.size(...).clip(...) の部分ですかねa とか div にそれを渡す形だ。attributes { class = "..." src = "..." href = "..." } 本当はこんな感じに書きたいけど Result Builder はグローバルな名前しか使えないからできないんだよなAttributes .class(...) .src(...) .href(...) メソッドチェーンならKotlinと同じようにSwiftでもできる。 SwiftUIも、まあそうか。Style .display("flex") .flexDirection("column") .alignItems("center")flex-direction や alignItems にできないのはしょうがないよなあ。 これはSwifty API なんだよという事かなあ。 .display(.flex).flexDirection(.column)...default (debug): 25.5MB -c release: 24.3MB -c release, -Osize: 13.4MB -c release, -Osize, -wmo: 13.4MB (変化なし?) (edited)-lto=llvm-full -experimental-hermetic-seal-at-link つけたらビルドできなかった・・・ wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/Chunked.swift.o: undefined symbol: swift_deallocObject wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/AdjacentPairs.swift.o: undefined symbol: swift_release wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/Keyed.swift.o: undefined symbol: swift_bridgeObjectRelease wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/Keyed.swift.o: undefined symbol: swift_bridgeObjectRelease wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/AdjacentPairs.swift.o: undefined symbol: swift_release wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/Chunked.swift.o: undefined symbol: swift_deallocObject wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/React.build/ChildrenBuilder.swift.o: undefined symbol: $sytWV clang: error: linker command failed with exit code 1 (use -v to see invocation) [10/11] Linking StringCounter.wasmdefault (debug): 25.5MB -c release: 24.3MB -c release, -Osize: 13.4MB -c release, -Osize, -wmo: 13.4MB (変化なし?) (edited)-c release は -wmo が有効になるので比較は実質上 2 つだけで十分ですよ.
1Osizeの存在わすれてたので手元のプロジェクトにかけてみたけど、0.1MBしか変わらなかった-Os の上の -Oz もありますしね.wasm-strip をかけてから wasm-opt をかけるとさらに小さくなった記憶があります.*.bc と言うファイルが大量に生成される。*.bc と言うファイルが大量に生成される。 -lto=llvm-full -experimental-hermetic-seal-at-link つけたらビルドできなかった・・・ wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/Chunked.swift.o: undefined symbol: swift_deallocObject wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/AdjacentPairs.swift.o: undefined symbol: swift_release wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/Keyed.swift.o: undefined symbol: swift_bridgeObjectRelease wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/Keyed.swift.o: undefined symbol: swift_bridgeObjectRelease wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/AdjacentPairs.swift.o: undefined symbol: swift_release wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/Algorithms.build/Chunked.swift.o: undefined symbol: swift_deallocObject wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/release/React.build/ChildrenBuilder.swift.o: undefined symbol: $sytWV clang: error: linker command failed with exit code 1 (use -v to see invocation) [10/11] Linking StringCounter.wasm .build ディレクトリを一旦消したら別のエラーになりませんか?ビルドディレクトリに *.swift.o ファイルが見つからないというようなエラーに. そして SwiftPM だと最近 LTO を有効にするための --experimental-lto-mode=full みたいなのが追加されたみたいなので,-Xswiftc -lto=llvm-full じゃなくてこっちのフラグで指定したらどうなりますか? https://github.com/apple/swift-package-manager/pull/6891/files-experimental-hermetic-seal-at-link と -lto=llvm-full を渡す方式じゃ同じエラー (*.swift.o が生成されない) が起こって,swiftc に -experimental-hermetic-seal-at-link で swift-build に --experimental-lto-mode=full を渡す方式だとちゃんとビルドが通ってバイナリサイズも小さくなりました.wasm-ld: error: /home/kebo/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/wasm32/swiftrt.o: undefined symbol: swift_addNewDSOImage wasm-ld: error: /home/kebo/swift-string-counter-web/.build/wasm32-unknown-wasi/debug/_CJavaScriptKit.build/_CJavaScriptKit.c.o: undefined symbol: _call_host_function_impl wasm-ld: error: /home/kebo/swift-string-counter-web/.build/wasm32-unknown-wasi/debug/_CJavaScriptKit.build/_CJavaScriptKit.c.o: undefined symbol: _free_host_function_impl wasm-ld: error: /home/kebo/swift-string-counter-web/.build/wasm32-unknown-wasi/debug/_CJavaScriptKit.build/_CJavaScriptKit.c.o: undefined symbol: _library_features clang: error: linker command failed with exit code 1 (use -v to see invocation) (edited)diff --git a/bin/build b/bin/build index ae8a56c..d0ba369 100755 --- a/bin/build +++ b/bin/build @@ -6,7 +6,9 @@ set -x swift build --swift-sdk wasm32-unknown-wasi \ --disable-build-manifest-caching \ - -Xswiftc -static-stdlib \ + --static-swift-stdlib \ + --experimental-lto-mode=full \ + -Xswiftc -experimental-hermetic-seal-at-link \ -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor \ -Xlinker --export-if-defined=__main_argc_argv \ -Xlinker --stack-first \undefined symbol: swift_addNewDSOImage は -Xlinker $HOME/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libswiftCore.a を追加すればとりあえず出なくなりました.残り 3 つは全部 _CJavaScriptKit module なのが気になりますね. https://github.com/apple/swift-package-manager/issues/4415#issuecomment-1116961059warning: Could not read SDKSettings.json for SDK at: /Users/omochi/Library/org.swift.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-04-28-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2024-04-28-a-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk wasm-ld: error: /Users/omochi/Library/org.swift.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-04-28-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2024-04-28-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/wasm32/swiftrt.o: undefined symbol: swift_addNewDSOImage wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/debug/_CJavaScriptKit.build/_CJavaScriptKit.c.o: undefined symbol: _call_host_function_impl wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/debug/_CJavaScriptKit.build/_CJavaScriptKit.c.o: undefined symbol: _free_host_function_impl wasm-ld: error: /Users/omochi/github/omochi/swift-string-counter-web/.build/wasm32-unknown-wasi/debug/_CJavaScriptKit.build/_CJavaScriptKit.c.o: undefined symbol: _library_features clang: error: linker command failed with exit code 1 (use -v to see invocation) [166/167] Linking StringCounter.wasmrenderChildren とかを見ていると大体最後で呼び出しているのでこれが実現すれば最適化後のコールスタックは浅くなりそうにも見えますけど,トレーシング結果だとどういう見え方になるんですかね? https://github.com/swiftwasm/swift/issues/5568[omochi@omochi-iMacPro temp]$ swift sdk install swift-wasm-DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi.artifactbundle.zip Swift SDK bundle at `swift-wasm-DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi.artifactbundle.zip` is assumed to be an archive, unpacking... zsh: segmentation fault swift sdk install /Users/omochi/github/omochi/swift-react/.build/wasm32-unknown-wasi/debug/swift-reactPackageTests.derived/runner.swift:113:19: error: no such module 'Darwin.C' @_exported import Darwin.C ^ (edited)$ swift sdk コマンドはなんなんだHmm, due to the absolute install_name specified by LC_ID_DYLIB in libswiftCore.dylib in toolchains, Swift executables always load libswiftCore.dylib from absolute /usr/lib/swift/libswiftCore.dylib without checking @rpath. So just adding -rpath linker option did not work unfortunately.libswiftCore.dylibはshared cacheというやつで固められた特殊な配布のされ方をしていて[omochi@omochi-iMacPro swift]$ pwd /usr/lib/swift [omochi@omochi-iMacPro swift]$ ls -al total 1488 drwxr-xr-x 8 root wheel 256 3 21 15:13 . drwxr-xr-x 32 root wheel 1024 3 21 15:13 .. lrwxr-xr-x 1 root wheel 71 3 21 15:13 libswiftCreateML.dylib -> /System/Library/Frameworks/CreateML.framework/Versions/Current/CreateML -rwxr-xr-x 1 root wheel 2021840 3 21 15:13 libswiftRemoteMirror.dylib lrwxr-xr-x 1 root wheel 84 3 21 15:13 libswiftSoundAnalysis.dylib -> ../../..//System/Library/Frameworks/SoundAnalysis.framework/Versions/A/SoundAnalysis lrwxr-xr-x 1 root wheel 84 3 21 15:13 libswiftSoundAnalysis_Private.dylib -> ../../..//System/Library/Frameworks/SoundAnalysis.framework/Versions/A/SoundAnalysis lrwxr-xr-x 1 root wheel 91 3 21 15:13 libswiftVirtualization.dylib -> ../../../System/Library/Frameworks/Virtualization.framework/Versions/Current/Virtualization drwxr-xr-x 3 root wheel 96 3 21 15:13 playgrounds/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e にいる[omochi@omochi-iMacPro swift]$ cd /System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/ [omochi@omochi-iMacPro dyld]$ ls -al total 3264760 drwxr-xr-x 9 root wheel 288 3 21 15:13 . drwxr-xr-x 9 root wheel 288 3 21 15:13 .. -rwxr-xr-x 1 root admin 868433920 3 21 15:13 dyld_shared_cache_x86_64h -rwxr-xr-x 1 root admin 820183040 3 21 15:13 dyld_shared_cache_x86_64h.01 -rwxr-xr-x 1 root admin 748994560 3 21 15:13 dyld_shared_cache_x86_64h.02 -rwxr-xr-x 1 root admin 721551360 3 21 15:13 dyld_shared_cache_x86_64h.03 -rwxr-xr-x 1 root admin 766492672 3 21 15:13 dyld_shared_cache_x86_64h.04 -rwxr-xr-x 1 root admin 287457280 3 21 15:13 dyld_shared_cache_x86_64h.05 -rwxr-xr-x 1 root admin 823374 3 21 15:13 dyld_shared_cache_x86_64h.map ファイル名見るだけでもうだるいじゃん[omochi@omochi-iMacPro bin]$ pwd /Users/omochi/Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2024-05-01-a.xctoolchain/usr/bin [omochi@omochi-iMacPro bin]$ ls -al total 4110776 drwxr-xr-x 51 omochi staff 1632 5 10 21:13 . drwxr-xr-x 8 omochi staff 256 5 2 04:27 .. lrwxr-xr-x 1 omochi staff 8 5 10 21:13 clang -> clang-17 lrwxr-xr-x 1 omochi staff 5 5 10 21:13 clang++ -> clang -rwxr-xr-x 1 omochi staff 485170160 5 2 18:05 clang-17 lrwxr-xr-x 1 omochi staff 5 5 10 21:13 clang-cache -> clang lrwxr-xr-x 1 omochi staff 5 5 10 21:13 clang-cl -> clang lrwxr-xr-x 1 omochi staff 5 5 10 21:13 clang-cpp -> clang -rwxr-xr-x 1 omochi staff 201968272 5 2 18:05 clangd -rwxr-xr-x 1 omochi staff 19181952 5 2 18:05 docc -rwxr-xr-x 1 omochi staff 179340336 5 2 18:05 dsymutil lrwxr-xr-x 1 omochi staff 3 5 10 21:13 ld.lld -> lld lrwxr-xr-x 1 omochi staff 3 5 10 21:13 ld64.lld -> lld -rwxr-xr-x 1 omochi staff 277899776 5 2 18:05 lld lrwxr-xr-x 1 omochi staff 3 5 10 21:13 lld-link -> lld -rwxr-xr-x 1 omochi staff 1231712 5 2 18:05 lldb -rwxr-xr-x 1 omochi staff 1929040 5 2 18:05 lldb-dap -rwxr-xr-x 1 omochi staff 48793296 5 2 18:05 llvm-ar -rwxr-xr-x 1 omochi staff 16037728 5 2 18:05 llvm-cov -rwxr-xr-x 1 omochi staff 17407808 5 2 18:05 llvm-profdata lrwxr-xr-x 1 omochi staff 7 5 10 21:13 llvm-ranlib -> llvm-ar drwxr-xr-x 16 omochi staff 512 5 2 04:27 sdk-module-lists -rwxr-xr-x 1 omochi staff 127166928 5 2 18:05 sourcekit-lsp lrwxr-xr-x 1 omochi staff 12 5 10 21:13 swift -> swift-driver -rwxr-xr-x@ 1 omochi staff 11865 5 2 06:58 swift-api-checker.py lrwxr-xr-x 1 omochi staff 14 5 10 21:13 swift-api-digester -> swift-frontend lrwxr-xr-x 1 omochi staff 14 5 10 21:13 swift-api-extract -> swift-frontend lrwxr-xr-x 1 omochi staff 14 5 10 21:13 swift-autolink-extract -> swift-frontend lrwxr-xr-x 1 omochi staff 13 5 10 21:13 swift-build -> swift-package -rwxr-xr-x 1 omochi staff 280080 5 2 18:05 swift-build-sdk-interfaces -rwxr-xr-x 1 omochi staff 3266944 5 2 18:05 swift-build-tool lrwxr-xr-x 1 omochi staff 14 5 10 21:13 swift-cache-tool -> swift-frontend -rwxr-xr-x 1 omochi staff 2236016 5 2 18:05 swift-demangle -rwxr-xr-x 1 omochi staff 259712 5 2 18:05 swift-driver lrwxr-xr-x 1 omochi staff 13 5 10 21:13 swift-experimental-sdk -> swift-package -rwxr-xr-x 1 omochi staff 43092736 5 2 18:05 swift-format -rwxr-xr-x 1 omochi staff 547557520 5 2 18:05 swift-frontend -rwxr-xr-x 1 omochi staff 307392 5 2 18:05 swift-help lrwxr-xr-x 1 omochi staff 14 5 10 21:13 swift-legacy-driver -> swift-frontend -rwxr-xr-x 1 omochi staff 108970480 5 2 18:05 swift-package lrwxr-xr-x 1 omochi staff 13 5 10 21:13 swift-package-collection -> swift-package lrwxr-xr-x 1 omochi staff 13 5 10 21:13 swift-package-registry -> swift-package -rwxr-xr-x 1 omochi staff 3966192 5 2 18:05 swift-plugin-server lrwxr-xr-x 1 omochi staff 13 5 10 21:13 swift-run -> swift-package lrwxr-xr-x 1 omochi staff 13 5 10 21:13 swift-sdk -> swift-package -rwxr-xr-x 1 omochi staff 263616 5 2 18:05 swift-stdlib-tool lrwxr-xr-x 1 omochi staff 14 5 10 21:13 swift-symbolgraph-extract -> swift-frontend lrwxr-xr-x 1 omochi staff 13 5 10 21:13 swift-test -> swift-package lrwxr-xr-x 1 omochi staff 12 5 10 21:13 swiftc -> swift-driver lrwxr-xr-x 1 omochi staff 14 5 10 21:13 swiftc-legacy-driver -> swift-frontend lrwxr-xr-x 1 omochi staff 3 5 10 21:13 wasm-ld -> lldswift-sdk -> swift-package (edited)[omochi@omochi-iMacPro macosx]$ pwd /Library/Developer/CommandLineTools/usr/lib/swift/macosx [omochi@omochi-iMacPro macosx]$ ls layouts-x86_64.yaml libcxxshim.h libswiftCompatibility50.a libswiftCompatibilityConcurrency.a libswiftCxx.a lib_InternalSwiftScan.dylib libcxxshim.modulemap libswiftCompatibility51.a libswiftCompatibilityDynamicReplacements.a libswiftCxxStdlib.a lib_InternalSwiftSyntaxParser.dylib libcxxstdlibshim.h libswiftCompatibility56.a libswiftCompatibilityPacks.a[omochi@omochi-iMacPro macosx]$ pwd /Library/Developer/CommandLineTools/usr/lib/swift-5.0/macosx [omochi@omochi-iMacPro macosx]$ ls libswiftAVFoundation.dylib libswiftCoreAudio.dylib libswiftCoreMedia.dylib libswiftGLKit.dylib libswiftMetalKit.dylib libswiftPhotos.dylib libswiftVision.dylib libswiftAccelerate.dylib libswiftCoreData.dylib libswiftCreateML.dylib libswiftGameplayKit.dylib libswiftModelIO.dylib libswiftQuartzCore.dylib libswiftXCTest.dylib libswiftAppKit.dylib libswiftCoreFoundation.dylib libswiftCryptoTokenKit.dylib libswiftIOKit.dylib libswiftNaturalLanguage.dylib libswiftSafariServices.dylib libswiftXPC.dylib libswiftCloudKit.dylib libswiftCoreGraphics.dylib libswiftDarwin.dylib libswiftIntents.dylib libswiftNetwork.dylib libswiftSceneKit.dylib libswiftos.dylib libswiftContacts.dylib libswiftCoreImage.dylib libswiftDispatch.dylib libswiftMapKit.dylib libswiftObjectiveC.dylib libswiftSpriteKit.dylib libswiftsimd.dylib libswiftCore.dylib libswiftCoreLocation.dylib libswiftFoundation.dylib libswiftMetal.dylib libswiftOpenCL.dylib libswiftSwiftOnoneSupport.dylib[omochi@omochi-iMacPro macosx]$ pwd /Library/Developer/CommandLineTools/usr/lib/swift-5.5/macosx [omochi@omochi-iMacPro macosx]$ ls libswift_Concurrency.dylib[omochi@omochi-iMacPro bin]$ pwd /Users/omochi/Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2024-05-01-a.xctoolchain/usr/bin [omochi@omochi-iMacPro bin]$ otool -L swift-package swift-package: /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 1600.157.0) /usr/lib/libsqlite3.dylib (compatibility version 9.0.0, current version 349.3.0) /usr/lib/libncurses.5.4.dylib (compatibility version 5.4.0, current version 5.4.0) /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation (compatibility version 300.0.0, current version 2201.0.0) /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1336.0.0) /System/Library/Frameworks/Combine.framework/Versions/A/Combine (compatibility version 1.0.0, current version 311.0.0, weak) /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 2201.0.0) /System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices (compatibility version 1.0.0, current version 1226.0.0) /System/Library/Frameworks/CryptoKit.framework/Versions/A/CryptoKit (compatibility version 1.0.0, current version 1.0.0) /System/Library/Frameworks/Security.framework/Versions/A/Security (compatibility version 1.0.0, current version 61040.60.20) /System/Library/Frameworks/SystemConfiguration.framework/Versions/A/SystemConfiguration (compatibility version 1.0.0, current version 1296.60.2) /usr/lib/swift/libswiftCore.dylib (compatibility version 1.0.0, current version 0.0.0) /usr/lib/swift/libswiftCoreFoundation.dylib (compatibility version 1.0.0, current version 120.100.0) /usr/lib/swift/libswiftDarwin.dylib (compatibility version 1.0.0, current version 0.0.0) /usr/lib/swift/libswiftDispatch.dylib (compatibility version 1.0.0, current version 34.0.2) /usr/lib/swift/libswiftIOKit.dylib (compatibility version 1.0.0, current version 1.0.0, weak) /usr/lib/swift/libswiftOSLog.dylib (compatibility version 1.0.0, current version 4.0.0, weak) /usr/lib/swift/libswiftObjectiveC.dylib (compatibility version 1.0.0, current version 8.0.0) /usr/lib/swift/libswiftXPC.dylib (compatibility version 1.0.0, current version 29.0.2, weak) /usr/lib/swift/libswift_Concurrency.dylib (compatibility version 1.0.0, current version 0.0.0) /usr/lib/swift/libswiftos.dylib (compatibility version 1.0.0, current version 1040.0.0)$ swift sdk コマンドは動くようになるかな?[omochi@omochi-iMacPro swift-DEVELOPMENT-SNAPSHOT-2024-05-01-a.xctoolchain]$ find usr -name "libswiftCore.dylib" usr/lib/swift/xros/libswiftCore.dylib usr/lib/swift/appletvsimulator/libswiftCore.dylib usr/lib/swift/watchos/libswiftCore.dylib usr/lib/swift/iphoneos/libswiftCore.dylib usr/lib/swift/appletvos/libswiftCore.dylib usr/lib/swift/watchsimulator/libswiftCore.dylib usr/lib/swift/macosx/libswiftCore.dylib usr/lib/swift/iphonesimulator/libswiftCore.dylib usr/lib/swift/xrsimulator/libswiftCore.dylib@executable_path/../lib/swift/libSwiftCore.dylib とかにしていけばいいな[omochi@omochi-iMacPro macosx]$ pwd /Users/omochi/Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2024-05-01-a.xctoolchain/usr/lib/swift/macosx [omochi@omochi-iMacPro macosx]$ otool -L libswiftDarwin.dylib libswiftDarwin.dylib: /usr/lib/swift/libswiftDarwin.dylib (compatibility version 1.0.0, current version 0.0.0) @rpath/libswiftCore.dylib (compatibility version 1.0.0, current version 0.0.0) /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 1600.157.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1336.0.0)[omochi@omochi-iMacPro macosx]$ otool -L libswiftDistributed.dylib libswiftDistributed.dylib: /usr/lib/swift/libswiftDistributed.dylib (compatibility version 1.0.0, current version 0.0.0) @rpath/libswift_Concurrency.dylib (compatibility version 1.0.0, current version 0.0.0) @rpath/libswiftDarwin.dylib (compatibility version 1.0.0, current version 0.0.0, weak) @rpath/libswiftCore.dylib (compatibility version 1.0.0, current version 0.0.0) /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 1600.157.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1336.0.0) /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0)<?xml version="1.0" encoding="UTF-8"?>.<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">.<plist version="1.0">.<dict>. <key>CFBundleIdentifier</key>. <string>com.apple.dt.runtime.swiftCore</string>. <key>CFBundleInfoDictionaryVersion</key>. <string>6.0</string>. <key>CFBundleName</key>. <string>swiftCore</string>. <key>CFBundleShortVersionString</key>. <string>5.10</string>. <key>CFBundleVersion</key>. <string></string>.</dict>.</plist>[omochi@omochi-iMacPro Foundation.framework]$ ls -al total 0 drwxr-xr-x 6 root wheel 192 3 21 15:13 . drwxr-xr-x 262 root wheel 8384 3 21 15:13 .. lrwxr-xr-x 1 root wheel 27 3 21 15:13 Foundation -> Versions/Current/Foundation lrwxr-xr-x 1 root wheel 26 3 21 15:13 Resources -> Versions/Current/Resources drwxr-xr-x 4 root wheel 128 3 21 15:13 Versions lrwxr-xr-x 1 root wheel 28 3 21 15:13 XPCServices -> Versions/Current/XPCServices [omochi@omochi-iMacPro Foundation.framework]$ pwd /System/Library/Frameworks/Foundation.framework [omochi@omochi-iMacPro Foundation.framework]$ ls -al total 0 drwxr-xr-x 6 root wheel 192 3 21 15:13 . drwxr-xr-x 262 root wheel 8384 3 21 15:13 .. lrwxr-xr-x 1 root wheel 27 3 21 15:13 Foundation -> Versions/Current/Foundation lrwxr-xr-x 1 root wheel 26 3 21 15:13 Resources -> Versions/Current/Resources drwxr-xr-x 4 root wheel 128 3 21 15:13 Versions lrwxr-xr-x 1 root wheel 28 3 21 15:13 XPCServices -> Versions/Current/XPCServices [omochi@omochi-iMacPro Foundation.framework]$ ls -al Versions/Current lrwxr-xr-x 1 root wheel 1 3 21 15:13 Versions/Current -> C [omochi@omochi-iMacPro Foundation.framework]$ ls -al Versions/C total 0 drwxr-xr-x 5 root wheel 160 3 21 15:13 . drwxr-xr-x 4 root wheel 128 3 21 15:13 .. drwxr-xr-x 60 root wheel 1920 3 21 15:13 Resources drwxr-xr-x 3 root wheel 96 3 21 15:13 XPCServices drwxr-xr-x 3 root wheel 96 3 21 15:13 _CodeSignature こいつも中身無い<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleIdentifier</key> <string>com.apple.dt.runtime.swiftCore</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>swiftCore</string> <key>CFBundleShortVersionString</key> <string>5.8.2</string> <key>CFBundleVersion</key> <string>5.8.2.0.1</string> </dict> </plist>/System/Library/Frameworks を見てるけど、見えないし、toolchainにはFoundationないから@rpath になってたらワンチャンあるな (edited)_stdlib_isOSVersionAtLeast の実装を変えるのは厳しいので_stdlib_isOSVersionAtLeast の実装をalwaysEmitIntoClientにして/usr/lib/ を読むものが生成されちゃうだけという理解_stdlib_isOSVersionAtLeast に対して9999をチェックするようなコードを持たないので動く_stdlib_isOSVersionAtLeast に対して9999をチェックするようなコードを持たないので動く
1_stdlib_isOSVersionAtLeast のふるまいが変わるのが良さそう?-override-runtime-os-version 9999 みたいな・・・_stdlib_isOSVersionAtLeast がリンクされるのってどのタイミングなんだっけ (edited)libswiftCore.dylib じゃなくて executable 自身に同じシンボルを置いといたらそっちが優先でリンクとか_stdlib_isOSVersionAtLeastがnon-weak symbolとして定義されてるからss23withCheckedContinuation9isolation8function_xScA_pSgYi_SSyScCyxs5NeverOGXEtYalFTu こっちを用意しちゃう手はあるか?[omochi@omochi-iMacPro C]$ pwd /Users/omochi/temp/libs/System/Library/Frameworks/Foundation.framework/Versions/C [omochi@omochi-iMacPro C]$ ls -al total 43608 drwxr-xr-x 3 omochi staff 96 5 10 23:15 . drwxr-xr-x 3 omochi staff 96 5 10 23:15 .. -rw-r--r-- 1 omochi staff 22327296 5 10 23:15 Foundation extract したやつちゃんと見えなかった部分だけ中身入ってるなあ[omochi@omochi-iMacPro C]$ otool -L Foundation Foundation: /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation (compatibility version 300.0.0, current version 2420.0.0) /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0, reexport) /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 2420.0.0, reexport) /System/Library/PrivateFrameworks/CoreAutoLayout.framework/Versions/A/CoreAutoLayout (compatibility version 1.0.0, current version 32.0.0, weak) /System/Library/Frameworks/SystemConfiguration.framework/Versions/A/SystemConfiguration (compatibility version 1.0.0, current version 1300.100.9) /usr/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.12) /usr/lib/libfakelink.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libcompression.dylib (compatibility version 1.0.0, current version 1.0.0) /System/Library/Frameworks/CFNetwork.framework/Versions/A/CFNetwork (compatibility version 1.0.0, current version 1494.0.7) /System/Library/Frameworks/DiskArbitration.framework/Versions/A/DiskArbitration (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libarchive.2.dylib (compatibility version 9.0.0, current version 9.2.0) /usr/lib/libDiagnosticMessagesClient.dylib (compatibility version 1.0.0, current version 113.0.0) /usr/lib/libicucore.A.dylib (compatibility version 1.0.0, current version 74.1.0) /usr/lib/libxml2.2.dylib (compatibility version 10.0.0, current version 10.9.0) /System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices (compatibility version 1.0.0, current version 1226.0.0) /usr/lib/liblangid.dylib (compatibility version 1.0.0, current version 1.0.0) /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit (compatibility version 1.0.0, current version 275.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1345.100.2) /System/Library/Frameworks/Combine.framework/Versions/A/Combine (compatibility version 1.0.0, current version 311.0.0) /System/Library/PrivateFrameworks/CollectionsInternal.framework/Versions/A/CollectionsInternal (compatibility version 22.0.0, current version 22.0.0) /System/Library/PrivateFrameworks/ReflectionInternal.framework/Versions/A/ReflectionInternal (compatibility version 22.0.0, current version 22.0.0) /System/Library/PrivateFrameworks/RuntimeInternal.framework/Versions/A/RuntimeInternal (compatibility version 22.0.0, current version 22.0.0) /System/Library/PrivateFrameworks/SoftLinking.framework/Versions/A/SoftLinking (compatibility version 1.0.0, current version 47.0.0) /usr/lib/swift/libswiftCore.dylib (compatibility version 1.0.0, current version 0.0.0) /usr/lib/swift/libswiftCoreFoundation.dylib (compatibility version 1.0.0, current version 120.100.0) /usr/lib/swift/libswiftDarwin.dylib (compatibility version 1.0.0, current version 0.0.0) /usr/lib/swift/libswiftDispatch.dylib (compatibility version 1.0.0, current version 41.0.0) /usr/lib/swift/libswiftIOKit.dylib (compatibility version 1.0.0, current version 1.0.0, weak) /usr/lib/swift/libswiftObjectiveC.dylib (compatibility version 1.0.0, current version 8.0.0) /usr/lib/swift/libswiftXPC.dylib (compatibility version 1.0.0, current version 36.100.7, weak) /usr/lib/swift/libswift_Concurrency.dylib (compatibility version 1.0.0, current version 0.0.0) /usr/lib/swift/libswift_StringProcessing.dylib (compatibility version 1.0.0, current version 0.0.0) /usr/lib/swift/libswiftos.dylib (compatibility version 1.0.0, current version 1049.100.4)Member Author finestructure commented 2 weeks ago Good news! We've got a new Orka base image with Sonoma 14.3.1 which doesn't crash. (The underlying issue is one in SwiftPM with newer macOS versions: apple/swift#73327)swift package --version と swift experimental-sdk install でセグメンテーションフォルト起きました.swift package --version と swift experimental-sdk install でセグメンテーションフォルト起きました. withUnsafeContinuation(isolation:) 以外に、それ以前に導入された backDeploy 付きの6.0 API を探してみました5.11 から 6.0 の書き換えが網羅されているのでわかりやすくて_willThrowTyped はこの時点で if #available だったので、swift package --version ですら落ちるのは、該当しないから、謎ですね。5.10-SNAPSHOT-2024-04-26-a-wasmでした[omochi@omochi-iMacPro ~]$ swift --version swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4) [omochi@omochi-iMacPro ~]$ swift experimental-sdk install https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.10-SNAPSHOT-2024-04-26-a/swift-wasm-5.10-SNAPSHOT-2024-04-26-a-macos_x86_64.artifactbundle.zip Downloading a Swift SDK bundle archive from `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.10-SNAPSHOT-2024-04-26-a/swift-wasm-5.10-SNAPSHOT-2024-04-26-a-macos_x86_64.artifactbundle.zip`... Swift SDK bundle archive successfully downloaded from `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.10-SNAPSHOT-2024-04-26-a/swift-wasm-5.10-SNAPSHOT-2024-04-26-a-macos_x86_64.artifactbundle.zip`. Swift SDK bundle at `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.10-SNAPSHOT-2024-04-26-a/swift-wasm-5.10-SNAPSHOT-2024-04-26-a-macos_x86_64.artifactbundle.zip` is assumed to be an archive, unpacking... Swift SDK bundle at `https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.10-SNAPSHOT-2024-04-26-a/swift-wasm-5.10-SNAPSHOT-2024-04-26-a-macos_x86_64.artifactbundle.zip` successfully installed as swift-wasm-5.10-SNAPSHOT-2024-04-26-a-macos_x86_64.artifactbundle. [omochi@omochi-iMacPro ~]$ swift experimental-sdk list 5.10-SNAPSHOT-2024-04-26-a-wasm Icemanの構成は多分こうだな 5.10系ベースの作業だから問題が起きるのは $ swift test だけで、 それはやってないという事だから、大丈夫だったんだexperimental-sdk じゃなくて sdk で書かれてるから互換性の問題があるけど、 Icemanは自作のアプリケーションを組んでみただけだから特にそのへんも使ってなくて踏んでないという事かな (edited)#include <stdio.h> #include <stdint.h> extern int8_t $ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF(int64_t major, int64_t minor, int64_t patch); int main() { int8_t y = $ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF(9999, 0, 0); printf("%d\n", y); return 0; }$ clang -L $(xcrun --show-sdk-path)/usr/lib/swift -lswiftcore v.c && ./a.out 0[omochi@omochi-mbp ~]$ xcode-select -p /Applications/Xcode15.3.app/Contents/Developer [omochi@omochi-mbp ~]$ swift --version swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4) Target: arm64-apple-macosx14.0 [omochi@omochi-mbp ~]$ xcode-select -p /Applications/Xcode15.4-beta.app/Contents/Developer [omochi@omochi-mbp ~]$ swift --version swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4) Target: arm64-apple-macosx14.0 [omochi@omochi-mbp ~]$ xcode-select -p /Applications/Xcode15.4-rc.app/Contents/Developer [omochi@omochi-mbp ~]$ swift --version swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4) Target: arm64-apple-macosx14.0 ついでに確認。XcodeのSwiftは15.3から15.4 RC にかけて全く変化していないらしい。/Users/omochi/github/omochi/swift-react/.build/wasm32-unknown-wasi/debug/swift-reactPackageTests.derived/runner.swift:31:31: error: value of type 'Data' has no member 'write' _ = try? data.write(to: URL(fileURLWithPath: self.testOutputPath)) ~~~~ ^~~~~ /Users/omochi/github/omochi/swift-react/.build/wasm32-unknown-wasi/debug/swift-reactPackageTests.derived/runner.swift:396:42: error: value of type 'Bundle' has no member 'bundleIdentifier' bundleIdentifier: testBundle.bundleIdentifier, ~~~~~~~~~~ ^~~~~~~~~~~~~~~~$ swift package --version zsh: segmentation fault swift package --version (edited)Thread 1 Crashed: 0 ??? 0x0 ??? 1 swift-package 0x1044756a0 static AsyncParsableCommand.main() + 72 2 swift-package 0x10445a331 specialized static SwiftPM.main(execName:) + 1 3 swift-package 0x10445a779 specialized static SwiftPM.main() + 1 4 swift-package 0x104459bc5 specialized thunk for @escaping @convention(thin) @async () -> () + 1 5 libswift_Concurrency.dylib 0x25125b149 completeTaskAndRelease(swift::AsyncContext*, swift::SwiftError*) + 1@available(macOS 10.15, macCatalyst 13, iOS 13, tvOS 13, watchOS 6, *) extension AsyncParsableCommand { /// Executes this command, or one of its subcommands, with the program's /// command-line arguments. /// /// Instead of calling this method directly, you can add `@main` to the root /// command for your command-line tool. public static func main() async { do { var command = try parseAsRoot() if var asyncCommand = command as? AsyncParsableCommand { try await asyncCommand.run() } else { try command.run() } } catch { exit(withError: error) } } }$ swift package --version でクラッシュするな--version オプションがくると、 swift-argument-parser は ParserError.versionRequested を throw するらしいswift_willThrow is called with an error right before it is thrown. This existing entrypoint requires an already-boxed error existential; with typed errors, we don't have the error existen...swift package --version: 04-02-a も 05-01-a もセグフォswift experimental-sdk list: 04-02-a も 05-01-a もセグフォなしswift experimental-sdk install: 04-02-a も 05-01-a もセグフォswift experimental-sdk install a: 04-02-a はセグフォなしで 05-01-a はセグフォ (ここだけ違う)Function 型 の variadic generics を諦めないといけない (edited)
1wasm32-unknown-wasiの置き場所が見つけられなくて終わってしまったswift experimental-sdk listがNo Swift SDKs are currently installed.だったのでどこかから取ってこないととなり探している間に終わりました$ swift package --version ですら死ぬんですよね $ swift test だけはできない。[omochi@omochi-mbp swift-react (swift510 *%)]$ docker/run srt bash + docker run -it -v/Users/omochi/github/omochi/swift-react:/work -w /work srt bash root@a6b7229d9153:/work# ls BrowserTests CartonExample Codegen LICENSE Package.resolved Package.swift README.ja.md README.md Sources Tests bin docker docs temp root@a6b7229d9153:/work# bin/test + swift build --experimental-swift-sdk wasm32-unknown-wasi --build-tests --disable-build-manifest-caching --static-swift-stdlib -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor -Xlinker --export-if-defined=__main_argc_argv -Xlinker --stack-first -Xlinker --global-base=1048576 -Xlinker -z -Xlinker stack-size=1048576 warning: `--experimental-swift-sdk` is deprecated and will be removed in a future version of SwiftPM. Use `--swift-sdk` instead. warning: 'swift-algorithms': found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /work/.build/checkouts/swift-algorithms/Sources/Algorithms/Documentation.docc Building for debugging... warning: Could not read SDKSettings.json for SDK at: /root/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk <unknown>:0: warning: libc not found for 'wasm32-unknown-wasi'; C stdlib may be unavailable warning: Could not read SDKSettings.json for SDK at: /root/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk <unknown>:0: warning: libc not found for 'wasm32-unknown-wasi'; C stdlib may be unavailable [5/5] Emitting module swift_reactPackageTests Build complete! (1.11s) + CartonFrontend test --prebuilt-test-bundle-path .build/debug/swift-reactPackageTests.wasm --environment browser--environment browser なしだと + CartonFrontend test --prebuilt-test-bundle-path .build/debug/swift-reactPackageTests.wasm Error: No WASI runtime found. Please install one of the following: wasmtime, wasmer ちゃんと入ってないっていうけど (edited)root@a6b7229d9153:/work# which chromedriver /usr/bin/chromedriver root@a6b7229d9153:/work# ls BrowserTests CartonExample Codegen LICENSE Package.resolved Package.swift README.ja.md README.md Sources Tests bin docker docs temp root@a6b7229d9153:/work# export WEBDRIVER_PATH=/usr/bin/chromedriver root@a6b7229d9153:/work# bin/test + swift build --experimental-swift-sdk wasm32-unknown-wasi --build-tests --disable-build-manifest-caching --static-swift-stdlib -Xswiftc -Xclang-linker -Xswiftc -mexec-model=reactor -Xlinker --export-if-defined=__main_argc_argv -Xlinker --stack-first -Xlinker --global-base=1048576 -Xlinker -z -Xlinker stack-size=1048576 warning: `--experimental-swift-sdk` is deprecated and will be removed in a future version of SwiftPM. Use `--swift-sdk` instead. warning: 'swift-algorithms': found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /work/.build/checkouts/swift-algorithms/Sources/Algorithms/Documentation.docc Building for debugging... warning: Could not read SDKSettings.json for SDK at: /root/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk <unknown>:0: warning: libc not found for 'wasm32-unknown-wasi'; C stdlib may be unavailable warning: Could not read SDKSettings.json for SDK at: /root/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2024-05-02-a-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk <unknown>:0: warning: libc not found for 'wasm32-unknown-wasi'; C stdlib may be unavailable [5/5] Emitting module swift_reactPackageTests Build complete! (1.16s) + CartonFrontend test --prebuilt-test-bundle-path .build/debug/swift-reactPackageTests.wasm --environment browser--headless を指定してなかった[5/5] Emitting module swift_reactPackageTests Build complete! (0.74s) + CartonFrontend test --prebuilt-test-bundle-path .build/debug/swift-reactPackageTests.wasm --environment browser --headless run() 155 enter run() 169 server.start run() 174 if headless - checking WebDriver endpoint: WEBDRIVER_REMOTE_URL - checking WebDriver executable: WEBDRIVER_PATH - checking WebDriver executable in PATH: chromedriver, geckodriver, safaridriver, msedgedriver Launch WebDriver executable: /usr/bin/chromedriver newSession enter newSession enter newSession enter newSession enter run() 193 catch Error: httpError("")safaridriver -p ポート番号 で指定できませんかね?sudo lsof -i -P | grep LISTEN とかで確認しました[omochi@omochi-mbp ~]$ sudo safaridriver --enable --port 17050 Password: [omochi@omochi-mbp ~]$ sudo lsof -i -P | grep LISTEN remoted 1119 root 5u IPv6 0xd0de49af35499627 0t0 TCP [fdc8:fba4:126c::2]:53195 (LISTEN) remoted 1119 root 7u IPv6 0x52292580606b05e6 0t0 TCP omochi-mbp.local:53191 (LISTEN) rapportd 1596 omochi 8u IPv4 0xe8d6be9266e195d6 0t0 TCP *:51137 (LISTEN) rapportd 1596 omochi 9u IPv6 0x15d7a11c09620632 0t0 TCP *:51137 (LISTEN) ControlCe 1674 omochi 8u IPv4 0x88e981bae7ea5bbb 0t0 TCP *:7000 (LISTEN) ControlCe 1674 omochi 9u IPv6 0xfc82083d7a198a98 0t0 TCP *:7000 (LISTEN) ControlCe 1674 omochi 10u IPv4 0xee38eb95712c7518 0t0 TCP *:5000 (LISTEN) ControlCe 1674 omochi 11u IPv6 0xb5908ffeaaf9caaf 0t0 TCP *:5000 (LISTEN) Spotify 1833 omochi 79u IPv4 0x86ee11d1436b4266 0t0 TCP *:57621 (LISTEN) Spotify 1833 omochi 167u IPv4 0x39ffee1aad0ac3fd 0t0 TCP *:50640 (LISTEN) Discord 2291 omochi 55u IPv4 0x2801755917c85bfb 0t0 TCP localhost:6463 (LISTEN) postgres 2620 omochi 6u IPv6 0xf5f90438e844e502 0t0 TCP *:5432 (LISTEN) postgres 2620 omochi 7u IPv4 0x2a937b5b848bb485 0t0 TCP *:5432 (LISTEN) minio 2621 omochi 13u IPv4 0x72943b925f8e67bb 0t0 TCP localhost:9000 (LISTEN) minio 2621 omochi 14u IPv6 0x4a5863c55dd6b38b 0t0 TCP *:9000 (LISTEN) minio 2621 omochi 15u IPv6 0x14a12d1a8a02ab08 0t0 TCP localhost:9000 (LISTEN) minio 2621 omochi 17u IPv6 0x2e68ab3e07de3095 0t0 TCP *:49482 (LISTEN) Dropbox 2627 omochi 96u IPv4 0x7f66e570c96ba2ff 0t0 TCP localhost:17600 (LISTEN) Dropbox 2627 omochi 100u IPv4 0x464c961894095d2a 0t0 TCP localhost:17603 (LISTEN) 手順はあってますかね?safaridriver -p ポート番号 ですね.--enable が余計なんだと思います.Error: httpError("{\"value\":{\"error\":\"invalid argument\",\"message\":\"\'Host\' header or \'Origin\' header is specified and is not localhost.\",\"stacktrace\":\"\"}}")WEBDRIVER_REMOTE_URL=http://host.docker.internal:7055Host ヘッダを localhost にすることで対応してたりするみたいですね. https://github.com/aerokube/selenoid/pull/1106/files#diff-d35ea78528174635da15762a20dcb5043d652bbf66b5c87b975f700701882400R509Command '/usr/bin/chromedriver' requires the chromium snap to be installed. Please install it with: snap install chromium chromeはapt-getのやつはもうダメらしいtest.js が返ってこないのなんだtest.js を返す制御ってどこですか? configuration.entrypoint に test.js って書いてあるんだけど、 routerの実装で configuration.entrypoint を読んでる部分がないので、 配送できないように見える 実際 index.html は取れるけど test.js は取れない [omochi@omochi-mbp swift-react (swift510 *%)]$ curl -v http://127.0.0.1:8080/ * Trying 127.0.0.1:8080... * Connected to 127.0.0.1 (127.0.0.1) port 8080 > GET / HTTP/1.1 > Host: 127.0.0.1:8080 > User-Agent: curl/8.6.0 > Accept: */* > < HTTP/1.1 200 OK < Content-Type: text/html < Content-Length: 228 < Connection: close < <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script type="module" src="test.js"></script> </head> <body> </body> * Closing connection </html>% [omochi@omochi-mbp swift-react (swift510 *%)]$ curl -v http://127.0.0.1:8080/test.js * Trying 127.0.0.1:8080... * Connected to 127.0.0.1 (127.0.0.1) port 8080 > GET /test.js HTTP/1.1 > Host: 127.0.0.1:8080 > User-Agent: curl/8.6.0 > Accept: */* > < HTTP/1.1 404 Not Found < Connection: close < Content-Length: 0 < * Closing connection.carton/static か print("\(#function) \(#line) \(FileManager.default.homeDirectoryForCurrentUser)") var responders = [ self.makeStaticResourcesResponder( baseDirectory: FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent(".carton") .appendingPathComponent("static") ) ] ↑これが /root になってることは確認できた (edited)respond(context:head:) 116 file:///root/ ちゃんと /root だったよroot@df5f8f3e3a18:/work/carton# ls -al /root total 40 drwx------ 1 root root 4096 May 14 12:40 . drwxr-xr-x 1 root root 4096 May 14 15:33 .. -rw-r--r-- 1 root root 3106 Oct 15 2021 .bashrc drwx------ 1 root root 4096 May 14 15:34 .cache drwxr-xr-x 1 root root 4096 May 14 12:40 .local -rw-r--r-- 1 root root 161 Jul 9 2019 .profile drwxr-xr-x 1 root root 4096 May 14 15:34 .swiftpmdev.js を配送できない問題の再現テストができた 大変だったSwift/ErrorType.swift:200: Fatal error: Error raised at top level: Response from https://api.github.com/repos/swiftwasm/swift/releases/tags/swift-wasm-5.9.2-RELEASE had invalid status 403 or didn't contain bodySwift/ErrorType.swift:200: Fatal error: Error raised at top level: Response from https://api.github.com/repos/swiftwasm/swift/releases/tags/swift-wasm-5.9.2-RELEASE had invalid status 403 with a body of 279 bytes: {"message":"API rate limit exceeded for 13.105.117.68. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)","documentation_url":"https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting"}TRACE fs home=/Users/runner [".net", ".config", ".yarn", "bootstrap", ".CFUserTextEncoding", ".bashrc", ".carton", "image-generation", ".vcpkg", ".local", "imagedata.json", "Desktop", "Library", "downloader", ".azcopy", "actionarchivecache", ".azure-devops", ".cargo", ".android", ".bash_sessions", "hostedtoolcache", "work", ".rustup", ".ssh", "Movies", ".dotnet", ".gradle", ".Trash", "systeminfo.md", "runners", ".npm", "systeminfo.json", "Documents", ".bash_profile", ".swiftpm", "Downloads", ".cache", ".gitconfig", ".Azure"] TRACE dot carton ["static"].carton/static が、居るぞ - name: Build and install JavaScript and sanitizer resources run: | set -ex npm install swift run carton-release hash-archive mkdir -p $HOME/.carton cp -r static $HOME/.carton これかっBuilder.swift がなくなって、それによってStackSanitizerを埋め込む動作がなくなっている?WasmTransformer パッケージも不要になったのかと思ったが、 stripCustomSections って関数だけ使われているらしい swift-test-linux: name: Build and test on Linux with Swift ${{ matrix.swift_version }} timeout-minutes: 40 runs-on: ubuntu-22.04 container: swift:${{ matrix.swift_version }} この container: を見落としていたというか意味が分かってなかった-v つけてみるか$ swift test がビルド終わった後着火しない848ae5a fix process env は完走できてて、同じ内容の 83755ca (HEAD -> look-ci, omochi/look-ci) investigate ci failures が止まってるから$ swift test して見たら良いのかMay 18 12:44:00 installer[20690] <Info>: Set authorization level to none for session May 18 12:44:00 installer[20690] <Info>: Authorization is being checked, waiting until authorization arrives. May 18 12:44:00 installer[20690] <Info>: Packages have been authorized for installation. May 18 12:44:00 installer[20690] <Debug>: Will use PK session May 18 12:44:00 installer[20690] <Debug>: Using authorization level of none for IFPKInstallElement May 18 12:44:00 installer[20690] <Info>: PackageKit: Bypassing the enforcement checker since the destination is read/write May 18 12:44:00 installer[20690] <Info>: Starting installation: May 18 12:44:00 installer[20690] <Notice>: Configuring volume "Macintosh HD" May 18 12:44:00 installer[20690] <Info>: Preparing disk for local booted install. May 18 12:44:00 installer[20690] <Notice>: Free space on "Macintosh HD": 162.34 GB (162337476608 bytes). May 18 12:44:00 installer[20690] <Notice>: Create temporary directory "/var/folders/yv/tw23g49x7kb1jh_s6mf3zvyh0000gn/T//Install.20690Q5seDJ" May 18 12:44:00 installer[20690] <Notice>: IFPKInstallElement (1 packages) May 18 12:44:00 installer[20690] <Info>: Current Path: /usr/sbin/installer May 18 12:44:00 installer[20690] <Info>: Current Path: /bin/bash May 18 12:44:00 installer[20690] <Info>: Current Path: /usr/local/Cellar/tmate/2.4.0/bin/tmate May 18 12:44:00 installer[20690] <Error>: PackageKit: Service connection invalidated! May 18 12:44:00 installer[20690] <Error>: PackageKit: XPC error in -[_PKInstallClientConnection blockingProxy]_block_invoke_2 (Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.installd.user was invalidated: failed at lookup with error 3 - No such process." UserInfo={NSDebugDescription=The connection to service named com.apple.installd.user was invalidated: failed at lookup with error 3 - No such process.}) May 18 12:44:00 installer[20690] <Debug>: PackageKit: Received request to finish installation before PKInstallClient initialization was complete. Ignoring. May 18 12:44:00 installer[20690] <Error>: Couldn't instantiate install client: Error Domain=PKInstallErrorDomain Code=201 "An error occurred establishing a connection to the installation service." UserInfo={NSLocalizedDescription=An error occurred establishing a connection to the installation service.} May 18 12:44:00 installer[20690] <Info>: PackageKit: Bypassing the enforcement checker since the destination is read/write May 18 12:44:00 installer[20690] <Error>: Install failed.bash-3.2$ swift run carton bundle warning: 'carton': /Users/runner/work/carton/carton/Package.swift:7:10: warning: Swift 5.9.1 or earlier is not supported by carton #warning("Swift 5.9.1 or earlier is not supported by carton") ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Building for debugging... Build complete! (1.09s) - checking Swift compiler path: /Users/runner/.carton/sdk/wasm-5.9.2-RELEASE/usr/bin/swift - checking Swift compiler path: /Users/runner/.swiftenv/versions/wasm-5.9.2-RELEASE/usr/bin/swift - checking Swift compiler path: /Users/runner/Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain/usr/bin/swift - checking Swift compiler path: /Library/Developer/Toolchains/swift-wasm-5.9.2-RELEASE.xctoolchain/usr/bin/swift Fetching release assets from https://api.github.com/repos/swiftwasm/swift/releases/tags/swift-wasm-5.9.2-RELEASE Response contained body, parsing it now... Response succesfully parsed, choosing from this number of assets: 14 Local installation of Swift version wasm-5.9.2-RELEASE not found Swift toolchain/SDK download URL: https://github.com/swiftwasm/swift/releases/download/swift-wasm-5.9.2-RELEASE/swift-wasm-5.9.2-RELEASE-macos_x86_64.pkg Archive size is 944 MB Downloading the archive 99% [=======================================================================================================================================================================--] saving to /Users/runner/.carton/sdk/wasm-5.9.2-RELEASE.pkgDownload completed successfully Unpacking the archive: installer -target CurrentUserHomeDirectory -pkg /Users/runner/.carton/sdk/wasm-5.9.2-RELEASE.pkg Running... installer -target CurrentUserHomeDirectory -pkg /Users/runner/.carton/sdk/wasm-5.9.2-RELEASE.pkginstaller: Package name is wasm-5.9.2-RELEASE installer: Installing at base path /Users/runner installer: The install failed.. Process failed and produced following output: Process failed with non-zero exit status and following output: and following error output: Swift/ErrorType.swift:200: Fatal error: Error raised at top level: Process failed with non-zero exit status and following output: and following error output: Illegal instruction: 4$ sudo installer -target / -pkg swift-wasm-5.9.2-RELEASE-macos_x86_64.pkg -dumplog これは通る$ sudo installer -target CurrentUserHomeDirectory -pkg swift-wasm-5.9.2-RELEASE-macos_x86_64.pkg -dumplog これは通らないactions/checkout@v4 より前だから、リポジトリは関係なくインストールができなくなったTest Case '-[CartonCommandTests.BundleCommandTests testWithDebugInfo]' passed (187.200 seconds)..carton ディレクトリ消したの関係あるかもなメモ .cartonあり Test Case '-[CartonCommandTests.BundleCommandTests testWasmOptimizationOptions]' passed (219.886 seconds). Test Case '-[CartonCommandTests.BundleCommandTests testWithDebugInfo]' passed (13.733 seconds). Test Case '-[CartonCommandTests.BundleCommandTests testWithNoArguments]' passed (23.640 seconds). Test Case '-[CartonCommandTests.BundleCommandTests testWithoutContentHash]' passed (7.714 seconds). .cartonなし Test Case '-[CartonCommandTests.BundleCommandTests testWasmOptimizationOptions]' passed (231.116 seconds). Test Case '-[CartonCommandTests.BundleCommandTests testWithDebugInfo]' passed (14.156 seconds). Test Case '-[CartonCommandTests.BundleCommandTests testWithNoArguments]' passed (23.088 seconds). Test Case '-[CartonCommandTests.BundleCommandTests testWithoutContentHash]' passed (7.911 seconds). (edited).carton がないから、test.js が落ちてこなくて、ブラウザテストが永久に停止しないのか!$ swift test だとまた違うのかなeval "$(/opt/homebrew/bin/brew shellenv)" しろってなってて
2NSURL とかは温存されてて、ブリッジプロトコルで対応させるんですねNSURL とかは温存されてて、ブリッジプロトコルで対応させるんですね NSURL には、値型の URL とかを、 参照型として共有するために boxingした型としての用途があるんで使ってる人がいるかもしれない。 Box<T> 作った方がいいけど・・・ (edited)DYLD_LIBRARY_PATH って絶対パス指定よりも強いの?1 は codesign 付け直してセキュリティを殺してるだけ?DYLD_LIBRARY_PATH って絶対パス指定よりも強いの?
1DYLD_LIBRARY_PATH パラメータめっちゃ強くて怖いな (edited)com.apple.quarantine xattrアトリビュートがファイルについてるとadhocでサインされたバイナリはGatekeeperが止めるはずcom.apple.quarantine xattrアトリビュートは普通ダウンロードしてきたファイルに付いてくるやつIntroduce a (temporary) dlsym check for swift_willThrowTypedImpl. #72801 もずっと止まってるし、個別に迂回するんじゃなくてバージョンチェック直す方向で見直してるのかな〜そうだといいな#if compiler でバージョン判定してるやつ、コンパイルタイムとランタイムで違うツールチェーンだったらダメな気がしたけどdiff --git a/Sources/CartonKit/Server/ServerHTTPHandler.swift b/Sources/CartonKit/Server/ServerHTTPHandler.swift index 87c72de..0f7c494 100644 --- a/Sources/CartonKit/Server/ServerHTTPHandler.swift +++ b/Sources/CartonKit/Server/ServerHTTPHandler.swift @@ -71,6 +71,11 @@ final class ServerHTTPHandler: ChannelInboundHandler, RemovableChannelHandler { bytes: localFileSystem.readFileContents(configuration.mainWasmPath).contents ) ) + case "/" + configuration.entrypoint.fileName: + response = StaticResponse( + contentType: "application/javascript", + body: ByteBuffer(bytes: configuration.entrypoint.content.contents) + ) default: guard let staticResponse = try self.respond(context: context, head: head) else { self.respond404(context: context) @@ -111,13 +116,7 @@ final class ServerHTTPHandler: ChannelInboundHandler, RemovableChannelHandler { private func respond(context: ChannelHandlerContext, head: HTTPRequestHead) throws -> StaticResponse? { - var responders = [ - self.makeStaticResourcesResponder( - baseDirectory: FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent(".carton") - .appendingPathComponent("static") - ) - ] + var responders: [(_ context: ChannelHandlerContext, _ uri: String) throws -> StaticResponse?] = [] let buildDirectory = configuration.mainWasmPath.parentDirectory for directoryName in try localFileSystem.resourcesDirectoryNames(relativeTo: buildDirectory) {$ carton-frontend dev を単体で動かしてレスポンスを見るテストを書こうとしてるんだけど$ carton dev がやるのと同じように、ToolchainSystem を直接叩いて 5.9.2 をインストールさせる作戦だったんだけどDevCommandTests がある)Environment 今2カ所にいるよね。CartonFrontendCommand.Environment と PluginShared.EnvironmentCartonCore だったんだけど。 func applyBuildParameters(_ parameters: inout Parameters) { // NOTE: We only support static linking for now, and the new SwiftDriver // does not infer `-static-stdlib` for WebAssembly targets intentionally // for future dynamic linking support. parameters.otherSwiftcFlags += ["-static-stdlib"] switch self { case .command: break case .node, .browser: parameters.otherSwiftcFlags += ["-Xclang-linker", "-mexec-model=reactor"] #if compiler(>=6.0) || compiler(>=5.11) parameters.otherLinkerFlags += ["--export-if-defined=__main_argc_argv"] #else // Before Swift 6.0, the main function is defined as "main" instead of mangled "__main_argc_argv" parameters.otherLinkerFlags += ["--export-if-defined=main"] #endif } } テストから叩くならこのcompiler directiveが問題になるなwpublic let defaultToolchainVersion = "wasm-5.9.2-RELEASE"wasm-5.9.2-RELEASE なんだけど5.9.2 をどうやって取り出すか?$ swift --version を叩きたいなあとも思っている (edited)#if compiler(>=6.0) print("6.0") #elseif ...#if compiler(>=6.0) #error("I am 6.0") #elseifcarton build コマンドを提供しないのはなぜ? (edited)--target とか --sdk は一番手前の $ swift build を叩かないと指定できないけど$ swift build --sdk wasm32... だけでうまくいくことよね--export-if-defined=main をつけるとかを知って、注入してくれないといけない? (edited)@expose(wasm) func して (edited)crate-type = cdylib ってCargo.tomlに書いとくとエントリポイント無しnon-PIC .wasmで決め打ちで作っちゃうんだけど@expose みたいなのと同じでpic: true みたいな、 設定が生えてきて欲しい (edited)$ carton configure とかやったら、Package.swiftを勝手に書き換えて埋め込んでくれたら良いのではplatform: .wasi ついてれば害もないしRun ボタン押した時の結果だけ事前に用意されてたURL: https://syzf23805k.execute-api.ap-northeast-1.amazonaws.com/prod/CompileSwiftWasm (edited)URL: https://swiftwasm-compiler-api-mgv5x4syda-uc.a.run.app/run.app は cloudrun らしいね switch event { case let .stackTrace(rawStackTrace): if let stackTrace = rawStackTrace.parsedStackTrace(in: environment) { terminal.write("\nAn error occurred, here's a stack trace for it:\n", inColor: .red) stackTrace.forEach { item in terminal.write(" \(item.symbol)", inColor: .cyan) terminal.write(" at \(item.location ?? "<unknown>")\n", inColor: .gray) } } else { terminal.write("\nAn error occurred, here's the raw stack trace for it:\n", inColor: .red) terminal.write( " Please create an issue or PR to the Carton repository\n" + " with your browser name and this raw stack trace so\n" + " we can add support for it: https://github.com/swiftwasm/carton\n", inColor: .gray ) terminal.write(rawStackTrace + "\n") } const wasmRunner = WasmRunner( { onStderr() { const prevLimit = Error.stackTraceLimit; Error.stackTraceLimit = 1000; socket.send( JSON.stringify({ kind: "stackTrace", stackTrace: new Error().stack, }) ); Error.stackTraceLimit = prevLimit; }, },unhandledrejectionをlistenしておくのと最初の main関数の呼び出しで捕まえておくので十分そう
1extension AbsolutePath { func ls() -> [String] { guard let paths = try? FileManager.default.subpathsOfDirectory(atPath: pathString) else { return [] } return paths } } XCTAssertFalse( (bundleDirectory.ls().filter { $0.contains("wasm") }).isEmpty, ".wasm file does not exist" ) XCTAssertFalse( (bundleDirectory.ls().filter { $0.contains("js") }).isEmpty, ".js does not exist" )bjorn3/browser_wasi_shimは壊れててもすぐ直せる程度の規模でよい let runtimeConstructor: SwiftRuntimeConstructor | undefined = undefined; try { const { SwiftRuntime } = await import( // @ts-ignore "./JavaScriptKit_JavaScriptKit.resources/Runtime/index.mjs" ); runtimeConstructor = SwiftRuntime; } catch { console.log( "JavaScriptKit module not available, running without JavaScriptKit runtime." ); } 意図的な制御があるし、そうっぽいな#if os(WASI) import WASILibc #else import Darwin #endif func fputs(_ string: String, file: UnsafeMutablePointer<FILE>) { _ = string.withCString { (cstr) in fputs(cstr, file) } } fputs("hello stdout", file: stdout) fputs("hello stderr", file: stderr)[1/3] Compiling app main.swift /Users/omochi/github/swiftwasm/carton/Tests/Fixtures/DevServerTestApp/Sources/app/main.swift:7:57: error: cannot find type 'FILE' in scope func fputs(_ string: String, file: UnsafeMutablePointer<FILE>) { ^~~~ /Users/omochi/github/swiftwasm/carton/Tests/Fixtures/DevServerTestApp/Sources/app/main.swift:13:6: error: extraneous argument label 'file:' in call fputs("hello stdout", file: stdout) ^ ~~~~~~ /Users/omochi/github/swiftwasm/carton/Tests/Fixtures/DevServerTestApp/Sources/app/main.swift:14:6: error: extraneous argument label 'file:' in call fputs("hello stderr", file: stderr) ^ ~~~~~~ Build completed successfullyWASILibc に FILE が無いみたい?どこ見ればいいんでしょう[omochi@omochi-mbp swift-wasm-5.9.2-RELEASE.xctoolchain]$ find . | grep stdio.h ./usr/share/wasi-sysroot/include/c++/v1/stdio.h ./usr/share/wasi-sysroot/include/stdio.hUnsafePointer<FILE> を OpaquePointerに置き換えるだけ#if os(WASI) import WASILibc typealias FILEPointer = OpaquePointer #else import Darwin typealias FILEPointer = UnsafeMutablePointer<FILE> #endif func fputs(_ string: String, file: FILEPointer) { _ = string.withCString { (cstr) in fputs(cstr, file) } } fputs("hello stdout", file: stdout) fputs("hello stderr", file: stderr)common.ts/WasmRunner の console.error これもその場でスタックトレースを収集する 2. dev.ts/handleError の console.error キャッチしたエラーオブジェクトをダンプしてる これもそこのトレースを出すからややこしい(パスが違うから出るものは違う) 3 dev.ts が WebAssembly.RuntimeError の stack を出してる$ swift run carton dev : stdout is not TTY (edited)$ .build/arm.../debug/carton dev : stdout is TTY (edited) // Open a message channel for communicating with the plugin host. pluginHostConnection = PluginHostConnection( inputStream: FileHandle(fileDescriptor: inputFD), outputStream: FileHandle(fileDescriptor: outputFD))URL: https://swiftfiddle-runner.onrender.com/runner/5.10.0/runFailed writing header っていうエラメッセージが内部に出てて if(writeheader) { size_t wrote = writeheader(ptr, 1, chunklen, data->set.writeheader); if(CURL_WRITEFUNC_PAUSE == wrote) /* here we pass in the HEADER bit only since if this was body as well then it was passed already and clearly that didn't trigger the pause, so this is saved for later with the HEADER bit only */ return pausewrite(data, CLIENTWRITE_HEADER, ptr, len); if(wrote != chunklen) { failf (data, "Failed writing header"); return CURLE_WRITE_ERROR; } }$ swift test --filter WebDriverClientTests.testGotoURLSession で踏む状態にはなってるimport Foundation import FoundationNetworking let defaultSessionRequestBody = #""" { "capabilities": { "alwaysMatch": { "goog:chromeOptions": { "w3c": true, "args": ["--headless", "--no-sandbox"] }, "moz:firefoxOptions": { "args": ["-headless"] }, "ms:edgeOptions": { "args": ["--headless", "--no-sandbox"] } } } } """# do { var request = URLRequest(url: URL(string: "http://0.0.0.0:9515/session")!) request.httpMethod = "POST" request.httpBody = defaultSessionRequestBody.data(using: .utf8) let _: (Data, URLResponse) = try await withCheckedThrowingContinuation { continuation in let task = URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data, let response = response else { let error = error ?? URLError(.badServerResponse) return continuation.resume(throwing: error) } continuation.resume(returning: (data, response)) } task.resume() } } catch { print("Error: \(error)") exit(1) }Adding more exported C++ symbols Replace assertEquals with assertEqual (edited)--build-testsが治るはず。しかし5.10と6.0の間でパッチ管理の方法を変えたのでバックポートがちょっとムズい--host 0.0.0.0 だったら接続アドレスとしては 127.0.0.1 に読み替える、というのも思いつくけど。open コマンドはダメだけど、 WEBDRIVER_REMOTE_URL を使えばいけるんだよね::0000:0000:0000:0000 とか 0000:0000:0000:0000:0000:0000:: も良いはずだWEBDRIVER_REMOTE_URL のことを考えるとやっぱりbindするアドレスと接続しに行くアドレスの両方が設定可能でないといけないから --listen しか無いかもしれないですねぇ--listen で 192.168.1.2 を埋めた場合は、 --host のデフォルトが 127.0.0.1 から 192.168.1.2 に変わる127.0.0.1 では絶対接続できないので、良い代替なはずだ192.168.1.2 では多くの場合で接続できるが、NATを介するなどの都合がある人は正しい指定をさらに上書きする。--listen のデフォルトが 0.0.0.0 だとして、 0.0.0.0 → 127.0.0.1 の読み替えを導入して、 --host のデフォルトになればいいかな。--host を省略した場合は --listen に基づいて決まるという一貫性が得られる (edited)--host だけ指定してて --listen がない場合。127.0.0.1 に対して、listen 127.0.0.1 が正当な指定だから、 0.0.0.0 は出てこないのが微妙だけど--host だけ指定する事が多いのが気になっている (edited)--host は実は我々の --listen の意味で使われてたり[omochi@omochi-mbp carton (org-procs *=)]$ swift test --filter DevCommandTests.testWithNoArguments Building for debugging... [5/5] Write swift-version-3874884F1997D323.txt Build complete! (0.37s) Test Suite 'Selected tests' started at 2024-06-04 22:01:42.891. Test Suite 'cartonPackageTests.xctest' started at 2024-06-04 22:01:42.892. Test Suite 'DevCommandTests' started at 2024-06-04 22:01:42.892. Test Case '-[CartonCommandTests.DevCommandTests testWithNoArguments]' started. warning: 'echoexecutable': 'my-echo' was identified as an executable target given the presence of a 'main.swift' file. Starting with tools version 5.4.0 executable targets should be declared as 'executableTarget()' [0/1] Planning build Building for debugging... [0/4] Write sources [1/4] Write swift-version-3874884F1997D323.txt [3/6] Emitting module CartonCore [4/6] Compiling CartonCore FoundationProcessEx.swift [4/7] Write Objects.LinkFileList error: link command failed with exit code 1 (use -v to see invocation) Undefined symbols for architecture arm64: "static (extension in CartonCore):__C.NSTask.checkRun(_: Foundation.URL, arguments: [Swift.String], printsLoadingMessage: Swift.Bool, didExit: (() -> ())?, forwardExit: Swift.Bool) throws -> ()", referenced from: CartonDriver.derivePackageCommandArguments(swiftExec: Foundation.URL, subcommand: Swift.String, scratchPath: Swift.String, extraArguments: [Swift.String]) throws -> [Swift.String] in CartonDriverCommand.swift.o CartonDriver.derivePackageCommandArguments(swiftExec: Foundation.URL, subcommand: Swift.String, scratchPath: Swift.String, extraArguments: [Swift.String]) throws -> [Swift.String] in CartonDriverCommand.swift.o (3) suspend resume partial function for CartonDriver.pluginSubcommand(subcommand: Swift.String, argv0: Swift.String, arguments: [Swift.String]) async throws -> () in CartonDriverCommand.swift.o (5) suspend resume partial function for CartonDriver.main(arguments: [Swift.String]) asyTERM=dumb を設定して、ttyであろうが、ttyでないとみなしてカラーコードを出させない$ swift package carton-dev から来てるんじゃないのか$ swift package 自体を空中で起動した場合か。 let process = try swiftRunProcess( ["carton", "dev", "--verbose", "--port", "8080", "--skip-auto-open"], packageDirectory: packageDirectory.asURL ) ↑このxctestの中で立ち上げた swift run プロセスの出力が xctest の出力に出てこないfunc swiftRunProcess( _ arguments: [String], packageDirectory: URL ) throws -> SwiftRunProcess { let swiftBin = try findSwiftExecutable().pathString var outputBuffer = Array<UInt8>() let process = CartonHelpers.Process( arguments: [swiftBin, "run"] + arguments, workingDirectory: try AbsolutePath(validating: packageDirectory.path), outputRedirection: .stream( stdout: { (chunk) in outputBuffer += chunk stdoutStream.write(sequence: chunk) }, stderr: { (chunk) in stderrStream.write(sequence: chunk) }, redirectStderr: false ) ) let buildRequestFileHandle = FileHandle(forReadingAtPath: buildRequestPipe)! let buildResponseFileHandle = FileHandle(forWritingAtPath: buildResponsePipe)! while let _ = try buildRequestFileHandle.read(upToCount: 1) { Diagnostics.remark("[Plugin] Received build request") let buildResult = try self.packageManager.build(buildSubset, parameters: parameters) if !buildResult.succeeded { Diagnostics.remark("[Plugin] **Build Failed**") print(buildResult.logText) } else { Diagnostics.remark("[Plugin] **Build Succeeded**") } try buildResponseFileHandle.write(contentsOf: Data([1])) } let buildRequestFileHandle = FileHandle(forReadingAtPath: buildRequestPipe)! let buildResponseFileHandle = FileHandle(forWritingAtPath: buildResponsePipe)! while let _ = try buildRequestFileHandle.read(upToCount: 1) { Diagnostics.remark("[Plugin] Received build request") let buildResult = try self.packageManager.build(buildSubset, parameters: parameters) if !buildResult.succeeded { Diagnostics.remark("[Plugin] **Build Failed**") print(buildResult.logText) } else { Diagnostics.remark("[Plugin] **Build Succeeded**") } try buildResponseFileHandle.write(contentsOf: Data([1])) } swift package -v とかswift package -vv でコントロールできるログレベルがあって-vで出るようになるBuilding "app" Building for debugging... [0/5] Write sources [1/5] Write swift-version-3874884F1997D323.txt error: -static-stdlib is no longer supported for Apple platforms error: Plugin ended with exit code 1-static-stdlib付くんだろう[omochi@omochi-mbp SandboxApp (main *=)]$ swift run carton dev Building for debugging... error: -static-stdlib is no longer supported for Apple platforms error: -static-stdlib is no longer supported for Apple platforms あれ、driver経由も壊れたThese paths have changed, rebuilding... - /Users/omochi/github/swiftwasm/carton/Tests/Fixtures/SandboxApp/Sources/app - /Users/omochi/github/swiftwasm/carton/Tests/Fixtures/SandboxApp/Sources/app info: [Plugin] Received build request info: [Plugin] **Build Succeeded** Build completed successfully The app is currently hosted at http://127.0.0.1:8080/ 2024-06-07T21:49:06+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET / 2024-06-07T21:49:06+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /dev.js 2024-06-07T21:49:06+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /main.wasm 2024-06-07T21:49:06+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /JavaScriptKit_JavaScriptKit.resources/Runtime/index.mjs stdout: hello stdout stdout: stderr: hello stderr stderr: -v で確かに出るようになりました-v をpluginに渡すようにしたThese paths have changed, rebuilding... - /Users/omochi/github/swiftwasm/carton/Tests/Fixtures/SandboxApp/Sources/app - /Users/omochi/github/swiftwasm/carton/Tests/Fixtures/SandboxApp/Sources/app info: [Plugin] Received build request info: [Plugin] **Build Succeeded** Build completed successfully The app is currently hosted at http://127.0.0.1:8080/ 2024-06-07T21:50:53+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET / 2024-06-07T21:50:53+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /dev.js 2024-06-07T21:50:53+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /main.wasm 2024-06-07T21:50:53+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /JavaScriptKit_JavaScriptKit.resources/Runtime/index.mjs stdout: hello stdout stdout: stderr: hello stderr stderr: -vv にしたけど変わらない気がするねRunning "/Users/omochi/Library/Developer/Toolchains/swift-wasm-5.10.0-RELEASE.xctoolchain/usr/bin/swift" "package" "--triple" "wasm32-unknown-wasi" "--scratch-path" "/Users/omochi/github/swiftwasm/carton/Tests/Fixtures/SandboxApp/.build/carton" "--disable-sandbox" "-vv" "plugin" "carton-dev" "--pid" "22729" それは出てるよ let buildResult = try self.packageManager.build(buildSubset, parameters: parameters) こっちはそもそもコマンドじゃないから出せなさそうinfo: Running command plugin <PluginTarget: CartonDevPlugin> on package <ResolvedPackage: sandboxapp> with options PluginOptions(_allowWritingToPackageDirectory: false, _additionalAllowedWritableDirectories: [], _allowNetworkConnections: none, _packageIdentity: nil) and arguments ["--pid", "22729"] これは -vv によって出たものかな? (edited)info: Running command plugin <PluginTarget: CartonDevPlugin> on package <ResolvedPackage: sandboxapp> with options PluginOptions(_allowWritingToPackageDirectory: false, _additionalAllowedWritableDirectories: [], _allowNetworkConnections: none, _packageIdentity: nil) and arguments ["--pid", "22729"] これは -vv によって出たものかな? (edited)internal func makeCartonFrontendProcess(context: PluginContext, arguments: [String]) throws -> Process { let frontend = try context.tool(named: "carton-frontend") Diagnostics.remark( "Running " + ([frontend.path.string] + arguments).map { "\"\($0)\"" }.joined(separator: " ")) let process = Process() process.executableURL = URL(fileURLWithPath: frontend.path.string) process.arguments = arguments return process }Diagnostics.remark で出してるようだから、driverが-v をつけないから出てこない (edited)--verbose フラグを持ってるし。 @Flag(name: .shortAndLong, help: "Don't clear terminal window after files change.") var verbose = false なんだこのhelpは・・・ func run() async throws { let terminal = InteractiveWriter.stdout if !verbose { terminal.revertCursorAndClear() } 確かにそうなってるけどw (edited)Server に渡してるけどおよそ何も影響ないな・・・(変数消したけどコンパイルできた (edited)$ swift run carton dev -Xpackage -vDiagnostics.remark を使うメリットを全く感じてなくて、 driver, plugin, frontendそれぞれに普通にstdout使ってログ出してるから、 pluginだけこれ使う意味ないしやめていいと思ったswift run carton dev -v で起動されたCartonDriverがswift package <ここ>carton-dev <remaining arguments> ここに-vを配置するために-vを解釈しないといけないのがなぁと。-v の振る舞いを融合する仕様にする場合を想定したコメントか。 (edited)CartonDriver は swift-arugment-parser に依存しないで実装してあるんすね。Diagnostics.remark を使うメリットがないのはそうなんだよなー2024-06-07T22:13:06+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET / 2024-06-07T22:13:06+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /dev.js 2024-06-07T22:13:06+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /main.wasm 2024-06-07T22:13:06+0900 info org.swiftwasm.carton.dev-server : [CartonKit] GET /JavaScriptKit_JavaScriptKit.resources/Runtime/index.mjs stdout: hello stdout stdout: stderr: hello stderr stderr: These paths have changed, rebuilding... - /Users/omochi/github/swiftwasm/carton/Tests/Fixtures/SandboxApp/Sources/app - /Users/omochi/github/swiftwasm/carton/Tests/Fixtures/SandboxApp/Sources/app Building for debugging... [0/2] Write swift-version--1B43874C0F24DF5E.txt [1/4] Write sources [3/5] Compiling app main.swift /Users/omochi/github/swiftwasm/carton/Tests/Fixtures/SandboxApp/Sources/app/main.swift:17:1: error: cannot find 'aafputs' in scope aafputs("hello stdout\n", file: stdout) ^~~~~~~ Build completed successfully The app is currently hosted at http://127.0.0.1:8080/ public enum Severity : String, Encodable { case error case warning case remark この3段階しかないのは普通に実用性がなくない? 「通常メッセージと、詳細メッセージ」を制御できない。 通常メッセージをwarningに格上げするわけにもいかないだろうし--verbose で制御するようなものが let buildResult = try self.packageManager.build(buildSubset, parameters: parameters) これで起動されてて、ここのダンプは package -v してもされない・・・ // Build products var parameters = PackageManager.BuildParameters( configuration: options.release ? .release : .debug, logging: options.verbose ? .verbose : .concise ) いや、あれ?されそうだな?BuildLogVerbosity.concice : エラーメッセージだけでる, BuildLogVerbosity.verbose : swift-frontend コマンドもダンプされる (edited)BuildLogVerbosity.debug にしても同じだった (edited)parameters.echoLogs これだなBuildLogVerbosity と Diagnostics.Severity の関係はどうなってんだろうね。レベルのワードも違うし、今やった感じ関係なさそうだけど。.verbose で出るログは -v なしでも出た気がするけど.debug と -vv を一緒に設定してみるかDYLD_LIBRARY_PATH の技で回避する方向で最新版を見ていくか〜
1find ${toolchain}/usr/bin -type f | xargs -n 1 -I {} \ sudo codesign --force --preserve-metadata=identifier,entitlements --sign - {} これやってみた[omochi@omochi-mbp bin]$ /Users/omochi/Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2024-06-06-a.xctoolchain/usr/bin/swift package --version Swift Package Manager - Swift 6.0.0-dev こっちはうまくいったけど[omochi@omochi-mbp bin]$ swift package --version zsh: segmentation fault swift package --version[omochi@omochi-mbp bin]$ which -a swift /Users/omochi/Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2024-06-06-a.xctoolchain/usr/bin/swift /usr/bin/swift [omochi@omochi-mbp bin]$ swift package --version Swift Package Manager - Swift 6.0.0-dev パス通していけた[omochi@omochi-mbp swift-react (swift510 =)]$ swift experimental-sdk list No Swift SDKs are currently installed. warning: Couldn't parse `info.json` manifest of a Swift SDK bundle at /Users/omochi/Library/org.swift.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-06-07-a-wasm32-unknown-wasi.artifactbundle: failed parsing ArtifactsArchive info.json at '/Users/omochi/Library/org.swift.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-06-07-a-wasm32-unknown-wasi.artifactbundle/info.json': keyNotFound(CodingKeys(stringValue: "supportedTriples", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "artifacts", intValue: nil), _JSONKey(stringValue: "DEVELOPMENT-SNAPSHOT-2024-06-07-a-wasm32-unknown-wasi", intValue: nil), CodingKeys(stringValue: "variants", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"supportedTriples\", intValue: nil) (\"supportedTriples\").", underlyingError: nil))--sdk じゃなくて --triple 吐くし).swift-version を置くのかしら?.swift-version をおけばOK--tripleでOK.swift-version がない時は (edited).swift-version を作らなくても 「ホストと実行が揃う」のがcartonのデフォルトの振る舞いになるcarton-driver が実行された時に、 PATH から見える swift を基準にしてもいい気がするけど#if compiler(>=6.0) #error("6.0") #elseif compiler(>=5.10) #error("5.10") #elseif compiler(>=5.9) #error("5.9") #endif これで、目の前の $ swift のバージョンを判定するのはうまくいきそうだった ( $ swift --version をパースするのはちょっと怪しさがある気がしている ) (edited)$ swift は原則一つなのでexport TOOLCHAINS で切り替えた時に carton-driver はそのまんま同じマシンインストール版を使っていてもうまく切り替わるみたいな事か#error を食わせる方がいいよね#error でなくてもこれで良かったりする? #if compiler(>=6.0) let defaultToolchainVersion = "wasm-6.0.0-XXXX" #elseif compiler(>=5.10) let defaultToolchainVersion = "wasm-5.10.0-RELEASE" #elseif compiler(>=5.9) let defaultToolchainVersion = "wasm-5.9.2-RELEASE" #endif#error を $ swift に食わせて出力を読む必要がある.swift-verison でいいな (edited).swift-version などで ) Swift6.0を指定した場合の挙動って、 ツールチェーンを codesign --force --preserve-metadata=identifier,entitlements --sign - するやつと、 起動時に DYLD_LIBRARY_PATH を指定するやつを、Cartonが面倒見るのがいい? (edited)-lswift_RegexParserをリンクオプションとしてつけるのがいいかな-lswift_RegexParserをリンクオプションとしてつけるのがいいかな Caused by: 0: failed to invoke command default 1: error while executing at wasm backtrace: 0: 0x670e08 - <unknown>!$s10Foundation6BundleC05_mainB033_6273FB07A96EB35BCC520B3A80F5C3CDLL_WZ 1: 0x4504d5 - <unknown>!swift_once 2: 0x670e31 - <unknown>!$s10Foundation6BundleC4mainACvgZ Bundle.mainだwasmtime run のオプションとして--dir . を渡せばOK wasm-ld: error: /Users/runner/Library/Developer/Toolchains/swift-wasm-6.0-SNAPSHOT-2024-06-08-a.xctoolchain/usr/lib/swift_static/wasi/libswift_StringProcessing.a(_StringProcessing.o): undefined symbol: $s12_RegexParser13PrettyPrinterVMn
[omochi@omochi-mbp wasi]$ nm -a libswift_RegexParser.a | grep RegexParser13PrettyPrinterVMn 00006cdc D $s12_RegexParser13PrettyPrinterVMn (edited)libswift_RegexParser.a に入ってんな-l が渡ってないか、 -L が無いか だろうか (edited)AbsolutePath と RelativePath って、どっちかわからない時はどうすればいいんだ?AbsolutePath と RelativePath って、どっちかわからない時はどうすればいいんだ? const fds = [ new OpenFile(new File([])), // stdin stdout, stderr, new PreopenDirectory("/", new Map()), ]; const wasi = new WASI(args, [], fds, { debug: false });entrypoint/test.ts の方でargs与えてないんだな["main.wasm"]を与えてもらえるとconst defaultRunnerOptions = (options: Options): Options => { if (options.args != null) { options.args = ["main.wasm"]; } return options; };["/main.wasm"] の方がいいかな。wasi-libcのcurrent working directoryエミュレーションに依存しなくなる-l オプションが渡ってきそうだな・・・ (edited)internal-get-build-command でビルドコマンド取ってくるのをやめてswift package carton-test するって意味?-l が command モードの時の分岐には適応されてないだけかも (edited)-emit-module が -index-system-modules を指定するのでツールチェインの_StringProcessing.swiftinterfaceからswiftmoduleを作って .build/debug/ModuleCache に新しく配置する。-module-cache-pathで明示的に指定された .build/debug/ModuleCache が優先されるので、壊れたswiftmoduleを参照してしまい問題が発現する (edited)
1--gc-sections をWasm向けに有効にしたので、実際に_RegexParser の実装を全く使わない場合、そもそも _RegexParser のシンボルをリンカが必要としなくなったので、StringProcsssingモジュールに関しては問題なくなってしまった (edited)_RegexParser のシンボルに依存する場合は同じ問題が発生するはずStringProcesing → RegexParser の依存関係がswiftinterfaceを通じて途切れていたって事だからRegexParser が StringProcesing のprivate dependencyなんですよね@_implementationOnly import ですねRunning... wasm-opt -Os --enable-bulk-memory /home/runner/work/carton/carton/Tests/Fixtures/EchoExecutable/Bundle/main.wasm -o /home/runner/work/carton/carton/Tests/Fixtures/EchoExecutable/Bundle/main.wasm Process failed and produced following output: Process failed with non-zero exit status and following output: and following error output: [wasm-validator error in function 120] unexpected false: all used features should be allowed, on (i32.extend8_s (local.get $20) ) [wasm-validator error in function 125] unexpected false: all used features should be allowed, on (i32.extend8_s (local.get $19) ) [wasm-validator error in function 178] unexpected false: all used features should be allowed, on (i32.extend8_s (local.get $8) ) [wasm-validator error in function 450] unexpected false: all used features should be allowed, on (i32.extend16_s (local.get $0) )wasm-opt がエラーを出してCIが失敗してる・・・ - name: Install dependent packages for WebAssembly run: > sudo apt-get update && sudo apt-get install -y wabt binaryen ↑ここで入ってんのかな--enable-sign-ext も付けとくかAdditionally, this PR defines stdlib/runtime version 6.1 with placeholder availability, and updates _SwiftStdlibVersion.current to report itself as that.SwiftStdlib 6.0:macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0 SwiftStdlib 6.1:macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, visionOS 9999-wasi: スレッド命令(?) を使わない、 stdlib の関連APIは削除されている -wasip1-threads: スレッド命令を発行する、stdlibの関連APIが使える 使い分け: ビルドしたwasmバイナリを実行する処理型が p1thread をサポートしている → 後者で良い サポートしていない → 前者にせよdiv(display: "flex", flex-direction: "column", align-items: "center", gap: "4px") って書ける事だけど
3swift build --build-tests して swift test --skip-build した場合は XCTest の実行結果と swift-testing の実行結果の両方が出てくるのに,swift build --build-tests --swift-sdk wasm32-unknown-wasi して wasmtime で実行した場合は swift-testing の実行結果しか出てこなくて,なぜなんだろうなと気になりました.(Linux) (edited)--testing-library swift-testing ありの挙動となしの挙動を比べてたら気付きました. https://github.com/apple/swift-testing/pull/587/filesrm Package.resolved して swift build --build-tests --swift-sdk wasm32-unknown-wasi するたびに swift-testing only のがビルドされたり XCTest only のがビルドされたりランダムに変わりますね...swift build --build-tests 時に --disable-xctest とかみたいに片方を無効化するフラグをつけてビルドしてもらえれば確実に防げそうではあります.FileManager.DirectoryEnumerator の移植の目処も立ちました。 https://github.com/WebAssembly/wasi-libc/pull/522
1FileManager.default.removeItem とかも FTS がブロッカーでしたね.symlink("/tmp/hoge", "/hoge/fuga") が実行できれば OK という条件です.symlink("/tmp/hoge", "/hoge/fuga") が実行できれば OK という条件です. --wasm max-wasm-stack=4194304 ですね.--wasm max-wasm-stack=4194304 ですね. wasmkit-cli run --stack-size 4194304 追加してみました https://github.com/swiftwasm/WasmKit/pull/136path_readlink はまだWasmKit実装提供してないんですけどテスト通ってるんですか? (edited)path_readlink って readlink とは別なんでしたっけ?もしそうであれば Foundation で readlink しか使われていないからかもしれません. https://github.com/swiftlang/swift-foundation/blob/bc7c25794410715fc7c669ac6b99e0e1868e4510/Sources/FoundationEssentials/FileManager/FileManager%2BSymbolicLinks.swift#L204path_readlink って readlink とは別なんでしたっけ?もしそうであれば Foundation で readlink しか使われていないからかもしれません. https://github.com/swiftlang/swift-foundation/blob/bc7c25794410715fc7c669ac6b99e0e1868e4510/Sources/FoundationEssentials/FileManager/FileManager%2BSymbolicLinks.swift#L204 readlink実装は最終的に path_readlinkの呼び出しになるはずなんですよねURL(filePath: "hoge").path が /hoge になっちゃうFileManager.default.createFile が使えない (options: .atomic 強制になっちゃうから)Bundle.main 問題がどうしても突破できなくて原因がわからないんですよね.wasmtime だとカレントディレクトリを --dir / みたいに指定しておけば十分なんですが,Wasmer だとそれじゃダメで... https://github.com/swiftwasm/swift/issues/5574 (edited)--dir /::. とかでもだめですか?--mapdir /:. みたいなことですかね?Bundle.main だけがこけます.(それも Wasmer だけで) import Foundation let items = try FileManager.default.contentsOfDirectory(atPath: "/") for item in items { print(item) } print(Bundle.main.bundleURL)Bundle.main.bundleURL は file:/// なんですね.Bundle.mainはargv[0]をベースに参照するディレクトリを決めるのでCommandLine.arguments
["BundleMainTest.wasm"][".build/wasm32-unknown-wasi/debug/BundleMainTest.wasm"]/.build/wasm32-unknown-wasi/debug をゲストにマップすると動くと思います--mapdir /.build:.build を付け足すことで Bundle.main で転けなくなったんですが,swift-format のテストの方はそれでも Bundle.main で転けてしまってうまくいかなかったので,そっちはそっちでもうちょっとデバッグしてみます. (edited)argv[0] が違うのかなーと思いつつも,それを見ようにも swiftwasm/swift#5574 みたいに実行時にクラッシュしちゃうので print デバッグは無理ですね. かといって wasminspect みたいなデバッガで実行すると wasmer で実行する場合と条件が変わっちゃいますし... (edited).build/wasm32-unknown-wasi/debug/*PackageTests.wasm を渡すと OK で,.build/debug/*PackageTests.wasm を渡すとダメみたいですね.debug -> wasm32-unknown-wasi/debug のシンボリックリンクを通るかどうかで挙動が変わってそうです. (edited)CommandLine.arguments が [".build/debug/BundleMainTest.wasm"] みたいになっていると,--mapdir /.build:.build でマップしても .build/debug がシンボリックリンクだからうまくいかないみたいですね.XCTest の executable なのかどうかじゃなくて原因はそこだったみたいです. (edited)--mapdir /.build/debug:.build/debug だと良いみたいです.readdir が通常のプラットフォームや wasmtime だとシンボリックリンクも返してくれるのですが,Wasmer だと返してくれないようです.std::fs::read_dir だと Wasmer でも symlink を返してくれるので,(Swift から readdir を呼んだ場合との違いが) どこで発生しているんだろうと気になってます. (edited)CMARK_THREADING 周りの分岐をいじっている辺りが本当にこのアプローチで良いのか自信がないのでどなたかアドバイスいただけると嬉しいです. https://github.com/kkebo/swift-cmark/commit/f0892103972876264fd059bc3daf0df1af530f34
CMARK_THREADING が定義されていてもスレッドサポートしていないターゲットだったらスレッドサポートしていない方の分岐に流すアプローチ (今やっている方) と,スレッドサポートしていないターゲット向けのビルド時はそもそも CMARK_THREADING を定義させないアプローチと二つある気がしていて,後者の方が筋が良い気もするんですが Package.swift の中でスレッドサポートしているターゲット向けにビルドしようとしているか否かを取る手段がわからなくて前者を採用しています. (edited)CMARK_THREADING はアップストリーム (github/cmark-gfm) には無くて、swiftlang/swift-cmarkにしか無いので自由にやってよさそうです。CMARK_THREADINGの定義を消してしまっても良い? (edited)CMARK_THREADING は常時 ON なんですが CMake でビルドする時は ON/OFF できるようになっていたので,一応残した方が良いのかなと思ってました.CMARK_THREADINGを定義するのをやめてヘッダに任せる。CMARK_THREADING が定義されている _POSIX_THREADS が定義されている CMARK_THREADING が定義されている _POSIX_THREADS が定義されている #if defined(__wasi__) && !defined(_REENTRANT) # define CMARK_THREADING_default 0 #else # define CMARK_THREADING_default 1 #endif #ifndef CMARK_THREADING # define CMARK_THREADING CMARK_THREADING_default #endif #if CMARK_THREADING // thread available #else // no thread #endif #undef CMARK_THREADING #undef CMARK_THREADING_default こんな感じかなと想像してました。CMARK_THREADING が今後他のファイルでも使われたりしないかどうかという点ですね.それがありうるなら CMARK_THRAEDING のデフォルト挙動の定義をどのヘッダファイルに書こうか迷いそうです.#if defined(__wasi__) && !defined(_REENTRANT) # define CMARK_THREADING_default 0 #else # define CMARK_THREADING_default 1 #endif #ifndef CMARK_THREADING # define CMARK_THREADING CMARK_THREADING_default #endif #if CMARK_THREADING // thread available #else // no thread #endif #undef CMARK_THREADING #undef CMARK_THREADING_default こんな感じかなと想像してました。 _REENTRANT ってなんだろうと思ったら,wasi-libc の wasm32-wasip1-threads でだけ _REENTRANT が定義されていて,wasm32-wasip1 や wasm32-wasip2 だと定義されていないんですね. https://github.com/WebAssembly/wasi-libc/blob/a05277a6803d99dc5f8d5c250a02cf37ff90882a/expected/wasm32-wasip1-threads/predefined-macros.txt#L2241
1x86.rb とか risc.rb とかファイル名がある時点で辛いなあ
1
1-Oz レベルで最適化すると不正なバイナリになっちゃいますね. root@03961603bf69:~/hoge# swift build -c release --swift-sdk wasm32-unknown-wasi ... root@03961603bf69:~/hoge# wasm-opt -Oz -all .build/release/hoge.wasm -o hoge.wasm warning: active memory segments have overlap, which prevents some optimizations. root@03961603bf69:~/hoge# wasmtime hoge.wasm Error: failed to parse WebAssembly module Caused by: invalid value type (at offset 0x2f1) wasm-opt が -Oz じゃなくて -Os だったら起こらないですし,コンテナのベースイメージが swift:6.0.2-noble じゃなくて swift:6.0.2-jammy だった場合も起こらないので,wasm-opt の問題なのか Swift の問題なのか Ubuntu の問題なのかわからないので一体どこで報告すれば...$ mkdir hoge; cd hoge/ $ docker container run -it --rm -v $PWD:/hoge swift:6.0.2-noble # apt update && apt install --no-install-recommends curl xz-utils binaryen wabt # curl https://wasmtime.dev/install.sh -sSf | bash # source ~/.bashrc # swift sdk install https://github.com/swiftwasm/swift/releases/download/swift-wasm-6.0.2-RELEASE/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle.zip --checksum 6ffedb055cb9956395d9f435d03d53ebe9f6a8d45106b979d1b7f53358e1dcb4 # cd /hoge # swift package init --type executable # swift build -c release --swift-sdk wasm32-unknown-wasi # wasm-opt -Oz -all .build/release/hoge.wasm -o hoge_optimized.wasm (edited)~$ wasm-objdump -x -j target_features /Users/katei/Downloads/hoge_optimized.wasm hoge_optimized.wasm: file format wasm 0x1 Section Details: Custom: - name: "target_features" - [+] atomics - [+] mutable-globals - [+] nontrapping-fptoint - [+] simd128 - [+] bulk-memory - [+] sign-ext - [+] exception-handling - [+] tail-call - [+] reference-types - [+] multivalue - [+] gc - [+] memory64 - [+] typed-function-references - [+] relaxed-simd - [+] extended-const ~$ wasm-objdump -x -j target_features /Users/katei/Downloads/hoge.wasm hoge.wasm: file format wasm 0x1 Section Details: Custom: - name: "target_features" - [+] bulk-memory - [+] mutable-globals - [+] sign-ext なんか余計なfeatureがたくさん有効になってますね-all をなくしてみたら正常に実行できました. なので feature が影響している & wasm-opt のバージョン説はありそうです. (edited)--enable-gc --enable-reference-types の組み合わせも試しましたが問題なかったので,どれか一つの feature が原因じゃなくて複合的に指定した時だけの問題っぽいです.流石に組合せ数が... $ wasm-opt --help | grep enable- | awk -F' ' '{print $1}' | xargs -I{} fish -c "echo {} && wasm-opt -Oz {} hoge.wasm -o hoge_host_opt.wasm && wasmtime hoge_host_opt.wasm" --enable-sign-ext warning: active memory segments have overlap, which prevents some optimizations. Hello, world! --enable-threads warning: active memory segments have overlap, which prevents some optimizations. Hello, world! --enable-mutable-globals warning: active memory segments have overlap, which prevents some optimizations. Hello, world! 以下略$ wasm-opt -Oz -all hoge.wasm -o hoge_host_opt.wasm && wasmtime hoge_host_opt.wasm warning: active memory segments have overlap, which prevents some optimizations. Error: failed to parse WebAssembly module Caused by: heap types not supported without the gc feature (at offset 0x2e8) $ wasm-opt -Oz -all --disable-gc --disable-reference-types hoge.wasm -o hoge_host_opt.wasm && wasmtime hoge_host_opt.wasm warning: active memory segments have overlap, which prevents some optimizations. Hello, world! $ wasm-opt -Oz --enable-gc --enable-reference-types hoge.wasm -o hoge_host_opt.wasm && wasmtime hoge_host_opt.wasm warning: active memory segments have overlap, which prevents some optimizations. Hello, world! (edited)-all を使うな」ってことですね.$ ~/downloads/binaryen-version_120_b/bin/wasm-opt -Oz -all hoge.wasm -o hoge_host_opt.wasm && wasmtime hoge_host_opt.wasm Error: failed to parse WebAssembly module Caused by: function references required for index reference types (at offset 0x2d0)-all をつけていたのかを思い出しました.Swift でビルドした Wasm バイナリを wasm-strip してから wasm-opt すると,以前は問題なかったんですが,あるタイミングから wasm-strip の段階で必要な feature が消されちゃうようになったのか wasm-opt の段階で必要な feature が無いみたいな validation エラーが起こるようになったので,何の feature が必要なのかわからなくて -all をつけていたんでした.(私の場合は --enable-bulk-memory --enable-sign-ext だけで十分でした) wasm-strip → wasm-opt してた理由は,wasm-opt 単体や wasm-opt → wasm-strip よりも wasm-strip → wasm-opt の方がバイナリサイズが小さくなる経験則があったからです. なので同じことをしている方がいたらご注意ください. (edited)$ echo ":wasm32-wasi:M::\x00asm:\xff\xff\xff\xff:/usr/bin/wasmtime:" | sudo tee /etc/binfmt.d/wasmtime.conf $ sudo systemctl restart systemd-binfmtswiftの標準入力へソースを渡すbotからは、wasm32-unknown-wasiは使えなさそう。残念。
print("Hello, WASI!") (edited)print("Hello, WASI!") (edited)Target: wasm32-unknown-wasi error: interactive mode is unsupported for target 'wasm32-unknown-wasi'; use 'swiftc' instead (edited)public func twice(number: Int) -> Int { return number * 2 } (edited)Target: wasm32-unknown-wasi error: interactive mode is unsupported for target 'wasm32-unknown-wasi'; use 'swiftc' insteadTarget: wasm32-unknown-wasi error: interactive mode is unsupported for target 'wasm32-unknown-wasi'; use 'swiftc' insteadTarget: wasm32-unknown-wasi error: interactive mode is unsupported for target 'wasm32-unknown-wasi'; use 'swiftc' instead (edited)swift-wasi -version -vは以下のようなコマンドラインでswiftを起動してます。 exec swift -target wasm32-unknown-wasi -I -resource-dir /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static -sdk /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk -Xcc -isysroot -Xcc /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk -Xfrontend -tools-directory -Xfrontend /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/bin -static-stdlib -version -v (edited)-frontendはswiftの直後にないとダメなのかswift-macos -version -vは動く。 exec swift -target arm64-apple-macosx15.2 -I /home/bot/.swiftpm/swift-sdks/darwin.artifactbundle/Developer/Platforms/MacOSX.platform/Developer/usr/lib -resource-dir /home/bot/.swiftpm/swift-sdks/darwin.artifactbundle/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift -sdk /home/bot/.swiftpm/swift-sdks/darwin.artifactbundle/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX15.2.sdk -Xcc -isysroot -Xcc /home/bot/.swiftpm/swift-sdks/darwin.artifactbundle/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX15.2.sdk -ld-path=/home/bot/.swiftpm/swift-sdks/darwin.artifactbundle/toolset/bin/ld64.lld -Xfrontend -tools-directory -Xfrontend /home/bot/.swiftpm/swift-sdks/darwin.artifactbundle/toolset/bin -use-ld=lld -version -v Swift version 6.0.3 (swift-6.0.3-RELEASE) Target: arm64-apple-macosx15.2 /usr/bin/swift-frontend --version Swift version 6.0.3 (swift-6.0.3-RELEASE) Target: aarch64-unknown-linux-gnu (edited) (edited)Target: x86_64-apple-macosx15.2 error: option '-emit-ir' is not supported by 'swift'; did you mean to use 'swiftc'? (edited)swift-macos, swift-wasiは[https://github.com/norio-nomura/swift_discord_bot/blob/main/swift-use-sdk.sh] へのシンボリックリンクswiftcにすると以下のようになります。 exit status: 1 with Target: wasm32-unknown-wasi warning: Could not read SDKSettings.json for SDK at: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk error: unexpected input file: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_staticswift-wasi -version -vは以下のようなコマンドラインでswiftを起動してます。 exec swift -target wasm32-unknown-wasi -I -resource-dir /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static -sdk /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk -Xcc -isysroot -Xcc /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk -Xfrontend -tools-directory -Xfrontend /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/bin -static-stdlib -version -v (edited)-I -resource-dir となってて-resource-dirがinclude dirとして解釈されちゃってそうincludeSearchPathsがない場合にエラーになってた。 $ swift sdk configure --show-configuration 6.0.2-RELEASE-wasm32-unknown-wasi wasm32-unknown-wasi sdkRootPath: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk swiftResourcesPath: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static swiftStaticResourcesPath: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static includeSearchPaths: not set librarySearchPaths: not set toolsetPaths: ["/home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/toolset.json"] (edited)swift sdk configure --show-configurationの出力が、YAMLの様でYAMLじゃないのか。yqで処理してた。info.json,swift-sdk.jsonを読んでいったほうが良い気がする。yqはフィールド型で処理分岐とか難しかったから、yqはJSONへの変換だけしてjqにしてフィールド型がarrayだったら〜ってして動く様にした。 あとswift-wasiはswiftcを呼ぶ様にした。 @swift-6.0.3 wasi -emit-assembly -O public func twice(number: Int) -> Int { return number * 2 }yqはフィールド型で処理分岐とか難しかったから、yqはJSONへの変換だけしてjqにしてフィールド型がarrayだったら〜ってして動く様にした。 あとswift-wasiはswiftcを呼ぶ様にした。 @swift-6.0.3 wasi -emit-assembly -O public func twice(number: Int) -> Int { return number * 2 } .text .file "<swift-imported-modules>" .functype __main_argc_argv (i32, i32) -> (i32)Target: wasm32-unknown-wasi warning: Could not read SDKSettings.json for SDK at: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdkpublic func twice(number: Int) -> Int { return number * 2 } (edited)public func twice(number: Int) -> Int { return number * 2 } (edited)Target: wasm32-unknown-wasi warning: Could not read SDKSettings.json for SDK at: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk error: link command failed with exit code 1 (use -v to see invocation) (edited)~/Library/org.swift.swiftpm/swift-sdksを/opt/homebrew/share/swift/sdksへのシンボリックリンクに(Homebrewは~以下のディレクトリへ書き込めないため) 2. brew tap-new swiftwasm/swiftwasm 3. /opt/homebrew/Library/Taps/swiftwasm/homebrew-swiftwasm/Formula/swiftwasm-sdk@6.0.rbを以下の内容で作成。 class SwiftwasmSdkAT60 < Formula desc "SwiftWasm SDK 6.0" homepage "https://github.com/swiftwasm/swift" version "6.0.2" url "https://github.com/swiftwasm/swift/releases/download/swift-wasm-#{version}-RELEASE/swift-wasm-#{version}-RELEASE-wasm32-unknown-wasi.artifactbundle.zip" license "" def install prefix.install Dir["*"] sdks_path = share/"swift/sdks" sdks_path.mkpath sdks_path.install_symlink prefix => "#{name}.artifactbundle" end def caveats <<~EOS SwiftWasm SDK #{version} has been installed at: #{prefix} A symlink has been created at: /opt/homebrew/share/swift/sdks/#{name}.artifactbundle EOS end end 4. brew install swiftwasm/swiftwasm/swiftwasm-sdk@6.0 でswift sdk listから認識されるインストールが出来た。 (edited)swift sdk に /opt/homebrew/share/swift/sdks を読み込ませているんですか? (edited)swift sdkは~/Library/org.swift.swiftpm/swift-sdksへartifactbundleをインストールするので、それをシンボリックリンクにしただけです。 $ la ~/Library/org.swift.swiftpm/swift-sdks lrwxr-xr-x 1 norio staff 30B 2 12 10:33 /Users/norio/Library/org.swift.swiftpm/swift-sdks@ -> /opt/homebrew/share/swift/sdks (edited)~/Library/org.swift.swiftpm/swift-sdksへ書き込めないためそうしてます。~/.swiftpm/swift-sdksswift-sdk側で~/...以外の場所を読んでくれるようにするか。 (edited)swift-sdk が SWIFT_SDK_SEARCH_PATH みたいな環境変数を見てくれるようになったらいいなあ --swift-sdks-path <swift-sdks-path> Path to the directory containing installed Swift SDKs~/Library/org.swift.swiftpm/swift-sdksを/opt/homebrew/share/swift/sdksへのシンボリックリンクに(Homebrewは~以下のディレクトリへ書き込めないため) 2. brew tap-new swiftwasm/swiftwasm 3. /opt/homebrew/Library/Taps/swiftwasm/homebrew-swiftwasm/Formula/swiftwasm-sdk@6.0.rbを以下の内容で作成。 class SwiftwasmSdkAT60 < Formula desc "SwiftWasm SDK 6.0" homepage "https://github.com/swiftwasm/swift" version "6.0.2" url "https://github.com/swiftwasm/swift/releases/download/swift-wasm-#{version}-RELEASE/swift-wasm-#{version}-RELEASE-wasm32-unknown-wasi.artifactbundle.zip" license "" def install prefix.install Dir["*"] sdks_path = share/"swift/sdks" sdks_path.mkpath sdks_path.install_symlink prefix => "#{name}.artifactbundle" end def caveats <<~EOS SwiftWasm SDK #{version} has been installed at: #{prefix} A symlink has been created at: /opt/homebrew/share/swift/sdks/#{name}.artifactbundle EOS end end 4. brew install swiftwasm/swiftwasm/swiftwasm-sdk@6.0 でswift sdk listから認識されるインストールが出来た。 (edited)#{version}を使うように変えたlicense(わからなかった)caveatsを整える@6.1, @mainとかも作るurlとsha256をCIで更新brew upgradeでそれぞれの最新を入手できる環境が作れるはず。 (edited)ghでリリースチェックするコード書きたくない)curlの出力をbashに読ませてHomebrew入れてtapしてbrew installするより、もっと簡単な最新版インストールの仕組みを作った方が良い気がする。 Homebrewのメリットは継続的に使う環境のアップグレードを簡単にできることだよね。/usr/bin/lldb って apple/swift-lldb なのか (edited)
1
1apple/swift-lldb じゃなくて 今は swiftlang/llvm-project だったbrew install norio-nomura/swift-sdks/swiftwasm-sdk でTapして最新リリースをインストール。 もしくは別途Tapしてインストール。 brew tap norio-nomura/swift-sdks brew install swiftwasm-sdk
@なしで最新リリース。@つきでバージョンピン。ネーミングはswiftwasmのタグ準拠略記 $ ls -1 Casks swiftwasm-sdk.rb swiftwasm-sdk@6.0-snapshot.rb swiftwasm-sdk@6.0.rb swiftwasm-sdk@6.1-snapshot.rb swiftwasm-sdk@development-snapshot.rb cronで自動更新。 (edited)sdkRootPath: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk swiftResourcesPath: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static swiftStaticResourcesPath: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static includeSearchPaths: not set librarySearchPaths: not set toolsetPaths: ["/home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/toolset.json"]print("Hello, WASI!")print("Hello, WASI!") Target: wasm32-unknown-wasi warning: Could not read SDKSettings.json for SDK at: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk error: link command failed with exit code 1 (use -v to see invocation) wasm-ld: error: cannot open /usr/lib/clang/17/lib/wasi/libclang_rt.builtins-wasm32.a: No such file or directory clang: error: linker command failed with exit code 1 (use -v to see invocation)librarySearchPathsが入ってないからリンクに失敗する?librarySearchPathsを設定してもダメだった。/usr/bin/wasm-ldが-lc /usr/lib/clang/17/lib/wasi/libclang_rt.builtins-wasm32.aオプション付きで起動されてた。 print("Hello, WASI!") (edited)print("Hello, WASI!") (edited)Target: wasm32-unknown-wasi warning: Could not read SDKSettings.json for SDK at: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.2-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.2-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk (edited)-resource-dirにswiftStaticResourcesPathかswiftResourcesPathのどちらを渡すか?って、-static-stdlibの有無で決まる感じなのかな?swift.xctoolchain/usr/lib/swift_staticだから、-static-stdlibの有無はチェックしなくても問題ないのか。 (edited)swift-wasm-*-SNAPSHOT-*-*-*-aがswiftlang/swiftのどのタグに対応しているか?ってのを機械的に取得するおすすめの方法ってありますか?$ gh release view --repo swiftwasm/swift swift-wasm-6.1-SNAPSHOT-2025-02-20-a --json body --jq ' .body |capture(".*(?<tag>swift-(\\d\\.\\d+-)?DEVELOPMENT-SNAPSHOT-\\d+-\\d+-\\d+-a).*") |.tag ' swift-6.1-DEVELOPMENT-SNAPSHOT-2025-02-20-a$ gh release view --repo swiftwasm/swift swift-wasm-6.1-SNAPSHOT-2025-02-20-a --json body --jq ' .body |capture(".*(?<tag>swift-(\\d\\.\\d+-)?DEVELOPMENT-SNAPSHOT-\\d+-\\d+-\\d+-a).*") |.tag ' swift-6.1-DEVELOPMENT-SNAPSHOT-2025-02-20-a ghにGitHub APIでタグをパターン検索できるextensionを作ったのですが、それにbodyを検索できる仕組みを作れないか調べてました。$ gh query-releases --repo swiftwasm/swift swift-6.1-DEVELOPMENT-SNAPSHOT-2025-02-20-a swift-wasm-6.1-SNAPSHOT-2025-02-20-agh query-tagsに--use-releaseオプションを追加する形にした。 $ gh extension install norio-nomura/gh-query-tags ⣾Cloning into '/Users/norio/.local/share/gh/extensions/gh-query-tags'... ⣟remote: Enumerating objects: 9, done. remote: Counting objects: 100% (9/9), done. remote: Compressing objects: 100% (7/7), done. ⣯remote: Total 9 (delta 3), reused 8 (delta 2), pack-reused 0 (from 0) Receiving objects: 100% (9/9), 5.96 KiB | 5.96 MiB/s, done. Resolving deltas: 100% (3/3), done. ✓ Installed extension norio-nomura/gh-query-tags $ gh query-tags --repo swiftwasm/swift --use-release swift-6.1-DEVELOPMENT-SNAPSHOT-2025-02-20-a swift-wasm-6.1-SNAPSHOT-2025-02-20-a (edited)swiftc --versionからタグ名も引けるようにした $ curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/tag-by-version.json" | jq -r --arg v "$(swiftc --version | head -n1)" '.[$v]' [ "swift-6.0.3-RELEASE" ] (edited)swift -versionの出力に含まれるハッシュ取得してのタグ検索はgh query-tagsでもできる様にしてる。 $ docker run -it --rm swiftlang/swift:nightly swift -version Swift version 6.2-dev (LLVM a73e2519b8d610d, Swift 47a7867f88a5d80) Target: aarch64-unknown-linux-gnu Build config: +assertions $ docker run -it --rm swiftlang/swift:nightly swift -version|gh query-tags --repo swiftlang/swift swift-DEVELOPMENT-SNAPSHOT-2025-02-25-a$ docker run --rm swiftlang/swift:nightly swift -version|gh query-tags --repo swiftlang/llvm-project swift-DEVELOPMENT-SNAPSHOT-2025-02-25-aSwift version 6.2-dev (LLVM a73e2519b8d610d, Swift 47a7867f88a5d80)から47a7867f88a5d80を取り出すシェルスクリプトをコピペ可能なサイズで書くのが難しいなと$は入れない方が良いかと。GitHub上でコードブロック右上のコピーボタンでのコピーに含まれてしまって、貼り付け時に$を削除しないといけない。$ swiftc -version swift-driver version: 1.115.1 Apple Swift version 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1) Target: arm64-apple-macosx15.0jqに-eを渡すとクエリがnullでコマンド失敗になるから、エラー処理できるかも。 jq -e -r --arg v "$V" '.[$v] | .[-1]')"print("Hello, WASI!")print("Hello, WASI!") Target: wasm32-unknown-wasiprint("Hello, WASI!") Target: wasm32-unknown-wasiprint("Hello, WASI!") Target: wasm32-unknown-wasi warning: Could not read SDKSettings.json for SDK at: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0.3-RELEASE-wasm32-unknown-wasi.artifactbundle/6.0.3-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdkprint("Hello, WASI!") Hello, WASI!Target: wasm32-unknown-wasi@Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello, world!") // Expectation failed: (greeting → "Hello, world!") == "Hello" }@Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello, world!") // Expectation failed: (greeting → "Hello, world!") == "Hello" } Target: wasm32-unknown-wasi wasm-ld: warning: function signature mismatch: swift_task_escalate >>> defined as (i32, i32, i32, i32) -> void in /home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libswift_Concurrency.a(_Concurrency.o) >>> defined as (i32, i32, i32, i32) -> i32 in /home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libswift_Concurrency.a(TaskStatus.cpp.o) /usr/bin/swift-swiftc: line 15: 722 Killed wasmtime main "$@"@Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello") // Expectation failed: (greeting → "Hello, world!") == "Hello" } (edited)@Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello") // Expectation failed: (greeting → "Hello, world!") == "Hello" } (edited)◇ Test run started. ↳ Testing Library Version: 6.2-dev (a7b5435933149b6) ↳ Target Platform: x86_64-unknown-linux-gnu ◇ Test helloWorld() started. ✘ Test helloWorld() recorded an issue at <stdin>:5:3: Expectation failed: (greeting → "Hello, world!") == "Hello" ✘ Test helloWorld() failed after 0.002 seconds with 1 issue. ✘ Test run with 1 test failed after 0.003 seconds with 1 issue. (edited)Target: wasm32-unknown-wasi wasm-ld: warning: function signature mismatch: swift_task_escalate >>> defined as (i32, i32, i32, i32) -> void in /home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libswift_Concurrency.a(_Concurrency.o) >>> defined as (i32, i32, i32, i32) -> i32 in /home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libswift_Concurrency.a(TaskStatus.cpp.o) /usr/bin/swift-swiftc: line 15: 722 Killed wasmtime main "$@" @Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello, world!") // Expectation failed: (greeting → "Hello, world!") == "Hello" }@Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello, world!") // Expectation failed: (greeting → "Hello, world!") == "Hello" } Target: wasm32-unknown-wasi wasm-ld: warning: function signature mismatch: swift_task_escalate >>> defined as (i32, i32, i32, i32) -> void in /home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libswift_Concurrency.a(_Concurrency.o) >>> defined as (i32, i32, i32, i32) -> i32 in /home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-02-28-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libswift_Concurrency.a(TaskStatus.cpp.o)@Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello") // Expectation failed: (greeting → "Hello, world!") == "Hello" }@Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello") // Expectation failed: (greeting → "Hello, world!") == "Hello" } Target: wasm32-unknown-wasi wasm-ld: warning: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.1-SNAPSHOT-2025-02-21-a-wasm32-unknown-wasi.artifactbundle/6.1-SNAPSHOT-2025-02-21-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libTesting.a: archive member 'Testing.autolink' is neither Wasm object file nor LLVM bitcodeswift-swiftc: 出力されたmainをFILE(1)でチェックして実行可能なら実行するswift-testing: 必要に応じてimport Testingとかを付け加えてswiftか次のサブコマンドへ送るswift-wasiはswiftcではなくswift-swiftcを呼び出す感じになった。$ time wasmtime -C cache=n /tmp/main.wasm ◇ Test run started. ↳ Testing Library Version: 6.1 (a27e55731a078f6) ↳ Target Platform: wasm32-unknown-wasi ◇ Test helloWorld() started. ✘ Test helloWorld() recorded an issue at <stdin>:5:3: Expectation failed: (greeting → "Hello, world!") == "Hello" ✘ Test helloWorld() failed after 0.000593298 seconds with 1 issue. ✘ Test run with 1 test failed after 0.000955983 seconds with 1 issue. wasmtime -C cache=n /tmp/main.wasm 12.13s user 2.01s system 1134% cpu 1.246 total$ time wasmtime -C parallel-compilation=n -C cache=n /tmp/main.wasm wasmtime -C parallel-compilation=n -C cache=n /tmp/main.wasm 7.53s user 1.78s system 100% cpu 9.310 total 並列コンパイルなしだと結構遅いなやっぱり。基本的に実行ではなくネイティブへのAOTコンパイルが時間かかってるんですよね$ time ../wasmkit/.build/release/wasmkit-cli run /tmp/main.wasm ... ✘ Test run with 1 test failed after 0.030376232 seconds with 1 issue. ../wasmkit/.build/release/wasmkit-cli run /tmp/main.wasm 0.13s user 0.05s system 99% cpu 0.178 total このくらいの規模でワンショットの実行ならトータルの時間はWasmKitの方がよっぽど速いwasmkit-cliってstatic linux sdkでビルドしたとして、実行時に何か依存するデータファイルとかありますか? (edited)wasmkit-cliのstatic linux sdkビルド、ファイルサイズでかい debugger@511f02288d87:/usr/local/bin$ ls -la w* -rwxr-xr-x 1 debugger 127 8869344 Feb 26 12:36 wasmer-headless -rwxr-xr-x 1 root root 155154088 Mar 10 06:10 wasmkit-cli -rwxr-xr-x 1 debugger 118 43895840 Feb 25 18:11 wasmtime -rwxr-xr-x 1 197108 197121 5177528 Feb 18 15:28 wazero debugger@511f02288d87:/usr/local/bin$ ldd w* wasmer-headless: linux-vdso.so.1 (0x0000f68e38e2f000) libc.so.6 => /lib/aarch64-linux-gnu/libc.so.6 (0x0000f68e38250000) /lib/ld-linux-aarch64.so.1 (0x0000f68e38df6000) libgcc_s.so.1 => /lib/aarch64-linux-gnu/libgcc_s.so.1 (0x0000f68e38dd0000) libm.so.6 => /lib/aarch64-linux-gnu/libm.so.6 (0x0000f68e38d30000) wasmkit-cli: not a dynamic executable wasmtime: linux-vdso.so.1 (0x0000e628382f4000) libdl.so.2 => /lib/aarch64-linux-gnu/libdl.so.2 (0x0000e628382a0000) libgcc_s.so.1 => /lib/aarch64-linux-gnu/libgcc_s.so.1 (0x0000e62838270000) libpthread.so.0 => /lib/aarch64-linux-gnu/libpthread.so.0 (0x0000e62838250000) libm.so.6 => /lib/aarch64-linux-gnu/libm.so.6 (0x0000e628381b0000) libc.so.6 => /lib/aarch64-linux-gnu/libc.so.6 (0x0000e62836050000) /lib/ld-linux-aarch64.so.1 (0x0000e628382bb000) wazero: not a dynamic executable そしてwazeroの小ささよ。$ strip wasmkit-cli $ ls -lh wasmkit-cli -rwxr-xr-x 1 katei katei 57M Mar 10 06:57 wasmkit-cli-c releaseでもdwarfつくんだ。-gnoneをつければ良いのかな--debug-info-format noneかな-は一つ-debug-info-format none-debug-info-format noneは効果がなくて、-Xlinker --strip-allで小さくなった。 debugger@6cf1e6635c61:/usr/local/bin$ ls -la wasmkit-cli -rwxr-xr-x 1 root root 57215536 Mar 10 07:47 wasmkit-cliFROM scratchから動くイメージを作れるので、悪くないサイズ感 $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE wasmkit-cli latest 22a4e3506671 11 minutes ago 81.2MB ubuntu noble 72297848456d 6 weeks ago 139MB mikefarah/yq latest 2c100efaca06 8 weeks ago 26.9MB $ docker run -it --rm wasmkit-cli OVERVIEW: WasmKit WebAssembly Runtime USAGE: wasmkit <subcommand> OPTIONS: --version Show the version. -h, --help Show help information. SUBCOMMANDS: run Run a WebAssembly module See 'wasmkit help <subcommand>' for detailed help. (edited)swift build -c release --swift-sdk aarch64-swift-linux-musl --experimental-lto-mode=full -Xswiftc -experimental-hermetic-seal-at-linkwasmkit-cliがパス以降のオプションを解釈しようとしてエラーを出してしまうみたい。 + wasmkit-cli run ./main --event-stream-output-path e.json Error: Unknown option '--event-stream-output-path' Usage: wasmkit run [--verbose] [--profile <path>] [--enable-signpost] [--disable-signpost] [--env <key=value> ...] [--dir <dir> ...] [--stack-size <bytes>] <path> [<arguments> ...] See 'wasmkit run --help' for more information.wasmkit-cli run ./main -- --event-stream-output-path e.json はどうでしょう--なしでいける。 + wasmtime ./main --event-stream-output-path e.json ◇ Test run started. ↳ Testing Library Version: 6.2-dev (cabf4d419cf9c8c) ↳ Target Platform: wasm32-unknown-wasi ◇ Test helloWorld() started. ✔ Test helloWorld() passed after 0.000343673 seconds. ✔ Test run with 1 test passed after 0.001216854 seconds.@Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello, world!") // Expectation failed: (greeting → "Hello, world!") == "Hello" }@Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello, world!") // Expectation failed: (greeting → "Hello, world!") == "Hello" } swift testing -- --event-stream-output-path e.json -
◇ Test run started. ↳ Testing Library Version: 6.2-dev (cabf4d419cf9c8c) ↳ Target Platform: x86_64-unknown-linux-gnu ◇ Test helloWorld() started. ✔ Test helloWorld() passed after 0.001 seconds. ✔ Test run with 1 test passed after 0.003 seconds.@Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello, world!") // Expectation failed: (greeting → "Hello, world!") == "Hello" } swift testing wasi -- --event-stream-output-path e.json -
Target: wasm32-unknown-wasi ◇ Test run started. ↳ Testing Library Version: 6.2-dev (cabf4d419cf9c8c) ↳ Target Platform: wasm32-unknown-wasi ◇ Test helloWorld() started. ✔ Test helloWorld() passed after 0.095084468 seconds. ✔ Test run with 1 test passed after 0.195883644 seconds.--event-stream-output-pathが効かないな。swiftcを呼び出してmainを生成して起動するので、--以前をswiftcへ以降をmainへ渡すようにしました。print("Hello, WASI") (edited)print("Hello, WASI") (edited)Hello, WASI Hello, WASI Hello, WASI-- Command being timed: swiftc 0.20user 0.17system 0:02.49elapsed 14%CPU (0text+0data 140500max)k (edited)Hello, WASI Hello, WASI Hello, WASI-- Command being timed: swiftc 0.20user 0.17system 0:02.49elapsed 14%CPU (0text+0data 140500max)k (edited)--event-stream-output-pathが動かないのって、wasmkit-cliに--dirを足して許可しないといけないのかと考え、.や${PWD}を渡してみたのですが動かず。wazeroにも似た機能があるのか?と考え調べたら、hostディレクトリをWASI内へマウントする的な仕組みがあるみたいで、色々調べてたら、下記のようなissueを見つけたので。 [https://github.com/WebAssembly/wasi-filesystem/issues/24]--dir .で動かないのは何かがおかしそうwasmkit-cliではホストのファイルシステムがそのまま見えて、--dirで書き込み許可?それとも--dir指定していない場所は見ることもできない?--dirはread/writeを許可しますswift-testingの--event-stream-output-pathは動かないってことか。--dir .を渡していればホストのcwdに書かれるはず/だから、/stream.jsonに書こうとするのでは? (edited)/はホストのカレントディレクトリにマップしてるので/stream.jsonはホストの ./stream.jsonimport Foundation let text="test" do { try text.write(toFile: "test.txt", atomically: true, encoding:.utf8) } catch { print("Error: \(error)") } をビルドしてwasmkit-cli run --dir . -v mainで + wasmkit-cli run --dir . -v main Started parsing module Finished parsing module: 0.064677335 seconds Error: Error Domain=NSCocoaErrorDomain Code=3328 "The requested operation is not supported." になった。atomically: falseで通った!atomically: falseでファイル書けたけど、エラーも出てた。 Error: Error Domain=NSCocoaErrorDomain Code=512 "(null)"UserInfo={NSURL=test.txt -- file:///, NSFilePath=test.txt}wasmtime run --dir . main, wazero run --mount . mainでそれぞれ通った。wasmkit-cliがwasi指定時のデフォルトです。 (edited)try! Data().write(to: URL(filePath: "test"), options: []) で試してたからでした.データの中身が空だと正常にファイル生成できるみたいですね. (edited)swift-testingの--event-stream-output-pathが動かないのは、wasmtime, wazeroでもやはり動かない。エラーも出ない。--event-stream-output-path は独自実装した FileHandle を使って書き込みを行っているっぽいですね.fopen して fwrite してる感じだったので,余計なところでエラーが throw されてなければ動きそうに見えたんですけどねswift-wasm-DEVELOPMENT-SNAPSHOT-2025-03-17-aを使ってます。swift-DEVELOPMENT-SNAPSHOT-2025-03-17-aを使ってるはずで、swift-testingも同じタグを使ってるはず。
1swift.xctoolchainに入ってるのですね。--event-stream-output-path での出力ハンドラがこういう感じのコードになっているので,必要な実装を swift-testing からコピーしてきて swift build --swift-sdk wasm32-unknown-wasi でコンパイルして wasmkit-cli run --dir . ファイル名 を実行してみたんですが,普通にファイル書き込みできちゃいました.(6.2-dev (LLVM 21406e90d7382d7, Swift 90340a069a706c3), aarch64-unknown-linux-gnu) let fd = try! FileHandle(forWritingAtPath: "test") try! fd.withLock { try fd.write("hoge") try fd.write("\n") }{ "sdkRootPath": "/home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-03-17-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-03-17-a-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk", "swiftResourcesPath": "/home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-03-17-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-03-17-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static", "swiftStaticResourcesPath": "/home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-03-17-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-03-17-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static", "toolsetPaths": [ "/home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-03-17-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-03-17-a-wasm32-unknown-wasi/wasm32-unknown-wasi/toolset.json" ] }--xunit-output は機能して --configuration-path は機能していなさそうであることから,この #if canImport(Foundation) で囲まれた範囲のオプション 3 つが全部無視されてそうに見えました. なので,ツールチェーンか Wasm SDK かわかりませんでしたがそのどっちかのビルドをする時の問題のように思いました. https://github.com/swiftlang/swift-testing/blob/ee700e25f3eb7d51a96ba806413818bbb571b1c8/Sources/Testing/ABI/EntryPoints/EntryPoint.swift#L340-L391 (edited)#if canImportを含むメソッドとかを@inlineとか使って.swiftinterfaceに埋め込んで、実際にimportされた際に判定するとか出来ないのかな?@inlinable 中の #if は .swiftinterface 出力時に アクティブな領域以外は除去されてしまいます https://github.com/swiftlang/swift/blob/a7b8cb79cd018e7ab54e89dcdb227ca5b21701d8/lib/ASTGen/Sources/ASTGen/CompilerBuildConfiguration.swift#L536-L541atomically: falseでファイル書けたけど、エラーも出てた。 Error: Error Domain=NSCocoaErrorDomain Code=512 "(null)"UserInfo={NSURL=test.txt -- file:///, NSFilePath=test.txt} import Foundation let text="test" do { try text.write(toFile: "test.txt", atomically: false, encoding:.utf8) } catch { print("Error: \(error)") }import Foundation let text="test" do { try text.write(toFile: "test.txt", atomically: false, encoding:.utf8) } catch { print("Error: \(error)") } <unknown>:0: error: compiled module was created by an older version of the compiler; rebuild 'Swift' and try again: /home/bot/.swiftpm/swift-sdks/swift-wasm-DEVELOPMENT-SNAPSHOT-2025-03-17-a-wasm32-unknown-wasi.artifactbundle/DEVELOPMENT-SNAPSHOT-2025-03-17-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/Swift.swiftmodule/wasm32-unknown-wasi.swiftmodulepath_readlink をいきなり自分で実装するのはまだハードルが高いなと思ったのでちょうどいいのが来たと思ってやっちゃいましたimport Foundation let text="test" do { try text.write(toFile: "test.txt", atomically: false, encoding:.utf8) } catch { print("Error: \(error)") }import Foundation let text="test" do { try text.write(toFile: "test.txt", atomically: false, encoding:.utf8) } catch { print("Error: \(error)") } import Foundation let text="test" do { try text.write(toFile: "test.txt", atomically: false, encoding:.utf8) } catch { print("Error: \(error)") } warning: Could not read SDKSettings.json for SDK at: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.0-SNAPSHOT-2025-03-24-a-wasm32-unknown-wasi.artifactbundle/6.0-SNAPSHOT-2025-03-24-a-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdkimport Foundation let text="test" do { try text.write(toFile: "test.txt", atomically: false, encoding:.utf8) } catch { print("Error: \(error)") } wasm-ld: warning: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.1-SNAPSHOT-2025-03-25-a-wasm32-unknown-wasi.artifactbundle/6.1-SNAPSHOT-2025-03-25-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/lib_FoundationCollections.a: archive member '_FoundationCollections.autolink' is neither Wasm object file nor LLVM bitcode wasm-ld: warning: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.1-SNAPSHOT-2025-03-25-a-wasm32-unknown-wasi.artifactbundle/6.1-SNAPSHOT-2025-03-25-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libFoundation.a: archive member 'Foundation.autolink' is neither Wasm object file nor LLVM bitcode wasm-ld: warning: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.1-SNAPSHOT-2025-03-25-a-wasm32-unknown-wasi.artifactbundle/6.1-SNAPSHOT-2025-03-25-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libFoundationEssentials.a: archive member 'FoundationEssentials.autolink' is neither Wasm object file nor LLVM bitcode wasm-ld: warning: /home/bot/.swiftpm/swift-sdks/swift-wasm-6.1-SNAPSHOT-2025-03-25-a-wasm32-unknown-wasi.artifactbundle/6.1-SNAPSHOT-2025-03-25-a-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static/wasi/libFoundationInternationalization.a: archive member 'FoundationInternationalization.autolink' is neither Wasm object file nor LLVM bitcodeswift-6.1-RELEASEでビルドできない?」と思ったら、swift/utils/update-checkout --scheme mainがとってくるWasmKitが0.1.2で0.1.4以降はビルド出来た。 (edited){ "sdkRootPath": "/home/bot/.swiftpm/swift-sdks/swift-wasm-6.1-RELEASE-wasm32-unknown-wasi.artifactbundle/6.1-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/WASI.sdk", "swiftResourcesPath": "/home/bot/.swiftpm/swift-sdks/swift-wasm-6.1-RELEASE-wasm32-unknown-wasi.artifactbundle/6.1-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static", "swiftStaticResourcesPath": "/home/bot/.swiftpm/swift-sdks/swift-wasm-6.1-RELEASE-wasm32-unknown-wasi.artifactbundle/6.1-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static", "toolsetPaths": [ "/home/bot/.swiftpm/swift-sdks/swift-wasm-6.1-RELEASE-wasm32-unknown-wasi.artifactbundle/6.1-RELEASE-wasm32-unknown-wasi/wasm32-unknown-wasi/toolset.json" ] }${SWIFT_SDK_${platform}_${arch}_TRIPLE}みたいな変数展開が必要)、プラットフォームごとにCMake単位を分ければその辺をフラットにできたり、色々嬉しい (edited)setjmp/longjmp を使った C++ コードが exception を使った Wasm バイナリにコンパイルされちゃうから使わざるを得ないって聞いたことがあります. https://github.com/holzschu/a-shell/discussions/843#discussioncomment-11115672setjmp/longjmp を使った C++ コードが exception を使った Wasm バイナリにコンパイルされちゃうから使わざるを得ないって聞いたことがあります. https://github.com/holzschu/a-shell/discussions/843#discussioncomment-11115672 setjmp/longjmp を使っているコードでコンパイルの時点で失敗するものがあるのかどうかについてはちょっとすぐにはわかりません.(C++ コードを見たら Rust や Swift で書き直せばええやん病にかかっているため)Hello, WASI Hello, WASI Hello, WASI-- Command being timed: swiftc 0.20user 0.17system 0:02.49elapsed 14%CPU (0text+0data 140500max)k (edited)print("Hello, WASI")print("Hello, WASI") Hello, WASI Hello, WASI Hello, WASI-- Command being timed: swiftc 0.23user 0.11system 0:00.34elapsed 100%CPU (0text+0data 140156max)k@cdecl の underscore をはずそうの pitch が出ていて,議論の中で @_expose(wasm) も触れられていますね. https://forums.swift.org/t/pitch-formalize-cdecl/79557--toolset を指定しなくてもデフォルトで swift run や swift test で WasmKit が走るようになりそうですね. ただ,ホストのファイルへのアクセスとかがあるなら結局追加のフラグが必要になるから自前の toolset でオーバーライドすることが多そうな気もしますが.wasm-sdk.yml追加とともに変わったぽい。 static_sdk.yml -> static-sdk.yml [https://github.com/swiftlang/swift-org-website/blob/main/_data/builds/swift-6_1-branch/static_sdk.yml] [https://github.com/swiftlang/swift-org-website/blob/main/_data/builds/swift-6_2-branch/static-sdk.yml] (edited)wasm-sdk.yml追加とともに変わったぽい。 static_sdk.yml -> static-sdk.yml [https://github.com/swiftlang/swift-org-website/blob/main/_data/builds/swift-6_1-branch/static_sdk.yml] [https://github.com/swiftlang/swift-org-website/blob/main/_data/builds/swift-6_2-branch/static-sdk.yml] (edited)static_sdk.ymlが正解ぽくて、apiが動かないというissueもないから、誰も使っていない気がする。 https://github.com/swiftlang/swift-org-website/blob/main/api/v1/install/dev/6.2/static-sdk.jsonwasmkit-cliではなくwasmkitなのね。そして古い(0.1.2)swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1 swift-DEVELOPMENT-SNAPSHOT-2025-06-17-a_wasm swift-DEVELOPMENT-SNAPSHOT-2025-06-17-a_wasm-embeddedwasm32-unknown-wasip1がwasm-embedded?wasm32-unknown-wasip1サポートをボットに追加したら、エラーになる。 @swift-6.2 wasi @swift-6.2 wasip1 -v // HelloEmbedded.swift print("Hello, Embedded Swift 😊")wasm32-unknown-wasip1サポートをボットに追加したら、エラーになる。 @swift-6.2 wasi @swift-6.2 wasip1 -v // HelloEmbedded.swift print("Hello, Embedded Swift 😊") swift wasi -
Hello, Embedded Swift 😊wasm32-unknown-wasip1サポートをボットに追加したら、エラーになる。 @swift-6.2 wasi @swift-6.2 wasip1 -v // HelloEmbedded.swift print("Hello, Embedded Swift 😊") swift wasip1 -v - exit status 1 with stdout:/usr/bin/swift-frontend -frontend -c - -target wasm32-unknown-wasip1 -disable-objc-interop -sdk /home/bot/.swiftpm/swift-sdks/swift-6.2-DEVELOPMENT-SNAPSHOT-2025-06-17-a_wasm.artifactbundle/swift-6.2-DEVELOPMENT-SNAPSHOT-2025-06-17-a_wasm/wasm32-unknown-wasi/WASI.sdk -no-color-diagnostics -Xcc -fno-color-diagnostics -tools-directory /home/bot/.swiftpm/swift-sdks/swift-6.2-DEVELOPMENT-SNAPSHOT-2025-06-17-a_wasm.artifactbundle/swift-6.2-DEVELOPMENT-SNAPSHOT-2025-06-17-a_wasm/wasm32-unknown-wasi/swift.xctoolchain/usr/bin -enable-experimental-feature Embedded -empty-abi-descriptor -resource-dir /home/bot/.swiftpm/swift-sdks/swift-6.2-DEVELOPMENT-SNAPSHOT-2025-06-17-a_wasm.artifactbundle/swift-6.2-DEVELOPMENT-SNAPSHOT-2025-06-17-a_wasm/wasm32-unknown-wasi/swift.xctoolchain/usr/lib/swift_static -use-static-resource-dir -Xcc -D__EMBEDDED_SWIFT__ -no-auto-bridging-header-chaining -module-name main -in-process-plugin-server-path /usr/lib/swift/host/libSwiftInProcPluginServer.so -plugin-path /usr/lib/swift/host/plugins -plugin-path /usr/local/lib/swift/host/plugins -o /tmp/TemporaryDirectory.3xkudn/main-1.oSwift version 6.2-dev (LLVM 5fbc818cf26c90b, Swift 2e1897356956e43) Target: wasm32-unknown-wasip1 <unknown>:0: error: unable to load standard library for target 'wasm32-unknown-wasip1'swift build -vの出力と比べると、-use-static-resource-dirが使われてるのに、.../usr/lib/swift_staticではなく.../usr/lib/swiftが渡されてるのが気になる。 (edited)swift buildに何渡してますか?-enable-experimental-feature Embeddedな時ってこと?--swift-sdkにターゲットトリプル渡すとwasm32-unknown-wasiとwasm32-unknown-wasip1がノーマライズによって同一視されてしまうのでSwift SDK IDを指定するようにしてみてください。wasm32-unknown-wasiもwasm32-unknown-wasip1にrenameする予定なので p1の有無はEmbedded性とは無関係です。swift buildを使わず、info.json,swift-sdk.json,toolset.jsonを直接展開して、swiftcへ渡すオプションを生成してます。 (edited)-resource-dirには何渡してますか?swiftResourcesPathを渡しておけば大丈夫なはずswift-sdk.jsonを読んでますか?toolset.jsonの-static-stdlibの有無でswiftResourcesPathとswiftStaticResourcesPathを切り替えてます。swift-sdk.jsonを読んでますか? embedded-swift-sdk.jsonを読めるように今日変えたところです。embedded-toolset.jsonに-static-stdlibが入ってるのがおかしい?-static-stdlibはほとんど意味をなしてないオプションなんですが一応Embedded向けSDKで指定してるのは意味としてはおかしくないですね。swiftResourcesPathを渡しておけば大丈夫なはず swiftResourcesPathもswift_staticを指してるので swiftResourcesPathをどちらのSDKでも指定するのはどうでしょうembedded-swift-sdk.jsonのswiftStaticResourcesPathを.../lib/swiftに将来変えるってこと?-enable-experimental-feature Embeddedな時にswiftResourcesPathを選択するロジックが、swiftlangのどこかにあればそれに倣うのですが、今探し中。embedded-swift-sdk.jsonのswiftStaticResourcesPathを.../lib/swiftに将来変えるってこと? lib/swift/embeddedをlib/swift_static/embeddedに移すかswiftStaticResourcesPathがlib/swiftを指すようにする話がたまに出てます。 (edited)-enable-experimental-feature Embeddedな時にswiftResourcesPathを選択するロジックが、swiftlangのどこかにあればそれに倣うのですが、今探し中。 swiftResourceDir/swiftStaticResourceDirは切り変えてなくて、swift buildに渡される--static-swift-stdlibによってのみ切り替わります。swift build -v --swift-sdk wasm32-unknown-wasip1のログに--static-swift-stdlibは見つからないみたいswift buildに--static-swift-stdlibを指定していないので swiftResourceDirに指定されているlib/swiftが-resource-dirとして渡ってますね。-static-stdlibがあったらswiftStaticResourceDirを使うってのが間違ってるのか。swift buildが--static-swift-stdlibを受け取ったら、-resource-dirの指す先を.../lib/swiftと.../lib/swift_staticで切り替えて、-static-stdlibをswiftcへ渡す。 しかし、swiftcへのオプションに-static-stdlibが渡されていても-resource-dirが../lib/swift_staticを指す必要はない。ということか。swiftResourcesPathを使えば良さそう。print("Hello, WASI!")print("Hello, WASI!") swift wasi -
Hello, WASI!print("Hello, WASI!") swift wasip1 -
Hello, WASI!-enable-experimental-feature Embeddedが渡ってるのは確認してるんだけど。#if hasFeature(Embedded) #error("Embedded enabled") #else #error("Full-featured Swift") #endif#if hasFeature(Embedded) #error("Embedded enabled") #else #error("Full-featured Swift") #endif swift wasi - exit status 1 with stderr:<stdin>:4:8: error: Full-featured Swift 2 | #error("Embedded enabled") 3 | #else 4 | #error("Full-featured Swift") | `- error: Full-featured Swift 5 | #endif 6 | #if hasFeature(Embedded) #error("Embedded enabled") #else #error("Full-featured Swift") #endif swift wasip1 - exit status 1 with stderr:<stdin>:2:8: error: Embedded enabled 1 | #if hasFeature(Embedded) 2 | #error("Embedded enabled") | `- error: Embedded enabled 3 | #else 4 | #error("Full-featured Swift")wasm32-unknown-wasip1になると。なったらその時また考えよう。swift test --swift-sdk wasm32-unknown-wasiもswift test --swift-sdk wasm32-unknown-wasip1もビルドエラーでtest runnerまで辿り着かなかった。 (edited)XCTest向けに生成するtest discoveryコードで邪魔してるぽい。 Embeddedでは無理としても、WASIでは動いて欲しいね。 @swift-main testing wasi @swift-main testing wasip1 @Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello") // Expectation failed: (greeting → "Hello, world!") == "Hello" }XCTest向けに生成するtest discoveryコードで邪魔してるぽい。 Embeddedでは無理としても、WASIでは動いて欲しいね。 @swift-main testing wasi @swift-main testing wasip1 @Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello") // Expectation failed: (greeting → "Hello, world!") == "Hello" } swift testing wasi -
◇ Test run started. ↳ Testing Library Version: 6.3-dev (b97b57687a8fe60) ↳ Target Platform: wasm32-unknown-wasi ◇ Test helloWorld() started. ✘ Test helloWorld() recorded an issue at <stdin>:4:3: Expectation failed: (greeting → "Hello, world!") == "Hello" ✘ Test helloWorld() failed after 0.033970847 seconds with 1 issue. ✘ Test run with 1 test in 0 suites failed after 0.054957862 seconds with 1 issue.XCTest向けに生成するtest discoveryコードで邪魔してるぽい。 Embeddedでは無理としても、WASIでは動いて欲しいね。 @swift-main testing wasi @swift-main testing wasip1 @Test func helloWorld() { let greeting = "Hello, world!" #expect(greeting == "Hello") // Expectation failed: (greeting → "Hello, world!") == "Hello" } swift testing wasip1 - exit status 1 with stderr:<stdin>:1:8: error: no such module 'Testing' 1 | import Testing | `- error: no such module 'Testing' 2 | @Test func helloWorld() { 3 | let greeting = "Hello, world!"--toolset <JSON file> とかがなくても swift run --swift-sdk wasm32-unknown-wasi で executableTarget が実行できるようになったのは嬉しいユースケースじゃないですか?ちょっとした実験コードを実行するときにすでによく使ってます./// A synchronization primitive that protects shared mutable state via mutual /// exclusion. /// /// The `Mutex` type offers non-recursive exclusive access to the state it is /// protecting by blocking threads attempting to acquire the lock. Only one /// execution context at a time has access to the value stored within the /// `Mutex` allowing for exclusive access. class Mutex<T>: @unchecked Sendable { /// The lock used to synchronize access to the value. var lock: NSLock /// The value protected by the mutex. var value: T
1.package(url: "https://github.com/GoodNotes/swift-icudata-slim.git", from: "1.0.0") は 1.0.0 じゃなくて 0.1.0 か 0.2.0 とかじゃないとまだそのままコピペじゃ使えない状態になっていると思います.ICUDataSlim 使用時かつ wasm-strip や wasm-opt なしのサイズだったのですが,wasm-strip と wasm-opt -Oz までかけた状態だと,元が 49 MB だったのが,ICUDataSlim 使用時が 27 MB,ICUDataSlim_Minimal 使用時が 20 MB まで小さくなりました.
(edited)
1.product(name: "ICUDataSlim", package: "swift-icudata-slim") を .product(name: "ICUDataSlim", package: "swift-icudata-slim", condition: .when(platforms: [.wasi])), みたいな感じにしておけば WASI 向けのビルド時だけ swift-icudata-slim をリンクするとかもできそうですね. (edited)wasm32-unknown-wasip1になると。なったらその時また考えよう。 { "x86_64-swift-linux-musl": { "swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1": { "toolsetPaths": [ "/home/bot/.swiftpm/swift-sdks/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1.artifactbundle/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1/swift-linux-musl/toolset.json" ], "sdkRootPath": "/home/bot/.swiftpm/swift-sdks/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1.artifactbundle/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1/swift-linux-musl/musl-1.2.5.sdk/x86_64", "swiftResourcesPath": "/home/bot/.swiftpm/swift-sdks/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1.artifactbundle/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1/swift-linux-musl/musl-1.2.5.sdk/x86_64/usr/lib/swift_static", "swiftStaticResourcesPath": "/home/bot/.swiftpm/swift-sdks/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1.artifactbundle/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1/swift-linux-musl/musl-1.2.5.sdk/x86_64/usr/lib/swift_static" } }, "aarch64-swift-linux-musl": { "swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1": { "toolsetPaths": [ "/home/bot/.swiftpm/swift-sdks/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1.artifactbundle/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1/swift-linux-musl/toolset.json" ], "sdkRootPath": "/home/bot/.swiftpm/swift-sdks/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1.artifactbundle/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1/swift-linux-musl/musl-1.2.5.sdk/aarch64", "swiftResourcesPath": "/home/bot/.swiftpm/swift-sdks/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1.artifactbundle/swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1/swift-linux-musl/musl-1.2.5.sdk/aarch64/usr/lib/swift_static", "swiftStaticResourcesPath": "/home/bot/.swiftpm/swift-sdprint("Hello, wasip1")print("Hello, wasip1") swift wasi -
Hello, wasip1swift-sdk-configuration: Error: Multiple SDK configuration found for matching target_triple: 'wasm32-unknown-wasi', sdk_id: ''print("Hello, wasip1") swift wasip1 -
Hello, wasip1swift-sdk-configuration: Error: Multiple SDK configuration found for matching target_triple: 'wasm32-unknown-wasip1', sdk_id: ''swift-DEVELOPMENT-SNAPSHOT-2025-06-12-a_static-linux-0.0.1 swift-DEVELOPMENT-SNAPSHOT-2025-07-24-a_wasm swift-DEVELOPMENT-SNAPSHOT-2025-07-24-a_wasm-embeddedswift-sdk.jsonとembedded-swift-sdk.jsonのどちらもtargetTriplesが{"wasm32-unknown-wasip1":...}だから、tripleでは区別できない。 (edited)info.json, swift-sdk.json, toolset.json以外は同じartifactbundleを2つインストールすることになって、あまり嬉しくないな。 (edited)embedded-toolset.jsonのオプションをEmbedded全体で共通化できるならば、ってところなのかな (edited)--swift-sdk wasm32-unknown-wasip1 だとランダムに衝突が起こるのを経験しましたが,公式の instructions に書かれている Swift SDK ID を使うようにして回避しちゃってました. https://www.swift.org/documentation/articles/wasm-getting-started.html (edited)swift test --swift-sdk wasm32-unknown-wasiもswift test --swift-sdk wasm32-unknown-wasip1もビルドエラーでtest runnerまで辿り着かなかった。 (edited)swift test が修正されるっぽいですよ.WasmKit 向けのコマンドラインオプションとかが SwiftPM にハードコーディングされるのはどうなんだろう...って気はしますが. https://github.com/swiftlang/swift-package-manager/pull/9114--toolset に JSON を渡せばできたはずです.swift test の --toolset に渡すと良いですよ. { "schemaVersion": "1.0", "testRunner": { "path": "/usr/bin/env", "extraCLIOptions": [ "wasmtime", "--dir", "." ] } } この JSON のドキュメントは Swift SDKs for Cross Compiling の Swift Evolution proposal の中に含まれてます.+ if runner.path?.components.last == "wasmkit" { を見てちょっと短絡的に考えてました。
1$は入れない方が良いかと。GitHub上でコードブロック右上のコピーボタンでのコピーに含まれてしまって、貼り付け時に$を削除しないといけない。 $を除去する機能がついたりしてることを、fish-shellのリリースノートで知った。 https://fishshell.com/docs/current/relnotes.html#interactive-improvements$ つけるのやめてたんだけど、 $ つけられるようにこれ流行ってほしいTarget Platform: wasm32-unknown-wasip と出てくるのが気になっていたんですが,swift-testing repo を追ってみると target の unversionedTriple というものが使われていることがわかり,swiftc で -print-target-info したときに "target" の下を見ると "unversionedTriple": "wasm32-unknown-wasip" となっていることから,おそらくこの情報が渡ってそうだというのがわかりました.この unversionedTriple って swiftlang/swift repo のテストケースを見るに x86_64-apple-macosx10.15 を x86_64-apple-macosx にしたりするときのためのものっぽいのですが,WASI ターゲットにおいて wasip1 が wasip になっちゃうのって意図されたものなのかどうかご存知の方っていらっしゃいますか? (edited)$ diff <(wasm-objdump -x -j linking .build.main-snapshot-2025-10-02/wasm32-unknown-wasip1/release/SwiftSyntax.build/AbsolutePosition.swift.o) <(wasm-objdump -x -j linking .build.main-snapshot-2025-10-16/wasm32-unknown-wasip1/release/SwiftSyntax.build/AbsolutePosition.swift.o) 52c52 < - 43: F <_swift_dead_method_stub> func=35 [ binding=local vis=default ] --- > - 43: F <_swift_dead_method_stub> func=35 [ binding=weak vis=hidden ] 182c182 < - comdat groups [count=33] --- > - comdat groups [count=34] 232a233,234 > - _swift_dead_method_stub: [count=1] > - func[35] <$s11SwiftSyntax0B8RewriterC9visitImpl33_F0C5D882E9301122F145EADC4573BFC8LLyAA0B0VAGF>mkdir foo && cd foo echo main-snapshot-2025-10-16 > .swift-version swiftly install swift package init --type library --disable-swift-testing --enable-xctest swift sdk install https://download.swift.org/development/wasm-sdk/swift-DEVELOPMENT-SNAPSHOT-2025-10-16-a/swift-DEVELOPMENT-SNAPSHOT-2025-10-16-a_wasm.artifactbundle.tar.gz --checksum aa7251d0fbc44c0894335363f19e37a39dc323d3d8274ee8a7fe03b537c6cf67 swift build --build-tests --swift-sdk "$(swiftc -print-target-info | jq -r '.swiftCompilerTag')_wasm" (edited)