1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ppapi/native_client/src/trusted/plugin/pnacl_translate_thread.h"
7 #include "native_client/src/trusted/desc/nacl_desc_wrapper.h"
8 #include "ppapi/native_client/src/trusted/plugin/plugin.h"
9 #include "ppapi/native_client/src/trusted/plugin/plugin_error.h"
10 #include "ppapi/native_client/src/trusted/plugin/pnacl_resources.h"
11 #include "ppapi/native_client/src/trusted/plugin/srpc_params.h"
12 #include "ppapi/native_client/src/trusted/plugin/temporary_file.h"
13 #include "ppapi/native_client/src/trusted/plugin/utility.h"
17 PnaclTranslateThread::PnaclTranslateThread() : llc_subprocess_active_(false),
18 ld_subprocess_active_(false),
24 coordinator_error_info_(NULL),
28 NaClXMutexCtor(&subprocess_mu_);
29 NaClXMutexCtor(&cond_mu_);
30 NaClXCondVarCtor(&buffer_cond_);
33 void PnaclTranslateThread::RunTranslate(
34 const pp::CompletionCallback& finish_callback,
35 const Manifest* manifest,
38 ErrorInfo* error_info,
39 PnaclResources* resources,
40 PnaclOptions* pnacl_options,
41 PnaclCoordinator* coordinator,
43 PLUGIN_PRINTF(("PnaclStreamingTranslateThread::RunTranslate)\n"));
46 nexe_file_ = nexe_file;
47 coordinator_error_info_ = error_info;
48 resources_ = resources;
49 pnacl_options_ = pnacl_options;
50 coordinator_ = coordinator;
53 // Invoke llc followed by ld off the main thread. This allows use of
54 // blocking RPCs that would otherwise block the JavaScript main thread.
55 report_translate_finished_ = finish_callback;
56 translate_thread_.reset(new NaClThread);
57 if (translate_thread_ == NULL) {
58 TranslateFailed(ERROR_PNACL_THREAD_CREATE,
59 "could not allocate thread struct.");
62 const int32_t kArbitraryStackSize = 128 * 1024;
63 if (!NaClThreadCreateJoinable(translate_thread_.get(),
66 kArbitraryStackSize)) {
67 TranslateFailed(ERROR_PNACL_THREAD_CREATE,
68 "could not create thread.");
69 translate_thread_.reset(NULL);
73 // Called from main thread to send bytes to the translator.
74 void PnaclTranslateThread::PutBytes(std::vector<char>* bytes,
76 PLUGIN_PRINTF(("PutBytes (this=%p, bytes=%p, size=%" NACL_PRIuS
78 this, bytes, bytes ? bytes->size() : 0, count));
79 size_t buffer_size = 0;
80 // If we are done (error or not), Signal the translation thread to stop.
82 NaClXMutexLock(&cond_mu_);
84 NaClXCondVarSignal(&buffer_cond_);
85 NaClXMutexUnlock(&cond_mu_);
90 // Ensure that the buffer we send to the translation thread is the right size
91 // (count can be < the buffer size). This can be done without the lock.
92 buffer_size = bytes->size();
95 NaClXMutexLock(&cond_mu_);
97 data_buffers_.push_back(std::vector<char>());
98 bytes->swap(data_buffers_.back()); // Avoid copying the buffer data.
100 NaClXCondVarSignal(&buffer_cond_);
101 NaClXMutexUnlock(&cond_mu_);
103 // Ensure the buffer we send back to the coordinator is the expected size
104 bytes->resize(buffer_size);
107 NaClSubprocess* PnaclTranslateThread::StartSubprocess(
108 const nacl::string& url_for_nexe,
109 const Manifest* manifest,
110 ErrorInfo* error_info) {
111 PLUGIN_PRINTF(("PnaclTranslateThread::StartSubprocess (url_for_nexe=%s)\n",
112 url_for_nexe.c_str()));
113 nacl::DescWrapper* wrapper = resources_->WrapperForUrl(url_for_nexe);
114 nacl::scoped_ptr<NaClSubprocess> subprocess(
115 plugin_->LoadHelperNaClModule(wrapper, manifest, error_info));
116 if (subprocess.get() == NULL) {
118 "PnaclTranslateThread::StartSubprocess: subprocess creation failed\n"));
121 return subprocess.release();
124 void WINAPI PnaclTranslateThread::DoTranslateThread(void* arg) {
125 PnaclTranslateThread* translator =
126 reinterpret_cast<PnaclTranslateThread*>(arg);
127 translator->DoTranslate();
130 void PnaclTranslateThread::DoTranslate() {
131 ErrorInfo error_info;
133 nacl::DescWrapper* llc_out_file = obj_file_->write_wrapper();
136 nacl::MutexLocker ml(&subprocess_mu_);
137 int64_t llc_start_time = NaClGetTimeOfDayMicroseconds();
138 llc_subprocess_.reset(
139 StartSubprocess(resources_->GetLlcUrl(), manifest_, &error_info));
140 if (llc_subprocess_ == NULL) {
141 TranslateFailed(ERROR_PNACL_LLC_SETUP,
142 "Compile process could not be created: " +
143 error_info.message());
146 llc_subprocess_active_ = true;
147 time_stats_.pnacl_llc_load_time =
148 (NaClGetTimeOfDayMicroseconds() - llc_start_time);
150 PluginReverseInterface* llc_reverse =
151 llc_subprocess_->service_runtime()->rev_interface();
152 llc_reverse->AddTempQuotaManagedFile(obj_file_->identifier());
155 int64_t compile_start_time = NaClGetTimeOfDayMicroseconds();
157 std::vector<char> options = pnacl_options_->GetOptCommandline();
158 init_success = llc_subprocess_->InvokeSrpcMethod(
159 "StreamInitWithOverrides",
162 llc_out_file->desc(),
167 if (llc_subprocess_->srpc_client()->GetLastError() ==
168 NACL_SRPC_RESULT_APP_ERROR) {
169 // The error message is only present if the error was returned from llc
170 TranslateFailed(ERROR_PNACL_LLC_INTERNAL,
171 nacl::string("Stream init failed: ") +
172 nacl::string(params.outs()[0]->arrays.str));
174 TranslateFailed(ERROR_PNACL_LLC_INTERNAL,
175 "Stream init internal error");
180 PLUGIN_PRINTF(("PnaclCoordinator: StreamInit successful\n"));
181 pp::Core* core = pp::Module::Get()->core();
183 // llc process is started.
184 while(!done_ || data_buffers_.size() > 0) {
185 NaClXMutexLock(&cond_mu_);
186 while(!done_ && data_buffers_.size() == 0) {
187 NaClXCondVarWait(&buffer_cond_, &cond_mu_);
189 PLUGIN_PRINTF(("PnaclTranslateThread awake (done=%d, size=%" NACL_PRIuS
191 done_, data_buffers_.size()));
192 if (data_buffers_.size() > 0) {
193 std::vector<char> data;
194 data.swap(data_buffers_.front());
195 data_buffers_.pop_front();
196 NaClXMutexUnlock(&cond_mu_);
197 PLUGIN_PRINTF(("StreamChunk\n"));
198 if (!llc_subprocess_->InvokeSrpcMethod("StreamChunk",
203 if (llc_subprocess_->srpc_client()->GetLastError() !=
204 NACL_SRPC_RESULT_APP_ERROR) {
205 // If the error was reported by the translator, then we fall through
206 // and call StreamEnd, which returns a string describing the error,
207 // which we can then send to the Javascript console. Otherwise just
208 // fail here, since the translator has probably crashed or asserted.
209 TranslateFailed(ERROR_PNACL_LLC_INTERNAL,
210 "Compile stream chunk failed. "
211 "The PNaCl translator has probably crashed.");
216 PLUGIN_PRINTF(("StreamChunk Successful\n"));
217 core->CallOnMainThread(
219 coordinator_->GetCompileProgressCallback(data.size()),
223 NaClXMutexUnlock(&cond_mu_);
226 PLUGIN_PRINTF(("PnaclTranslateThread done with chunks\n"));
228 if (!llc_subprocess_->InvokeSrpcMethod("StreamEnd", std::string(), ¶ms)) {
229 PLUGIN_PRINTF(("PnaclTranslateThread StreamEnd failed\n"));
230 if (llc_subprocess_->srpc_client()->GetLastError() ==
231 NACL_SRPC_RESULT_APP_ERROR) {
232 // The error string is only present if the error was sent back from llc.
233 TranslateFailed(ERROR_PNACL_LLC_INTERNAL,
234 params.outs()[3]->arrays.str);
236 TranslateFailed(ERROR_PNACL_LLC_INTERNAL,
237 "Compile StreamEnd internal error");
241 time_stats_.pnacl_compile_time =
242 (NaClGetTimeOfDayMicroseconds() - compile_start_time);
244 // LLC returns values that are used to determine how linking is done.
245 int is_shared_library = (params.outs()[0]->u.ival != 0);
246 nacl::string soname = params.outs()[1]->arrays.str;
247 nacl::string lib_dependencies = params.outs()[2]->arrays.str;
248 PLUGIN_PRINTF(("PnaclCoordinator: compile (translator=%p) succeeded"
249 " is_shared_library=%d, soname='%s', lib_dependencies='%s')\n",
250 this, is_shared_library, soname.c_str(),
251 lib_dependencies.c_str()));
253 // Shut down the llc subprocess.
254 NaClXMutexLock(&subprocess_mu_);
255 llc_subprocess_active_ = false;
256 llc_subprocess_.reset(NULL);
257 NaClXMutexUnlock(&subprocess_mu_);
259 if(!RunLdSubprocess(is_shared_library, soname, lib_dependencies)) {
262 core->CallOnMainThread(0, report_translate_finished_, PP_OK);
265 bool PnaclTranslateThread::RunLdSubprocess(int is_shared_library,
266 const nacl::string& soname,
267 const nacl::string& lib_dependencies
269 ErrorInfo error_info;
271 // Reset object file for reading first.
272 if (!obj_file_->Reset()) {
273 TranslateFailed(ERROR_PNACL_LD_SETUP,
274 "Link process could not reset object file");
277 nacl::DescWrapper* ld_in_file = obj_file_->read_wrapper();
278 nacl::DescWrapper* ld_out_file = nexe_file_->write_wrapper();
282 nacl::MutexLocker ml(&subprocess_mu_);
283 int64_t ld_start_time = NaClGetTimeOfDayMicroseconds();
284 ld_subprocess_.reset(
285 StartSubprocess(resources_->GetLdUrl(), manifest_, &error_info));
286 if (ld_subprocess_ == NULL) {
287 TranslateFailed(ERROR_PNACL_LD_SETUP,
288 "Link process could not be created: " +
289 error_info.message());
292 ld_subprocess_active_ = true;
293 time_stats_.pnacl_ld_load_time =
294 (NaClGetTimeOfDayMicroseconds() - ld_start_time);
295 PluginReverseInterface* ld_reverse =
296 ld_subprocess_->service_runtime()->rev_interface();
297 ld_reverse->AddTempQuotaManagedFile(nexe_file_->identifier());
300 int64_t link_start_time = NaClGetTimeOfDayMicroseconds();
302 if (!ld_subprocess_->InvokeSrpcMethod("RunWithDefaultCommandLine",
309 lib_dependencies.c_str())) {
310 TranslateFailed(ERROR_PNACL_LD_INTERNAL,
314 time_stats_.pnacl_link_time =
315 NaClGetTimeOfDayMicroseconds() - link_start_time;
316 PLUGIN_PRINTF(("PnaclCoordinator: link (translator=%p) succeeded\n",
318 // Shut down the ld subprocess.
319 NaClXMutexLock(&subprocess_mu_);
320 ld_subprocess_active_ = false;
321 ld_subprocess_.reset(NULL);
322 NaClXMutexUnlock(&subprocess_mu_);
326 void PnaclTranslateThread::TranslateFailed(
327 enum PluginErrorCode err_code,
328 const nacl::string& error_string) {
329 PLUGIN_PRINTF(("PnaclTranslateThread::TranslateFailed (error_string='%s')\n",
330 error_string.c_str()));
331 pp::Core* core = pp::Module::Get()->core();
332 if (coordinator_error_info_->message().empty()) {
333 // Only use our message if one hasn't already been set by the coordinator
334 // (e.g. pexe load failed).
335 coordinator_error_info_->SetReport(err_code,
336 nacl::string("PnaclCoordinator: ") +
339 core->CallOnMainThread(0, report_translate_finished_, PP_ERROR_FAILED);
342 void PnaclTranslateThread::AbortSubprocesses() {
343 PLUGIN_PRINTF(("PnaclTranslateThread::AbortSubprocesses\n"));
344 NaClXMutexLock(&subprocess_mu_);
345 if (llc_subprocess_ != NULL && llc_subprocess_active_) {
346 llc_subprocess_->service_runtime()->Shutdown();
347 llc_subprocess_active_ = false;
349 if (ld_subprocess_ != NULL && ld_subprocess_active_) {
350 ld_subprocess_->service_runtime()->Shutdown();
351 ld_subprocess_active_ = false;
353 NaClXMutexUnlock(&subprocess_mu_);
354 nacl::MutexLocker ml(&cond_mu_);
356 // Free all buffered bitcode chunks
357 data_buffers_.clear();
358 NaClXCondVarSignal(&buffer_cond_);
361 PnaclTranslateThread::~PnaclTranslateThread() {
362 PLUGIN_PRINTF(("~PnaclTranslateThread (translate_thread=%p)\n", this));
364 if (translate_thread_ != NULL)
365 NaClThreadJoin(translate_thread_.get());
366 PLUGIN_PRINTF(("~PnaclTranslateThread joined\n"));
367 NaClCondVarDtor(&buffer_cond_);
368 NaClMutexDtor(&cond_mu_);
369 NaClMutexDtor(&subprocess_mu_);
372 } // namespace plugin