summaryrefslogtreecommitdiff
path: root/llvm/lib/Support/Path.cpp
AgeCommit message (Collapse)Author
2025-10-01[llvm][support] Move `make_absolute` from `sys::fs` to `sys::path` (#161459)Jan Svoboda
The `llvm::sys::fs::make_absolute(const Twine &, SmallVectorImpl<char> &)` functions doesn't perform any FS access - it only modifies the second parameter via path/string operations. This function should live in the `llvm::sys::path` namespace for consistency and for making it easier to spot function calls that perform IO.
2025-04-26[llvm] Use llvm::replace (NFC) (#137481)Kazu Hirata
2024-11-20[Support] Remove unused includes (NFC) (#116752)Kazu Hirata
Identified with misc-include-cleaner.
2024-03-08[llvm][Support] Add and use errnoAsErrorCode (#84423)Michael Spencer
LLVM is inconsistent about how it converts `errno` to `std::error_code`. This can cause problems because values outside of `std::errc` compare differently if one is system and one is generic on POSIX systems. This is even more of a problem on Windows where use of the system category is just wrong, as that is for Windows errors, which have a completely different mapping than POSIX/generic errors. This patch fixes one instance of this mistake in `JSONTransport.cpp`. This patch adds `errnoAsErrorCode()` which makes it so people do not need to think about this issue in the future. It also cleans up a lot of usage of `errno` in LLVM and Clang.
2024-02-29[Support] Use all_read | all_write for createTemporaryFile (#83360)Jonas Devlieghere
In a04879ce7dd6, dsymutil switched from using TempFile to createTemporaryFile. This caused a regression because the two use different permissions: - TempFile opens the file as all_read | all_write - createTemporaryFile opens the file as owner_read | owner_write The latter turns out to be problematic for dsymutil because it either promotes the temporary to a proper output file, or it would pass it to `lipo` to create a universal binary and `lipo` preserves the permissions of the input files. Either way, this caused issues when the build system was run as a different user than the one ingesting the resulting binaries. I did some version control archeology and I couldn't find evidence that these permissions were chosen purposely. Both could be considered reasonable default. This patch changes the permissions to `all read | all write` to make the two consistent and match the one currently used by the higher level abstraction (TempFile). rdar://123722848
2024-01-18[Path] Fix off-by-one in finding filename for win style paths (#78055)Matheus Izvekov
This fixes a crash where `path::parent_path` causes an invalid access on a string upon receiving a path that consists of a single colon. On Windows machine, with runtime checks enabled build, upon `clang -I: test.cc` produces: ``` Assertion failed: Index < Length && "Invalid index!", file llvm\include\llvm/ADT/StringRef.h, line 232 ... #6 0x00007ff7816201eb `anonymous namespace'::parent_path_end llvm\lib\Support\Path.cpp:144:0 #7 0x00007ff781620135 llvm::sys::path::parent_path(class llvm::StringRef, enum llvm::sys::path::Style) llvm\lib\Support\Path.cpp:470:0 ``` Ideally, we can look for the last colon starting from the last character, but we can instead start from second to last, and handle empty paths by abusing `0 - 1 == npos`.
2024-01-17[Support] Use SmallString::operator std::string (NFC)Kazu Hirata
2023-11-03[Support] Use StringRef::starts_with/ends_with instead of ↵Simon Pilgrim
startswith/endswith. NFC. startswith/endswith wrap starts_with/ends_with and will eventually go away (to more closely match string_view)
2023-06-25[llvm] Add missing StringExtras.h includesElliot Goodrich
In preparation for removing the `#include "llvm/ADT/StringExtras.h"` from the header to source file of `llvm/Support/Error.h`, first add in all the missing includes that were previously included transitively through this header.
2023-05-11llvm/lib: Use <cerrno> explicitly since D146395 has hidden `errno`NAKAMURA Takumi
Differential Revision: https://reviews.llvm.org/D149513
2023-02-10[llvm-driver] Reinvoke clang as described by llvm driver extra argsAlex Brachet
Differential Revision: https://reviews.llvm.org/D137800
2023-01-16[llvm][ADT] Replace uses of `makeMutableArrayRef` with deduction guidesJoe Loser
Similar to how `makeArrayRef` is deprecated in favor of deduction guides, do the same for `makeMutableArrayRef`. Once all of the places in-tree are using the deduction guides for `MutableArrayRef`, we can mark `makeMutableArrayRef` as deprecated. Differential Revision: https://reviews.llvm.org/D141814
2023-01-05Move from llvm::makeArrayRef to ArrayRef deduction guides - llvm/ partserge-sans-paille
Use deduction guides instead of helper functions. The only non-automatic changes have been: 1. ArrayRef(some_uint8_pointer, 0) needs to be changed into ArrayRef(some_uint8_pointer, (size_t)0) to avoid an ambiguous call with ArrayRef((uint8_t*), (uint8_t*)) 2. CVSymbol sym(makeArrayRef(symStorage)); needed to be rewritten as CVSymbol sym{ArrayRef(symStorage)}; otherwise the compiler is confused and thinks we have a (bad) function prototype. There was a few similar situation across the codebase. 3. ADL doesn't seem to work the same for deduction-guides and functions, so at some point the llvm namespace must be explicitly stated. 4. The "reference mode" of makeArrayRef(ArrayRef<T> &) that acts as no-op is not supported (a constructor cannot achieve that). Per reviewers' comment, some useless makeArrayRef have been removed in the process. This is a follow-up to https://reviews.llvm.org/D140896 that introduced the deduction guides. Differential Revision: https://reviews.llvm.org/D140955
2022-06-06LLVM Driver Multicall toolChris Bieneman
This patch adds an llvm-driver multicall tool that can combine multiple LLVM-based tools. The build infrastructure is enabled for a tool by adding the GENERATE_DRIVER option to the add_llvm_executable CMake call, and changing the tool's main function to a canonicalized tool_name_main format (i.e. llvm_ar_main, clang_main, etc...). As currently implemented llvm-driver contains dsymutil, llvm-ar, llvm-cxxfilt, llvm-objcopy, and clang (if clang is included in the build). llvm-driver can be enabled from builds by setting LLVM_TOOL_LLVM_DRIVER_BUILD=On. There are several limitations in the current implementation, which can be addressed in subsequent patches: (1) the multicall binary cannot currently properly handle multi-dispatch tools. This means symlinking llvm-ranlib to llvm-driver will not properly result in llvm-ar's main being called. (2) the multicall binary cannot be comprised of tools containing conflicting cl::opt options as the global cl::opt option list cannot contain duplicates. These limitations can be addressed in subsequent patches. Differential revision: https://reviews.llvm.org/D109977
2022-06-02Fix a buglet in remove_dots().Paul Pluzhnikov
The function promises to canonicalize the path, but neglected to do so for the root component. For example, calling remove_dots("/tmp/foo.c", Style::windows_backslash) resulted in "/tmp\foo.c". Now it produces "\tmp\foo.c". Also fix FIXME in the corresponding test. Reviewed By: rnk Differential Revision: https://reviews.llvm.org/D126412
2022-03-11Cleanup include: TableGenserge-sans-paille
This also includes a few cleanup from Support. Discourse thread: https://discourse.llvm.org/t/include-what-you-use-include-cleanup Differential Revision: https://reviews.llvm.org/D121331
2022-01-27[Support] [Windows] Don't cancel delete if we failed to set deleteShezan Baig
Following up on commit 177176f75c6fa3f624d6d964b9d340ce39511565, if we failed to setDeleteDisposition(true) during TempFile creation, then don't try to setDeleteDisposition(false) during TempFile::keep, since it will likely fail as well. Instead of letting TempFile::keep just fail, we should let it go ahead and try renaming the file. This fixes an issue we are seeing when running clang-cl.exe through the Incredibuild distributed build system. We're seeing that renaming temporary object files would fail here: https://github.com/llvm/llvm-project/blob/5c1f7b296ac0dddeca02891976e6ab5cfc006719/clang/lib/Frontend/CompilerInstance.cpp#L789 Reviewed By: mstorsjo Differential Revision: https://reviews.llvm.org/D118212
2022-01-11Support: Extract sys::fs::readNativeFileToEOF() from MemoryBufferDuncan P. N. Exon Smith
Extract the `readNativeFile()` loop from `MemoryBuffer::getMemoryBufferForStream()` into `readNativeFileToEOF()` to allow reuse. The chunk size is configurable; the default of `4*4096` is exposed as `sys::fs::DefaultReadChunkSize` to allow sizing of SmallVectors. There's somewhere I'd like to read a usually-small file without overhead of a MemoryBuffer; extracting existing logic rather than duplicating it. Differential Revision: https://reviews.llvm.org/D115397
2021-12-08Support: Avoid using SmallVector::set_size() in sys::pathDuncan P. N. Exon Smith
Stop using `SmallVector::set_size()` in sys::path APIs. In both cases, use `truncate()` instead. Differential Revision: https://reviews.llvm.org/D115391
2021-11-05[Support] Allow configuring the preferred type of slashes on WindowsMartin Storsjö
Default to preferring forward slashes when built for MinGW, as many usecases, when e.g. Clang is used as a drop-in replacement for GCC, requires the compiler to output paths with forward slashes. Not all tests pass yet, if configuring to prefer forward slashes though. Differential Revision: https://reviews.llvm.org/D112787
2021-11-05[Support] Add a new path style for Windows with forward slashesMartin Storsjö
This behaves just like the regular Windows style, with both separator forms accepted, but with get_separator() returning forward slashes. Add a more descriptive name for the existing style, keeping the old name around as an alias initially. Add a new function `make_preferred()` (like the C++17 `std::filesystem::path` function with the same name), which converts windows paths to the preferred separator form (while this one works on any platform and takes a `path::Style` argument). Contrary to `native()` (just like `make_preferred()` in `std::filesystem`), this doesn't do anything at all on Posix, it doesn't try to reinterpret backslashes into forward slashes there. Differential Revision: https://reviews.llvm.org/D111879
2021-11-03[Support] [Windows] Use RemoveFileOnSignal if unable to use the ↵Martin Storsjö
delete-on-close flag This takes care of cleaning up the temp files on crashes. It doesn't handle cleanup when explicitly killed though. Differential Revision: https://reviews.llvm.org/D112710
2021-10-29Support: Use sys::path::is_style_{posix,windows}() in a few placesDuncan P. N. Exon Smith
Use the new sys::path::is_style_posix() and is_style_windows() in a few places that need to detect the system's native path style. In llvm/lib/Support/Path.cpp, this patch removes most uses of the private `real_style()`, where is_style_posix() and is_style_windows() are just a little tidier. Elsewhere, this removes `_WIN32` macro checks. Added a FIXME to a FileManagerTest that seemed fishy, but maintained the existing behaviour. Differential Revision: https://reviews.llvm.org/D112289
2021-10-29Support: Expose sys::path::is_style_{posix,windows,native}()Duncan P. N. Exon Smith
Expose three helpers in namespace llvm::sys::path to detect the path rules followed by sys::path::Style. - is_style_posix() - is_style_windows() - is_style_native() This are constexpr functions that that will allow a bunch of path-related code to stop checking `_WIN32`. Originally I looked at adding system_style(), analogous to sys::endian::system_endianness(), but future patches (from others) will add more Windows style variants for slash preferences. These helpers should be resilient to that change, allowing callers to detect basic path rules. Differential Revision: https://reviews.llvm.org/D112288
2021-10-28[Support] [Windows] Manually clean up temp files if not setting delete ↵Martin Storsjö
disposition Since D81803 / 79657e2339b58bc01fe1b85a448bb073d57d90bb, temp files created on network shares don't set "Disposition.DeleteFile = true". This flag normally takes care of removing the temp file both if the process exits abnormally (either crashing or killed externally), and when the file is closed cleanly. For network shares, we voluntarily choose to not set the flag, and if the operation to inspect the file handle (as a prerequisite to setting the flag since 79657e2339b58bc01fe1b85a448bb073d57d90bb) fails we also error out. In both of these cases, we can at least make sure to remove the temp files when they are closed cleanly. Adjust the semantics of "OF_Delete" to not set the delete disposition, but only set the access mode for allowing deletion. Move the call to setDeleteDisposition into TempFile::create, where we can check if it failed, and if it did, set a flag noting that the file should be removed manually at the end. This does leak files on crash, but at least doesn't leak files in regular successful runs. (Technically, the alternative codepath could use the RemoveFileOnSignal function, but that might complicate the TempFile implementation further.) This fixes https://github.com/mstorsjo/llvm-mingw/issues/233 and https://bugs.llvm.org/show_bug.cgi?id=52080. Differential Revision: https://reviews.llvm.org/D111875
2021-10-13[Support] [Path] Use std::replace instead of an explicit comparison loop. NFC.Martin Storsjö
After 8fc7a907b93a8e9eef96e872f8f926db3ebfe9b6, this loop does the same as a plain `std::replace`. Also clarify the comment about what this function does. Differential Revision: https://reviews.llvm.org/D111730
2021-06-08[SystemZ][z/OS] Pass OpenFlags when creating tmp filesAbhina Sreeskantharajan
This patch https://reviews.llvm.org/D102876 caused some lit regressions on z/OS because tmp files were no longer being opened based on binary/text mode. This patch passes OpenFlags when creating tmp files so we can open files in different modes. Reviewed By: amccarth Differential Revision: https://reviews.llvm.org/D103806
2021-06-02Recommit "Fix tmp files being left on Windows builds." with a fix forAmy Huang
incorrect std::string use. (Also remove redundant call to RemoveFileOnSignal.) Clang writes object files by first writing to a .tmp file and then renaming to the final .obj name. On Windows, if a compile is killed partway through the .tmp files don't get deleted. Currently it seems like RemoveFileOnSignal takes care of deleting the tmp files on Linux, but on Windows we need to call setDeleteDisposition on tmp files so that they are deleted when closed. This patch switches to using TempFile to create the .tmp files we write when creating object files, since it uses setDeleteDisposition on Windows. This change applies to both Linux and Windows for consistency. Differential Revision: https://reviews.llvm.org/D102876 This reverts commit 20797b129f844d4b12ffb2b12cf33baa2d42985c.
2021-06-01Revert "Fix tmp files being left on Windows builds." for now;Amy Huang
causing some asan test failures. This reverts commit 7daa18215905c831e130c7542f17619e9d936dfc.
2021-06-01Fix tmp files being left on Windows builds.Amy Huang
Clang writes object files by first writing to a .tmp file and then renaming to the final .obj name. On Windows, if a compile is killed partway through the .tmp files don't get deleted. Currently it seems like RemoveFileOnSignal takes care of deleting the tmp files on Linux, but on Windows we need to call setDeleteDisposition on tmp files so that they are deleted when closed. This patch switches to using TempFile to create the .tmp files we write when creating object files, since it uses setDeleteDisposition on Windows. This change applies to both Linux and Windows for consistency. Differential Revision: https://reviews.llvm.org/D102876
2021-04-09Support: Remove code duplication for mapped_file_region accessors, NFCDuncan P. N. Exon Smith
2021-03-19[SystemZ][z/OS] Distinguish between text and binary files on z/OSAbhina Sreeskantharajan
This patch consists of the initial changes to help distinguish between text and binary content correctly on z/OS. I would like to get feedback from Windows users on setting OF_None for all ToolOutputFiles. This seems to have been done as an optimization to prevent CRLF translation on Windows in the past. Reviewed By: zibi Differential Revision: https://reviews.llvm.org/D97785
2020-10-21[llvm] Use early exits and get rid of if-return-else-return pattern; NFCKirill Bobyrev
https://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code Reviewed By: kadircet Differential Revision: https://reviews.llvm.org/D89857
2020-10-19Revert "Reland "[Modules] Add stats to measure performance of building and ↵Volodymyr Sapsai
loading modules."" This reverts commit 4000c9ee18ecebe3ff0f197af8c1fb434ad986e5. Test "LLVM :: Other/statistic.ll" is failing on Windows.
2020-10-19Reland "[Modules] Add stats to measure performance of building and loading ↵Volodymyr Sapsai
modules." Measure amount of high-level or fixed-cost operations performed during building/loading modules and during header search. High-level operations like building a module or processing a .pcm file are motivated by previous issues where clang was re-building modules or re-reading .pcm files unnecessarily. Fixed-cost operations like `stat` calls are tracked because clang cannot change how long each operation takes but it can perform fewer of such operations to improve the compile time. Also tracking such stats over time can help us detect compile-time regressions. Added stats are more stable than the actual measured compilation time, so expect the detected regressions to be less noisy. On relanding drop stats in MemoryBuffer.cpp as their value is pretty low but affects a lot of clients and many of those aren't interested in modules and header search. rdar://problem/55715134 Reviewed By: aprantl, bruno Differential Revision: https://reviews.llvm.org/D86895
2020-09-24Revert "[Modules] Add stats to measure performance of building and loading ↵Volodymyr Sapsai
modules." This reverts commit c4bacc3c9b333bb7032fb96f41d6f5b851623132. Test "LLVM :: ThinLTO/X86/funcimport-stats.ll" is failing. Reverting now and will recommit after making the test not fail with the added stats.
2020-09-24[Modules] Add stats to measure performance of building and loading modules.Volodymyr Sapsai
Measure amount of high-level or fixed-cost operations performed during building/loading modules and during header search. High-level operations like building a module or processing a .pcm file are motivated by previous issues where clang was re-building modules or re-reading .pcm files unnecessarily. Fixed-cost operations like `stat` calls are tracked because clang cannot change how long each operation takes but it can perform fewer of such operations to improve the compile time. Also tracking such stats over time can help us detect compile-time regressions. Added stats are more stable than the actual measured compilation time, so expect the detected regressions to be less noisy. rdar://problem/55715134 Reviewed By: aprantl, bruno Differential Revision: https://reviews.llvm.org/D86895
2020-09-23[Support/Path] Add path::is_absolute_gnuVinicius Tinti
Implements IS_ABSOLUTE_PATH from GNU tools. C++17 is_absolute behavior is different the from the behavior defined by GNU tools. According to cppreference.com, C++17 states: "An absolute path is a path that unambiguously identifies the location of a file without reference to an additional starting location." In other words, the rules are: 1. POSIX style paths with nonempty root directory are absolute. 2. Windows style paths with nonempty root name and root directory are absolute. 3. No other paths are absolute. GNU rules are: 1. Paths starting with a path separator are absolute. 2. Windows style paths are also absolute if they start with a character followed by ':'. 3. No other paths are absolute. On Windows style the path "C:\Users\Default" has "C:" as root name and "\" as root directory. Hence "C:" on Windows is absolute under GNU rules and not absolute under C++17 because it has no root directory. Likewise "/" and "\" on Windows are absolute under GNU and are not absolute under C++17 due to empty root name. Related to PR46368. Differential Revision: https://reviews.llvm.org/D87667
2020-05-13[Clang] Restore replace_path_prefix instead of startswithSylvain Audi
In D49466, sys::path::replace_path_prefix was used instead startswith for -f[macro/debug/file]-prefix-map options. However those were reverted later (commit rG3bb24bf25767ef5bbcef958b484e7a06d8689204) due to broken Windows tests. This patch restores those replace_path_prefix calls. It also modifies the prefix matching to be case-insensitive under Windows. Differential Revision : https://reviews.llvm.org/D76869
2020-05-05Let normalize() for posix style convert backslash to slash unconditionally.Nico Weber
Currently, normalize() for posix replaces backslashes to slashes, except that two backslashes in sequence are kept as-is. clang calls normalize() to convert \ to / is microsoft compat mode. This generally works well, but a path like "c:\\foo\\bar.h" with two backslashes doesn't work due to the exception in normalize(). These paths happen naturally on Windows hosts with e.g. `#include __FILE__`, and them not working on other hosts makes it more difficult to write tests for this case. The special case has been around without justification since this code was added in r203611 (since then moved around in r215241 r215243). No integration tests fail if I remove it. Try removing the special case. Differential Revision: https://reviews.llvm.org/D79265
2020-05-04Re-land "Optimize path::remove_dots"Reid Kleckner
This reverts commit fb5fd74685e728b1d5e68d33e9842bcd734b98e6. Re-instates commit 53913a65b408ade2956061b4c0aaed6bba907403 The fix is to trim off trailing separators, as in `/foo/bar/` and produce `/foo/bar`. VFS tests rely on this. I added unit tests for remove_dots.
2020-05-03Revert "Optimize path::remove_dots"Nico Weber
This reverts commit 53913a65b408ade2956061b4c0aaed6bba907403. Breaks VFSFromYAMLTest.DirectoryIterationSameDirMultipleEntries in SupportTests on non-Windows.
2020-05-03Optimize path::remove_dotsReid Kleckner
LLD calls this on every source file string in every object file when writing PDBs, so it is somewhat hot. Avoid rewriting paths that do not contain path traversal components (./..). Use find_first_not_of(separators) directly instead of using the path iterators. The path component iterators appear to be slow, and directly searching for slashes makes it easier to find double separators that need to be canonicalized. I discovered that the VFS relies on remote_dots to not canonicalize early slashes (/foo or C:/foo) on Windows, so I had to leave that behavior behind with unit tests for it. This is undesirable, but I claim that my change is NFC.
2020-04-03[Support/Path] sys::path::replace_path_prefix fix and simplificationsSylvain Audi
Added unit tests for 2 scenarios that were failing. Made replace_path_prefix back to 3 parameters instead of 5, simplifying the implementation. The other 2 were always used with the default value. This commit is intended to be the first of 3: 1) simplify/fix replace_path_prefix. 2) use it in the context of -fdebug-prefix-map and -fmacro-prefix-map (see D76869). 3) Make Windows version of replace_path_prefix insensitive to both case and separators (slash vs backslash). Differential Revision: https://reviews.llvm.org/D77223
2020-02-10Revert "Remove redundant "std::move"s in return statements"Bill Wendling
The build failed with error: call to deleted constructor of 'llvm::Error' errors. This reverts commit 1c2241a7936bf85aa68aef94bd40c3ba77d8ddf2.
2020-02-10Remove redundant "std::move"s in return statementsBill Wendling
2020-01-28Make llvm::StringRef to std::string conversions explicit.Benjamin Kramer
This is how it should've been and brings it more in line with std::string_view. There should be no functional change here. This is mostly mechanical from a custom clang-tidy check, with a lot of manual fixups. It uncovers a lot of minor inefficiencies. This doesn't actually modify StringRef yet, I'll do that in a follow-up.
2019-11-26Initial implementation of -fmacro-prefix-map and -ffile-prefix-mapDan McGregor
GCC 8 implements -fmacro-prefix-map. Like -fdebug-prefix-map, it replaces a string prefix for the __FILE__ macro. -ffile-prefix-map is the union of -fdebug-prefix-map and -fmacro-prefix-map Reviewed By: rnk, Lekensteyn, maskray Differential Revision: https://reviews.llvm.org/D49466
2019-08-06[Path] Fix bug in make_absolute logicJonas Devlieghere
This fixes a bug for making path with a //net style root absolute. I discovered the bug while writing a test case for the VFS, which uses these paths because they're both legal absolute paths on Windows and Unix. Differential revision: https://reviews.llvm.org/D65675 llvm-svn: 368053
2019-06-11[Path] Set FD to -1 in moved-from TempFileJonas Devlieghere
When moving a temp file, explicitly set the file descriptor to -1 so we can never accidentally close the moved-from TempFile. Differential revision: https://reviews.llvm.org/D63087 llvm-svn: 363083