Commit Graph

336 Commits

Author SHA1 Message Date
mlugg
d11bbde5f9
compiler: remove anonymous struct types, unify all tuples
This commit reworks how anonymous struct literals and tuples work.

Previously, an untyped anonymous struct literal
(e.g. `const x = .{ .a = 123 }`) was given an "anonymous struct type",
which is a special kind of struct which coerces using structural
equivalence. This mechanism was a holdover from before we used
RLS / result types as the primary mechanism of type inference. This
commit changes the language so that the type assigned here is a "normal"
struct type. It uses a form of equivalence based on the AST node and the
type's structure, much like a reified (`@Type`) type.

Additionally, tuples have been simplified. The distinction between
"simple" and "complex" tuple types is eliminated. All tuples, even those
explicitly declared using `struct { ... }` syntax, use structural
equivalence, and do not undergo staged type resolution. Tuples are very
restricted: they cannot have non-`auto` layouts, cannot have aligned
fields, and cannot have default values with the exception of `comptime`
fields. Tuples currently do not have optimized layout, but this can be
changed in the future.

This change simplifies the language, and fixes some problematic
coercions through pointers which led to unintuitive behavior.

Resolves: #16865
2024-10-31 20:42:53 +00:00
kcbanner
7edd69d8aa tests: add tests for is_dll_import externs
- tests/standalone/extern wasn't running its test step
- add compile error tests for thread local / dll import @extern in a comptime scope
2024-10-22 18:46:14 -04:00
kcbanner
85d87c9ca1 coff: fix incorrect default image_base values and re-enable shared library tests on Windows
This was the cause of aarch64-windows shared libraries causing  "bad image" errors
during load-time linking. I also re-enabled the tests that were surfacing this bug.
2024-10-21 22:54:52 -07:00
Parzival-3141
e1e151df0d untangle skip conditions 2024-10-08 23:34:20 +02:00
Parzival-3141
7dc0014769 revert disabling aarch64 skip
I was too optimistic in disabling the aarch64 skip, assuming it was also
caused by ConEmu. Unfortunately I don't have access to a machine for testing.
2024-10-08 23:34:20 +02:00
Parzival-3141
f522fb9ca3 fix standalone/empty_env test
The problem seems to be ConEmu setting environment variables before
executing the test process. The test passes when run in Windows CMD.
2024-10-08 23:34:20 +02:00
Alex Rønne Petersen
bc278719d9 test: Disable shared_lib_unwind on x86_64-macos.
https://github.com/ziglang/zig/issues/21337
2024-09-19 18:20:21 -07:00
Linus Groh
8588964972 Replace deprecated default initializations with decl literals 2024-09-12 16:01:23 +01:00
mlugg
0fe3fd01dd
std: update std.builtin.Type fields to follow naming conventions
The compiler actually doesn't need any functional changes for this: Sema
does reification based on the tag indices of `std.builtin.Type` already!
So, no zig1.wasm update is necessary.

This change is necessary to disallow name clashes between fields and
decls on a type, which is a prerequisite of #9938.
2024-08-28 08:39:59 +01:00
mlugg
a3a737e9a6
lib,test,tools,doc: update usages of @export 2024-08-27 00:44:35 +01:00
Robin Voetter
80999391d9
re-enable emit_asm_and_bin and emit_llvm_no_bin tests
These were fixed during the last few commits too. The emit_llvm_no_bin test
is renamed from the issue_12588 test.

Closes #17484
2024-08-19 19:09:13 +02:00
Robin Voetter
294ca6563e
add standalone test for only dependending on the emitted assembly and not the bin 2024-08-19 19:09:13 +02:00
Xavier Bouchoux
7e966de45e std.debug.Dwarf: fix loading external debuginfo in the ".debuglink" case.
- look up the debuglink file in the directory of the executable file (instead of the cwd)
 - fix parsing of debuglink section (the 4-byte alignement is within the file, unrelated to the in-memory address)
2024-08-08 07:15:00 +02:00
Andrew Kelley
d721d9af69 update coff_dwarf standalone test to new API
and make it still test compilation on non-Windows
2024-08-07 00:48:32 -07:00
Evan Haas
8daf7673a5
test: Add generate_c_size_and_align_checks.zig to standalone build test 2024-08-05 13:15:05 -07:00
Andrew Kelley
975c185b92 fix compilation on powerpc GNU systems
...which have a ucontext_t but not a PC register. The current stack
unwinding implementation does not yet support this architecture.

Also fix name of `std.debug.SelfInfo.openSelf` to remove redundancy.

Also removed this hook into root providing an "openSelfDebugInfo"
function. Sorry, this debugging code is not of sufficient quality to
offer a plugin API right now.
2024-08-02 14:14:59 -07:00
Pat Tullmann
e8503ecb65 Default std.posix.system.ucontext_t is void
PR https://github.com/ziglang/zig/pull/20679 ("std.c reorganization")
switched feature-detection code to use "T != void" checks in place of
"@hasDecl".  However, the std.posix.system struct is empty, so
compile-time feature detection against symbols in there (specifically
`std.posix.system.ucontext_t` in this case), fail at compile time on
freestanding targets.

This PR adds a void ucontext_t into the std.posix.system default.

This PR also adds pseudo-"freestanding" variation of the StackIterator
"unwind" test.  It is sort of hacky (its freestanding, but assumes it can
invoke a Linux exit syscall), but it does detect this problem.

Fixes #20710
2024-07-23 11:47:29 -07:00
David Rubin
08cddaf11c test: update make functions to use MakeOptions 2024-07-21 11:22:14 -07:00
Techatrix
c746d7a35d test: check output file caching of run steps with side-effects 2024-07-21 02:03:32 -07:00
Andrew Kelley
abf8955951 make zig compiler processes live across rebuilds
Changes the `make` function signature to take an options struct, which
additionally includes `watch: bool`. I intentionally am not exposing
this information to configure phase logic.

Also adds global zig cache to the compiler cache prefixes.

Closes #20600
2024-07-14 19:51:16 -07:00
Jonathan Marler
d9f1a952b8 build: fix WriteFile and addCSourceFiles not adding LazyPath deps
Adds a missing call to addLazyPathDependenciesOnly in
std.Build.Module.addCSourceFiles.  Also fixes an issue in
std.Build.Step.WriteFile where it wasn't updating all the GeneratedFile
instances for every directory.  To fix the second issue, I removed
all the GeneratedFile instances and now all files/directories reference
the steps main GeneratedFile via sub paths.
2024-07-04 13:34:17 -04:00
Andrew Kelley
8db1490b8a update test build script to latest API 2024-07-01 16:38:02 -07:00
Sashko
a717ac0340 Add a standalone test to cover the duplicate module bug 2024-07-01 16:36:39 -07:00
Krzysztof Wolicki
45c77931c2 Change deprecated b.host to b.graph.host in tests and Zig's build.zig 2024-06-13 10:49:06 -04:00
Ryan Liptak
76fb2b685b std: Convert deprecated aliases to compile errors and fix usages
Deprecated aliases that are now compile errors:

- `std.fs.MAX_PATH_BYTES` (renamed to `std.fs.max_path_bytes`)
- `std.mem.tokenize` (split into `tokenizeAny`, `tokenizeSequence`, `tokenizeScalar`)
- `std.mem.split` (split into `splitSequence`, `splitAny`, `splitScalar`)
- `std.mem.splitBackwards` (split into `splitBackwardsSequence`, `splitBackwardsAny`, `splitBackwardsScalar`)
- `std.unicode`
  + `utf16leToUtf8Alloc`, `utf16leToUtf8AllocZ`, `utf16leToUtf8`, `fmtUtf16le` (all renamed to have capitalized `Le`)
  + `utf8ToUtf16LeWithNull` (renamed to `utf8ToUtf16LeAllocZ`)
- `std.zig.CrossTarget` (moved to `std.Target.Query`)

Deprecated `lib/std/std.zig` decls were deleted instead of made a `@compileError` because the `refAllDecls` in the test block would trigger the `@compileError`. The deleted top-level `std` namespaces are:

- `std.rand` (renamed to `std.Random`)
- `std.TailQueue` (renamed to `std.DoublyLinkedList`)
- `std.ChildProcess` (renamed/moved to `std.process.Child`)

This is not exhaustive. Deprecated aliases that I didn't touch:
  + `std.io.*`
  + `std.Build.*`
  + `std.builtin.Mode`
  + `std.zig.c_translation.CIntLiteralRadix`
  + anything in `src/`
2024-06-13 10:18:59 -04:00
Michael Dusan
2cd536d7e8 libcxx: fix building when -fsingle-threaded
* Skip building libcxx mt-only source files when single-threaded.
* This change is required for llvm18 libcxx.
* Add standalone test to link a trivial:
    - mt-executable with libcxx
    - st-executable with libcxx
2024-06-08 15:34:19 -04:00
MrDmitry
84d1580873 Report error on missing values for addConfigHeader 2024-06-08 15:18:56 -04:00
Andrew Kelley
a5e4fe5487 std.Build.Step.Run: account for new environment variable
Introduces `disable_zig_progress` which prevents the build runner from
assigning the child process a progress node.

This is needed for the empty_env test which requires the environment to
be completely empty.
2024-05-27 20:56:49 -07:00
Andrew Kelley
f97c2f28fd update the codebase for the new std.Progress API 2024-05-27 20:56:48 -07:00
Andrew Kelley
f47824f24d std: restructure child process namespace 2024-05-26 09:31:55 -07:00
Jakub Konka
6f117dbca4 test/standalone: fix iOS smoke test 2024-05-13 08:55:27 +02:00
Jacob Young
d9b00ee4ba standalone: support relative cache path 2024-05-08 19:37:03 -07:00
Jacob Young
dee9f82f69 Run: add output directory arguments
This allows running commands that take an output directory argument. The
main thing that was needed for this feature was generated file subpaths,
to allow access to the files in a generated directory. Additionally, a
minor change was required to so that the correct directory is created
for output directory args.
2024-05-05 15:58:08 -04:00
Jacob Young
e3424332d3 Build: cleanup
* `doc/langref` formatting
 * upgrade `.{ .path = "..." }` to `b.path("...")`
 * avoid using arguments named `self`
 * make `Build.Step.Id` usage more consistent
 * add `Build.pathResolve`
 * use `pathJoin` and `pathResolve` everywhere
 * make sure `Build.LazyPath.getPath2` returns an absolute path
2024-05-05 09:42:51 -04:00
Ryan Liptak
b86c4bde64 Rename Dir.writeFile2 -> Dir.writeFile and update all callsites
writeFile was deprecated in favor of writeFile2 in f645022d16. This commit renames writeFile2 to writeFile and makes writeFile2 a compile error.
2024-05-03 13:29:22 -07:00
Ryan Liptak
ea9d817a90 Build system: Allow specifying Win32 resource include paths using LazyPath
Adds an `include_paths` field to RcSourceFile that takes a slice of LazyPaths. The paths are resolved and subsequently appended to the -rcflags as `/I <resolved path>`.

This fixes an accidental regression from https://github.com/ziglang/zig/pull/19174. Before that PR, all Win32 resource compilation would inherit the CC flags (via `addCCArgs`), which included things like include directories. After that PR, though, that is no longer the case.

However, this commit intentionally does not restore the previous behavior (inheriting the C include paths). Instead, each .rc file will need to have its include paths specified directly and the include paths only apply to one particular resource script. This allows more fine-grained control and has less potentially surprising behavior (at the cost of some convenience).

Closes #19605
2024-05-02 22:08:00 -07:00
Andrew Kelley
9d64332a59
Merge pull request #19698 from squeek502/windows-batbadbut
std.process.Child: Mitigate arbitrary command execution vulnerability on Windows (BatBadBut)
2024-04-24 13:49:43 -07:00
Ryan Liptak
422464d540 std.process.Child: Mitigate arbitrary command execution vulnerability on Windows (BatBadBut)
> Note: This first part is mostly a rephrasing of https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/
> See that article for more details

On Windows, it is possible to execute `.bat`/`.cmd` scripts via CreateProcessW. When this happens, `CreateProcessW` will (under-the-hood) spawn a `cmd.exe` process with the path to the script and the args like so:

    cmd.exe /c script.bat arg1 arg2

This is a problem because:

- `cmd.exe` has its own, separate, parsing/escaping rules for arguments
- Environment variables in arguments will be expanded before the `cmd.exe` parsing rules are applied

Together, this means that (1) maliciously constructed arguments can lead to arbitrary command execution via the APIs in `std.process.Child` and (2) escaping according to the rules of `cmd.exe` is not enough on its own.

A basic example argv field that reproduces the vulnerability (this will erroneously spawn `calc.exe`):

    .argv = &.{ "test.bat", "\"&calc.exe" },

And one that takes advantage of environment variable expansion to still spawn calc.exe even if the args are properly escaped for `cmd.exe`:

    .argv = &.{ "test.bat", "%CMDCMDLINE:~-1%&calc.exe" },

(note: if these spawned e.g. `test.exe` instead of `test.bat`, they wouldn't be vulnerable; it's only `.bat`/`.cmd` scripts that are vulnerable since they go through `cmd.exe`)

Zig allows passing `.bat`/`.cmd` scripts as `argv[0]` via `std.process.Child`, so the Zig API is affected by this vulnerability. Note also that Zig will search `PATH` for `.bat`/`.cmd` scripts, so spawning something like `foo` may end up executing `foo.bat` somewhere in the PATH (the PATH searching of Zig matches the behavior of cmd.exe).

> Side note to keep in mind: On Windows, the extension is significant in terms of how Windows will try to execute the command. If the extension is not `.bat`/`.cmd`, we know that it will not attempt to be executed as a `.bat`/`.cmd` script (and vice versa). This means that we can just look at the extension to know if we are trying to execute a `.bat`/`.cmd` script.

---

This general class of problem has been documented before in 2011 here:

https://learn.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way

and the course of action it suggests for escaping when executing .bat/.cmd files is:

- Escape first using the non-cmd.exe rules
- Then escape all cmd.exe 'metacharacters' (`(`, `)`, `%`, `!`, `^`, `"`, `<`, `>`, `&`, and `|`) with `^`

However, escaping with ^ on its own is insufficient because it does not stop cmd.exe from expanding environment variables. For example:

```
args.bat %PATH%
```

escaped with ^ (and wrapped in quotes that are also escaped), it *will* stop cmd.exe from expanding `%PATH%`:

```
> args.bat ^"^%PATH^%^"
"%PATH%"
```

but it will still try to expand `%PATH^%`:

```
set PATH^^=123
> args.bat ^"^%PATH^%^"
"123"
```

The goal is to stop *all* environment variable expansion, so this won't work.

Another problem with the ^ approach is that it does not seem to allow all possible command lines to round trip through cmd.exe (as far as I can tell at least).

One known example:

```
args.bat ^"\^"key^=value\^"^"
```

where args.bat is:

```
@echo %1 %2 %3 %4 %5 %6 %7 %8 %9
```

will print

```
"\"key value\""
```

(it will turn the `=` into a space for an unknown reason; other minor variations do roundtrip, e.g. `\^"key^=value\^"`, `^"key^=value^"`, so it's unclear what's going on)

It may actually be possible to escape with ^ such that every possible command line round trips correctly, but it's probably not worth the effort to figure it out, since the suggested mitigation for BatBadBut has better roundtripping and leads to less garbled command lines overall.

---

Ultimately, the mitigation used here is the same as the one suggested in:

https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/

The mitigation steps are reproduced here, noted with one deviation that Zig makes (following Rust's lead):

1. Replace percent sign (%) with %%cd:~,%.
2. Replace the backslash (\) in front of the double quote (") with two backslashes (\\).
3. Replace the double quote (") with two double quotes ("").
4. ~~Remove newline characters (\n).~~
  - Instead, `\n`, `\r`, and NUL are disallowed and will trigger `error.InvalidBatchScriptArg` if they are found in `argv`. These three characters do not roundtrip through a `.bat` file and therefore are of dubious/no use. It's unclear to me if `\n` in particular is relevant to the BatBadBut vulnerability (I wasn't able to find a reproduction with \n and the post doesn't mention anything about it except in the suggested mitigation steps); it just seems to act as a 'end of arguments' marker and therefore anything after the `\n` is lost (and same with NUL). `\r` seems to be stripped from the command line arguments when passed through a `.bat`/`.cmd`, so that is also disallowed to ensure that `argv` can always fully roundtrip through `.bat`/`.cmd`.
5. Enclose the argument with double quotes (").

The escaped command line is then run as something like:

    cmd.exe /d /e:ON /v:OFF /c "foo.bat arg1 arg2"

Note: Previously, we would pass `foo.bat arg1 arg2` as the command line and the path to `foo.bat` as the app name and let CreateProcessW handle the `cmd.exe` spawning for us, but because we need to pass `/e:ON` and `/v:OFF` to cmd.exe to ensure the mitigation is effective, that is no longer tenable. Instead, we now get the full path to `cmd.exe` and use that as the app name when executing `.bat`/`.cmd` files.

---

A standalone test has also been added that tests two things:

1. Known reproductions of the vulnerability are tested to ensure that they do not reproduce the vulnerability
2. Randomly generated command line arguments roundtrip when passed to a `.bat` file and then are passed from the `.bat` file to a `.exe`. This fuzz test is as thorough as possible--it tests that things like arbitrary Unicode codepoints and unpaired surrogates roundtrip successfully.

Note: In order for the `CreateProcessW` -> `.bat` -> `.exe` roundtripping to succeed, the .exe must split the arguments using the post-2008 C runtime argv splitting implementation, see https://github.com/ziglang/zig/pull/19655 for details on when that change was made in Zig.
2024-04-23 03:21:51 -07:00
Meghan Denny
1b4ea80654
do more robust import
Co-authored-by: Carl Åstholm <carl@astholm.se>
2024-04-18 11:24:42 -07:00
Meghan Denny
0820aa4a46 std: fix and add test for Build.dependencyFromBuildZig 2024-04-18 03:07:44 -07:00
Andrew Kelley
b78b2689ed
Merge pull request #19655 from squeek502/windows-argv-post-2008
ArgIteratorWindows: Match post-2008 C runtime rather than `CommandLineToArgvW`
2024-04-15 15:28:33 -07:00
Ryan Liptak
cffe1999c6 windows_argv standalone test: Only test against MSVC if it's available 2024-04-15 02:09:48 -07:00
Ryan Liptak
f4c4c04f1c ArgIteratorWindows: Match post-2008 C runtime rather than CommandLineToArgvW
On Windows, the command line arguments of a program are a single WTF-16 encoded string and it's up to the program to split it into an array of strings. In C/C++, the entry point of the C runtime takes care of splitting the command line and passing argc/argv to the main function.

https://github.com/ziglang/zig/pull/18309 updated ArgIteratorWindows to match the behavior of CommandLineToArgvW, but it turns out that CommandLineToArgvW's behavior does not match the behavior of the C runtime post-2008. In 2008, the C runtime argv splitting changed how it handles consecutive double quotes within a quoted argument (it's now considered an escaped quote, e.g. `"foo""bar"` post-2008 would get parsed into `foo"bar`), and the rules around argv[0] were also changed.

This commit makes ArgIteratorWindows match the behavior of the post-2008 C runtime, and adds a standalone test that verifies the behavior matches both the MSVC and MinGW argv splitting exactly in all cases (it checks that randomly generated command line strings get split the same way).

The motivation here is roughly the same as when the same change was made in Rust (https://github.com/rust-lang/rust/pull/87580), that is (paraphrased):

- Consistent behavior between Zig and modern C/C++ programs
- Allows users to escape double quotes in a way that can be more straightforward

Additionally, the suggested mitigation for BatBadBut (https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/) relies on the post-2008 argv splitting behavior for roundtripping of the arguments given to `cmd.exe`. Note: it's not necessary for the suggested mitigation to work, but it is necessary for the suggested escaping to be parsed back into the intended argv by ArgIteratorWindows after being run through a `.bat` file.
2024-04-15 02:09:48 -07:00
Andrew Kelley
b30ad74908 remove deprecated LazyPath.path union tag 2024-04-11 14:02:47 -07:00
Andrew Kelley
7fb5a0b18b introduce std.Build.path; deprecate LazyPath.relative
This adds the *std.Build owner to LazyPath so that lazy paths returned
from a dependency can be used in the application without friction or
footguns.

closes #19313
2024-04-10 15:02:20 -07:00
Carl Åstholm
33b8fdb6bc Turn "simple" standalone test cases into a package 2024-04-07 16:05:54 -07:00
Carl Åstholm
c3ecc6972e Don't add standalone test cases until we've built stage3 2024-04-07 16:05:54 -07:00
Carl Åstholm
d6ecfa7025 Move "simple" standalone test cases to a new directory 2024-04-07 16:05:54 -07:00
Carl Åstholm
3ed221f149 Promote standalone test cases to packages
This is a prerequisite for removing `b.anonymousDependency()`, but
having compiler tests dogfood package management might be a good idea
in general.
2024-04-07 16:05:53 -07:00
Carl Åstholm
eee5400b7d Account for dependency boundaries when duping headers
This is a temporary workaround that can be revered if/when 'path'
lazy paths are updated to encode which build root they are relative to.
2024-04-07 15:34:47 +02:00