Add GetTempPath2W function

Recently I needed an API for writing a temporary file, so I started to check what API was available on Windows for getting the path to a temporary directory.

I found https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2w.html.

This API was added in Windows 11 but was also added to Windows 10.

I think that GetTempPath2W should be added to lib/std/os/windows/kernel32.zig.

What do you think?

Thanks

The goal is to reduce the amount of kernel32 bindings, not add more. Relevant issues:

Note also that bindings do not have to be part of the standard library for you to be able to use them. They can go in your project’s source and it’ll work just fine.

2 Likes

If you already have some sort of cache path for your application you also could consider copying std.testing.tmpDir and adapt it towards using that application specific cache path or possibly using something like GitHub - ziglibs/known-folders: Provides access to well-known folders across several operating systems to get the cache parent directory, that way you would have a cross platform solution.

GetTempPath2W is necessary in case a general purpose API for writing temporary files is implemented.

The Go std, as an example, do use GetTempPath2W is it is available.

If there’s a need for a general purpose API for writing temporary files in the standard library, then the linked issues above still apply. Adding bindings for GetTempPath2W would still be discouraged, and instead the goal would be to re-implement the functionality using lower-level ntdll syscalls (I typically use NtTrace to see what a function is doing for this purpose).

Again, though, if you need this function, you can just put this in your project and use it:

const std = @import("std");
const windows = std.os.windows;

pub extern "kernel32" fn GetTempPath2W(
    BufferLength: windows.DWORD,
    Buffer: windows.LPWSTR,
) callconv(.winapi) windows.DWORD;

For my simple application the cache directory is ok, but I want a more specialized API, and using the OS temporary directory seems a better choice.

One problem is that I’m not sure how GetTempPath2W fixed the problem in case the user have admin role.

Thanks.

What problem do you mean? The behavior of GetTempPath2W is clearly documented.

I mean:

The reason GetTempPath2 exists and defaults to returning C:\Windows\SystemTemp is because that directory is ACL’d with the correct permissions to prevent common path redirection issues. For security reasons, only set the SystemTemp environment variable to a directory with permissions that only allow for a SYSTEM process/administrator to access it.

I’m not sure how common path redirection is a security issue.