blob: f341b4e0c2af4c55d6cd3fdad453e7343420d5c2 [file] [log] [blame]
Jason Sams709a0972012-11-15 18:18:04 -08001/*
2 * Copyright (C) 2011-2012 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
Jean-Luc Brouillet9ab50942014-06-18 18:10:32 -07007 *
Jason Sams709a0972012-11-15 18:18:04 -08008 * 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
Jason Sams709a0972012-11-15 18:18:04 -080017#include "rsCpuCore.h"
Jason Sams709a0972012-11-15 18:18:04 -080018#include "rsCpuScript.h"
Jason Sams709a0972012-11-15 18:18:04 -080019
Jason Sams110f1812013-03-14 16:02:18 -070020#ifdef RS_COMPATIBILITY_LIB
Jason Sams110f1812013-03-14 16:02:18 -070021 #include <stdio.h>
Stephen Hinesee48c0b2013-10-30 17:48:30 -070022 #include <sys/stat.h>
Stephen Hinesc2c11cc2013-07-19 01:07:42 -070023 #include <unistd.h>
Jason Sams110f1812013-03-14 16:02:18 -070024#else
25 #include <bcc/BCCContext.h>
Stephen Hines82e0a672014-05-05 15:40:56 -070026 #include <bcc/Config/Config.h>
Jason Sams110f1812013-03-14 16:02:18 -070027 #include <bcc/Renderscript/RSCompilerDriver.h>
Jason Sams110f1812013-03-14 16:02:18 -070028 #include <bcc/Renderscript/RSInfo.h>
Stephen Hinesb58d9ad2013-06-19 19:26:19 -070029 #include <bcinfo/MetadataExtractor.h>
Stephen Hinesba17ae42013-06-05 17:18:04 -070030 #include <cutils/properties.h>
Stephen Hinesb58d9ad2013-06-19 19:26:19 -070031
32 #include <sys/types.h>
33 #include <sys/wait.h>
34 #include <unistd.h>
Stephen Hines00511322014-01-31 11:20:23 -080035
36 #include <string>
37 #include <vector>
Jason Sams110f1812013-03-14 16:02:18 -070038#endif
Jason Sams709a0972012-11-15 18:18:04 -080039
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -080040#include <set>
41#include <string>
42#include <dlfcn.h>
43#include <stdlib.h>
44#include <string.h>
45#include <fstream>
46#include <iostream>
47
48#ifdef __LP64__
49#define SYSLIBPATH "/system/lib64"
50#else
51#define SYSLIBPATH "/system/lib"
52#endif
53
Stephen Hinesba17ae42013-06-05 17:18:04 -070054namespace {
Stephen Hinesc2c11cc2013-07-19 01:07:42 -070055
56// Create a len length string containing random characters from [A-Za-z0-9].
57static std::string getRandomString(size_t len) {
58 char buf[len + 1];
59 for (size_t i = 0; i < len; i++) {
60 uint32_t r = arc4random() & 0xffff;
61 r %= 62;
62 if (r < 26) {
63 // lowercase
64 buf[i] = 'a' + r;
65 } else if (r < 52) {
66 // uppercase
67 buf[i] = 'A' + (r - 26);
68 } else {
69 // Use a number
70 buf[i] = '0' + (r - 52);
71 }
72 }
73 buf[len] = '\0';
74 return std::string(buf);
75}
76
Stephen Hinesee48c0b2013-10-30 17:48:30 -070077// Check if a path exists and attempt to create it if it doesn't.
78static bool ensureCacheDirExists(const char *path) {
79 if (access(path, R_OK | W_OK | X_OK) == 0) {
80 // Done if we can rwx the directory
81 return true;
82 }
83 if (mkdir(path, 0700) == 0) {
84 return true;
85 }
86 return false;
87}
88
Stephen Hines7d774852014-10-01 12:57:57 -070089// Copy the file named \p srcFile to \p dstFile.
90// Return 0 on success and -1 if anything wasn't copied.
91static int copyFile(const char *dstFile, const char *srcFile) {
92 std::ifstream srcStream(srcFile);
93 if (!srcStream) {
94 ALOGE("Could not verify or read source file: %s", srcFile);
95 return -1;
96 }
97 std::ofstream dstStream(dstFile);
98 if (!dstStream) {
99 ALOGE("Could not verify or write destination file: %s", dstFile);
100 return -1;
101 }
102 dstStream << srcStream.rdbuf();
103 if (!dstStream) {
104 ALOGE("Could not write destination file: %s", dstFile);
105 return -1;
106 }
107
108 srcStream.close();
109 dstStream.close();
110
111 return 0;
112}
113
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800114#define RS_CACHE_DIR "com.android.renderscript.cache"
115
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700116// Attempt to load the shared library from origName, but then fall back to
Stephen Hines7d774852014-10-01 12:57:57 -0700117// creating a copy of the shared library if necessary (to ensure instancing).
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700118// This function returns the dlopen()-ed handle if successful.
119static void *loadSOHelper(const char *origName, const char *cacheDir,
120 const char *resName) {
121 // Keep track of which .so libraries have been loaded. Once a library is
Stephen Hines7d774852014-10-01 12:57:57 -0700122 // in the set (per-process granularity), we must instead make a copy of
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700123 // the original shared object (randomly named .so file) and load that one
124 // instead. If we don't do this, we end up aliasing global data between
125 // the various Script instances (which are supposed to be completely
126 // independent).
127 static std::set<std::string> LoadedLibraries;
128
Chris Wailes44bef6f2014-08-12 13:51:10 -0700129 void *loaded = nullptr;
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700130
131 // Skip everything if we don't even have the original library available.
132 if (access(origName, F_OK) != 0) {
Chris Wailes44bef6f2014-08-12 13:51:10 -0700133 return nullptr;
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700134 }
135
136 // Common path is that we have not loaded this Script/library before.
137 if (LoadedLibraries.find(origName) == LoadedLibraries.end()) {
138 loaded = dlopen(origName, RTLD_NOW | RTLD_LOCAL);
139 if (loaded) {
140 LoadedLibraries.insert(origName);
141 }
142 return loaded;
143 }
144
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700145 std::string newName(cacheDir);
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800146
147 // Append RS_CACHE_DIR only if it is not found in cacheDir
148 // In driver mode, RS_CACHE_DIR is already appended to cacheDir.
149 if (newName.find(RS_CACHE_DIR) == std::string::npos) {
150 newName.append("/" RS_CACHE_DIR "/");
151 }
Stephen Hinesee48c0b2013-10-30 17:48:30 -0700152
153 if (!ensureCacheDirExists(newName.c_str())) {
154 ALOGE("Could not verify or create cache dir: %s", cacheDir);
Chris Wailes44bef6f2014-08-12 13:51:10 -0700155 return nullptr;
Stephen Hinesee48c0b2013-10-30 17:48:30 -0700156 }
157
Stephen Hines7d774852014-10-01 12:57:57 -0700158 // Construct an appropriately randomized filename for the copy.
Stephen Hinesee48c0b2013-10-30 17:48:30 -0700159 newName.append("librs.");
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700160 newName.append(resName);
161 newName.append("#");
162 newName.append(getRandomString(6)); // 62^6 potential filename variants.
163 newName.append(".so");
164
Stephen Hines7d774852014-10-01 12:57:57 -0700165 int r = copyFile(newName.c_str(), origName);
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700166 if (r != 0) {
Stephen Hines7d774852014-10-01 12:57:57 -0700167 ALOGE("Could not create copy %s -> %s", origName, newName.c_str());
Chris Wailes44bef6f2014-08-12 13:51:10 -0700168 return nullptr;
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700169 }
170 loaded = dlopen(newName.c_str(), RTLD_NOW | RTLD_LOCAL);
171 r = unlink(newName.c_str());
172 if (r != 0) {
Stephen Hines7d774852014-10-01 12:57:57 -0700173 ALOGE("Could not unlink copy %s", newName.c_str());
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700174 }
175 if (loaded) {
176 LoadedLibraries.insert(newName.c_str());
177 }
178
179 return loaded;
180}
181
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800182static std::string findSharedObjectName(const char *cacheDir,
183 const char *resName) {
184
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700185#ifndef RS_SERVER
186 std::string scriptSOName(cacheDir);
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800187#ifdef RS_COMPATIBILITY_LIB
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700188 size_t cutPos = scriptSOName.rfind("cache");
189 if (cutPos != std::string::npos) {
190 scriptSOName.erase(cutPos);
191 } else {
192 ALOGE("Found peculiar cacheDir (missing \"cache\"): %s", cacheDir);
193 }
194 scriptSOName.append("/lib/librs.");
195#else
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800196 scriptSOName.append("/librs.");
197#endif
198
199#else
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700200 std::string scriptSOName("lib");
201#endif
202 scriptSOName.append(resName);
203 scriptSOName.append(".so");
204
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800205 return scriptSOName;
206}
207
208// Load the shared library referred to by cacheDir and resName. If we have
209// already loaded this library, we instead create a new copy (in the
210// cache dir) and then load that. We then immediately destroy the copy.
211// This is required behavior to implement script instancing for the support
212// library, since shared objects are loaded and de-duped by name only.
213static void *loadSharedLibrary(const char *cacheDir, const char *resName) {
214 void *loaded = nullptr;
215
216 std::string scriptSOName = findSharedObjectName(cacheDir, resName);
217
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700218 // We should check if we can load the library from the standard app
219 // location for shared libraries first.
220 loaded = loadSOHelper(scriptSOName.c_str(), cacheDir, resName);
221
Chris Wailes44bef6f2014-08-12 13:51:10 -0700222 if (loaded == nullptr) {
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700223 ALOGE("Unable to open shared library (%s): %s",
224 scriptSOName.c_str(), dlerror());
225
226 // One final attempt to find the library in "/system/lib".
227 // We do this to allow bundled applications to use the compatibility
228 // library fallback path. Those applications don't have a private
229 // library path, so they need to install to the system directly.
230 // Note that this is really just a testing path.
Chris Wailes93d6bc82014-07-28 16:54:38 -0700231 std::string scriptSONameSystem("/system/lib/librs.");
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700232 scriptSONameSystem.append(resName);
233 scriptSONameSystem.append(".so");
234 loaded = loadSOHelper(scriptSONameSystem.c_str(), cacheDir,
235 resName);
Chris Wailes44bef6f2014-08-12 13:51:10 -0700236 if (loaded == nullptr) {
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700237 ALOGE("Unable to open system shared library (%s): %s",
238 scriptSONameSystem.c_str(), dlerror());
239 }
240 }
241
242 return loaded;
243}
244
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800245#ifndef RS_COMPATIBILITY_LIB
246
Stephen Hinesba17ae42013-06-05 17:18:04 -0700247static bool is_force_recompile() {
248#ifdef RS_SERVER
249 return false;
250#else
251 char buf[PROPERTY_VALUE_MAX];
252
253 // Re-compile if floating point precision has been overridden.
254 property_get("debug.rs.precision", buf, "");
255 if (buf[0] != '\0') {
256 return true;
257 }
258
259 // Re-compile if debug.rs.forcerecompile is set.
260 property_get("debug.rs.forcerecompile", buf, "0");
261 if ((::strcmp(buf, "1") == 0) || (::strcmp(buf, "true") == 0)) {
262 return true;
263 } else {
264 return false;
265 }
266#endif // RS_SERVER
267}
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700268
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700269const static char *BCC_EXE_PATH = "/system/bin/bcc";
270
Chris Wailes6847e732014-08-11 17:30:51 -0700271static void setCompileArguments(std::vector<const char*>* args,
272 const std::string& bcFileName,
273 const char* cacheDir, const char* resName,
274 const char* core_lib, bool useRSDebugContext,
275 const char* bccPluginName) {
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700276 rsAssert(cacheDir && resName && core_lib);
277 args->push_back(BCC_EXE_PATH);
Tim Murray687cfe82015-01-08 14:59:38 -0800278 args->push_back("-unroll-runtime");
279 args->push_back("-scalarize-load-store");
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700280 args->push_back("-o");
281 args->push_back(resName);
282 args->push_back("-output_path");
283 args->push_back(cacheDir);
284 args->push_back("-bclib");
285 args->push_back(core_lib);
286 args->push_back("-mtriple");
287 args->push_back(DEFAULT_TARGET_TRIPLE_STRING);
288
Tim Murray358ffb82014-12-09 11:53:06 -0800289 // Enable workaround for A53 codegen by default.
290#if defined(__aarch64__) && !defined(DISABLE_A53_WORKAROUND)
291 args->push_back("-aarch64-fix-cortex-a53-835769");
292#endif
293
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700294 // Execute the bcc compiler.
295 if (useRSDebugContext) {
296 args->push_back("-rs-debug-ctx");
297 } else {
298 // Only load additional libraries for compiles that don't use
299 // the debug context.
300 if (bccPluginName && strlen(bccPluginName) > 0) {
301 args->push_back("-load");
302 args->push_back(bccPluginName);
303 }
304 }
305
Stephen Hines45e753a2015-01-19 20:58:44 -0800306 args->push_back("-fPIC");
307 args->push_back("-embedRSInfo");
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800308
Chris Wailes6847e732014-08-11 17:30:51 -0700309 args->push_back(bcFileName.c_str());
Chris Wailes44bef6f2014-08-12 13:51:10 -0700310 args->push_back(nullptr);
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700311}
312
Chris Wailes6847e732014-08-11 17:30:51 -0700313static bool compileBitcode(const std::string &bcFileName,
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700314 const char *bitcode,
315 size_t bitcodeSize,
Chris Wailes6847e732014-08-11 17:30:51 -0700316 const char **compileArguments,
317 const std::string &compileCommandLine) {
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700318 rsAssert(bitcode && bitcodeSize);
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700319
Chris Wailes6847e732014-08-11 17:30:51 -0700320 FILE *bcfile = fopen(bcFileName.c_str(), "w");
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700321 if (!bcfile) {
Chris Wailes6847e732014-08-11 17:30:51 -0700322 ALOGE("Could not write to %s", bcFileName.c_str());
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700323 return false;
324 }
325 size_t nwritten = fwrite(bitcode, 1, bitcodeSize, bcfile);
326 fclose(bcfile);
327 if (nwritten != bitcodeSize) {
328 ALOGE("Could not write %zu bytes to %s", bitcodeSize,
Chris Wailes6847e732014-08-11 17:30:51 -0700329 bcFileName.c_str());
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700330 return false;
331 }
332
333 pid_t pid = fork();
Stephen Hines00511322014-01-31 11:20:23 -0800334
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700335 switch (pid) {
336 case -1: { // Error occurred (we attempt no recovery)
337 ALOGE("Couldn't fork for bcc compiler execution");
338 return false;
339 }
340 case 0: { // Child process
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700341 ALOGV("Invoking BCC with: %s", compileCommandLine.c_str());
342 execv(BCC_EXE_PATH, (char* const*)compileArguments);
Stephen Hines00511322014-01-31 11:20:23 -0800343
Stephen Hines00511322014-01-31 11:20:23 -0800344 ALOGE("execv() failed: %s", strerror(errno));
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700345 abort();
346 return false;
347 }
348 default: { // Parent process (actual driver)
349 // Wait on child process to finish compiling the source.
350 int status = 0;
351 pid_t w = waitpid(pid, &status, 0);
352 if (w == -1) {
353 ALOGE("Could not wait for bcc compiler");
354 return false;
355 }
356
357 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
358 return true;
359 }
360
361 ALOGE("bcc compiler terminated unexpectedly");
362 return false;
363 }
364 }
365}
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700366
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800367const static char *LD_EXE_PATH = "/system/bin/ld.mc";
368
369static bool createSharedLib(const char *cacheDir, const char *resName) {
370 std::string sharedLibName = findSharedObjectName(cacheDir, resName);
371 std::string objFileName = cacheDir;
372 objFileName.append("/");
373 objFileName.append(resName);
374 objFileName.append(".o");
375
376 const char *compiler_rt = SYSLIBPATH"/libcompiler_rt.so";
377 std::vector<const char *> args = {
378 LD_EXE_PATH,
379 "-shared",
380 "-nostdlib",
381 compiler_rt,
382 "-mtriple", DEFAULT_TARGET_TRIPLE_STRING,
383 "-L", SYSLIBPATH,
384 "-lRSDriver", "-lm", "-lc",
385 objFileName.c_str(),
386 "-o", sharedLibName.c_str(),
387 nullptr
388 };
389
390 std::string cmdLineStr = bcc::getCommandLine(args.size()-1, args.data());
391
392 pid_t pid = fork();
393
394 switch (pid) {
395 case -1: { // Error occurred (we attempt no recovery)
396 ALOGE("Couldn't fork for linker (%s) execution", LD_EXE_PATH);
397 return false;
398 }
399 case 0: { // Child process
400 ALOGV("Invoking ld.mc with args '%s'", cmdLineStr.c_str());
401 execv(LD_EXE_PATH, (char* const*) args.data());
402
403 ALOGE("execv() failed: %s", strerror(errno));
404 abort();
405 return false;
406 }
407 default: { // Parent process (actual driver)
408 // Wait on child process to finish compiling the source.
409 int status = 0;
410 pid_t w = waitpid(pid, &status, 0);
411 if (w == -1) {
412 ALOGE("Could not wait for linker (%s)", LD_EXE_PATH);
413 return false;
414 }
415
416 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
417 return true;
418 }
419
420 ALOGE("Linker (%s) terminated unexpectedly", LD_EXE_PATH);
421 return false;
422 }
423 }
424}
Stephen Hinesba17ae42013-06-05 17:18:04 -0700425#endif // !defined(RS_COMPATIBILITY_LIB)
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700426} // namespace
Stephen Hinesba17ae42013-06-05 17:18:04 -0700427
Jason Sams709a0972012-11-15 18:18:04 -0800428namespace android {
429namespace renderscript {
430
Jason Sams110f1812013-03-14 16:02:18 -0700431#define MAXLINE 500
432#define MAKE_STR_HELPER(S) #S
433#define MAKE_STR(S) MAKE_STR_HELPER(S)
434#define EXPORT_VAR_STR "exportVarCount: "
Jason Sams110f1812013-03-14 16:02:18 -0700435#define EXPORT_FUNC_STR "exportFuncCount: "
Jason Sams110f1812013-03-14 16:02:18 -0700436#define EXPORT_FOREACH_STR "exportForEachCount: "
Jason Sams110f1812013-03-14 16:02:18 -0700437#define OBJECT_SLOT_STR "objectSlotCount: "
Jason Sams110f1812013-03-14 16:02:18 -0700438
439// Copy up to a newline or size chars from str -> s, updating str
Chris Wailes44bef6f2014-08-12 13:51:10 -0700440// Returns s when successful and nullptr when '\0' is finally reached.
Jason Sams110f1812013-03-14 16:02:18 -0700441static char* strgets(char *s, int size, const char **ppstr) {
442 if (!ppstr || !*ppstr || **ppstr == '\0' || size < 1) {
Chris Wailes44bef6f2014-08-12 13:51:10 -0700443 return nullptr;
Jason Sams110f1812013-03-14 16:02:18 -0700444 }
445
446 int i;
447 for (i = 0; i < (size - 1); i++) {
448 s[i] = **ppstr;
449 (*ppstr)++;
450 if (s[i] == '\0') {
451 return s;
452 } else if (s[i] == '\n') {
453 s[i+1] = '\0';
454 return s;
455 }
456 }
457
458 // size has been exceeded.
459 s[i] = '\0';
460
461 return s;
462}
Jason Sams709a0972012-11-15 18:18:04 -0800463
464RsdCpuScriptImpl::RsdCpuScriptImpl(RsdCpuReferenceImpl *ctx, const Script *s) {
465 mCtx = ctx;
466 mScript = s;
467
Chris Wailes44bef6f2014-08-12 13:51:10 -0700468 mScriptSO = nullptr;
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800469
Chris Wailes44bef6f2014-08-12 13:51:10 -0700470 mInvokeFunctions = nullptr;
471 mForEachFunctions = nullptr;
472 mFieldAddress = nullptr;
473 mFieldIsObject = nullptr;
474 mForEachSignatures = nullptr;
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800475
476#ifndef RS_COMPATIBILITY_LIB
Chris Wailes44bef6f2014-08-12 13:51:10 -0700477 mCompilerDriver = nullptr;
Jason Sams110f1812013-03-14 16:02:18 -0700478#endif
479
Tim Murraye195a3f2014-03-13 15:04:58 -0700480
Chris Wailes44bef6f2014-08-12 13:51:10 -0700481 mRoot = nullptr;
482 mRootExpand = nullptr;
483 mInit = nullptr;
484 mFreeChildren = nullptr;
Jason Sams709a0972012-11-15 18:18:04 -0800485
Jason Sams709a0972012-11-15 18:18:04 -0800486
Chris Wailes44bef6f2014-08-12 13:51:10 -0700487 mBoundAllocs = nullptr;
488 mIntrinsicData = nullptr;
Jason Sams709a0972012-11-15 18:18:04 -0800489 mIsThreadable = true;
490}
491
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800492bool RsdCpuScriptImpl::storeRSInfoFromSO() {
493 char line[MAXLINE];
494 size_t varCount = 0;
495 size_t funcCount = 0;
496 size_t forEachCount = 0;
497 size_t objectSlotCount = 0;
498
499 mRoot = (RootFunc_t) dlsym(mScriptSO, "root");
500 if (mRoot) {
501 //ALOGE("Found root(): %p", mRoot);
502 }
503 mRootExpand = (RootFunc_t) dlsym(mScriptSO, "root.expand");
504 if (mRootExpand) {
505 //ALOGE("Found root.expand(): %p", mRootExpand);
506 }
507 mInit = (InvokeFunc_t) dlsym(mScriptSO, "init");
508 if (mInit) {
509 //ALOGE("Found init(): %p", mInit);
510 }
511 mFreeChildren = (InvokeFunc_t) dlsym(mScriptSO, ".rs.dtor");
512 if (mFreeChildren) {
513 //ALOGE("Found .rs.dtor(): %p", mFreeChildren);
514 }
515
516 const char *rsInfo = (const char *) dlsym(mScriptSO, ".rs.info");
517 if (rsInfo) {
518 //ALOGE("Found .rs.info(): %p - %s", rsInfo, rsInfo);
519 }
520
521 if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
522 goto error;
523 }
524 if (sscanf(line, EXPORT_VAR_STR "%zu", &varCount) != 1) {
525 ALOGE("Invalid export var count!: %s", line);
526 goto error;
527 }
528
529 mExportedVariableCount = varCount;
530 //ALOGE("varCount: %zu", varCount);
531 if (varCount > 0) {
532 // Start by creating/zeroing this member, since we don't want to
533 // accidentally clean up invalid pointers later (if we error out).
534 mFieldIsObject = new bool[varCount];
535 if (mFieldIsObject == nullptr) {
536 goto error;
537 }
538 memset(mFieldIsObject, 0, varCount * sizeof(*mFieldIsObject));
539 mFieldAddress = new void*[varCount];
540 if (mFieldAddress == nullptr) {
541 goto error;
542 }
543 for (size_t i = 0; i < varCount; ++i) {
544 if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
545 goto error;
546 }
547 char *c = strrchr(line, '\n');
548 if (c) {
549 *c = '\0';
550 }
551 mFieldAddress[i] = dlsym(mScriptSO, line);
552 if (mFieldAddress[i] == nullptr) {
553 ALOGE("Failed to find variable address for %s: %s",
554 line, dlerror());
555 // Not a critical error if we don't find a global variable.
556 }
557 else {
558 //ALOGE("Found variable %s at %p", line,
559 //mFieldAddress[i]);
560 }
561 }
562 }
563
564 if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
565 goto error;
566 }
567 if (sscanf(line, EXPORT_FUNC_STR "%zu", &funcCount) != 1) {
568 ALOGE("Invalid export func count!: %s", line);
569 goto error;
570 }
571
572 mExportedFunctionCount = funcCount;
573 //ALOGE("funcCount: %zu", funcCount);
574
575 if (funcCount > 0) {
576 mInvokeFunctions = new InvokeFunc_t[funcCount];
577 if (mInvokeFunctions == nullptr) {
578 goto error;
579 }
580 for (size_t i = 0; i < funcCount; ++i) {
581 if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
582 goto error;
583 }
584 char *c = strrchr(line, '\n');
585 if (c) {
586 *c = '\0';
587 }
588
589 mInvokeFunctions[i] = (InvokeFunc_t) dlsym(mScriptSO, line);
590 if (mInvokeFunctions[i] == nullptr) {
591 ALOGE("Failed to get function address for %s(): %s",
592 line, dlerror());
593 goto error;
594 }
595 else {
596 //ALOGE("Found InvokeFunc_t %s at %p", line, mInvokeFunctions[i]);
597 }
598 }
599 }
600
601 if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
602 goto error;
603 }
604 if (sscanf(line, EXPORT_FOREACH_STR "%zu", &forEachCount) != 1) {
605 ALOGE("Invalid export forEach count!: %s", line);
606 goto error;
607 }
608
609 if (forEachCount > 0) {
610
611 mForEachSignatures = new uint32_t[forEachCount];
612 if (mForEachSignatures == nullptr) {
613 goto error;
614 }
615 mForEachFunctions = new ForEachFunc_t[forEachCount];
616 if (mForEachFunctions == nullptr) {
617 goto error;
618 }
619 for (size_t i = 0; i < forEachCount; ++i) {
620 unsigned int tmpSig = 0;
621 char tmpName[MAXLINE];
622
623 if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
624 goto error;
625 }
626 if (sscanf(line, "%u - %" MAKE_STR(MAXLINE) "s",
627 &tmpSig, tmpName) != 2) {
628 ALOGE("Invalid export forEach!: %s", line);
629 goto error;
630 }
631
632 // Lookup the expanded ForEach kernel.
633 strncat(tmpName, ".expand", MAXLINE-1-strlen(tmpName));
634 mForEachSignatures[i] = tmpSig;
635 mForEachFunctions[i] =
636 (ForEachFunc_t) dlsym(mScriptSO, tmpName);
637 if (i != 0 && mForEachFunctions[i] == nullptr) {
638 // Ignore missing root.expand functions.
639 // root() is always specified at location 0.
640 ALOGE("Failed to find forEach function address for %s: %s",
641 tmpName, dlerror());
642 goto error;
643 }
644 else {
645 //ALOGE("Found forEach %s at %p", tmpName, mForEachFunctions[i]);
646 }
647 }
648 }
649
650 if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
651 goto error;
652 }
653 if (sscanf(line, OBJECT_SLOT_STR "%zu", &objectSlotCount) != 1) {
654 ALOGE("Invalid object slot count!: %s", line);
655 goto error;
656 }
657
658 if (objectSlotCount > 0) {
659 rsAssert(varCount > 0);
660 for (size_t i = 0; i < objectSlotCount; ++i) {
661 uint32_t varNum = 0;
662 if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
663 goto error;
664 }
665 if (sscanf(line, "%u", &varNum) != 1) {
666 ALOGE("Invalid object slot!: %s", line);
667 goto error;
668 }
669
670 if (varNum < varCount) {
671 mFieldIsObject[varNum] = true;
672 }
673 }
674 }
675
676 if (varCount > 0) {
677 mBoundAllocs = new Allocation *[varCount];
678 memset(mBoundAllocs, 0, varCount * sizeof(*mBoundAllocs));
679 }
680
681 if (mScriptSO == (void*)1) {
682 //rsdLookupRuntimeStub(script, "acos");
683 }
684
685 return true;
686
687error:
688 delete[] mInvokeFunctions;
689 delete[] mForEachFunctions;
690 delete[] mFieldAddress;
691 delete[] mFieldIsObject;
692 delete[] mForEachSignatures;
693 delete[] mBoundAllocs;
694
695 return false;
696}
697
Jason Sams709a0972012-11-15 18:18:04 -0800698bool RsdCpuScriptImpl::init(char const *resName, char const *cacheDir,
699 uint8_t const *bitcode, size_t bitcodeSize,
Stephen Hines00511322014-01-31 11:20:23 -0800700 uint32_t flags, char const *bccPluginName) {
Jason Sams709a0972012-11-15 18:18:04 -0800701 //ALOGE("rsdScriptCreate %p %p %p %p %i %i %p", rsc, resName, cacheDir, bitcode, bitcodeSize, flags, lookupFunc);
702 //ALOGE("rsdScriptInit %p %p", rsc, script);
703
704 mCtx->lockMutex();
Jason Sams110f1812013-03-14 16:02:18 -0700705#ifndef RS_COMPATIBILITY_LIB
Stephen Hines00511322014-01-31 11:20:23 -0800706 bool useRSDebugContext = false;
Jason Sams709a0972012-11-15 18:18:04 -0800707
Chris Wailes44bef6f2014-08-12 13:51:10 -0700708 mCompilerDriver = nullptr;
Jason Sams709a0972012-11-15 18:18:04 -0800709
Jason Sams709a0972012-11-15 18:18:04 -0800710 mCompilerDriver = new bcc::RSCompilerDriver();
Chris Wailes44bef6f2014-08-12 13:51:10 -0700711 if (mCompilerDriver == nullptr) {
Jason Sams709a0972012-11-15 18:18:04 -0800712 ALOGE("bcc: FAILS to create compiler driver (out of memory)");
713 mCtx->unlockMutex();
714 return false;
715 }
716
Stephen Hinesb7d9c802013-04-29 19:13:09 -0700717 // Run any compiler setup functions we have been provided with.
718 RSSetupCompilerCallback setupCompilerCallback =
719 mCtx->getSetupCompilerCallback();
Chris Wailes44bef6f2014-08-12 13:51:10 -0700720 if (setupCompilerCallback != nullptr) {
Stephen Hinesb7d9c802013-04-29 19:13:09 -0700721 setupCompilerCallback(mCompilerDriver);
722 }
723
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700724 bcinfo::MetadataExtractor bitcodeMetadata((const char *) bitcode, bitcodeSize);
725 if (!bitcodeMetadata.extract()) {
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700726 ALOGE("Could not extract metadata from bitcode");
Stephen Hinesf94e8db2014-06-26 11:55:29 -0700727 mCtx->unlockMutex();
Stephen Hinesb58d9ad2013-06-19 19:26:19 -0700728 return false;
729 }
730
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700731 const char* core_lib = findCoreLib(bitcodeMetadata, (const char*)bitcode, bitcodeSize);
Stephen Hinescca3d6c2013-04-15 01:06:39 -0700732
733 if (mCtx->getContext()->getContextType() == RS_CONTEXT_TYPE_DEBUG) {
Stephen Hinesf47e8b42013-04-18 01:06:29 -0700734 mCompilerDriver->setDebugContext(true);
Stephen Hines00511322014-01-31 11:20:23 -0800735 useRSDebugContext = true;
Stephen Hinescca3d6c2013-04-15 01:06:39 -0700736 }
Stephen Hinesba17ae42013-06-05 17:18:04 -0700737
Chris Wailes6847e732014-08-11 17:30:51 -0700738 std::string bcFileName(cacheDir);
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700739 bcFileName.append("/");
740 bcFileName.append(resName);
741 bcFileName.append(".bc");
742
743 std::vector<const char*> compileArguments;
744 setCompileArguments(&compileArguments, bcFileName, cacheDir, resName, core_lib,
745 useRSDebugContext, bccPluginName);
Chris Wailes44bef6f2014-08-12 13:51:10 -0700746 // The last argument of compileArguments ia a nullptr, so remove 1 from the size.
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700747 std::string compileCommandLine =
748 bcc::getCommandLine(compileArguments.size() - 1, compileArguments.data());
749
Stephen Hines45e753a2015-01-19 20:58:44 -0800750 if (!is_force_recompile()) {
751 mScriptSO = loadSharedLibrary(cacheDir, resName);
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700752 }
753
754 // If we can't, it's either not there or out of date. We compile the bit code and try loading
755 // again.
Stephen Hines45e753a2015-01-19 20:58:44 -0800756 if (mScriptSO == nullptr) {
757 if (!compileBitcode(bcFileName, (const char*)bitcode, bitcodeSize,
758 compileArguments.data(), compileCommandLine))
759 {
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700760 ALOGE("bcc: FAILS to compile '%s'", resName);
761 mCtx->unlockMutex();
762 return false;
763 }
Stephen Hines45e753a2015-01-19 20:58:44 -0800764
765 if (!createSharedLib(cacheDir, resName)) {
766 ALOGE("Linker: Failed to link object file '%s'", resName);
767 mCtx->unlockMutex();
768 return false;
769 }
770
771 mScriptSO = loadSharedLibrary(cacheDir, resName);
772 if (mScriptSO == nullptr) {
773 ALOGE("Unable to load '%s'", resName);
Jean-Luc Brouillet40e35cd2014-06-25 18:21:45 -0700774 mCtx->unlockMutex();
775 return false;
Stephen Hinesba17ae42013-06-05 17:18:04 -0700776 }
777 }
Jason Sams709a0972012-11-15 18:18:04 -0800778
Stephen Hines45e753a2015-01-19 20:58:44 -0800779 // Read RS symbol information from the .so.
780 if ( !mScriptSO) {
781 goto error;
Jason Sams709a0972012-11-15 18:18:04 -0800782 }
783
Stephen Hines45e753a2015-01-19 20:58:44 -0800784 if ( !storeRSInfoFromSO()) {
785 goto error;
Tim Murray29809d12014-05-28 12:04:19 -0700786 }
Jean-Luc Brouilletf4d216e2014-06-09 18:04:16 -0700787#else // RS_COMPATIBILITY_LIB is defined
Jason Sams110f1812013-03-14 16:02:18 -0700788
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700789 mScriptSO = loadSharedLibrary(cacheDir, resName);
Jason Sams110f1812013-03-14 16:02:18 -0700790
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800791 if (!mScriptSO) {
792 goto error;
793 }
Jason Sams110f1812013-03-14 16:02:18 -0700794
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -0800795 if (!storeRSInfoFromSO()) {
Stephen Hinesc2c11cc2013-07-19 01:07:42 -0700796 goto error;
Jason Sams110f1812013-03-14 16:02:18 -0700797 }
798#endif
Jason Sams709a0972012-11-15 18:18:04 -0800799 mCtx->unlockMutex();
800 return true;
Jason Sams110f1812013-03-14 16:02:18 -0700801
Jason Sams110f1812013-03-14 16:02:18 -0700802error:
803
804 mCtx->unlockMutex();
Jason Sams110f1812013-03-14 16:02:18 -0700805 if (mScriptSO) {
806 dlclose(mScriptSO);
807 }
808 return false;
Jason Sams709a0972012-11-15 18:18:04 -0800809}
810
Jean-Luc Brouillet9ab50942014-06-18 18:10:32 -0700811#ifndef RS_COMPATIBILITY_LIB
812
Jean-Luc Brouillet9ab50942014-06-18 18:10:32 -0700813const char* RsdCpuScriptImpl::findCoreLib(const bcinfo::MetadataExtractor& ME, const char* bitcode,
814 size_t bitcodeSize) {
815 const char* defaultLib = SYSLIBPATH"/libclcore.bc";
816
817 // If we're debugging, use the debug library.
818 if (mCtx->getContext()->getContextType() == RS_CONTEXT_TYPE_DEBUG) {
819 return SYSLIBPATH"/libclcore_debug.bc";
820 }
821
822 // If a callback has been registered to specify a library, use that.
823 RSSelectRTCallback selectRTCallback = mCtx->getSelectRTCallback();
Chris Wailes44bef6f2014-08-12 13:51:10 -0700824 if (selectRTCallback != nullptr) {
Jean-Luc Brouillet9ab50942014-06-18 18:10:32 -0700825 return selectRTCallback((const char*)bitcode, bitcodeSize);
826 }
827
828 // Check for a platform specific library
829#if defined(ARCH_ARM_HAVE_NEON) && !defined(DISABLE_CLCORE_NEON)
830 enum bcinfo::RSFloatPrecision prec = ME.getRSFloatPrecision();
Jean-Luc Brouilletf4d38362014-07-09 17:46:03 -0700831 if (prec == bcinfo::RS_FP_Relaxed) {
Jean-Luc Brouillet9ab50942014-06-18 18:10:32 -0700832 // NEON-capable ARMv7a devices can use an accelerated math library
833 // for all reduced precision scripts.
834 // ARMv8 does not use NEON, as ASIMD can be used with all precision
835 // levels.
836 return SYSLIBPATH"/libclcore_neon.bc";
837 } else {
838 return defaultLib;
839 }
840#elif defined(__i386__) || defined(__x86_64__)
841 // x86 devices will use an optimized library.
842 return SYSLIBPATH"/libclcore_x86.bc";
843#else
844 return defaultLib;
845#endif
846}
847
848#endif
849
Jason Sams709a0972012-11-15 18:18:04 -0800850void RsdCpuScriptImpl::populateScript(Script *script) {
Jason Sams110f1812013-03-14 16:02:18 -0700851 // Copy info over to runtime
852 script->mHal.info.exportedFunctionCount = mExportedFunctionCount;
853 script->mHal.info.exportedVariableCount = mExportedVariableCount;
854 script->mHal.info.exportedPragmaCount = 0;
855 script->mHal.info.exportedPragmaKeyList = 0;
856 script->mHal.info.exportedPragmaValueList = 0;
857
858 // Bug, need to stash in metadata
859 if (mRootExpand) {
860 script->mHal.info.root = mRootExpand;
861 } else {
862 script->mHal.info.root = mRoot;
863 }
Jason Sams709a0972012-11-15 18:18:04 -0800864}
865
Jason Sams709a0972012-11-15 18:18:04 -0800866
867typedef void (*rs_t)(const void *, void *, const void *, uint32_t, uint32_t, uint32_t, uint32_t);
868
Chris Wailesf3712132014-07-16 15:18:30 -0700869void RsdCpuScriptImpl::forEachMtlsSetup(const Allocation ** ains,
870 uint32_t inLen,
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700871 Allocation * aout,
872 const void * usr, uint32_t usrLen,
873 const RsScriptCall *sc,
874 MTLaunchStruct *mtls) {
875
876 memset(mtls, 0, sizeof(MTLaunchStruct));
877
Chris Wailesf3712132014-07-16 15:18:30 -0700878 for (int index = inLen; --index >= 0;) {
879 const Allocation* ain = ains[index];
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700880
Chris Wailesf3712132014-07-16 15:18:30 -0700881 // possible for this to occur if IO_OUTPUT/IO_INPUT with no bound surface
Chris Wailes44bef6f2014-08-12 13:51:10 -0700882 if (ain != nullptr &&
883 (const uint8_t *)ain->mHal.drvState.lod[0].mallocPtr == nullptr) {
884
Chris Wailesf3712132014-07-16 15:18:30 -0700885 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT,
886 "rsForEach called with null in allocations");
887 return;
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700888 }
889 }
890
Chris Wailes44bef6f2014-08-12 13:51:10 -0700891 if (aout &&
892 (const uint8_t *)aout->mHal.drvState.lod[0].mallocPtr == nullptr) {
893
Chris Wailesf3712132014-07-16 15:18:30 -0700894 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT,
895 "rsForEach called with null out allocations");
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700896 return;
897 }
898
Chris Wailesf3712132014-07-16 15:18:30 -0700899 if (inLen > 0) {
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700900 const Allocation *ain0 = ains[0];
901 const Type *inType = ain0->getType();
902
Jason Samsc0d68472015-01-20 14:29:52 -0800903 mtls->fep.dim.x = inType->getDimX();
904 mtls->fep.dim.y = inType->getDimY();
905 mtls->fep.dim.z = inType->getDimZ();
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700906
907 for (int Index = inLen; --Index >= 1;) {
908 if (!ain0->hasSameDims(ains[Index])) {
909 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT,
910 "Failed to launch kernel; dimensions of input and output allocations do not match.");
911
912 return;
913 }
914 }
915
Chris Wailes44bef6f2014-08-12 13:51:10 -0700916 } else if (aout != nullptr) {
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700917 const Type *outType = aout->getType();
918
Jason Samsc0d68472015-01-20 14:29:52 -0800919 mtls->fep.dim.x = outType->getDimX();
920 mtls->fep.dim.y = outType->getDimY();
921 mtls->fep.dim.z = outType->getDimZ();
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700922
923 } else {
Chris Wailesf3712132014-07-16 15:18:30 -0700924 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT,
925 "rsForEach called with null allocations");
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700926 return;
927 }
928
Chris Wailes44bef6f2014-08-12 13:51:10 -0700929 if (inLen > 0 && aout != nullptr) {
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700930 if (!ains[0]->hasSameDims(aout)) {
931 mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT,
932 "Failed to launch kernel; dimensions of input and output allocations do not match.");
933
934 return;
935 }
936 }
937
938 if (!sc || (sc->xEnd == 0)) {
Jason Samsc0d68472015-01-20 14:29:52 -0800939 mtls->xEnd = mtls->fep.dim.x;
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700940 } else {
Jason Samsc0d68472015-01-20 14:29:52 -0800941 rsAssert(sc->xStart < mtls->fep.dim.x);
942 rsAssert(sc->xEnd <= mtls->fep.dim.x);
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700943 rsAssert(sc->xStart < sc->xEnd);
Jason Samsc0d68472015-01-20 14:29:52 -0800944 mtls->xStart = rsMin(mtls->fep.dim.x, sc->xStart);
945 mtls->xEnd = rsMin(mtls->fep.dim.x, sc->xEnd);
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700946 if (mtls->xStart >= mtls->xEnd) return;
947 }
948
949 if (!sc || (sc->yEnd == 0)) {
Jason Samsc0d68472015-01-20 14:29:52 -0800950 mtls->yEnd = mtls->fep.dim.y;
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700951 } else {
Jason Samsc0d68472015-01-20 14:29:52 -0800952 rsAssert(sc->yStart < mtls->fep.dim.y);
953 rsAssert(sc->yEnd <= mtls->fep.dim.y);
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700954 rsAssert(sc->yStart < sc->yEnd);
Jason Samsc0d68472015-01-20 14:29:52 -0800955 mtls->yStart = rsMin(mtls->fep.dim.y, sc->yStart);
956 mtls->yEnd = rsMin(mtls->fep.dim.y, sc->yEnd);
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700957 if (mtls->yStart >= mtls->yEnd) return;
958 }
959
960 if (!sc || (sc->zEnd == 0)) {
Jason Samsc0d68472015-01-20 14:29:52 -0800961 mtls->zEnd = mtls->fep.dim.z;
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700962 } else {
Jason Samsc0d68472015-01-20 14:29:52 -0800963 rsAssert(sc->zStart < mtls->fep.dim.z);
964 rsAssert(sc->zEnd <= mtls->fep.dim.z);
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700965 rsAssert(sc->zStart < sc->zEnd);
Jason Samsc0d68472015-01-20 14:29:52 -0800966 mtls->zStart = rsMin(mtls->fep.dim.z, sc->zStart);
967 mtls->zEnd = rsMin(mtls->fep.dim.z, sc->zEnd);
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700968 if (mtls->zStart >= mtls->zEnd) return;
969 }
970
971 mtls->xEnd = rsMax((uint32_t)1, mtls->xEnd);
972 mtls->yEnd = rsMax((uint32_t)1, mtls->yEnd);
973 mtls->zEnd = rsMax((uint32_t)1, mtls->zEnd);
974 mtls->arrayEnd = rsMax((uint32_t)1, mtls->arrayEnd);
975
Chris Wailesf3712132014-07-16 15:18:30 -0700976 rsAssert(inLen == 0 || (ains[0]->getType()->getDimZ() == 0));
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700977
978 mtls->rsc = mCtx;
Jason Samsc0d68472015-01-20 14:29:52 -0800979 if (ains) {
980 memcpy(mtls->ains, ains, inLen * sizeof(ains[0]));
981 }
982 mtls->aout[0] = aout;
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700983 mtls->fep.usr = usr;
984 mtls->fep.usrLen = usrLen;
985 mtls->mSliceSize = 1;
986 mtls->mSliceNum = 0;
987
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700988 mtls->isThreadable = mIsThreadable;
989
Chris Wailesf3712132014-07-16 15:18:30 -0700990 if (inLen > 0) {
Chris Wailesf3712132014-07-16 15:18:30 -0700991 mtls->fep.inLen = inLen;
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700992 for (int index = inLen; --index >= 0;) {
Jason Samsc0d68472015-01-20 14:29:52 -0800993 mtls->fep.inPtr[index] = (const uint8_t*)ains[index]->mHal.drvState.lod[0].mallocPtr;
994 mtls->fep.inStride[index] = ains[index]->getType()->getElementSizeBytes();
Chris Wailes4b3c34e2014-06-11 12:00:29 -0700995 }
996 }
997
Chris Wailes44bef6f2014-08-12 13:51:10 -0700998 if (aout != nullptr) {
Jason Samsc0d68472015-01-20 14:29:52 -0800999 mtls->fep.outPtr[0] = (uint8_t *)aout->mHal.drvState.lod[0].mallocPtr;
1000 mtls->fep.outStride[0] = aout->getType()->getElementSizeBytes();
Chris Wailes4b3c34e2014-06-11 12:00:29 -07001001 }
1002}
1003
Jason Sams709a0972012-11-15 18:18:04 -08001004
1005void RsdCpuScriptImpl::invokeForEach(uint32_t slot,
Chris Wailesf3712132014-07-16 15:18:30 -07001006 const Allocation ** ains,
1007 uint32_t inLen,
Jason Sams709a0972012-11-15 18:18:04 -08001008 Allocation * aout,
1009 const void * usr,
1010 uint32_t usrLen,
1011 const RsScriptCall *sc) {
1012
1013 MTLaunchStruct mtls;
Chris Wailes4b3c34e2014-06-11 12:00:29 -07001014
1015 forEachMtlsSetup(ains, inLen, aout, usr, usrLen, sc, &mtls);
1016 forEachKernelSetup(slot, &mtls);
1017
1018 RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
1019 mCtx->launchThreads(ains, inLen, aout, sc, &mtls);
1020 mCtx->setTLS(oldTLS);
1021}
1022
Jason Sams709a0972012-11-15 18:18:04 -08001023void RsdCpuScriptImpl::forEachKernelSetup(uint32_t slot, MTLaunchStruct *mtls) {
Jason Sams709a0972012-11-15 18:18:04 -08001024 mtls->script = this;
1025 mtls->fep.slot = slot;
Jason Sams110f1812013-03-14 16:02:18 -07001026 mtls->kernel = reinterpret_cast<ForEachFunc_t>(mForEachFunctions[slot]);
Chris Wailes44bef6f2014-08-12 13:51:10 -07001027 rsAssert(mtls->kernel != nullptr);
Jason Sams110f1812013-03-14 16:02:18 -07001028 mtls->sig = mForEachSignatures[slot];
Jason Sams709a0972012-11-15 18:18:04 -08001029}
1030
1031int RsdCpuScriptImpl::invokeRoot() {
1032 RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
1033 int ret = mRoot();
1034 mCtx->setTLS(oldTLS);
1035 return ret;
1036}
1037
1038void RsdCpuScriptImpl::invokeInit() {
1039 if (mInit) {
1040 mInit();
1041 }
1042}
1043
1044void RsdCpuScriptImpl::invokeFreeChildren() {
1045 if (mFreeChildren) {
1046 mFreeChildren();
1047 }
1048}
1049
1050void RsdCpuScriptImpl::invokeFunction(uint32_t slot, const void *params,
1051 size_t paramLength) {
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -08001052 //ALOGE("invoke %i %p %zu", slot, params, paramLength);
Yong Cheneaba5a32014-12-12 13:25:18 +08001053 void * ap = nullptr;
1054
1055#if defined(__x86_64__)
1056 // The invoked function could have input parameter of vector type for example float4 which
1057 // requires void* params to be 16 bytes aligned when using SSE instructions for x86_64 platform.
1058 // So try to align void* params before passing them into RS exported function.
1059
1060 if ((uint8_t)(uint64_t)params & 0x0F) {
1061 if ((ap = (void*)memalign(16, paramLength)) != nullptr) {
1062 memcpy(ap, params, paramLength);
1063 } else {
1064 ALOGE("x86_64: invokeFunction memalign error, still use params which is not 16 bytes aligned.");
1065 }
1066 }
1067#endif
Jason Sams709a0972012-11-15 18:18:04 -08001068
1069 RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -08001070 reinterpret_cast<void (*)(const void *, uint32_t)>(
1071 mInvokeFunctions[slot])(ap? (const void *) ap: params, paramLength);
Yong Cheneaba5a32014-12-12 13:25:18 +08001072
Jason Sams709a0972012-11-15 18:18:04 -08001073 mCtx->setTLS(oldTLS);
1074}
1075
1076void RsdCpuScriptImpl::setGlobalVar(uint32_t slot, const void *data, size_t dataLength) {
1077 //rsAssert(!script->mFieldIsObject[slot]);
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -08001078 //ALOGE("setGlobalVar %i %p %zu", slot, data, dataLength);
Jason Sams709a0972012-11-15 18:18:04 -08001079
1080 //if (mIntrinsicID) {
1081 //mIntrinsicFuncs.setVar(dc, script, drv->mIntrinsicData, slot, data, dataLength);
1082 //return;
1083 //}
1084
Jason Sams110f1812013-03-14 16:02:18 -07001085 int32_t *destPtr = reinterpret_cast<int32_t *>(mFieldAddress[slot]);
Jason Sams709a0972012-11-15 18:18:04 -08001086 if (!destPtr) {
1087 //ALOGV("Calling setVar on slot = %i which is null", slot);
1088 return;
1089 }
1090
1091 memcpy(destPtr, data, dataLength);
1092}
1093
Tim Murray9c642392013-04-11 13:29:59 -07001094void RsdCpuScriptImpl::getGlobalVar(uint32_t slot, void *data, size_t dataLength) {
1095 //rsAssert(!script->mFieldIsObject[slot]);
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -08001096 //ALOGE("getGlobalVar %i %p %zu", slot, data, dataLength);
Tim Murray9c642392013-04-11 13:29:59 -07001097
Tim Murray9c642392013-04-11 13:29:59 -07001098 int32_t *srcPtr = reinterpret_cast<int32_t *>(mFieldAddress[slot]);
Tim Murray9c642392013-04-11 13:29:59 -07001099 if (!srcPtr) {
1100 //ALOGV("Calling setVar on slot = %i which is null", slot);
1101 return;
1102 }
1103 memcpy(data, srcPtr, dataLength);
1104}
1105
1106
Jason Sams709a0972012-11-15 18:18:04 -08001107void RsdCpuScriptImpl::setGlobalVarWithElemDims(uint32_t slot, const void *data, size_t dataLength,
1108 const Element *elem,
Stephen Hinesac8d1462014-06-25 00:01:23 -07001109 const uint32_t *dims, size_t dimLength) {
Jason Sams110f1812013-03-14 16:02:18 -07001110 int32_t *destPtr = reinterpret_cast<int32_t *>(mFieldAddress[slot]);
Jason Sams709a0972012-11-15 18:18:04 -08001111 if (!destPtr) {
1112 //ALOGV("Calling setVar on slot = %i which is null", slot);
1113 return;
1114 }
1115
1116 // We want to look at dimension in terms of integer components,
1117 // but dimLength is given in terms of bytes.
1118 dimLength /= sizeof(int);
1119
1120 // Only a single dimension is currently supported.
1121 rsAssert(dimLength == 1);
1122 if (dimLength == 1) {
1123 // First do the increment loop.
1124 size_t stride = elem->getSizeBytes();
1125 const char *cVal = reinterpret_cast<const char *>(data);
Stephen Hinesac8d1462014-06-25 00:01:23 -07001126 for (uint32_t i = 0; i < dims[0]; i++) {
Jason Sams709a0972012-11-15 18:18:04 -08001127 elem->incRefs(cVal);
1128 cVal += stride;
1129 }
1130
1131 // Decrement loop comes after (to prevent race conditions).
1132 char *oldVal = reinterpret_cast<char *>(destPtr);
Stephen Hinesac8d1462014-06-25 00:01:23 -07001133 for (uint32_t i = 0; i < dims[0]; i++) {
Jason Sams709a0972012-11-15 18:18:04 -08001134 elem->decRefs(oldVal);
1135 oldVal += stride;
1136 }
1137 }
1138
1139 memcpy(destPtr, data, dataLength);
1140}
1141
1142void RsdCpuScriptImpl::setGlobalBind(uint32_t slot, Allocation *data) {
1143
1144 //rsAssert(!script->mFieldIsObject[slot]);
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -08001145 //ALOGE("setGlobalBind %i %p", slot, data);
Jason Sams709a0972012-11-15 18:18:04 -08001146
Jason Sams110f1812013-03-14 16:02:18 -07001147 int32_t *destPtr = reinterpret_cast<int32_t *>(mFieldAddress[slot]);
Jason Sams709a0972012-11-15 18:18:04 -08001148 if (!destPtr) {
1149 //ALOGV("Calling setVar on slot = %i which is null", slot);
1150 return;
1151 }
1152
Chris Wailes44bef6f2014-08-12 13:51:10 -07001153 void *ptr = nullptr;
Jason Sams709a0972012-11-15 18:18:04 -08001154 mBoundAllocs[slot] = data;
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -08001155 if (data) {
Jason Sams709a0972012-11-15 18:18:04 -08001156 ptr = data->mHal.drvState.lod[0].mallocPtr;
1157 }
1158 memcpy(destPtr, &ptr, sizeof(void *));
1159}
1160
1161void RsdCpuScriptImpl::setGlobalObj(uint32_t slot, ObjectBase *data) {
1162
1163 //rsAssert(script->mFieldIsObject[slot]);
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -08001164 //ALOGE("setGlobalObj %i %p", slot, data);
Jason Sams709a0972012-11-15 18:18:04 -08001165
Jason Sams110f1812013-03-14 16:02:18 -07001166 int32_t *destPtr = reinterpret_cast<int32_t *>(mFieldAddress[slot]);
Jason Sams709a0972012-11-15 18:18:04 -08001167 if (!destPtr) {
1168 //ALOGV("Calling setVar on slot = %i which is null", slot);
1169 return;
1170 }
1171
Jason Sams05ef73f2014-08-05 14:59:22 -07001172 rsrSetObject(mCtx->getContext(), (rs_object_base *)destPtr, data);
Jason Sams709a0972012-11-15 18:18:04 -08001173}
1174
1175RsdCpuScriptImpl::~RsdCpuScriptImpl() {
Jason Sams110f1812013-03-14 16:02:18 -07001176#ifndef RS_COMPATIBILITY_LIB
Jason Sams709a0972012-11-15 18:18:04 -08001177
Jason Sams709a0972012-11-15 18:18:04 -08001178 if (mCompilerDriver) {
1179 delete mCompilerDriver;
1180 }
Tim Murraybee48d72014-06-13 12:44:47 -07001181
Stephen Hines45e753a2015-01-19 20:58:44 -08001182#endif
Pirama Arumuga Nainardc0d8f72014-12-02 15:23:38 -08001183
1184 if (mFieldIsObject) {
1185 for (size_t i = 0; i < mExportedVariableCount; ++i) {
1186 if (mFieldIsObject[i]) {
1187 if (mFieldAddress[i] != nullptr) {
1188 rs_object_base *obj_addr =
1189 reinterpret_cast<rs_object_base *>(mFieldAddress[i]);
1190 rsrClearObject(mCtx->getContext(), obj_addr);
1191 }
1192 }
1193 }
1194 }
1195
Jason Sams110f1812013-03-14 16:02:18 -07001196 if (mInvokeFunctions) delete[] mInvokeFunctions;
1197 if (mForEachFunctions) delete[] mForEachFunctions;
1198 if (mFieldAddress) delete[] mFieldAddress;
1199 if (mFieldIsObject) delete[] mFieldIsObject;
1200 if (mForEachSignatures) delete[] mForEachSignatures;
1201 if (mBoundAllocs) delete[] mBoundAllocs;
1202 if (mScriptSO) {
1203 dlclose(mScriptSO);
1204 }
Jason Sams709a0972012-11-15 18:18:04 -08001205}
1206
1207Allocation * RsdCpuScriptImpl::getAllocationForPointer(const void *ptr) const {
1208 if (!ptr) {
Chris Wailes44bef6f2014-08-12 13:51:10 -07001209 return nullptr;
Jason Sams709a0972012-11-15 18:18:04 -08001210 }
1211
1212 for (uint32_t ct=0; ct < mScript->mHal.info.exportedVariableCount; ct++) {
1213 Allocation *a = mBoundAllocs[ct];
1214 if (!a) continue;
1215 if (a->mHal.drvState.lod[0].mallocPtr == ptr) {
1216 return a;
1217 }
1218 }
1219 ALOGE("rsGetAllocation, failed to find %p", ptr);
Chris Wailes44bef6f2014-08-12 13:51:10 -07001220 return nullptr;
Jason Sams709a0972012-11-15 18:18:04 -08001221}
1222
Chris Wailesf3712132014-07-16 15:18:30 -07001223void RsdCpuScriptImpl::preLaunch(uint32_t slot, const Allocation ** ains,
1224 uint32_t inLen, Allocation * aout,
1225 const void * usr, uint32_t usrLen,
1226 const RsScriptCall *sc) {}
Jason Sams17e3cdc2013-09-09 17:32:16 -07001227
Chris Wailesf3712132014-07-16 15:18:30 -07001228void RsdCpuScriptImpl::postLaunch(uint32_t slot, const Allocation ** ains,
1229 uint32_t inLen, Allocation * aout,
1230 const void * usr, uint32_t usrLen,
1231 const RsScriptCall *sc) {}
Jason Sams17e3cdc2013-09-09 17:32:16 -07001232
Jason Sams709a0972012-11-15 18:18:04 -08001233
1234}
1235}