1 /*
2 * Copyright 2020, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <cstdio>
18 #include <cstdlib>
19 #include <string>
20 #include <vector>
21 #include <unistd.h>
22
main(int argc,const char ** argv)23 int main(int argc, const char **argv) {
24 // Create a copy of argv strings that we can modify, and then eventually
25 // const_cast away the const-ness of the buffers to call execv().
26 std::vector<std::unique_ptr<std::string>> argv_strings;
27 std::vector<const char *> argv_chars;
28
29 // Replace lld.exe with lld-bin\lld.exe instead on Windows.
30 argv_strings.push_back(std::make_unique<std::string>(argv[0]));
31 size_t idx = argv_strings[0]->rfind("lld.exe");
32 argv_strings[0]->insert(idx, "lld-bin\\");
33 argv_chars.push_back(argv_strings[0]->c_str());
34
35 // Make a copy of every other argv entry, and map a pointer to the C string
36 // buffer as argv_chars for use with execv() later.
37 for (int i = 1; i < argc; ++i) {
38 argv_strings.push_back(std::make_unique<std::string>(argv[i]));
39 argv_chars.push_back(argv_strings[i]->c_str());
40 }
41
42 // execv() expects a nullptr to terminate the argument list for argv.
43 argv_chars.push_back(nullptr);
44
45 // We cast away the const-ness of the char buffers, but it should be safe,
46 // since we own these strings.
47 int status = execv(argv_chars[0], const_cast<char **>(argv_chars.data()));
48
49 // We shouldn't get here unless we failed to execute the new binary.
50 if (status != 0) {
51 std::string command;
52 bool first = true;
53 for (auto arg : argv_chars) {
54 if (arg) {
55 if (!first) {
56 command.append(" ");
57 } else {
58 first = false;
59 }
60 command.append(arg);
61 }
62 }
63 fprintf(stderr, "Failed to execute command: %s\n", command.c_str());
64 }
65 return status;
66 }
67