clang 24.0.0git
Utils.cpp
Go to the documentation of this file.
1//===- Utils.cpp - Shared utilities for SSAF tools ------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/STLExtras.h"
11#include "llvm/ADT/SmallVector.h"
12#include "llvm/Support/CommandLine.h"
13#include "llvm/Support/DynamicLibrary.h"
14#include "llvm/Support/Error.h"
15#include "llvm/Support/FileSystem.h"
16#include "llvm/Support/FormatVariadic.h"
17#include "llvm/Support/Path.h"
18#include "llvm/Support/Process.h"
19#include "llvm/Support/WithColor.h"
20#include "llvm/Support/raw_ostream.h"
21#include <cassert>
22#include <memory>
23#include <string>
24
25using namespace clang::ssaf;
26
27namespace fs = llvm::sys::fs;
28namespace path = llvm::sys::path;
29
30namespace {
31
32//===----------------------------------------------------------------------===//
33// Error Messages
34//===----------------------------------------------------------------------===//
35
36namespace ErrorMessages {
37
38constexpr const char *CannotValidatePath = "failed to validate path '{0}': {1}";
39
40constexpr const char *ExtensionNotSupplied = "Extension not supplied";
41
42constexpr const char *NoFormatForExtension =
43 "No format registered for extension '{0}'";
44
45constexpr const char *PathDoesNotExist = "Path does not exist";
46
47constexpr const char *PathIsNotAFile = "Path is not a file";
48
49constexpr const char *OutputDirectoryMissing =
50 "Parent directory does not exist";
51
52constexpr const char *OutputDirectoryNotWritable =
53 "Parent directory is not writable";
54
55constexpr const char *FileAlreadyExists = "File already exists";
56
57constexpr const char *FailedToLoadPlugin = "failed to load plugin '{0}': {1}";
58
59constexpr const char *InvalidTargetTriple =
60 "invalid {0} '{1}': unrecognized architecture";
61
62} // namespace ErrorMessages
63
64llvm::StringRef ToolName;
65llvm::StringRef ToolVersion;
66
67void printVersion(llvm::raw_ostream &OS) {
68 OS << ToolName << " " << ToolVersion << "\n";
69}
70
71// Returns the SerializationFormat registered for \p Extension, or nullptr if
72// none is registered. Results are cached for the lifetime of the process.
73// FIXME: This will be revisited after we add support for registering formats
74// with extensions.
75SerializationFormat *getFormatForExtension(llvm::StringRef Extension) {
76 // This cache is not thread-safe. SSAF tools are single-threaded CLIs, so
77 // concurrent calls to this function are not expected.
78
79 // Realistically, we don't expect to encounter more than four registered
80 // formats.
81 static llvm::SmallVector<
82 std::pair<std::string, std::unique_ptr<SerializationFormat>>, 4>
83 ExtensionFormatList;
84
85 // Most recently used format is most likely to be reused again.
86 auto ReversedList = llvm::reverse(ExtensionFormatList);
87 auto It = llvm::find_if(ReversedList, [&](const auto &Entry) {
88 return Entry.first == Extension;
89 });
90 if (It != ReversedList.end()) {
91 return It->second.get();
92 }
93
94 if (!isFormatRegistered(Extension)) {
95 return nullptr;
96 }
97
98 auto Format = makeFormat(Extension);
99 SerializationFormat *Result = Format.get();
100 assert(Result &&
101 "makeFormat must return non-null for a registered extension");
102
103 ExtensionFormatList.emplace_back(Extension, std::move(Format));
104
105 return Result;
106}
107
108FormatFile fromPath(llvm::StringRef Path) {
109 llvm::StringRef Extension = path::extension(Path);
110 if (Extension.empty()) {
111 fail(ErrorMessages::CannotValidatePath, Path,
112 ErrorMessages::ExtensionNotSupplied);
113 }
114
115 Extension = Extension.drop_front();
116 SerializationFormat *Format = getFormatForExtension(Extension);
117 if (!Format) {
118 std::string BadExtension =
119 llvm::formatv(ErrorMessages::NoFormatForExtension, Extension);
120 fail(ErrorMessages::CannotValidatePath, Path, BadExtension);
121 }
122
123 return {Path.str(), Format};
124}
125
126} // namespace
127
128llvm::StringRef clang::ssaf::getToolName() { return ToolName; }
129
130[[noreturn]] void clang::ssaf::fail(const char *Msg) {
131 llvm::WithColor::error(llvm::errs(), ToolName) << Msg << "\n";
132 llvm::sys::Process::Exit(1);
133}
134
135[[noreturn]] void clang::ssaf::fail(llvm::Error Err) {
136 std::string Message = llvm::toString(std::move(Err));
137 clang::ssaf::fail(Message.data());
138}
139
141 for (const std::string &PluginPath : Paths) {
142 if (!fs::exists(PluginPath)) {
143 fail(ErrorMessages::FailedToLoadPlugin, PluginPath,
144 ErrorMessages::PathDoesNotExist);
145 }
146 std::string ErrMsg;
147 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(PluginPath.c_str(),
148 &ErrMsg)) {
149 fail(ErrorMessages::FailedToLoadPlugin, PluginPath, ErrMsg);
150 }
151 }
152}
153
154llvm::Triple clang::ssaf::parseTargetTripleOrFail(llvm::StringRef FlagName,
155 llvm::StringRef Value) {
156 assert(!Value.empty() &&
157 "parseTargetTripleOrFail: triple value cannot be empty");
158
159 // Normalize so the components are moved to their proper places.
160 llvm::Triple T(llvm::Triple::normalize(Value));
161
162 // Only the architecture is validated. Validating vendor or OS rejects real
163 // targets like x86_64-unknown-linux-gnu. A misspelled vendor or OS is instead
164 // caught as a triple mismatch during linking or library creation.
165 if (T.getArch() == llvm::Triple::UnknownArch) {
166 fail(ErrorMessages::InvalidTargetTriple, FlagName, Value);
167 }
168
169 return T;
170}
171
172void clang::ssaf::initTool(int argc, const char **argv, llvm::StringRef Version,
173 llvm::cl::OptionCategory &Category,
174 llvm::StringRef ToolHeading) {
175 // path::stem strips the .exe extension on Windows so ToolName is consistent.
176 ToolName = path::stem(argv[0]);
177
178 // Set tool version for the version printer.
179 ToolVersion = Version;
180
181 // Hide options unrelated to the tool from --help output.
182 llvm::cl::HideUnrelatedOptions(Category);
183
184 // Register a custom version printer for the --version flag.
185 llvm::cl::SetVersionPrinter(printVersion);
186
187 // Parse command-line arguments and exit with an error if they are invalid.
188 std::string Overview = (ToolHeading + "\n").str();
189 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
190}
191
194 if (!fs::exists(Path)) {
195 fail(ErrorMessages::CannotValidatePath, Path,
196 ErrorMessages::PathDoesNotExist);
197 }
198
199 if (!fs::is_regular_file(Path)) {
200 fail(ErrorMessages::CannotValidatePath, Path,
201 ErrorMessages::PathIsNotAFile);
202 }
203
204 return fromPath(Path);
205}
206
209 if (fs::exists(Path)) {
210 fail(ErrorMessages::CannotValidatePath, Path,
211 ErrorMessages::FileAlreadyExists);
212 }
213
214 llvm::StringRef ParentDir = path::parent_path(Path);
215 llvm::StringRef DirToCheck = ParentDir.empty() ? "." : ParentDir;
216
217 if (!fs::exists(DirToCheck)) {
218 fail(ErrorMessages::CannotValidatePath, Path,
219 ErrorMessages::OutputDirectoryMissing);
220 }
221
222 if (fs::access(DirToCheck, fs::AccessMode::Write)) {
223 fail(ErrorMessages::CannotValidatePath, Path,
224 ErrorMessages::OutputDirectoryNotWritable);
225 }
226
227 return fromPath(Path);
228}
Result
Implement __builtin_bit_cast and related operations.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
llvm::StringRef getToolName()
Returns the name of the running tool, as set by initTool().
Definition Utils.cpp:128
std::unique_ptr< SerializationFormat > makeFormat(llvm::StringRef FormatName)
Try to instantiate a SerializationFormat with a given name.
llvm::Triple parseTargetTripleOrFail(llvm::StringRef FlagName, llvm::StringRef Value)
Parses and validates a target triple supplied on the command line.
Definition Utils.cpp:154
void fail(const char *Msg)
Definition Utils.cpp:130
void initTool(int argc, const char **argv, llvm::StringRef Version, llvm::cl::OptionCategory &Category, llvm::StringRef ToolHeading)
Sets ToolName, ToolVersion, and the version printer, hides unrelated command-line options,...
Definition Utils.cpp:172
llvm::json::Value Value
bool isFormatRegistered(llvm::StringRef FormatName)
Check if a SerializationFormat was registered with a given name.
void loadPlugins(llvm::ArrayRef< std::string > Paths)
Definition Utils.cpp:140
const FunctionProtoType * T
#define noreturn
Definition stdnoreturn.h:17
static FormatFile fromInputPath(llvm::StringRef Path)
Validates an input path and returns a FormatFile.
Definition Utils.cpp:193
static FormatFile fromOutputPath(llvm::StringRef Path)
Validates an output path and returns a FormatFile.
Definition Utils.cpp:208
std::string Path
Definition Utils.h:98