blob: ba11e0125491c850abeaa4082f0b8726e75233ca [file] [log] [blame]
Jan Voung44c3a802015-03-27 16:29:08 -07001//===- subzero/src/IceBrowserCompileServer.cpp - Browser compile server ---===//
2//
3// The Subzero Code Generator
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the browser-based compile server.
11//
12//===----------------------------------------------------------------------===//
13
14// Can only compile this with the NaCl compiler (needs irt.h, and the
15// unsandboxed LLVM build using the trusted compiler does not have irt.h).
16#if PNACL_BROWSER_TRANSLATOR
17
18#include <cstring>
19#include <irt.h>
20#include <irt_dev.h>
Jan Voung2f7f2b72015-06-03 17:50:20 -070021#include <pthread.h>
Jan Voung44c3a802015-03-27 16:29:08 -070022#include <thread>
23
24#include "llvm/Support/QueueStreamer.h"
25
26#include "IceBrowserCompileServer.h"
27
28namespace Ice {
29
30// Create C wrappers around callback handlers for the IRT interface.
31namespace {
32
33BrowserCompileServer *gCompileServer;
34struct nacl_irt_private_pnacl_translator_compile gIRTFuncs;
35
36void getIRTInterfaces() {
37 size_t QueryResult =
38 nacl_interface_query(NACL_IRT_PRIVATE_PNACL_TRANSLATOR_COMPILE_v0_1,
39 &gIRTFuncs, sizeof(gIRTFuncs));
40 if (QueryResult != sizeof(gIRTFuncs))
41 llvm::report_fatal_error("Failed to get translator compile IRT interface");
42}
43
44char *onInitCallback(uint32_t NumThreads, int *ObjFileFDs,
Jan Voung9c1d3862015-03-31 14:14:20 -070045 size_t ObjFileFDCount, char **CLArgs, size_t CLArgsLen) {
Jan Voung44c3a802015-03-27 16:29:08 -070046 if (ObjFileFDCount < 1) {
47 std::string Buffer;
48 llvm::raw_string_ostream StrBuf(Buffer);
49 StrBuf << "Invalid number of FDs for onInitCallback " << ObjFileFDCount
50 << "\n";
51 return strdup(StrBuf.str().c_str());
52 }
53 int ObjFileFD = ObjFileFDs[0];
54 if (ObjFileFD < 0) {
55 std::string Buffer;
56 llvm::raw_string_ostream StrBuf(Buffer);
57 StrBuf << "Invalid FD given for onInitCallback " << ObjFileFD << "\n";
58 return strdup(StrBuf.str().c_str());
59 }
Jan Voung9c1d3862015-03-31 14:14:20 -070060 // CLArgs is almost an "argv", but is missing the argv[0] program name.
61 std::vector<char *> Argv;
62 char ProgramName[] = "pnacl-sz.nexe";
63 Argv.reserve(CLArgsLen + 1);
64 Argv.push_back(ProgramName);
65 for (size_t i = 0; i < CLArgsLen; ++i) {
66 Argv.push_back(CLArgs[i]);
67 }
68 // NOTE: strings pointed to by argv are owned by the caller, but we parse
69 // here before returning and don't store them.
70 gCompileServer->getParsedFlags(NumThreads, Argv.size(), Argv.data());
Jan Voung44c3a802015-03-27 16:29:08 -070071 gCompileServer->startCompileThread(ObjFileFD);
72 return nullptr;
73}
74
75int onDataCallback(const void *Data, size_t NumBytes) {
76 return gCompileServer->pushInputBytes(Data, NumBytes) ? 1 : 0;
77}
78
79char *onEndCallback() {
80 gCompileServer->endInputStream();
81 gCompileServer->waitForCompileThread();
Jan Voung2f7f2b72015-06-03 17:50:20 -070082 // TODO(jvoung): Also return UMA data.
Jan Voung44c3a802015-03-27 16:29:08 -070083 if (gCompileServer->getErrorCode().value()) {
Karl Schimpf2f67b922015-04-22 15:20:16 -070084 const std::string Error = gCompileServer->getErrorStream().getContents();
85 return strdup(Error.empty() ? "Some error occurred" : Error.c_str());
Jan Voung44c3a802015-03-27 16:29:08 -070086 }
87 return nullptr;
88}
89
90struct nacl_irt_pnacl_compile_funcs SubzeroCallbacks {
91 &onInitCallback, &onDataCallback, &onEndCallback
92};
93
94std::unique_ptr<llvm::raw_fd_ostream> getOutputStream(int FD) {
95 if (FD <= 0)
96 llvm::report_fatal_error("Invalid output FD");
97 const bool CloseOnDtor = true;
98 const bool Unbuffered = false;
99 return std::unique_ptr<llvm::raw_fd_ostream>(
100 new llvm::raw_fd_ostream(FD, CloseOnDtor, Unbuffered));
101}
102
Jan Voung2f7f2b72015-06-03 17:50:20 -0700103void fatalErrorHandler(void *UserData, const std::string &Reason,
104 bool GenCrashDialog) {
105 BrowserCompileServer *Server =
106 reinterpret_cast<BrowserCompileServer *>(UserData);
107 Server->setFatalError(Reason);
108 // Only kill the current thread instead of the whole process.
109 // We need the server thread to remain alive in order to respond with the
110 // error message.
111 // We could also try to pthread_kill all other worker threads, but
112 // pthread_kill / raising signals is not supported by NaCl.
113 // We'll have to assume that the worker/emitter threads will be well behaved
114 // after a fatal error in other threads, and either get stuck waiting
115 // on input from a previous stage, or also call report_fatal_error.
116 pthread_exit(0);
117}
118
Jan Voung44c3a802015-03-27 16:29:08 -0700119} // end of anonymous namespace
120
121BrowserCompileServer::~BrowserCompileServer() {}
122
123void BrowserCompileServer::run() {
124 gCompileServer = this;
Jan Voung44c3a802015-03-27 16:29:08 -0700125 getIRTInterfaces();
126 gIRTFuncs.serve_translate_request(&SubzeroCallbacks);
127}
128
129void BrowserCompileServer::getParsedFlags(uint32_t NumThreads, int argc,
130 char **argv) {
131 ClFlags::parseFlags(argc, argv);
132 ClFlags::getParsedClFlags(Flags);
133 ClFlags::getParsedClFlagsExtra(ExtraFlags);
134 // Set some defaults which aren't specified via the argv string.
135 Flags.setNumTranslationThreads(NumThreads);
136 Flags.setUseSandboxing(true);
137 Flags.setOutFileType(FT_Elf);
138 // TODO(jvoung): allow setting different target arches.
139 Flags.setTargetArch(Target_X8632);
140 ExtraFlags.setBuildOnRead(true);
141 ExtraFlags.setInputFileFormat(llvm::PNaClFormat);
142}
143
144bool BrowserCompileServer::pushInputBytes(const void *Data, size_t NumBytes) {
Jan Voung2f7f2b72015-06-03 17:50:20 -0700145 // If there was an earlier error, do not attempt to push bytes to
146 // the QueueStreamer. Otherwise the thread could become blocked.
147 if (HadError.load())
148 return true;
Jan Voung44c3a802015-03-27 16:29:08 -0700149 return InputStream->PutBytes(
150 const_cast<unsigned char *>(
151 reinterpret_cast<const unsigned char *>(Data)),
152 NumBytes) != NumBytes;
153}
154
Jan Voung2f7f2b72015-06-03 17:50:20 -0700155void BrowserCompileServer::setFatalError(const IceString &Reason) {
156 HadError.store(true);
157 Ctx->getStrError() << Reason;
158 // Make sure that the QueueStreamer is not stuck by signaling an early end.
159 InputStream->SetDone();
160}
161
162ErrorCode &BrowserCompileServer::getErrorCode() {
163 if (HadError.load()) {
164 // HadError means report_fatal_error is called. Make sure that the
165 // LastError is not EC_None. We don't know the type of error so
166 // just pick some error category.
167 LastError.assign(EC_Translation);
168 }
169 return LastError;
170}
171
Jan Voung44c3a802015-03-27 16:29:08 -0700172void BrowserCompileServer::endInputStream() { InputStream->SetDone(); }
173
174void BrowserCompileServer::startCompileThread(int ObjFD) {
175 InputStream = new llvm::QueueStreamer();
176 LogStream = getOutputStream(STDOUT_FILENO);
177 LogStream->SetUnbuffered();
178 EmitStream = getOutputStream(ObjFD);
179 EmitStream->SetBufferSize(1 << 14);
Karl Schimpf2f67b922015-04-22 15:20:16 -0700180 std::unique_ptr<StringStream> ErrStrm(new StringStream());
181 ErrorStream = std::move(ErrStrm);
Jan Voung44c3a802015-03-27 16:29:08 -0700182 ELFStream.reset(new ELFStreamer(*EmitStream.get()));
183 Ctx.reset(new GlobalContext(LogStream.get(), EmitStream.get(),
Karl Schimpf2f67b922015-04-22 15:20:16 -0700184 &ErrorStream->getStream(), ELFStream.get(),
185 Flags));
Jan Voung44c3a802015-03-27 16:29:08 -0700186 CompileThread = std::thread([this]() {
Jan Voung2f7f2b72015-06-03 17:50:20 -0700187 llvm::install_fatal_error_handler(fatalErrorHandler, this);
Jan Voung44c3a802015-03-27 16:29:08 -0700188 Ctx->initParserThread();
189 this->getCompiler().run(ExtraFlags, *Ctx.get(),
190 // Retain original reference, but the compiler
191 // (LLVM's MemoryObject) wants to handle deletion.
192 std::unique_ptr<llvm::DataStreamer>(InputStream));
193 });
194}
195
196} // end of namespace Ice
197
198#endif // PNACL_BROWSER_TRANSLATOR