From cb08677869568993bda926fe14c607b20163b898 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Sat, 30 Nov 2019 14:55:05 +0100 Subject: [PATCH 1/8] parse_enum_item -> parse_enum_variant --- src/librustc_parse/parser/item.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/librustc_parse/parser/item.rs b/src/librustc_parse/parser/item.rs index a0669a2a1748e..6b3e7c0789d2f 100644 --- a/src/librustc_parse/parser/item.rs +++ b/src/librustc_parse/parser/item.rs @@ -1332,7 +1332,7 @@ impl<'a> Parser<'a> { let (variants, _) = self.parse_delim_comma_seq( token::Brace, - |p| p.parse_enum_item(), + |p| p.parse_enum_variant(), ).map_err(|e| { self.recover_stmt(); e @@ -1344,7 +1344,7 @@ impl<'a> Parser<'a> { Ok((id, ItemKind::Enum(enum_definition, generics), None)) } - fn parse_enum_item(&mut self) -> PResult<'a, Option> { + fn parse_enum_variant(&mut self) -> PResult<'a, Option> { let variant_attrs = self.parse_outer_attributes()?; let vlo = self.token.span; From ff5fcac6c240fd40e24356dd4fab07bbb2b41f5e Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 2 Dec 2019 10:59:06 +0100 Subject: [PATCH 2/8] miri: add throw_machine_stop macro --- src/librustc/mir/interpret/mod.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/librustc/mir/interpret/mod.rs b/src/librustc/mir/interpret/mod.rs index 65f4ee88a9c2f..fff876752db55 100644 --- a/src/librustc/mir/interpret/mod.rs +++ b/src/librustc/mir/interpret/mod.rs @@ -90,6 +90,13 @@ macro_rules! throw_exhaust { ($($tt:tt)*) => { return Err(err_exhaust!($($tt)*).into()) }; } +#[macro_export] +macro_rules! throw_machine_stop { + ($($tt:tt)*) => { + return Err($crate::mir::interpret::InterpError::MachineStop(Box::new($($tt)*)).into()) + }; +} + mod error; mod value; mod allocation; From 2304c25f31fb69c279110ecaf51627cc36bffd55 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Mon, 2 Dec 2019 11:35:59 -0800 Subject: [PATCH 3/8] Update the minimum external LLVM to 7 LLVM 7 is over a year old, which should be plenty for compatibility. The last LLVM 6 holdout was llvm-emscripten, which went away in #65501. I've also included a fix for LLVM 8 lacking `MemorySanitizerOptions`, which was broken by #66522. --- src/bootstrap/native.rs | 4 +- src/ci/azure-pipelines/auto.yml | 2 +- src/ci/azure-pipelines/pr.yml | 2 +- .../Dockerfile | 6 +-- src/librustc_codegen_llvm/intrinsic.rs | 31 +++------------- src/rustllvm/PassWrapper.cpp | 16 ++------ src/rustllvm/RustWrapper.cpp | 37 ------------------- src/test/codegen/align-enum.rs | 1 - src/test/codegen/align-struct.rs | 1 - src/test/codegen/consts.rs | 1 - src/test/codegen/packed.rs | 1 - src/test/codegen/repeat-trusted-len.rs | 1 - .../simd-intrinsic-float-minmax.rs | 2 - src/test/codegen/stores.rs | 1 - .../emit-stack-sizes/Makefile | 1 - .../ui/simd/simd-intrinsic-float-minmax.rs | 1 - src/test/ui/target-feature/gate.rs | 1 - src/test/ui/target-feature/gate.stderr | 2 +- 18 files changed, 16 insertions(+), 95 deletions(-) rename src/ci/docker/{x86_64-gnu-llvm-6.0 => x86_64-gnu-llvm-7}/Dockerfile (90%) diff --git a/src/bootstrap/native.rs b/src/bootstrap/native.rs index 2e89fd5398dfc..be13b9aa2eb49 100644 --- a/src/bootstrap/native.rs +++ b/src/bootstrap/native.rs @@ -294,11 +294,11 @@ fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) { let mut parts = version.split('.').take(2) .filter_map(|s| s.parse::().ok()); if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) { - if major >= 6 { + if major >= 7 { return } } - panic!("\n\nbad LLVM version: {}, need >=6.0\n\n", version) + panic!("\n\nbad LLVM version: {}, need >=7.0\n\n", version) } fn configure_cmake(builder: &Builder<'_>, diff --git a/src/ci/azure-pipelines/auto.yml b/src/ci/azure-pipelines/auto.yml index bfe5174bf1e57..70d6bad297dce 100644 --- a/src/ci/azure-pipelines/auto.yml +++ b/src/ci/azure-pipelines/auto.yml @@ -18,7 +18,7 @@ jobs: - template: steps/run.yml strategy: matrix: - x86_64-gnu-llvm-6.0: + x86_64-gnu-llvm-7: RUST_BACKTRACE: 1 dist-x86_64-linux: {} dist-x86_64-linux-alt: diff --git a/src/ci/azure-pipelines/pr.yml b/src/ci/azure-pipelines/pr.yml index aee4d8d5136aa..1f0be53677de2 100644 --- a/src/ci/azure-pipelines/pr.yml +++ b/src/ci/azure-pipelines/pr.yml @@ -18,7 +18,7 @@ jobs: - template: steps/run.yml strategy: matrix: - x86_64-gnu-llvm-6.0: {} + x86_64-gnu-llvm-7: {} mingw-check: {} x86_64-gnu-tools: CI_ONLY_WHEN_SUBMODULES_CHANGED: 1 diff --git a/src/ci/docker/x86_64-gnu-llvm-6.0/Dockerfile b/src/ci/docker/x86_64-gnu-llvm-7/Dockerfile similarity index 90% rename from src/ci/docker/x86_64-gnu-llvm-6.0/Dockerfile rename to src/ci/docker/x86_64-gnu-llvm-7/Dockerfile index 6dbbb2203470b..a1c9c13fc471a 100644 --- a/src/ci/docker/x86_64-gnu-llvm-6.0/Dockerfile +++ b/src/ci/docker/x86_64-gnu-llvm-7/Dockerfile @@ -1,4 +1,4 @@ -FROM ubuntu:16.04 +FROM ubuntu:18.04 RUN apt-get update && apt-get install -y --no-install-recommends \ g++ \ @@ -11,7 +11,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ cmake \ sudo \ gdb \ - llvm-6.0-tools \ + llvm-7-tools \ libedit-dev \ libssl-dev \ pkg-config \ @@ -24,7 +24,7 @@ RUN sh /scripts/sccache.sh # using llvm-link-shared due to libffi issues -- see #34486 ENV RUST_CONFIGURE_ARGS \ --build=x86_64-unknown-linux-gnu \ - --llvm-root=/usr/lib/llvm-6.0 \ + --llvm-root=/usr/lib/llvm-7 \ --enable-llvm-link-shared ENV SCRIPT python2.7 ../x.py test src/tools/tidy && python2.7 ../x.py test diff --git a/src/librustc_codegen_llvm/intrinsic.rs b/src/librustc_codegen_llvm/intrinsic.rs index aa55f3a19e2be..c34bee802f7aa 100644 --- a/src/librustc_codegen_llvm/intrinsic.rs +++ b/src/librustc_codegen_llvm/intrinsic.rs @@ -442,32 +442,11 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> { let is_left = name == "rotate_left"; let val = args[0].immediate(); let raw_shift = args[1].immediate(); - if llvm_util::get_major_version() >= 7 { - // rotate = funnel shift with first two args the same - let llvm_name = &format!("llvm.fsh{}.i{}", - if is_left { 'l' } else { 'r' }, width); - let llfn = self.get_intrinsic(llvm_name); - self.call(llfn, &[val, val, raw_shift], None) - } else { - // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW)) - // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW)) - let width = self.const_uint( - self.type_ix(width), - width, - ); - let shift = self.urem(raw_shift, width); - let width_minus_raw_shift = self.sub(width, raw_shift); - let inv_shift = self.urem(width_minus_raw_shift, width); - let shift1 = self.shl( - val, - if is_left { shift } else { inv_shift }, - ); - let shift2 = self.lshr( - val, - if !is_left { shift } else { inv_shift }, - ); - self.or(shift1, shift2) - } + // rotate = funnel shift with first two args the same + let llvm_name = &format!("llvm.fsh{}.i{}", + if is_left { 'l' } else { 'r' }, width); + let llfn = self.get_intrinsic(llvm_name); + self.call(llfn, &[val, val, raw_shift], None) }, "saturating_add" | "saturating_sub" => { let is_add = name == "saturating_add"; diff --git a/src/rustllvm/PassWrapper.cpp b/src/rustllvm/PassWrapper.cpp index a116ed282acd1..a6b46f40dbce2 100644 --- a/src/rustllvm/PassWrapper.cpp +++ b/src/rustllvm/PassWrapper.cpp @@ -101,11 +101,13 @@ extern "C" LLVMPassRef LLVMRustCreateModuleAddressSanitizerPass(bool Recover) { } extern "C" LLVMPassRef LLVMRustCreateMemorySanitizerPass(int TrackOrigins, bool Recover) { -#if LLVM_VERSION_GE(8, 0) +#if LLVM_VERSION_GE(9, 0) const bool CompileKernel = false; return wrap(createMemorySanitizerLegacyPassPass( MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel})); +#elif LLVM_VERSION_GE(8, 0) + return wrap(createMemorySanitizerLegacyPassPass(TrackOrigins, Recover)); #else return wrap(createMemorySanitizerPass(TrackOrigins, Recover)); #endif @@ -449,9 +451,7 @@ extern "C" void LLVMRustConfigurePassManagerBuilder( LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel, bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO, const char* PGOGenPath, const char* PGOUsePath) { -#if LLVM_VERSION_GE(7, 0) unwrap(PMBR)->MergeFunctions = MergeFunctions; -#endif unwrap(PMBR)->SLPVectorize = SLPVectorize; unwrap(PMBR)->OptLevel = fromRust(OptLevel); unwrap(PMBR)->LoopVectorize = LoopVectorize; @@ -558,12 +558,8 @@ LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR, return LLVMRustResult::Failure; } -#if LLVM_VERSION_GE(7, 0) buffer_ostream BOS(OS); unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false); -#else - unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false); -#endif PM->run(*unwrap(M)); // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output @@ -847,9 +843,7 @@ struct LLVMRustThinLTOData { StringMap ExportLists; StringMap ModuleToDefinedGVSummaries; -#if LLVM_VERSION_GE(7, 0) LLVMRustThinLTOData() : Index(/* HaveGVs = */ false) {} -#endif }; // Just an argument to the `LLVMRustCreateThinLTOData` function below. @@ -920,7 +914,6 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, // combined index // // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` -#if LLVM_VERSION_GE(7, 0) auto deadIsPrevailing = [&](GlobalValue::GUID G) { return PrevailingType::Unknown; }; @@ -932,9 +925,6 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, deadIsPrevailing, /* ImportEnabled = */ false); #else computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing); -#endif -#else - computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols); #endif ComputeCrossModuleImport( Ret->Index, diff --git a/src/rustllvm/RustWrapper.cpp b/src/rustllvm/RustWrapper.cpp index e6c45b8e3628b..a83ba9a8f1308 100644 --- a/src/rustllvm/RustWrapper.cpp +++ b/src/rustllvm/RustWrapper.cpp @@ -88,11 +88,7 @@ extern "C" char *LLVMRustGetLastError(void) { } extern "C" unsigned int LLVMRustGetInstructionCount(LLVMModuleRef M) { -#if LLVM_VERSION_GE(7, 0) return unwrap(M)->getInstructionCount(); -#else - report_fatal_error("Module::getInstructionCount not available before LLVM 7"); -#endif } extern "C" void LLVMRustSetLastError(const char *Err) { @@ -761,14 +757,10 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantPart( LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Discriminator, LLVMMetadataRef Elements, const char *UniqueId) { -#if LLVM_VERSION_GE(7, 0) return wrap(Builder->createVariantPart( unwrapDI(Scope), Name, unwrapDI(File), LineNumber, SizeInBits, AlignInBits, fromRust(Flags), unwrapDI(Discriminator), DINodeArray(unwrapDI(Elements)), UniqueId)); -#else - abort(); -#endif } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType( @@ -787,7 +779,6 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantMemberType( const char *Name, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant, LLVMRustDIFlags Flags, LLVMMetadataRef Ty) { -#if LLVM_VERSION_GE(7, 0) llvm::ConstantInt* D = nullptr; if (Discriminant) { D = unwrap(Discriminant); @@ -796,12 +787,6 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantMemberType( unwrapDI(File), LineNo, SizeInBits, AlignInBits, OffsetInBits, D, fromRust(Flags), unwrapDI(Ty))); -#else - return wrap(Builder->createMemberType(unwrapDI(Scope), Name, - unwrapDI(File), LineNo, - SizeInBits, AlignInBits, OffsetInBits, - fromRust(Flags), unwrapDI(Ty))); -#endif } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock( @@ -911,18 +896,10 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType( LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef Elements, LLVMMetadataRef ClassTy, bool IsScoped) { -#if LLVM_VERSION_GE(7, 0) return wrap(Builder->createEnumerationType( unwrapDI(Scope), Name, unwrapDI(File), LineNumber, SizeInBits, AlignInBits, DINodeArray(unwrapDI(Elements)), unwrapDI(ClassTy), "", IsScoped)); -#else - // Ignore IsScoped on older LLVM. - return wrap(Builder->createEnumerationType( - unwrapDI(Scope), Name, unwrapDI(File), LineNumber, - SizeInBits, AlignInBits, DINodeArray(unwrapDI(Elements)), - unwrapDI(ClassTy), "")); -#endif } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType( @@ -1275,34 +1252,20 @@ extern "C" LLVMValueRef LLVMRustBuildMemCpy(LLVMBuilderRef B, LLVMValueRef Dst, unsigned DstAlign, LLVMValueRef Src, unsigned SrcAlign, LLVMValueRef Size, bool IsVolatile) { -#if LLVM_VERSION_GE(7, 0) return wrap(unwrap(B)->CreateMemCpy( unwrap(Dst), DstAlign, unwrap(Src), SrcAlign, unwrap(Size), IsVolatile)); -#else - unsigned Align = std::min(DstAlign, SrcAlign); - return wrap(unwrap(B)->CreateMemCpy( - unwrap(Dst), unwrap(Src), - unwrap(Size), Align, IsVolatile)); -#endif } extern "C" LLVMValueRef LLVMRustBuildMemMove(LLVMBuilderRef B, LLVMValueRef Dst, unsigned DstAlign, LLVMValueRef Src, unsigned SrcAlign, LLVMValueRef Size, bool IsVolatile) { -#if LLVM_VERSION_GE(7, 0) return wrap(unwrap(B)->CreateMemMove( unwrap(Dst), DstAlign, unwrap(Src), SrcAlign, unwrap(Size), IsVolatile)); -#else - unsigned Align = std::min(DstAlign, SrcAlign); - return wrap(unwrap(B)->CreateMemMove( - unwrap(Dst), unwrap(Src), - unwrap(Size), Align, IsVolatile)); -#endif } extern "C" LLVMValueRef diff --git a/src/test/codegen/align-enum.rs b/src/test/codegen/align-enum.rs index 4241fcea8047d..72447fbc079dd 100644 --- a/src/test/codegen/align-enum.rs +++ b/src/test/codegen/align-enum.rs @@ -1,6 +1,5 @@ // compile-flags: -C no-prepopulate-passes // ignore-tidy-linelength -// min-llvm-version 7.0 #![crate_type = "lib"] diff --git a/src/test/codegen/align-struct.rs b/src/test/codegen/align-struct.rs index c0d6a0c80e1cf..5e290323907d0 100644 --- a/src/test/codegen/align-struct.rs +++ b/src/test/codegen/align-struct.rs @@ -1,6 +1,5 @@ // compile-flags: -C no-prepopulate-passes // ignore-tidy-linelength -// min-llvm-version 7.0 #![crate_type = "lib"] diff --git a/src/test/codegen/consts.rs b/src/test/codegen/consts.rs index e0843f5ff08b3..7d65ad1435e12 100644 --- a/src/test/codegen/consts.rs +++ b/src/test/codegen/consts.rs @@ -1,6 +1,5 @@ // compile-flags: -C no-prepopulate-passes // ignore-tidy-linelength -// min-llvm-version 7.0 #![crate_type = "lib"] diff --git a/src/test/codegen/packed.rs b/src/test/codegen/packed.rs index 3c8ff394849a1..f3f5202206ced 100644 --- a/src/test/codegen/packed.rs +++ b/src/test/codegen/packed.rs @@ -1,6 +1,5 @@ // ignore-tidy-linelength // compile-flags: -C no-prepopulate-passes -// min-llvm-version 7.0 #![crate_type = "lib"] diff --git a/src/test/codegen/repeat-trusted-len.rs b/src/test/codegen/repeat-trusted-len.rs index 87f29f6047c6a..99f3464c0768d 100644 --- a/src/test/codegen/repeat-trusted-len.rs +++ b/src/test/codegen/repeat-trusted-len.rs @@ -1,6 +1,5 @@ // compile-flags: -O // ignore-tidy-linelength -// min-llvm-version 7.0 #![crate_type = "lib"] diff --git a/src/test/codegen/simd-intrinsic/simd-intrinsic-float-minmax.rs b/src/test/codegen/simd-intrinsic/simd-intrinsic-float-minmax.rs index 7b9b1aec6c855..4e0abed78cd64 100644 --- a/src/test/codegen/simd-intrinsic/simd-intrinsic-float-minmax.rs +++ b/src/test/codegen/simd-intrinsic/simd-intrinsic-float-minmax.rs @@ -1,5 +1,3 @@ -// min-llvm-version 7.0 - // compile-flags: -C no-prepopulate-passes #![crate_type = "lib"] diff --git a/src/test/codegen/stores.rs b/src/test/codegen/stores.rs index 64143aee669d5..4ea003e99ad28 100644 --- a/src/test/codegen/stores.rs +++ b/src/test/codegen/stores.rs @@ -1,6 +1,5 @@ // compile-flags: -C no-prepopulate-passes // ignore-tidy-linelength -// min-llvm-version 7.0 #![crate_type = "lib"] diff --git a/src/test/run-make-fulldeps/emit-stack-sizes/Makefile b/src/test/run-make-fulldeps/emit-stack-sizes/Makefile index 604fc4688f532..d270289484284 100644 --- a/src/test/run-make-fulldeps/emit-stack-sizes/Makefile +++ b/src/test/run-make-fulldeps/emit-stack-sizes/Makefile @@ -2,7 +2,6 @@ # ignore-windows # ignore-macos -# min-llvm-version 6.0 # # This feature only works when the output object format is ELF so we ignore # macOS and Windows diff --git a/src/test/ui/simd/simd-intrinsic-float-minmax.rs b/src/test/ui/simd/simd-intrinsic-float-minmax.rs index dd5551d28441d..5f0aa11af5fb8 100644 --- a/src/test/ui/simd/simd-intrinsic-float-minmax.rs +++ b/src/test/ui/simd/simd-intrinsic-float-minmax.rs @@ -1,6 +1,5 @@ // run-pass // ignore-emscripten -// min-llvm-version 7.0 // Test that the simd_f{min,max} intrinsics produce the correct results. diff --git a/src/test/ui/target-feature/gate.rs b/src/test/ui/target-feature/gate.rs index bc7f7caa10766..2d51cab675e00 100644 --- a/src/test/ui/target-feature/gate.rs +++ b/src/test/ui/target-feature/gate.rs @@ -25,7 +25,6 @@ // gate-test-movbe_target_feature // gate-test-rtm_target_feature // gate-test-f16c_target_feature -// min-llvm-version 6.0 #[target_feature(enable = "avx512bw")] //~^ ERROR: currently unstable diff --git a/src/test/ui/target-feature/gate.stderr b/src/test/ui/target-feature/gate.stderr index 05dbc6e90adc8..423a893e88f5e 100644 --- a/src/test/ui/target-feature/gate.stderr +++ b/src/test/ui/target-feature/gate.stderr @@ -1,5 +1,5 @@ error[E0658]: the target feature `avx512bw` is currently unstable - --> $DIR/gate.rs:30:18 + --> $DIR/gate.rs:29:18 | LL | #[target_feature(enable = "avx512bw")] | ^^^^^^^^^^^^^^^^^^^ From 7693bb9e1d122bea1b0645dcc201c6ed79c910e2 Mon Sep 17 00:00:00 2001 From: Reese Williams Date: Mon, 2 Dec 2019 21:52:04 -0500 Subject: [PATCH 4/8] Add long error for E0631 and update ui tests. --- src/librustc_error_codes/error_codes.rs | 2 +- src/librustc_error_codes/error_codes/E0631.md | 29 +++++++++++++++++++ .../anonymous-higher-ranked-lifetime.stderr | 1 + .../expect-fn-supply-fn.stderr | 3 +- .../expect-infer-var-appearing-twice.stderr | 1 + src/test/ui/closures/issue-41366.stderr | 3 +- src/test/ui/issues/issue-43623.stderr | 3 +- src/test/ui/issues/issue-60283.stderr | 3 +- src/test/ui/mismatched_types/E0631.stderr | 1 + .../closure-arg-type-mismatch.stderr | 3 +- .../mismatched_types/closure-mismatch.stderr | 3 +- .../ui/mismatched_types/fn-variance-1.stderr | 1 + .../ui/mismatched_types/issue-36053-2.stderr | 3 +- .../unboxed-closures-vtable-mismatch.stderr | 1 + 14 files changed, 49 insertions(+), 8 deletions(-) create mode 100644 src/librustc_error_codes/error_codes/E0631.md diff --git a/src/librustc_error_codes/error_codes.rs b/src/librustc_error_codes/error_codes.rs index 7f111b42403b5..9e4b704170b9b 100644 --- a/src/librustc_error_codes/error_codes.rs +++ b/src/librustc_error_codes/error_codes.rs @@ -347,6 +347,7 @@ E0622: include_str!("./error_codes/E0622.md"), E0623: include_str!("./error_codes/E0623.md"), E0624: include_str!("./error_codes/E0624.md"), E0626: include_str!("./error_codes/E0626.md"), +E0631: include_str!("./error_codes/E0631.md"), E0633: include_str!("./error_codes/E0633.md"), E0635: include_str!("./error_codes/E0635.md"), E0636: include_str!("./error_codes/E0636.md"), @@ -580,7 +581,6 @@ E0745: include_str!("./error_codes/E0745.md"), // rustc_const_unstable attribute must be paired with stable/unstable // attribute E0630, - E0631, // type mismatch in closure arguments E0632, // cannot provide explicit generic arguments when `impl Trait` is // used in argument position E0634, // type has conflicting packed representaton hints diff --git a/src/librustc_error_codes/error_codes/E0631.md b/src/librustc_error_codes/error_codes/E0631.md new file mode 100644 index 0000000000000..ad419f82250cc --- /dev/null +++ b/src/librustc_error_codes/error_codes/E0631.md @@ -0,0 +1,29 @@ +This error indicates a type mismatch in closure arguments. + +Erroneous code example: + +```compile_fail,E0631 +fn test_strings(string_vec: Vec) -> Vec { + string_vec + .iter() + .map(|arg: &i32| arg.eq("Test String")) + .collect() +} +``` + +The closure passed to `map` expects a `&String` argument, since `some_vec` +has the type `Vec`. +However, the closure argument is annotated as an `&i32`, which does not match +the type of the iterable. + +This can be resolved by changing the type annotation or removing it entirely +if it can be inferred. + +``` +fn test_strings(string_vec: Vec) -> Vec { + string_vec + .iter() + .map(|arg| arg.eq("Test String")) + .collect() +} +``` diff --git a/src/test/ui/anonymous-higher-ranked-lifetime.stderr b/src/test/ui/anonymous-higher-ranked-lifetime.stderr index 9be44c7f44807..c6d9a61bdd95a 100644 --- a/src/test/ui/anonymous-higher-ranked-lifetime.stderr +++ b/src/test/ui/anonymous-higher-ranked-lifetime.stderr @@ -121,3 +121,4 @@ LL | fn h2(_: F) where F: for<'t0> Fn(&(), Box, &'t0 (), fn(&(), error: aborting due to 11 previous errors +For more information about this error, try `rustc --explain E0631`. diff --git a/src/test/ui/closure-expected-type/expect-fn-supply-fn.stderr b/src/test/ui/closure-expected-type/expect-fn-supply-fn.stderr index a15444207f5cd..0033395846815 100644 --- a/src/test/ui/closure-expected-type/expect-fn-supply-fn.stderr +++ b/src/test/ui/closure-expected-type/expect-fn-supply-fn.stderr @@ -77,4 +77,5 @@ LL | with_closure_expecting_fn_with_bound_region(|x: Foo<'_>, y| { error: aborting due to 5 previous errors -For more information about this error, try `rustc --explain E0308`. +Some errors have detailed explanations: E0308, E0631. +For more information about an error, try `rustc --explain E0308`. diff --git a/src/test/ui/closure-expected-type/expect-infer-var-appearing-twice.stderr b/src/test/ui/closure-expected-type/expect-infer-var-appearing-twice.stderr index 9fbe95a9c3945..1c6564ee426e5 100644 --- a/src/test/ui/closure-expected-type/expect-infer-var-appearing-twice.stderr +++ b/src/test/ui/closure-expected-type/expect-infer-var-appearing-twice.stderr @@ -13,3 +13,4 @@ LL | with_closure(|x: u32, y: i32| { error: aborting due to previous error +For more information about this error, try `rustc --explain E0631`. diff --git a/src/test/ui/closures/issue-41366.stderr b/src/test/ui/closures/issue-41366.stderr index 91d26efbc4f35..2f2871e9f0e90 100644 --- a/src/test/ui/closures/issue-41366.stderr +++ b/src/test/ui/closures/issue-41366.stderr @@ -19,4 +19,5 @@ LL | (&|_|()) as &dyn for<'x> Fn(>::V); error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0271`. +Some errors have detailed explanations: E0271, E0631. +For more information about an error, try `rustc --explain E0271`. diff --git a/src/test/ui/issues/issue-43623.stderr b/src/test/ui/issues/issue-43623.stderr index 2c57b8585d924..d90eb53f9006f 100644 --- a/src/test/ui/issues/issue-43623.stderr +++ b/src/test/ui/issues/issue-43623.stderr @@ -25,4 +25,5 @@ LL | break_me::; error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0271`. +Some errors have detailed explanations: E0271, E0631. +For more information about an error, try `rustc --explain E0271`. diff --git a/src/test/ui/issues/issue-60283.stderr b/src/test/ui/issues/issue-60283.stderr index 69c1d85e4e12d..d13dcd54a479a 100644 --- a/src/test/ui/issues/issue-60283.stderr +++ b/src/test/ui/issues/issue-60283.stderr @@ -27,4 +27,5 @@ LL | foo((), drop) error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0271`. +Some errors have detailed explanations: E0271, E0631. +For more information about an error, try `rustc --explain E0271`. diff --git a/src/test/ui/mismatched_types/E0631.stderr b/src/test/ui/mismatched_types/E0631.stderr index 88c1efdbb90f4..06f5c058f81f5 100644 --- a/src/test/ui/mismatched_types/E0631.stderr +++ b/src/test/ui/mismatched_types/E0631.stderr @@ -46,3 +46,4 @@ LL | bar(f); error: aborting due to 4 previous errors +For more information about this error, try `rustc --explain E0631`. diff --git a/src/test/ui/mismatched_types/closure-arg-type-mismatch.stderr b/src/test/ui/mismatched_types/closure-arg-type-mismatch.stderr index 85cad61210ebf..ed5028247124f 100644 --- a/src/test/ui/mismatched_types/closure-arg-type-mismatch.stderr +++ b/src/test/ui/mismatched_types/closure-arg-type-mismatch.stderr @@ -45,4 +45,5 @@ LL | baz(f); error: aborting due to 5 previous errors -For more information about this error, try `rustc --explain E0271`. +Some errors have detailed explanations: E0271, E0631. +For more information about an error, try `rustc --explain E0271`. diff --git a/src/test/ui/mismatched_types/closure-mismatch.stderr b/src/test/ui/mismatched_types/closure-mismatch.stderr index fd2b9f3c66b04..f3874c0907be0 100644 --- a/src/test/ui/mismatched_types/closure-mismatch.stderr +++ b/src/test/ui/mismatched_types/closure-mismatch.stderr @@ -24,4 +24,5 @@ LL | baz(|_| ()); error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0271`. +Some errors have detailed explanations: E0271, E0631. +For more information about an error, try `rustc --explain E0271`. diff --git a/src/test/ui/mismatched_types/fn-variance-1.stderr b/src/test/ui/mismatched_types/fn-variance-1.stderr index 1a82dd53edc70..88c92661994cb 100644 --- a/src/test/ui/mismatched_types/fn-variance-1.stderr +++ b/src/test/ui/mismatched_types/fn-variance-1.stderr @@ -24,3 +24,4 @@ LL | apply(&mut 3, takes_imm); error: aborting due to 2 previous errors +For more information about this error, try `rustc --explain E0631`. diff --git a/src/test/ui/mismatched_types/issue-36053-2.stderr b/src/test/ui/mismatched_types/issue-36053-2.stderr index 72f3220cc1aba..da018aa89482c 100644 --- a/src/test/ui/mismatched_types/issue-36053-2.stderr +++ b/src/test/ui/mismatched_types/issue-36053-2.stderr @@ -18,4 +18,5 @@ LL | once::<&str>("str").fuse().filter(|a: &str| true).count(); error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0599`. +Some errors have detailed explanations: E0599, E0631. +For more information about an error, try `rustc --explain E0599`. diff --git a/src/test/ui/mismatched_types/unboxed-closures-vtable-mismatch.stderr b/src/test/ui/mismatched_types/unboxed-closures-vtable-mismatch.stderr index 2daf4781c7e6f..3c999f200d9c7 100644 --- a/src/test/ui/mismatched_types/unboxed-closures-vtable-mismatch.stderr +++ b/src/test/ui/mismatched_types/unboxed-closures-vtable-mismatch.stderr @@ -12,3 +12,4 @@ LL | let z = call_it(3, f); error: aborting due to previous error +For more information about this error, try `rustc --explain E0631`. From 54b206034fe50b2234ab8ddb15214f723fe8d951 Mon Sep 17 00:00:00 2001 From: Parth Sane Date: Mon, 2 Dec 2019 17:52:45 +0530 Subject: [PATCH 5/8] Change linker for x86_64-fortanix-unknown-sgx to rust-lld For SGX, the relocation using the relocation table is done by the code in rust/src/libstd/sys/sgx/abi/reloc.rs and this code should not require relocation. Setting RelaxELFRelocations flag if allows this to happen, hence adding a Target Option for it. --- src/librustc_codegen_llvm/back/write.rs | 3 +- src/librustc_codegen_llvm/llvm/ffi.rs | 3 +- src/librustc_codegen_ssa/back/linker.rs | 3 +- src/librustc_target/spec/mod.rs | 6 +++ .../spec/x86_64_fortanix_unknown_sgx.rs | 52 +++++++++---------- src/rustllvm/PassWrapper.cpp | 4 +- 6 files changed, 40 insertions(+), 31 deletions(-) diff --git a/src/librustc_codegen_llvm/back/write.rs b/src/librustc_codegen_llvm/back/write.rs index 07ac76cec990b..48bbc13072387 100644 --- a/src/librustc_codegen_llvm/back/write.rs +++ b/src/librustc_codegen_llvm/back/write.rs @@ -167,7 +167,7 @@ pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_fea let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes; let asm_comments = sess.asm_comments(); - + let relax_elf_relocations = sess.target.target.options.relax_elf_relocations; Arc::new(move || { let tm = unsafe { llvm::LLVMRustCreateTargetMachine( @@ -183,6 +183,7 @@ pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_fea singlethread, asm_comments, emit_stack_size_section, + relax_elf_relocations, ) }; diff --git a/src/librustc_codegen_llvm/llvm/ffi.rs b/src/librustc_codegen_llvm/llvm/ffi.rs index a49e863fa2185..fd31e65c9d320 100644 --- a/src/librustc_codegen_llvm/llvm/ffi.rs +++ b/src/librustc_codegen_llvm/llvm/ffi.rs @@ -1702,7 +1702,8 @@ extern "C" { TrapUnreachable: bool, Singlethread: bool, AsmComments: bool, - EmitStackSizeSection: bool) + EmitStackSizeSection: bool, + RelaxELFRelocations: bool) -> Option<&'static mut TargetMachine>; pub fn LLVMRustDisposeTargetMachine(T: &'static mut TargetMachine); pub fn LLVMRustAddBuilderLibraryInfo(PMB: &'a PassManagerBuilder, diff --git a/src/librustc_codegen_ssa/back/linker.rs b/src/librustc_codegen_ssa/back/linker.rs index 999cc40658503..4278852123bea 100644 --- a/src/librustc_codegen_ssa/back/linker.rs +++ b/src/librustc_codegen_ssa/back/linker.rs @@ -398,7 +398,8 @@ impl<'a> Linker for GccLinker<'a> { fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType) { // Symbol visibility in object files typically takes care of this. - if crate_type == CrateType::Executable { + if crate_type == CrateType::Executable && + self.sess.target.target.options.override_export_symbols.is_none() { return; } diff --git a/src/librustc_target/spec/mod.rs b/src/librustc_target/spec/mod.rs index 29076254584c0..693cf75e8fd64 100644 --- a/src/librustc_target/spec/mod.rs +++ b/src/librustc_target/spec/mod.rs @@ -803,6 +803,9 @@ pub struct TargetOptions { /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers pub llvm_abiname: String, + + /// Whether or not RelaxElfRelocation flag will be passed to the linker + pub relax_elf_relocations: bool, } impl Default for TargetOptions { @@ -890,6 +893,7 @@ impl Default for TargetOptions { merge_functions: MergeFunctions::Aliases, target_mcount: "mcount".to_string(), llvm_abiname: "".to_string(), + relax_elf_relocations: false, } } } @@ -1207,6 +1211,7 @@ impl Target { key!(merge_functions, MergeFunctions)?; key!(target_mcount); key!(llvm_abiname); + key!(relax_elf_relocations, bool); if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) { for name in array.iter().filter_map(|abi| abi.as_string()) { @@ -1426,6 +1431,7 @@ impl ToJson for Target { target_option_val!(merge_functions); target_option_val!(target_mcount); target_option_val!(llvm_abiname); + target_option_val!(relax_elf_relocations); if default.abi_blacklist != self.options.abi_blacklist { d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter() diff --git a/src/librustc_target/spec/x86_64_fortanix_unknown_sgx.rs b/src/librustc_target/spec/x86_64_fortanix_unknown_sgx.rs index 7c24c88f7aee0..dbcd77bc753e8 100644 --- a/src/librustc_target/spec/x86_64_fortanix_unknown_sgx.rs +++ b/src/librustc_target/spec/x86_64_fortanix_unknown_sgx.rs @@ -1,35 +1,31 @@ use std::iter; -use super::{LinkerFlavor, PanicStrategy, Target, TargetOptions}; +use super::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions}; pub fn target() -> Result { const PRE_LINK_ARGS: &[&str] = &[ - "-Wl,--as-needed", - "-Wl,-z,noexecstack", - "-m64", - "-fuse-ld=gold", - "-nostdlib", - "-shared", - "-Wl,-e,sgx_entry", - "-Wl,-Bstatic", - "-Wl,--gc-sections", - "-Wl,-z,text", - "-Wl,-z,norelro", - "-Wl,--rosegment", - "-Wl,--no-undefined", - "-Wl,--error-unresolved-symbols", - "-Wl,--no-undefined-version", - "-Wl,-Bsymbolic", - "-Wl,--export-dynamic", + "--as-needed", + "--eh-frame-hdr", + "-z" , "noexecstack", + "-e","sgx_entry", + "-Bstatic", + "--gc-sections", + "-z","text", + "-z","norelro", + "--no-undefined", + "--error-unresolved-symbols", + "--no-undefined-version", + "-Bsymbolic", + "--export-dynamic", // The following symbols are needed by libunwind, which is linked after // libstd. Make sure they're included in the link. - "-Wl,-u,__rust_abort", - "-Wl,-u,__rust_c_alloc", - "-Wl,-u,__rust_c_dealloc", - "-Wl,-u,__rust_print_err", - "-Wl,-u,__rust_rwlock_rdlock", - "-Wl,-u,__rust_rwlock_unlock", - "-Wl,-u,__rust_rwlock_wrlock", + "-u","__rust_abort", + "-u","__rust_c_alloc", + "-u","__rust_c_dealloc", + "-u","__rust_print_err", + "-u","__rust_rwlock_rdlock", + "-u","__rust_rwlock_unlock", + "-u","__rust_rwlock_wrlock" ]; const EXPORT_SYMBOLS: &[&str] = &[ @@ -50,18 +46,20 @@ pub fn target() -> Result { dynamic_linking: false, executables: true, linker_is_gnu: true, + linker: Some("rust-lld".to_owned()), max_atomic_width: Some(64), panic_strategy: PanicStrategy::Unwind, cpu: "x86-64".into(), features: "+rdrnd,+rdseed".into(), position_independent_executables: true, pre_link_args: iter::once(( - LinkerFlavor::Gcc, + LinkerFlavor::Lld(LldFlavor::Ld), PRE_LINK_ARGS.iter().cloned().map(String::from).collect(), )) .collect(), post_link_objects: vec!["libunwind.a".into()], override_export_symbols: Some(EXPORT_SYMBOLS.iter().cloned().map(String::from).collect()), + relax_elf_relocations: true, ..Default::default() }; Ok(Target { @@ -74,7 +72,7 @@ pub fn target() -> Result { target_vendor: "fortanix".into(), data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".into(), arch: "x86_64".into(), - linker_flavor: LinkerFlavor::Gcc, + linker_flavor: LinkerFlavor::Lld(LldFlavor::Ld), options: opts, }) } diff --git a/src/rustllvm/PassWrapper.cpp b/src/rustllvm/PassWrapper.cpp index a116ed282acd1..b7f8e83590943 100644 --- a/src/rustllvm/PassWrapper.cpp +++ b/src/rustllvm/PassWrapper.cpp @@ -393,7 +393,8 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( bool TrapUnreachable, bool Singlethread, bool AsmComments, - bool EmitStackSizeSection) { + bool EmitStackSizeSection, + bool RelaxELFRelocations) { auto OptLevel = fromRust(RustOptLevel); auto RM = fromRust(RustReloc); @@ -418,6 +419,7 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( Options.MCOptions.AsmVerbose = AsmComments; Options.MCOptions.PreserveAsmComments = AsmComments; Options.MCOptions.ABIName = ABIStr; + Options.RelaxELFRelocations = RelaxELFRelocations; if (TrapUnreachable) { // Tell LLVM to codegen `unreachable` into an explicit trap instruction. From 0be80f2909e0b5246c884db241a602a2f6d90488 Mon Sep 17 00:00:00 2001 From: Wesley Wiser Date: Thu, 28 Nov 2019 21:36:06 -0500 Subject: [PATCH 6/8] [const-prop] Fix ICE calculating enum discriminant Fixes #66787 --- src/librustc_mir/interpret/place.rs | 23 +++++++++-------- src/test/ui/consts/issue-66787.rs | 39 +++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 10 deletions(-) create mode 100644 src/test/ui/consts/issue-66787.rs diff --git a/src/librustc_mir/interpret/place.rs b/src/librustc_mir/interpret/place.rs index 5b263f7680131..3a204c350b4ab 100644 --- a/src/librustc_mir/interpret/place.rs +++ b/src/librustc_mir/interpret/place.rs @@ -1038,13 +1038,16 @@ where variant_index: VariantIdx, dest: PlaceTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx> { - let variant_scalar = Scalar::from_u32(variant_index.as_u32()).into(); + + // Layout computation excludes uninhabited variants from consideration + // therefore there's no way to represent those variants in the given layout. + if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() { + throw_ub!(Unreachable); + } match dest.layout.variants { layout::Variants::Single { index } => { - if index != variant_index { - throw_ub!(InvalidDiscriminant(variant_scalar)); - } + assert_eq!(index, variant_index); } layout::Variants::Multiple { discr_kind: layout::DiscriminantKind::Tag, @@ -1052,9 +1055,9 @@ where discr_index, .. } => { - if !dest.layout.ty.variant_range(*self.tcx).unwrap().contains(&variant_index) { - throw_ub!(InvalidDiscriminant(variant_scalar)); - } + // No need to validate that the discriminant here because the + // `TyLayout::for_variant()` call earlier already checks the variant is valid. + let discr_val = dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val; @@ -1077,9 +1080,9 @@ where discr_index, .. } => { - if !variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len() { - throw_ub!(InvalidDiscriminant(variant_scalar)); - } + // No need to validate that the discriminant here because the + // `TyLayout::for_variant()` call earlier already checks the variant is valid. + if variant_index != dataful_variant { let variants_start = niche_variants.start().as_u32(); let variant_index_relative = variant_index.as_u32() diff --git a/src/test/ui/consts/issue-66787.rs b/src/test/ui/consts/issue-66787.rs new file mode 100644 index 0000000000000..612b795eb5cd0 --- /dev/null +++ b/src/test/ui/consts/issue-66787.rs @@ -0,0 +1,39 @@ +// build-pass +// compile-flags: --crate-type lib + +// Regression test for ICE which occurred when const propagating an enum with three variants +// one of which is uninhabited. + +pub enum ApiError {} +#[allow(dead_code)] +pub struct TokioError { + b: bool, +} +pub enum Error { + Api { + source: ApiError, + }, + Ethereum, + Tokio { + source: TokioError, + }, +} +struct Api; +impl IntoError for Api +{ + type Source = ApiError; + fn into_error(self, error: Self::Source) -> Error { + Error::Api { + source: (|v| v)(error), + } + } +} + +pub trait IntoError +{ + /// The underlying error + type Source; + + /// Combine the information to produce the error + fn into_error(self, source: Self::Source) -> E; +} From 26a1ba85b890cdf7bbb7066c3a18aab84aef171f Mon Sep 17 00:00:00 2001 From: Reese Williams Date: Tue, 3 Dec 2019 07:51:11 -0500 Subject: [PATCH 7/8] Use simpler code example for E0631 long error. --- src/librustc_error_codes/error_codes/E0631.md | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/src/librustc_error_codes/error_codes/E0631.md b/src/librustc_error_codes/error_codes/E0631.md index ad419f82250cc..6188d5f61a7f9 100644 --- a/src/librustc_error_codes/error_codes/E0631.md +++ b/src/librustc_error_codes/error_codes/E0631.md @@ -3,27 +3,25 @@ This error indicates a type mismatch in closure arguments. Erroneous code example: ```compile_fail,E0631 -fn test_strings(string_vec: Vec) -> Vec { - string_vec - .iter() - .map(|arg: &i32| arg.eq("Test String")) - .collect() +fn foo(f: F) { +} + +fn main() { + foo(|x: &str| {}); } ``` -The closure passed to `map` expects a `&String` argument, since `some_vec` -has the type `Vec`. -However, the closure argument is annotated as an `&i32`, which does not match -the type of the iterable. +The error occurs because `foo` accepts a closure that takes an `i32` argument, +but in `main`, it is passed a closure with a `&str` argument. This can be resolved by changing the type annotation or removing it entirely if it can be inferred. ``` -fn test_strings(string_vec: Vec) -> Vec { - string_vec - .iter() - .map(|arg| arg.eq("Test String")) - .collect() +fn foo(f: F) { +} + +fn main() { + foo(|x: i32| {}); } ``` From f3fb1c5e95b9fef29df00f0924a27790b03c524b Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 25 Nov 2019 09:27:25 -0800 Subject: [PATCH 8/8] Update the `wasi` crate for `wasm32-wasi` This commit updates the `wasi` crate used by the standard library which is used to implement most of the functionality of libstd on the `wasm32-wasi` target. This update comes with a brand new crate structure in the `wasi` crate which caused quite a few changes for the wasi target here, but it also comes with a significant change to where the functionality is coming from. The WASI specification is organized into "snapshots" and a new snapshot happened recently, so the WASI APIs themselves have changed since the previous revision. This had only minor impact on the public facing surface area of libstd, only changing on `u32` to a `u64` in an unstable API. The actual source for all of these types and such, however, is now coming from the `wasi_preview_snapshot1` module instead of the `wasi_unstable` module like before. This means that any implementors generating binaries will need to ensure that their embedding environment handles the `wasi_preview_snapshot1` module. --- Cargo.lock | 10 +- src/libstd/Cargo.toml | 2 +- src/libstd/sys/wasi/args.rs | 39 ++++--- src/libstd/sys/wasi/ext/fs.rs | 117 +++++++++---------- src/libstd/sys/wasi/ext/io.rs | 8 +- src/libstd/sys/wasi/fd.rs | 122 +++++++++----------- src/libstd/sys/wasi/fs.rs | 211 +++++++++++++++------------------- src/libstd/sys/wasi/io.rs | 15 +-- src/libstd/sys/wasi/mod.rs | 44 +++---- src/libstd/sys/wasi/stdio.rs | 25 ++-- src/libstd/sys/wasi/thread.rs | 52 ++++----- src/libstd/sys/wasi/time.rs | 23 ++-- 12 files changed, 304 insertions(+), 364 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8fd0285a7e62a..5a56bf03f4da2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1294,7 +1294,7 @@ checksum = "473a1265acc8ff1e808cd0a1af8cee3c2ee5200916058a2ca113c29f2d903571" dependencies = [ "cfg-if", "libc", - "wasi", + "wasi 0.7.0", ] [[package]] @@ -4301,7 +4301,7 @@ dependencies = [ "rustc_msan", "rustc_tsan", "unwind", - "wasi", + "wasi 0.9.0+wasi-snapshot-preview1", ] [[package]] @@ -5172,6 +5172,12 @@ name = "wasi" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b89c3ce4ce14bdc6fb6beaf9ec7928ca331de5df7e5ea278375642a2f478570d" + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" dependencies = [ "compiler_builtins", "rustc-std-workspace-alloc", diff --git a/src/libstd/Cargo.toml b/src/libstd/Cargo.toml index c55911a33f524..a22e162bbff48 100644 --- a/src/libstd/Cargo.toml +++ b/src/libstd/Cargo.toml @@ -54,7 +54,7 @@ fortanix-sgx-abi = { version = "0.3.2", features = ['rustc-dep-of-std'] } hermit-abi = { version = "0.1", features = ['rustc-dep-of-std'] } [target.wasm32-wasi.dependencies] -wasi = { version = "0.7.0", features = ['rustc-dep-of-std', 'alloc'] } +wasi = { version = "0.9.0", features = ['rustc-dep-of-std'], default-features = false } [features] default = ["std_detect_file_io", "std_detect_dlsym_getauxval"] diff --git a/src/libstd/sys/wasi/args.rs b/src/libstd/sys/wasi/args.rs index 3280c4990dc66..3db36f5e13251 100644 --- a/src/libstd/sys/wasi/args.rs +++ b/src/libstd/sys/wasi/args.rs @@ -1,15 +1,11 @@ -use crate::ffi::OsString; +use crate::ffi::{CStr, OsStr, OsString}; use crate::marker::PhantomData; -use crate::os::wasi::ffi::OsStringExt; +use crate::os::wasi::ffi::OsStrExt; use crate::vec; -use ::wasi::wasi_unstable as wasi; +pub unsafe fn init(_argc: isize, _argv: *const *const u8) {} -pub unsafe fn init(_argc: isize, _argv: *const *const u8) { -} - -pub unsafe fn cleanup() { -} +pub unsafe fn cleanup() {} pub struct Args { iter: vec::IntoIter, @@ -18,17 +14,24 @@ pub struct Args { /// Returns the command line arguments pub fn args() -> Args { - let buf = wasi::args_sizes_get().and_then(|args_sizes| { - let mut buf = Vec::with_capacity(args_sizes.get_count()); - wasi::args_get(args_sizes, |arg| { - let arg = OsString::from_vec(arg.to_vec()); - buf.push(arg); - })?; - Ok(buf) - }).unwrap_or(vec![]); Args { - iter: buf.into_iter(), - _dont_send_or_sync_me: PhantomData + iter: maybe_args().unwrap_or(Vec::new()).into_iter(), + _dont_send_or_sync_me: PhantomData, + } +} + +fn maybe_args() -> Option> { + unsafe { + let (argc, buf_size) = wasi::args_sizes_get().ok()?; + let mut argv = Vec::with_capacity(argc); + let mut buf = Vec::with_capacity(buf_size); + wasi::args_get(argv.as_mut_ptr(), buf.as_mut_ptr()).ok()?; + let mut ret = Vec::with_capacity(argc); + for ptr in argv { + let s = CStr::from_ptr(ptr.cast()); + ret.push(OsStr::from_bytes(s.to_bytes()).to_owned()); + } + Some(ret) } } diff --git a/src/libstd/sys/wasi/ext/fs.rs b/src/libstd/sys/wasi/ext/fs.rs index 9fa4abfd171b5..92d0e60c07e83 100644 --- a/src/libstd/sys/wasi/ext/fs.rs +++ b/src/libstd/sys/wasi/ext/fs.rs @@ -4,12 +4,10 @@ use crate::fs::{self, File, Metadata, OpenOptions}; use crate::io::{self, IoSlice, IoSliceMut}; -use crate::os::wasi::ffi::OsStrExt; use crate::path::{Path, PathBuf}; +use crate::sys::fs::osstr2str; use crate::sys_common::{AsInner, AsInnerMut, FromInner}; -use ::wasi::wasi_unstable as wasi; - /// WASI-specific extensions to [`File`]. /// /// [`File`]: ../../../../std/fs/struct.File.html @@ -49,62 +47,62 @@ pub trait FileExt { /// Returns the current position within the file. /// - /// This corresponds to the `__wasi_fd_tell` syscall and is similar to + /// This corresponds to the `fd_tell` syscall and is similar to /// `seek` where you offset 0 bytes from the current position. fn tell(&self) -> io::Result; /// Adjust the flags associated with this file. /// - /// This corresponds to the `__wasi_fd_fdstat_set_flags` syscall. + /// This corresponds to the `fd_fdstat_set_flags` syscall. fn fdstat_set_flags(&self, flags: u16) -> io::Result<()>; /// Adjust the rights associated with this file. /// - /// This corresponds to the `__wasi_fd_fdstat_set_rights` syscall. + /// This corresponds to the `fd_fdstat_set_rights` syscall. fn fdstat_set_rights(&self, rights: u64, inheriting: u64) -> io::Result<()>; /// Provide file advisory information on a file descriptor. /// - /// This corresponds to the `__wasi_fd_advise` syscall. + /// This corresponds to the `fd_advise` syscall. fn advise(&self, offset: u64, len: u64, advice: u8) -> io::Result<()>; /// Force the allocation of space in a file. /// - /// This corresponds to the `__wasi_fd_allocate` syscall. + /// This corresponds to the `fd_allocate` syscall. fn allocate(&self, offset: u64, len: u64) -> io::Result<()>; /// Create a directory. /// - /// This corresponds to the `__wasi_path_create_directory` syscall. + /// This corresponds to the `path_create_directory` syscall. fn create_directory>(&self, dir: P) -> io::Result<()>; /// Read the contents of a symbolic link. /// - /// This corresponds to the `__wasi_path_readlink` syscall. + /// This corresponds to the `path_readlink` syscall. fn read_link>(&self, path: P) -> io::Result; /// Return the attributes of a file or directory. /// - /// This corresponds to the `__wasi_path_filestat_get` syscall. + /// This corresponds to the `path_filestat_get` syscall. fn metadata_at>(&self, lookup_flags: u32, path: P) -> io::Result; /// Unlink a file. /// - /// This corresponds to the `__wasi_path_unlink_file` syscall. + /// This corresponds to the `path_unlink_file` syscall. fn remove_file>(&self, path: P) -> io::Result<()>; /// Remove a directory. /// - /// This corresponds to the `__wasi_path_remove_directory` syscall. + /// This corresponds to the `path_remove_directory` syscall. fn remove_directory>(&self, path: P) -> io::Result<()>; } -// FIXME: bind __wasi_fd_fdstat_get - need to define a custom return type -// FIXME: bind __wasi_fd_readdir - can't return `ReadDir` since we only have entry name -// FIXME: bind __wasi_fd_filestat_set_times maybe? - on crates.io for unix -// FIXME: bind __wasi_path_filestat_set_times maybe? - on crates.io for unix -// FIXME: bind __wasi_poll_oneoff maybe? - probably should wait for I/O to settle -// FIXME: bind __wasi_random_get maybe? - on crates.io for unix +// FIXME: bind fd_fdstat_get - need to define a custom return type +// FIXME: bind fd_readdir - can't return `ReadDir` since we only have entry name +// FIXME: bind fd_filestat_set_times maybe? - on crates.io for unix +// FIXME: bind path_filestat_set_times maybe? - on crates.io for unix +// FIXME: bind poll_oneoff maybe? - probably should wait for I/O to settle +// FIXME: bind random_get maybe? - on crates.io for unix impl FileExt for fs::File { fn read_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result { @@ -136,9 +134,7 @@ impl FileExt for fs::File { } fn create_directory>(&self, dir: P) -> io::Result<()> { - self.as_inner() - .fd() - .create_directory(dir.as_ref().as_os_str().as_bytes()) + self.as_inner().fd().create_directory(osstr2str(dir.as_ref().as_ref())?) } fn read_link>(&self, path: P) -> io::Result { @@ -151,15 +147,11 @@ impl FileExt for fs::File { } fn remove_file>(&self, path: P) -> io::Result<()> { - self.as_inner() - .fd() - .unlink_file(path.as_ref().as_os_str().as_bytes()) + self.as_inner().fd().unlink_file(osstr2str(path.as_ref().as_ref())?) } fn remove_directory>(&self, path: P) -> io::Result<()> { - self.as_inner() - .fd() - .remove_directory(path.as_ref().as_os_str().as_bytes()) + self.as_inner().fd().remove_directory(osstr2str(path.as_ref().as_ref())?) } } @@ -167,10 +159,10 @@ impl FileExt for fs::File { /// /// [`fs::OpenOptions`]: ../../../../std/fs/struct.OpenOptions.html pub trait OpenOptionsExt { - /// Pass custom `dirflags` argument to `__wasi_path_open`. + /// Pass custom `dirflags` argument to `path_open`. /// /// This option configures the `dirflags` argument to the - /// `__wasi_path_open` syscall which `OpenOptions` will eventually call. The + /// `path_open` syscall which `OpenOptions` will eventually call. The /// `dirflags` argument configures how the file is looked up, currently /// primarily affecting whether symlinks are followed or not. /// @@ -188,31 +180,31 @@ pub trait OpenOptionsExt { fn directory(&mut self, dir: bool) -> &mut Self; /// Indicates whether `__WASI_FDFLAG_DSYNC` is passed in the `fs_flags` - /// field of `__wasi_path_open`. + /// field of `path_open`. /// /// This option is by default `false` fn dsync(&mut self, dsync: bool) -> &mut Self; /// Indicates whether `__WASI_FDFLAG_NONBLOCK` is passed in the `fs_flags` - /// field of `__wasi_path_open`. + /// field of `path_open`. /// /// This option is by default `false` fn nonblock(&mut self, nonblock: bool) -> &mut Self; /// Indicates whether `__WASI_FDFLAG_RSYNC` is passed in the `fs_flags` - /// field of `__wasi_path_open`. + /// field of `path_open`. /// /// This option is by default `false` fn rsync(&mut self, rsync: bool) -> &mut Self; /// Indicates whether `__WASI_FDFLAG_SYNC` is passed in the `fs_flags` - /// field of `__wasi_path_open`. + /// field of `path_open`. /// /// This option is by default `false` fn sync(&mut self, sync: bool) -> &mut Self; /// Indicates the value that should be passed in for the `fs_rights_base` - /// parameter of `__wasi_path_open`. + /// parameter of `path_open`. /// /// This option defaults based on the `read` and `write` configuration of /// this `OpenOptions` builder. If this method is called, however, the @@ -220,7 +212,7 @@ pub trait OpenOptionsExt { fn fs_rights_base(&mut self, rights: u64) -> &mut Self; /// Indicates the value that should be passed in for the - /// `fs_rights_inheriting` parameter of `__wasi_path_open`. + /// `fs_rights_inheriting` parameter of `path_open`. /// /// The default for this option is the same value as what will be passed /// for the `fs_rights_base` parameter but if this method is called then @@ -229,7 +221,7 @@ pub trait OpenOptionsExt { /// Open a file or directory. /// - /// This corresponds to the `__wasi_path_open` syscall. + /// This corresponds to the `path_open` syscall. fn open_at>(&self, file: &File, path: P) -> io::Result; } @@ -284,38 +276,38 @@ impl OpenOptionsExt for OpenOptions { /// /// [`fs::Metadata`]: ../../../../std/fs/struct.Metadata.html pub trait MetadataExt { - /// Returns the `st_dev` field of the internal `__wasi_filestat_t` + /// Returns the `st_dev` field of the internal `filestat_t` fn dev(&self) -> u64; - /// Returns the `st_ino` field of the internal `__wasi_filestat_t` + /// Returns the `st_ino` field of the internal `filestat_t` fn ino(&self) -> u64; - /// Returns the `st_nlink` field of the internal `__wasi_filestat_t` - fn nlink(&self) -> u32; - /// Returns the `st_atim` field of the internal `__wasi_filestat_t` + /// Returns the `st_nlink` field of the internal `filestat_t` + fn nlink(&self) -> u64; + /// Returns the `st_atim` field of the internal `filestat_t` fn atim(&self) -> u64; - /// Returns the `st_mtim` field of the internal `__wasi_filestat_t` + /// Returns the `st_mtim` field of the internal `filestat_t` fn mtim(&self) -> u64; - /// Returns the `st_ctim` field of the internal `__wasi_filestat_t` + /// Returns the `st_ctim` field of the internal `filestat_t` fn ctim(&self) -> u64; } impl MetadataExt for fs::Metadata { fn dev(&self) -> u64 { - self.as_inner().as_wasi().st_dev + self.as_inner().as_wasi().dev } fn ino(&self) -> u64 { - self.as_inner().as_wasi().st_ino + self.as_inner().as_wasi().ino } - fn nlink(&self) -> u32 { - self.as_inner().as_wasi().st_nlink + fn nlink(&self) -> u64 { + self.as_inner().as_wasi().nlink } fn atim(&self) -> u64 { - self.as_inner().as_wasi().st_atim + self.as_inner().as_wasi().atim } fn mtim(&self) -> u64 { - self.as_inner().as_wasi().st_mtim + self.as_inner().as_wasi().mtim } fn ctim(&self) -> u64 { - self.as_inner().as_wasi().st_ctim + self.as_inner().as_wasi().ctim } } @@ -355,7 +347,7 @@ impl FileTypeExt for fs::FileType { /// /// [`fs::DirEntry`]: ../../../../std/fs/struct.DirEntry.html pub trait DirEntryExt { - /// Returns the underlying `d_ino` field of the `__wasi_dirent_t` + /// Returns the underlying `d_ino` field of the `dirent_t` fn ino(&self) -> u64; } @@ -367,7 +359,7 @@ impl DirEntryExt for fs::DirEntry { /// Create a hard link. /// -/// This corresponds to the `__wasi_path_link` syscall. +/// This corresponds to the `path_link` syscall. pub fn link, U: AsRef>( old_fd: &File, old_flags: u32, @@ -377,15 +369,15 @@ pub fn link, U: AsRef>( ) -> io::Result<()> { old_fd.as_inner().fd().link( old_flags, - old_path.as_ref().as_os_str().as_bytes(), + osstr2str(old_path.as_ref().as_ref())?, new_fd.as_inner().fd(), - new_path.as_ref().as_os_str().as_bytes(), + osstr2str(new_path.as_ref().as_ref())?, ) } /// Rename a file or directory. /// -/// This corresponds to the `__wasi_path_rename` syscall. +/// This corresponds to the `path_rename` syscall. pub fn rename, U: AsRef>( old_fd: &File, old_path: P, @@ -393,22 +385,21 @@ pub fn rename, U: AsRef>( new_path: U, ) -> io::Result<()> { old_fd.as_inner().fd().rename( - old_path.as_ref().as_os_str().as_bytes(), + osstr2str(old_path.as_ref().as_ref())?, new_fd.as_inner().fd(), - new_path.as_ref().as_os_str().as_bytes(), + osstr2str(new_path.as_ref().as_ref())?, ) } /// Create a symbolic link. /// -/// This corresponds to the `__wasi_path_symlink` syscall. +/// This corresponds to the `path_symlink` syscall. pub fn symlink, U: AsRef>( old_path: P, fd: &File, new_path: U, ) -> io::Result<()> { - fd.as_inner().fd().symlink( - old_path.as_ref().as_os_str().as_bytes(), - new_path.as_ref().as_os_str().as_bytes(), - ) + fd.as_inner() + .fd() + .symlink(osstr2str(old_path.as_ref().as_ref())?, osstr2str(new_path.as_ref().as_ref())?) } diff --git a/src/libstd/sys/wasi/ext/io.rs b/src/libstd/sys/wasi/ext/io.rs index f1839df380112..f678b71a2b9f0 100644 --- a/src/libstd/sys/wasi/ext/io.rs +++ b/src/libstd/sys/wasi/ext/io.rs @@ -8,8 +8,6 @@ use crate::sys; use crate::net; use crate::sys_common::{AsInner, FromInner, IntoInner}; -use ::wasi::wasi_unstable as wasi; - /// Raw file descriptors. pub type RawFd = u32; @@ -127,18 +125,18 @@ impl IntoRawFd for fs::File { impl AsRawFd for io::Stdin { fn as_raw_fd(&self) -> RawFd { - wasi::STDIN_FD + sys::stdio::Stdin.as_raw_fd() } } impl AsRawFd for io::Stdout { fn as_raw_fd(&self) -> RawFd { - wasi::STDOUT_FD + sys::stdio::Stdout.as_raw_fd() } } impl AsRawFd for io::Stderr { fn as_raw_fd(&self) -> RawFd { - wasi::STDERR_FD + sys::stdio::Stderr.as_raw_fd() } } diff --git a/src/libstd/sys/wasi/fd.rs b/src/libstd/sys/wasi/fd.rs index 5b7a8678b66ea..00327c1743c3d 100644 --- a/src/libstd/sys/wasi/fd.rs +++ b/src/libstd/sys/wasi/fd.rs @@ -1,40 +1,31 @@ #![allow(dead_code)] +use super::err2io; use crate::io::{self, IoSlice, IoSliceMut, SeekFrom}; use crate::mem; use crate::net::Shutdown; -use super::err2io; -use ::wasi::wasi_unstable as wasi; #[derive(Debug)] pub struct WasiFd { fd: wasi::Fd, } -fn iovec<'a>(a: &'a mut [IoSliceMut<'_>]) -> &'a [wasi::IoVec] { - assert_eq!( - mem::size_of::>(), - mem::size_of::() - ); - assert_eq!( - mem::align_of::>(), - mem::align_of::() - ); +fn iovec<'a>(a: &'a mut [IoSliceMut<'_>]) -> &'a [wasi::Iovec] { + assert_eq!(mem::size_of::>(), mem::size_of::()); + assert_eq!(mem::align_of::>(), mem::align_of::()); /// SAFETY: `IoSliceMut` and `IoVec` have exactly the same memory layout - unsafe { mem::transmute(a) } + unsafe { + mem::transmute(a) + } } -fn ciovec<'a>(a: &'a [IoSlice<'_>]) -> &'a [wasi::CIoVec] { - assert_eq!( - mem::size_of::>(), - mem::size_of::() - ); - assert_eq!( - mem::align_of::>(), - mem::align_of::() - ); +fn ciovec<'a>(a: &'a [IoSlice<'_>]) -> &'a [wasi::Ciovec] { + assert_eq!(mem::size_of::>(), mem::size_of::()); + assert_eq!(mem::align_of::>(), mem::align_of::()); /// SAFETY: `IoSlice` and `CIoVec` have exactly the same memory layout - unsafe { mem::transmute(a) } + unsafe { + mem::transmute(a) + } } impl WasiFd { @@ -87,7 +78,7 @@ impl WasiFd { // FIXME: __wasi_fd_fdstat_get - pub fn set_flags(&self, flags: wasi::FdFlags) -> io::Result<()> { + pub fn set_flags(&self, flags: wasi::Fdflags) -> io::Result<()> { unsafe { wasi::fd_fdstat_set_flags(self.fd, flags).map_err(err2io) } } @@ -107,31 +98,30 @@ impl WasiFd { unsafe { wasi::fd_allocate(self.fd, offset, len).map_err(err2io) } } - pub fn create_directory(&self, path: &[u8]) -> io::Result<()> { + pub fn create_directory(&self, path: &str) -> io::Result<()> { unsafe { wasi::path_create_directory(self.fd, path).map_err(err2io) } } pub fn link( &self, - old_flags: wasi::LookupFlags, - old_path: &[u8], + old_flags: wasi::Lookupflags, + old_path: &str, new_fd: &WasiFd, - new_path: &[u8], + new_path: &str, ) -> io::Result<()> { unsafe { - wasi::path_link(self.fd, old_flags, old_path, new_fd.fd, new_path) - .map_err(err2io) + wasi::path_link(self.fd, old_flags, old_path, new_fd.fd, new_path).map_err(err2io) } } pub fn open( &self, - dirflags: wasi::LookupFlags, - path: &[u8], - oflags: wasi::OFlags, + dirflags: wasi::Lookupflags, + path: &str, + oflags: wasi::Oflags, fs_rights_base: wasi::Rights, fs_rights_inheriting: wasi::Rights, - fs_flags: wasi::FdFlags, + fs_flags: wasi::Fdflags, ) -> io::Result { unsafe { wasi::path_open( @@ -142,25 +132,25 @@ impl WasiFd { fs_rights_base, fs_rights_inheriting, fs_flags, - ).map(|fd| WasiFd::from_raw(fd)).map_err(err2io) + ) + .map(|fd| WasiFd::from_raw(fd)) + .map_err(err2io) } } - pub fn readdir(&self, buf: &mut [u8], cookie: wasi::DirCookie) -> io::Result { - unsafe { wasi::fd_readdir(self.fd, buf, cookie).map_err(err2io) } + pub fn readdir(&self, buf: &mut [u8], cookie: wasi::Dircookie) -> io::Result { + unsafe { wasi::fd_readdir(self.fd, buf.as_mut_ptr(), buf.len(), cookie).map_err(err2io) } } - pub fn readlink(&self, path: &[u8], buf: &mut [u8]) -> io::Result { - unsafe { wasi::path_readlink(self.fd, path, buf).map_err(err2io) } + pub fn readlink(&self, path: &str, buf: &mut [u8]) -> io::Result { + unsafe { wasi::path_readlink(self.fd, path, buf.as_mut_ptr(), buf.len()).map_err(err2io) } } - pub fn rename(&self, old_path: &[u8], new_fd: &WasiFd, new_path: &[u8]) -> io::Result<()> { - unsafe { - wasi::path_rename(self.fd, old_path, new_fd.fd, new_path).map_err(err2io) - } + pub fn rename(&self, old_path: &str, new_fd: &WasiFd, new_path: &str) -> io::Result<()> { + unsafe { wasi::path_rename(self.fd, old_path, new_fd.fd, new_path).map_err(err2io) } } - pub fn filestat_get(&self) -> io::Result { + pub fn filestat_get(&self) -> io::Result { unsafe { wasi::fd_filestat_get(self.fd).map_err(err2io) } } @@ -168,11 +158,9 @@ impl WasiFd { &self, atim: wasi::Timestamp, mtim: wasi::Timestamp, - fstflags: wasi::FstFlags, + fstflags: wasi::Fstflags, ) -> io::Result<()> { - unsafe { - wasi::fd_filestat_set_times(self.fd, atim, mtim, fstflags).map_err(err2io) - } + unsafe { wasi::fd_filestat_set_times(self.fd, atim, mtim, fstflags).map_err(err2io) } } pub fn filestat_set_size(&self, size: u64) -> io::Result<()> { @@ -181,61 +169,55 @@ impl WasiFd { pub fn path_filestat_get( &self, - flags: wasi::LookupFlags, - path: &[u8], - ) -> io::Result { + flags: wasi::Lookupflags, + path: &str, + ) -> io::Result { unsafe { wasi::path_filestat_get(self.fd, flags, path).map_err(err2io) } } pub fn path_filestat_set_times( &self, - flags: wasi::LookupFlags, - path: &[u8], + flags: wasi::Lookupflags, + path: &str, atim: wasi::Timestamp, mtim: wasi::Timestamp, - fstflags: wasi::FstFlags, + fstflags: wasi::Fstflags, ) -> io::Result<()> { unsafe { - wasi::path_filestat_set_times( - self.fd, - flags, - path, - atim, - mtim, - fstflags, - ).map_err(err2io) + wasi::path_filestat_set_times(self.fd, flags, path, atim, mtim, fstflags) + .map_err(err2io) } } - pub fn symlink(&self, old_path: &[u8], new_path: &[u8]) -> io::Result<()> { + pub fn symlink(&self, old_path: &str, new_path: &str) -> io::Result<()> { unsafe { wasi::path_symlink(old_path, self.fd, new_path).map_err(err2io) } } - pub fn unlink_file(&self, path: &[u8]) -> io::Result<()> { + pub fn unlink_file(&self, path: &str) -> io::Result<()> { unsafe { wasi::path_unlink_file(self.fd, path).map_err(err2io) } } - pub fn remove_directory(&self, path: &[u8]) -> io::Result<()> { + pub fn remove_directory(&self, path: &str) -> io::Result<()> { unsafe { wasi::path_remove_directory(self.fd, path).map_err(err2io) } } pub fn sock_recv( &self, ri_data: &mut [IoSliceMut<'_>], - ri_flags: wasi::RiFlags, - ) -> io::Result<(usize, wasi::RoFlags)> { + ri_flags: wasi::Riflags, + ) -> io::Result<(usize, wasi::Roflags)> { unsafe { wasi::sock_recv(self.fd, iovec(ri_data), ri_flags).map_err(err2io) } } - pub fn sock_send(&self, si_data: &[IoSlice<'_>], si_flags: wasi::SiFlags) -> io::Result { + pub fn sock_send(&self, si_data: &[IoSlice<'_>], si_flags: wasi::Siflags) -> io::Result { unsafe { wasi::sock_send(self.fd, ciovec(si_data), si_flags).map_err(err2io) } } pub fn sock_shutdown(&self, how: Shutdown) -> io::Result<()> { let how = match how { - Shutdown::Read => wasi::SHUT_RD, - Shutdown::Write => wasi::SHUT_WR, - Shutdown::Both => wasi::SHUT_WR | wasi::SHUT_RD, + Shutdown::Read => wasi::SDFLAGS_RD, + Shutdown::Write => wasi::SDFLAGS_WR, + Shutdown::Both => wasi::SDFLAGS_WR | wasi::SDFLAGS_RD, }; unsafe { wasi::sock_shutdown(self.fd, how).map_err(err2io) } } diff --git a/src/libstd/sys/wasi/fs.rs b/src/libstd/sys/wasi/fs.rs index 4113f6a2e09c0..fad092e35c3e6 100644 --- a/src/libstd/sys/wasi/fs.rs +++ b/src/libstd/sys/wasi/fs.rs @@ -15,20 +15,18 @@ use crate::sys_common::FromInner; pub use crate::sys_common::fs::copy; pub use crate::sys_common::fs::remove_dir_all; -use ::wasi::wasi_unstable as wasi; - pub struct File { fd: WasiFd, } #[derive(Clone)] pub struct FileAttr { - meta: wasi::FileStat, + meta: wasi::Filestat, } pub struct ReadDir { inner: Arc, - cookie: Option, + cookie: Option, buf: Vec, offset: usize, cap: usize, @@ -49,9 +47,9 @@ pub struct DirEntry { pub struct OpenOptions { read: bool, write: bool, - dirflags: wasi::LookupFlags, - fdflags: wasi::FdFlags, - oflags: wasi::OFlags, + dirflags: wasi::Lookupflags, + fdflags: wasi::Fdflags, + oflags: wasi::Oflags, rights_base: Option, rights_inheriting: Option, } @@ -63,7 +61,7 @@ pub struct FilePermissions { #[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)] pub struct FileType { - bits: wasi::FileType, + bits: wasi::Filetype, } #[derive(Debug)] @@ -71,7 +69,7 @@ pub struct DirBuilder {} impl FileAttr { pub fn size(&self) -> u64 { - self.meta.st_size + self.meta.size } pub fn perm(&self) -> FilePermissions { @@ -80,24 +78,22 @@ impl FileAttr { } pub fn file_type(&self) -> FileType { - FileType { - bits: self.meta.st_filetype, - } + FileType { bits: self.meta.filetype } } pub fn modified(&self) -> io::Result { - Ok(SystemTime::from_wasi_timestamp(self.meta.st_mtim)) + Ok(SystemTime::from_wasi_timestamp(self.meta.mtim)) } pub fn accessed(&self) -> io::Result { - Ok(SystemTime::from_wasi_timestamp(self.meta.st_atim)) + Ok(SystemTime::from_wasi_timestamp(self.meta.atim)) } pub fn created(&self) -> io::Result { - Ok(SystemTime::from_wasi_timestamp(self.meta.st_ctim)) + Ok(SystemTime::from_wasi_timestamp(self.meta.ctim)) } - pub fn as_wasi(&self) -> &wasi::FileStat { + pub fn as_wasi(&self) -> &wasi::Filestat { &self.meta } } @@ -125,7 +121,7 @@ impl FileType { self.bits == wasi::FILETYPE_SYMBOLIC_LINK } - pub fn bits(&self) -> wasi::FileType { + pub fn bits(&self) -> wasi::Filetype { self.bits } } @@ -177,8 +173,7 @@ impl Iterator for ReadDir { continue; } let (dirent, data) = data.split_at(dirent_size); - let dirent = - unsafe { ptr::read_unaligned(dirent.as_ptr() as *const wasi::Dirent) }; + let dirent = unsafe { ptr::read_unaligned(dirent.as_ptr() as *const wasi::Dirent) }; // If the file name was truncated, then we need to reinvoke // `readdir` so we truncate our buffer to start over and reread this @@ -224,17 +219,11 @@ impl DirEntry { } pub fn metadata(&self) -> io::Result { - metadata_at( - &self.inner.dir.fd, - 0, - OsStr::from_bytes(&self.name).as_ref(), - ) + metadata_at(&self.inner.dir.fd, 0, OsStr::from_bytes(&self.name).as_ref()) } pub fn file_type(&self) -> io::Result { - Ok(FileType { - bits: self.meta.d_type, - }) + Ok(FileType { bits: self.meta.d_type }) } pub fn ino(&self) -> wasi::Inode { @@ -245,7 +234,7 @@ impl DirEntry { impl OpenOptions { pub fn new() -> OpenOptions { let mut base = OpenOptions::default(); - base.dirflags = wasi::LOOKUP_SYMLINK_FOLLOW; + base.dirflags = wasi::LOOKUPFLAGS_SYMLINK_FOLLOW; return base; } @@ -258,23 +247,23 @@ impl OpenOptions { } pub fn truncate(&mut self, truncate: bool) { - self.oflag(wasi::O_TRUNC, truncate); + self.oflag(wasi::OFLAGS_TRUNC, truncate); } pub fn create(&mut self, create: bool) { - self.oflag(wasi::O_CREAT, create); + self.oflag(wasi::OFLAGS_CREAT, create); } pub fn create_new(&mut self, create_new: bool) { - self.oflag(wasi::O_EXCL, create_new); - self.oflag(wasi::O_CREAT, create_new); + self.oflag(wasi::OFLAGS_EXCL, create_new); + self.oflag(wasi::OFLAGS_CREAT, create_new); } pub fn directory(&mut self, directory: bool) { - self.oflag(wasi::O_DIRECTORY, directory); + self.oflag(wasi::OFLAGS_DIRECTORY, directory); } - fn oflag(&mut self, bit: wasi::OFlags, set: bool) { + fn oflag(&mut self, bit: wasi::Oflags, set: bool) { if set { self.oflags |= bit; } else { @@ -283,26 +272,26 @@ impl OpenOptions { } pub fn append(&mut self, set: bool) { - self.fdflag(wasi::FDFLAG_APPEND, set); + self.fdflag(wasi::FDFLAGS_APPEND, set); } pub fn dsync(&mut self, set: bool) { - self.fdflag(wasi::FDFLAG_DSYNC, set); + self.fdflag(wasi::FDFLAGS_DSYNC, set); } pub fn nonblock(&mut self, set: bool) { - self.fdflag(wasi::FDFLAG_NONBLOCK, set); + self.fdflag(wasi::FDFLAGS_NONBLOCK, set); } pub fn rsync(&mut self, set: bool) { - self.fdflag(wasi::FDFLAG_RSYNC, set); + self.fdflag(wasi::FDFLAGS_RSYNC, set); } pub fn sync(&mut self, set: bool) { - self.fdflag(wasi::FDFLAG_SYNC, set); + self.fdflag(wasi::FDFLAGS_SYNC, set); } - fn fdflag(&mut self, bit: wasi::FdFlags, set: bool) { + fn fdflag(&mut self, bit: wasi::Fdflags, set: bool) { if set { self.fdflags |= bit; } else { @@ -330,36 +319,36 @@ impl OpenOptions { // based on that. let mut base = 0; if self.read { - base |= wasi::RIGHT_FD_READ; - base |= wasi::RIGHT_FD_READDIR; + base |= wasi::RIGHTS_FD_READ; + base |= wasi::RIGHTS_FD_READDIR; } if self.write { - base |= wasi::RIGHT_FD_WRITE; - base |= wasi::RIGHT_FD_DATASYNC; - base |= wasi::RIGHT_FD_ALLOCATE; - base |= wasi::RIGHT_FD_FILESTAT_SET_SIZE; + base |= wasi::RIGHTS_FD_WRITE; + base |= wasi::RIGHTS_FD_DATASYNC; + base |= wasi::RIGHTS_FD_ALLOCATE; + base |= wasi::RIGHTS_FD_FILESTAT_SET_SIZE; } // FIXME: some of these should probably be read-only or write-only... - base |= wasi::RIGHT_FD_ADVISE; - base |= wasi::RIGHT_FD_FDSTAT_SET_FLAGS; - base |= wasi::RIGHT_FD_FILESTAT_SET_TIMES; - base |= wasi::RIGHT_FD_SEEK; - base |= wasi::RIGHT_FD_SYNC; - base |= wasi::RIGHT_FD_TELL; - base |= wasi::RIGHT_PATH_CREATE_DIRECTORY; - base |= wasi::RIGHT_PATH_CREATE_FILE; - base |= wasi::RIGHT_PATH_FILESTAT_GET; - base |= wasi::RIGHT_PATH_LINK_SOURCE; - base |= wasi::RIGHT_PATH_LINK_TARGET; - base |= wasi::RIGHT_PATH_OPEN; - base |= wasi::RIGHT_PATH_READLINK; - base |= wasi::RIGHT_PATH_REMOVE_DIRECTORY; - base |= wasi::RIGHT_PATH_RENAME_SOURCE; - base |= wasi::RIGHT_PATH_RENAME_TARGET; - base |= wasi::RIGHT_PATH_SYMLINK; - base |= wasi::RIGHT_PATH_UNLINK_FILE; - base |= wasi::RIGHT_POLL_FD_READWRITE; + base |= wasi::RIGHTS_FD_ADVISE; + base |= wasi::RIGHTS_FD_FDSTAT_SET_FLAGS; + base |= wasi::RIGHTS_FD_FILESTAT_SET_TIMES; + base |= wasi::RIGHTS_FD_SEEK; + base |= wasi::RIGHTS_FD_SYNC; + base |= wasi::RIGHTS_FD_TELL; + base |= wasi::RIGHTS_PATH_CREATE_DIRECTORY; + base |= wasi::RIGHTS_PATH_CREATE_FILE; + base |= wasi::RIGHTS_PATH_FILESTAT_GET; + base |= wasi::RIGHTS_PATH_LINK_SOURCE; + base |= wasi::RIGHTS_PATH_LINK_TARGET; + base |= wasi::RIGHTS_PATH_OPEN; + base |= wasi::RIGHTS_PATH_READLINK; + base |= wasi::RIGHTS_PATH_REMOVE_DIRECTORY; + base |= wasi::RIGHTS_PATH_RENAME_SOURCE; + base |= wasi::RIGHTS_PATH_RENAME_TARGET; + base |= wasi::RIGHTS_PATH_SYMLINK; + base |= wasi::RIGHTS_PATH_UNLINK_FILE; + base |= wasi::RIGHTS_POLL_FD_READWRITE; return base; } @@ -368,14 +357,14 @@ impl OpenOptions { self.rights_inheriting.unwrap_or_else(|| self.rights_base()) } - pub fn lookup_flags(&mut self, flags: wasi::LookupFlags) { + pub fn lookup_flags(&mut self, flags: wasi::Lookupflags) { self.dirflags = flags; } } impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result { - let (dir, file) = open_parent(path, wasi::RIGHT_PATH_OPEN)?; + let (dir, file) = open_parent(path, wasi::RIGHTS_PATH_OPEN)?; open_at(&dir, &file, opts) } @@ -387,11 +376,7 @@ impl File { self.fd.filestat_get().map(|meta| FileAttr { meta }) } - pub fn metadata_at( - &self, - flags: wasi::LookupFlags, - path: &Path, - ) -> io::Result { + pub fn metadata_at(&self, flags: wasi::Lookupflags, path: &Path) -> io::Result { metadata_at(&self.fd, flags, path) } @@ -457,11 +442,7 @@ impl File { impl FromInner for File { fn from_inner(fd: u32) -> File { - unsafe { - File { - fd: WasiFd::from_raw(fd), - } - } + unsafe { File { fd: WasiFd::from_raw(fd) } } } } @@ -471,16 +452,14 @@ impl DirBuilder { } pub fn mkdir(&self, p: &Path) -> io::Result<()> { - let (dir, file) = open_parent(p, wasi::RIGHT_PATH_CREATE_DIRECTORY)?; - dir.create_directory(file.as_os_str().as_bytes()) + let (dir, file) = open_parent(p, wasi::RIGHTS_PATH_CREATE_DIRECTORY)?; + dir.create_directory(osstr2str(file.as_ref())?) } } impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("File") - .field("fd", &self.fd.as_raw()) - .finish() + f.debug_struct("File").field("fd", &self.fd.as_raw()).finish() } } @@ -494,26 +473,19 @@ pub fn readdir(p: &Path) -> io::Result { buf: vec![0; 128], offset: 0, cap: 0, - inner: Arc::new(ReadDirInner { - dir, - root: p.to_path_buf(), - }), + inner: Arc::new(ReadDirInner { dir, root: p.to_path_buf() }), }) } pub fn unlink(p: &Path) -> io::Result<()> { - let (dir, file) = open_parent(p, wasi::RIGHT_PATH_UNLINK_FILE)?; - dir.unlink_file(file.as_os_str().as_bytes()) + let (dir, file) = open_parent(p, wasi::RIGHTS_PATH_UNLINK_FILE)?; + dir.unlink_file(osstr2str(file.as_ref())?) } pub fn rename(old: &Path, new: &Path) -> io::Result<()> { - let (old, old_file) = open_parent(old, wasi::RIGHT_PATH_RENAME_SOURCE)?; - let (new, new_file) = open_parent(new, wasi::RIGHT_PATH_RENAME_TARGET)?; - old.rename( - old_file.as_os_str().as_bytes(), - &new, - new_file.as_os_str().as_bytes(), - ) + let (old, old_file) = open_parent(old, wasi::RIGHTS_PATH_RENAME_SOURCE)?; + let (new, new_file) = open_parent(new, wasi::RIGHTS_PATH_RENAME_TARGET)?; + old.rename(osstr2str(old_file.as_ref())?, &new, osstr2str(new_file.as_ref())?) } pub fn set_perm(_p: &Path, _perm: FilePermissions) -> io::Result<()> { @@ -523,12 +495,12 @@ pub fn set_perm(_p: &Path, _perm: FilePermissions) -> io::Result<()> { } pub fn rmdir(p: &Path) -> io::Result<()> { - let (dir, file) = open_parent(p, wasi::RIGHT_PATH_REMOVE_DIRECTORY)?; - dir.remove_directory(file.as_os_str().as_bytes()) + let (dir, file) = open_parent(p, wasi::RIGHTS_PATH_REMOVE_DIRECTORY)?; + dir.remove_directory(osstr2str(file.as_ref())?) } pub fn readlink(p: &Path) -> io::Result { - let (dir, file) = open_parent(p, wasi::RIGHT_PATH_READLINK)?; + let (dir, file) = open_parent(p, wasi::RIGHTS_PATH_READLINK)?; read_link(&dir, &file) } @@ -549,7 +521,7 @@ fn read_link(fd: &WasiFd, file: &Path) -> io::Result { // Now that we have an initial guess of how big to make our buffer, call // `readlink` in a loop until it fails or reports it filled fewer bytes than // we asked for, indicating we got everything. - let file = file.as_os_str().as_bytes(); + let file = osstr2str(file.as_ref())?; let mut destination = vec![0u8; initial_size]; loop { let len = fd.readlink(file, &mut destination)?; @@ -564,38 +536,34 @@ fn read_link(fd: &WasiFd, file: &Path) -> io::Result { } pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> { - let (dst, dst_file) = open_parent(dst, wasi::RIGHT_PATH_SYMLINK)?; - dst.symlink(src.as_os_str().as_bytes(), dst_file.as_os_str().as_bytes()) + let (dst, dst_file) = open_parent(dst, wasi::RIGHTS_PATH_SYMLINK)?; + dst.symlink(osstr2str(src.as_ref())?, osstr2str(dst_file.as_ref())?) } pub fn link(src: &Path, dst: &Path) -> io::Result<()> { - let (src, src_file) = open_parent(src, wasi::RIGHT_PATH_LINK_SOURCE)?; - let (dst, dst_file) = open_parent(dst, wasi::RIGHT_PATH_LINK_TARGET)?; + let (src, src_file) = open_parent(src, wasi::RIGHTS_PATH_LINK_SOURCE)?; + let (dst, dst_file) = open_parent(dst, wasi::RIGHTS_PATH_LINK_TARGET)?; src.link( - wasi::LOOKUP_SYMLINK_FOLLOW, - src_file.as_os_str().as_bytes(), + wasi::LOOKUPFLAGS_SYMLINK_FOLLOW, + osstr2str(src_file.as_ref())?, &dst, - dst_file.as_os_str().as_bytes(), + osstr2str(dst_file.as_ref())?, ) } pub fn stat(p: &Path) -> io::Result { - let (dir, file) = open_parent(p, wasi::RIGHT_PATH_FILESTAT_GET)?; - metadata_at(&dir, wasi::LOOKUP_SYMLINK_FOLLOW, &file) + let (dir, file) = open_parent(p, wasi::RIGHTS_PATH_FILESTAT_GET)?; + metadata_at(&dir, wasi::LOOKUPFLAGS_SYMLINK_FOLLOW, &file) } pub fn lstat(p: &Path) -> io::Result { - let (dir, file) = open_parent(p, wasi::RIGHT_PATH_FILESTAT_GET)?; + let (dir, file) = open_parent(p, wasi::RIGHTS_PATH_FILESTAT_GET)?; metadata_at(&dir, 0, &file) } -fn metadata_at( - fd: &WasiFd, - flags: wasi::LookupFlags, - path: &Path, -) -> io::Result { - fd.path_filestat_get(flags, path.as_os_str().as_bytes()) - .map(|meta| FileAttr { meta }) +fn metadata_at(fd: &WasiFd, flags: wasi::Lookupflags, path: &Path) -> io::Result { + let meta = fd.path_filestat_get(flags, osstr2str(path.as_ref())?)?; + Ok(FileAttr { meta }) } pub fn canonicalize(_p: &Path) -> io::Result { @@ -607,7 +575,7 @@ pub fn canonicalize(_p: &Path) -> io::Result { fn open_at(fd: &WasiFd, path: &Path, opts: &OpenOptions) -> io::Result { let fd = fd.open( opts.dirflags, - path.as_os_str().as_bytes(), + osstr2str(path.as_ref())?, opts.oflags, opts.rights_base(), opts.rights_inheriting(), @@ -643,10 +611,7 @@ fn open_at(fd: &WasiFd, path: &Path, opts: &OpenOptions) -> io::Result { /// /// Note that this can fail if `p` doesn't look like it can be opened relative /// to any preopened file descriptor. -fn open_parent( - p: &Path, - rights: wasi::Rights, -) -> io::Result<(ManuallyDrop, PathBuf)> { +fn open_parent(p: &Path, rights: wasi::Rights) -> io::Result<(ManuallyDrop, PathBuf)> { let p = CString::new(p.as_os_str().as_bytes())?; unsafe { let mut ret = ptr::null(); @@ -671,3 +636,7 @@ fn open_parent( return Ok((ManuallyDrop::new(WasiFd::from_raw(fd as u32)), path)); } } + +pub fn osstr2str(f: &OsStr) -> io::Result<&str> { + f.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::Other, "input must be utf-8")) +} diff --git a/src/libstd/sys/wasi/io.rs b/src/libstd/sys/wasi/io.rs index 4be92faed308f..41a6e9783c047 100644 --- a/src/libstd/sys/wasi/io.rs +++ b/src/libstd/sys/wasi/io.rs @@ -1,12 +1,9 @@ use crate::marker::PhantomData; use crate::slice; -use ::wasi::wasi_unstable as wasi; -use core::ffi::c_void; - #[repr(transparent)] pub struct IoSlice<'a> { - vec: wasi::CIoVec, + vec: wasi::Ciovec, _p: PhantomData<&'a [u8]>, } @@ -14,8 +11,8 @@ impl<'a> IoSlice<'a> { #[inline] pub fn new(buf: &'a [u8]) -> IoSlice<'a> { IoSlice { - vec: wasi::CIoVec { - buf: buf.as_ptr() as *const c_void, + vec: wasi::Ciovec { + buf: buf.as_ptr(), buf_len: buf.len(), }, _p: PhantomData, @@ -44,7 +41,7 @@ impl<'a> IoSlice<'a> { #[repr(transparent)] pub struct IoSliceMut<'a> { - vec: wasi::IoVec, + vec: wasi::Iovec, _p: PhantomData<&'a mut [u8]>, } @@ -52,8 +49,8 @@ impl<'a> IoSliceMut<'a> { #[inline] pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> { IoSliceMut { - vec: wasi::IoVec { - buf: buf.as_mut_ptr() as *mut c_void, + vec: wasi::Iovec { + buf: buf.as_mut_ptr(), buf_len: buf.len() }, _p: PhantomData, diff --git a/src/libstd/sys/wasi/mod.rs b/src/libstd/sys/wasi/mod.rs index 517e3be9cb58c..83f98a19f4706 100644 --- a/src/libstd/sys/wasi/mod.rs +++ b/src/libstd/sys/wasi/mod.rs @@ -17,7 +17,6 @@ use crate::io as std_io; use crate::mem; use crate::os::raw::c_char; -use ::wasi::wasi_unstable as wasi; pub mod alloc; pub mod args; @@ -72,25 +71,21 @@ pub fn decode_error_kind(errno: i32) -> std_io::ErrorKind { if errno > u16::max_value() as i32 || errno < 0 { return Other; } - let code = match wasi::Error::new(errno as u16) { - Some(code) => code, - None => return Other, - }; - match code { - wasi::ECONNREFUSED => ConnectionRefused, - wasi::ECONNRESET => ConnectionReset, - wasi::EPERM | wasi::EACCES => PermissionDenied, - wasi::EPIPE => BrokenPipe, - wasi::ENOTCONN => NotConnected, - wasi::ECONNABORTED => ConnectionAborted, - wasi::EADDRNOTAVAIL => AddrNotAvailable, - wasi::EADDRINUSE => AddrInUse, - wasi::ENOENT => NotFound, - wasi::EINTR => Interrupted, - wasi::EINVAL => InvalidInput, - wasi::ETIMEDOUT => TimedOut, - wasi::EEXIST => AlreadyExists, - wasi::EAGAIN => WouldBlock, + match errno as u16 { + wasi::ERRNO_CONNREFUSED => ConnectionRefused, + wasi::ERRNO_CONNRESET => ConnectionReset, + wasi::ERRNO_PERM | wasi::ERRNO_ACCES => PermissionDenied, + wasi::ERRNO_PIPE => BrokenPipe, + wasi::ERRNO_NOTCONN => NotConnected, + wasi::ERRNO_CONNABORTED => ConnectionAborted, + wasi::ERRNO_ADDRNOTAVAIL => AddrNotAvailable, + wasi::ERRNO_ADDRINUSE => AddrInUse, + wasi::ERRNO_NOENT => NotFound, + wasi::ERRNO_INTR => Interrupted, + wasi::ERRNO_INVAL => InvalidInput, + wasi::ERRNO_TIMEDOUT => TimedOut, + wasi::ERRNO_EXIST => AlreadyExists, + wasi::ERRNO_AGAIN => WouldBlock, _ => Other, } } @@ -116,16 +111,13 @@ pub unsafe fn abort_internal() -> ! { pub fn hashmap_random_keys() -> (u64, u64) { let mut ret = (0u64, 0u64); unsafe { - let base = &mut ret as *mut (u64, u64) as *mut core::ffi::c_void; + let base = &mut ret as *mut (u64, u64) as *mut u8; let len = mem::size_of_val(&ret); - let ret = wasi::raw::__wasi_random_get(base, len); - if ret != 0 { - panic!("__wasi_random_get failure") - } + wasi::random_get(base, len).expect("random_get failure"); } return ret } fn err2io(err: wasi::Error) -> std_io::Error { - std_io::Error::from_raw_os_error(err.get() as i32) + std_io::Error::from_raw_os_error(err.raw_error().into()) } diff --git a/src/libstd/sys/wasi/stdio.rs b/src/libstd/sys/wasi/stdio.rs index 1d57b9922e599..1d53884f2d6b4 100644 --- a/src/libstd/sys/wasi/stdio.rs +++ b/src/libstd/sys/wasi/stdio.rs @@ -2,8 +2,6 @@ use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem::ManuallyDrop; use crate::sys::fd::WasiFd; -use ::wasi::wasi_unstable as wasi; - pub struct Stdin; pub struct Stdout; pub struct Stderr; @@ -18,8 +16,11 @@ impl Stdin { } pub fn read_vectored(&self, data: &mut [IoSliceMut<'_>]) -> io::Result { - ManuallyDrop::new(unsafe { WasiFd::from_raw(wasi::STDIN_FD) }) - .read(data) + ManuallyDrop::new(unsafe { WasiFd::from_raw(self.as_raw_fd()) }).read(data) + } + + pub fn as_raw_fd(&self) -> u32 { + 0 } } @@ -33,13 +34,16 @@ impl Stdout { } pub fn write_vectored(&self, data: &[IoSlice<'_>]) -> io::Result { - ManuallyDrop::new(unsafe { WasiFd::from_raw(wasi::STDOUT_FD) }) - .write(data) + ManuallyDrop::new(unsafe { WasiFd::from_raw(self.as_raw_fd()) }).write(data) } pub fn flush(&self) -> io::Result<()> { Ok(()) } + + pub fn as_raw_fd(&self) -> u32 { + 1 + } } impl Stderr { @@ -52,13 +56,16 @@ impl Stderr { } pub fn write_vectored(&self, data: &[IoSlice<'_>]) -> io::Result { - ManuallyDrop::new(unsafe { WasiFd::from_raw(wasi::STDERR_FD) }) - .write(data) + ManuallyDrop::new(unsafe { WasiFd::from_raw(self.as_raw_fd()) }).write(data) } pub fn flush(&self) -> io::Result<()> { Ok(()) } + + pub fn as_raw_fd(&self) -> u32 { + 2 + } } impl io::Write for Stderr { @@ -74,7 +81,7 @@ impl io::Write for Stderr { pub const STDIN_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE; pub fn is_ebadf(err: &io::Error) -> bool { - err.raw_os_error() == Some(wasi::EBADF.get() as i32) + err.raw_os_error() == Some(wasi::ERRNO_BADF.into()) } pub fn panic_output() -> Option { diff --git a/src/libstd/sys/wasi/thread.rs b/src/libstd/sys/wasi/thread.rs index 6ce41420284e5..0986759b89b7c 100644 --- a/src/libstd/sys/wasi/thread.rs +++ b/src/libstd/sys/wasi/thread.rs @@ -4,22 +4,18 @@ use crate::mem; use crate::sys::{unsupported, Void}; use crate::time::Duration; -use ::wasi::wasi_unstable as wasi; - pub struct Thread(Void); pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(_stack: usize, _p: Box) - -> io::Result - { + pub unsafe fn new(_stack: usize, _p: Box) -> io::Result { unsupported() } pub fn yield_now() { - let ret = wasi::sched_yield(); + let ret = unsafe { wasi::sched_yield() }; debug_assert_eq!(ret, Ok(())); } @@ -33,32 +29,30 @@ impl Thread { const USERDATA: wasi::Userdata = 0x0123_45678; - let clock = wasi::raw::__wasi_subscription_u_clock_t { - identifier: 0, - clock_id: wasi::CLOCK_MONOTONIC, + let clock = wasi::SubscriptionClock { + id: wasi::CLOCKID_MONOTONIC, timeout: nanos as u64, precision: 0, flags: 0, }; - let in_ = [wasi::Subscription { + let in_ = wasi::Subscription { userdata: USERDATA, - type_: wasi::EVENTTYPE_CLOCK, - u: wasi::raw::__wasi_subscription_u { clock: clock }, - }]; - let (res, event) = unsafe { - let mut out: [wasi::Event; 1] = mem::zeroed(); - let res = wasi::poll_oneoff(&in_, &mut out); - (res, out[0]) + r#type: wasi::EVENTTYPE_CLOCK, + u: wasi::SubscriptionU { clock }, }; - match (res, event) { - (Ok(1), wasi::Event { - userdata: USERDATA, - error: 0, - type_: wasi::EVENTTYPE_CLOCK, - .. - }) => {} - _ => panic!("thread::sleep(): unexpected result of poll_oneoff"), + unsafe { + let mut event: wasi::Event = mem::zeroed(); + let res = wasi::poll_oneoff(&in_, &mut event, 1); + match (res, event) { + ( + Ok(1), + wasi::Event { + userdata: USERDATA, error: 0, r#type: wasi::EVENTTYPE_CLOCK, .. + }, + ) => {} + _ => panic!("thread::sleep(): unexpected result of poll_oneoff"), + } } } @@ -69,6 +63,10 @@ impl Thread { pub mod guard { pub type Guard = !; - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + pub unsafe fn current() -> Option { + None + } + pub unsafe fn init() -> Option { + None + } } diff --git a/src/libstd/sys/wasi/time.rs b/src/libstd/sys/wasi/time.rs index 4394a22f9c233..80ec317b5a2c6 100644 --- a/src/libstd/sys/wasi/time.rs +++ b/src/libstd/sys/wasi/time.rs @@ -1,5 +1,4 @@ use crate::time::Duration; -use ::wasi::wasi_unstable as wasi; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct Instant(Duration); @@ -10,19 +9,18 @@ pub struct SystemTime(Duration); pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0)); fn current_time(clock: u32) -> Duration { - let ts = wasi::clock_time_get( - clock, - 1, // precision... seems ignored though? - ).unwrap(); - Duration::new( - (ts / 1_000_000_000) as u64, - (ts % 1_000_000_000) as u32, - ) + let ts = unsafe { + wasi::clock_time_get( + clock, 1, // precision... seems ignored though? + ) + .unwrap() + }; + Duration::new((ts / 1_000_000_000) as u64, (ts % 1_000_000_000) as u32) } impl Instant { pub fn now() -> Instant { - Instant(current_time(wasi::CLOCK_MONOTONIC)) + Instant(current_time(wasi::CLOCKID_MONOTONIC)) } pub const fn zero() -> Instant { @@ -48,15 +46,14 @@ impl Instant { impl SystemTime { pub fn now() -> SystemTime { - SystemTime(current_time(wasi::CLOCK_REALTIME)) + SystemTime(current_time(wasi::CLOCKID_REALTIME)) } pub fn from_wasi_timestamp(ts: wasi::Timestamp) -> SystemTime { SystemTime(Duration::from_nanos(ts)) } - pub fn sub_time(&self, other: &SystemTime) - -> Result { + pub fn sub_time(&self, other: &SystemTime) -> Result { self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0) }