<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/56725>56725</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            libc++: possible out-of-bound write when calling `std::filesystem::current_path`
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          quentin
      </td>
    </tr>
</table>

<pre>
    This code may write out of `buff`'s bounds when `pathconf` returns the error code `-1`:

https://github.com/llvm/llvm-project/blob/0d191b7553e7efbf7ce57c77274b83c15b681933/libcxx/src/filesystem/operations.cpp#L1106-L1119

- When `pathconf` returns `(long) -1`, the `new` allocation at line `1109` will allocate a `0` byte long buffer.
- The buffer length argument of `getcwd` is a `std::size_t`.
- At line `1118`, the `size` is converted from signed `(long) -1` to unsigned integer `(std::size_t) SIZE_MAX`.
- The call to `getcwd(ptr, SIZE_MAX)` will overwrite memory starting from `ptr` and up-to `SIZE_MAX` bytes (although the length of the actual current working directory is probably less than `SIZE_MAX` but you see the point). 

I was able to reproduce the issue with XCode 13.2 (reported `libcxx` version is `1200.3.0`). It turns-out that `pathconf` returns `-1` for the `_PC_PATH_MAX` argument.

The issue is probably fixed by libcxx version `>= 13` on the following platforms:
https://github.com/llvm/llvm-project/blob/0d191b7553e7efbf7ce57c77274b83c15b681933/libcxx/src/filesystem/operations.cpp#L1098

The issue remains for other platforms where `pathconf` returns `-1` for `_PC_PATH_MAX`.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzNVFGP4yYQ_jX2C4plQxzbD35Id6_qSq10UlfqqS8RYGzTEuMCvmz66zuDk6zbO53at0oWBgZmvu-bYYTtru3rqD2RtlPkzK_k4nRQxC6B2J4kh1wsfQ-_hFaeCLtMnSeXUU1omnkYpZ3QTJwKi5s8CaMiyjnrVo9g2hV4nR2T_DnJb-MYwuxxj34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