rsCpuExecutable.cpp revision 2abfcc6d129fe3defddef4540aa95cc445c03a7a
1#include "rsCpuExecutable.h"
2#include "rsCppUtils.h"
3
4#include <fstream>
5#include <set>
6#include <memory>
7
8#ifdef RS_COMPATIBILITY_LIB
9#include <stdio.h>
10#include <sys/stat.h>
11#include <unistd.h>
12#else
13#include "bcc/Config/Config.h"
14#include <bcc/Renderscript/RSInfo.h>
15#include <sys/wait.h>
16#endif
17
18#include <dlfcn.h>
19
20namespace android {
21namespace renderscript {
22
23namespace {
24
25// Create a len length string containing random characters from [A-Za-z0-9].
26static std::string getRandomString(size_t len) {
27    char buf[len + 1];
28    for (size_t i = 0; i < len; i++) {
29        uint32_t r = arc4random() & 0xffff;
30        r %= 62;
31        if (r < 26) {
32            // lowercase
33            buf[i] = 'a' + r;
34        } else if (r < 52) {
35            // uppercase
36            buf[i] = 'A' + (r - 26);
37        } else {
38            // Use a number
39            buf[i] = '0' + (r - 52);
40        }
41    }
42    buf[len] = '\0';
43    return std::string(buf);
44}
45
46// Check if a path exists and attempt to create it if it doesn't.
47static bool ensureCacheDirExists(const char *path) {
48    if (access(path, R_OK | W_OK | X_OK) == 0) {
49        // Done if we can rwx the directory
50        return true;
51    }
52    if (mkdir(path, 0700) == 0) {
53        return true;
54    }
55    return false;
56}
57
58// Copy the file named \p srcFile to \p dstFile.
59// Return 0 on success and -1 if anything wasn't copied.
60static int copyFile(const char *dstFile, const char *srcFile) {
61    std::ifstream srcStream(srcFile);
62    if (!srcStream) {
63        ALOGE("Could not verify or read source file: %s", srcFile);
64        return -1;
65    }
66    std::ofstream dstStream(dstFile);
67    if (!dstStream) {
68        ALOGE("Could not verify or write destination file: %s", dstFile);
69        return -1;
70    }
71    dstStream << srcStream.rdbuf();
72    if (!dstStream) {
73        ALOGE("Could not write destination file: %s", dstFile);
74        return -1;
75    }
76
77    srcStream.close();
78    dstStream.close();
79
80    return 0;
81}
82
83static std::string findSharedObjectName(const char *cacheDir,
84                                        const char *resName) {
85#ifndef RS_SERVER
86    std::string scriptSOName(cacheDir);
87#if defined(RS_COMPATIBILITY_LIB) && !defined(__LP64__)
88    size_t cutPos = scriptSOName.rfind("cache");
89    if (cutPos != std::string::npos) {
90        scriptSOName.erase(cutPos);
91    } else {
92        ALOGE("Found peculiar cacheDir (missing \"cache\"): %s", cacheDir);
93    }
94    scriptSOName.append("/lib/librs.");
95#else
96    scriptSOName.append("/librs.");
97#endif // RS_COMPATIBILITY_LIB
98
99#else
100    std::string scriptSOName("lib");
101#endif // RS_SERVER
102    scriptSOName.append(resName);
103    scriptSOName.append(".so");
104
105    return scriptSOName;
106}
107
108}  // anonymous namespace
109
110const char* SharedLibraryUtils::LD_EXE_PATH = "/system/bin/ld.mc";
111const char* SharedLibraryUtils::RS_CACHE_DIR = "com.android.renderscript.cache";
112
113#ifndef RS_COMPATIBILITY_LIB
114
115bool SharedLibraryUtils::createSharedLibrary(const char *cacheDir, const char *resName) {
116    std::string sharedLibName = findSharedObjectName(cacheDir, resName);
117    std::string objFileName = cacheDir;
118    objFileName.append("/");
119    objFileName.append(resName);
120    objFileName.append(".o");
121
122    const char *compiler_rt = SYSLIBPATH"/libcompiler_rt.so";
123    std::vector<const char *> args = {
124        LD_EXE_PATH,
125        "-shared",
126        "-nostdlib",
127        compiler_rt,
128        "-mtriple", DEFAULT_TARGET_TRIPLE_STRING,
129        "-L", SYSLIBPATH,
130        "-lRSDriver", "-lm", "-lc",
131        objFileName.c_str(),
132        "-o", sharedLibName.c_str(),
133        nullptr
134    };
135
136    std::unique_ptr<const char> joined(
137        rsuJoinStrings(args.size()-1, args.data()));
138    std::string cmdLineStr (joined.get());
139
140    pid_t pid = fork();
141
142    switch (pid) {
143    case -1: {  // Error occurred (we attempt no recovery)
144        ALOGE("Couldn't fork for linker (%s) execution", LD_EXE_PATH);
145        return false;
146    }
147    case 0: {  // Child process
148        ALOGV("Invoking ld.mc with args '%s'", cmdLineStr.c_str());
149        execv(LD_EXE_PATH, (char* const*) args.data());
150
151        ALOGE("execv() failed: %s", strerror(errno));
152        abort();
153        return false;
154    }
155    default: {  // Parent process (actual driver)
156        // Wait on child process to finish compiling the source.
157        int status = 0;
158        pid_t w = waitpid(pid, &status, 0);
159        if (w == -1) {
160            ALOGE("Could not wait for linker (%s)", LD_EXE_PATH);
161            return false;
162        }
163
164        if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
165            return true;
166        }
167
168        ALOGE("Linker (%s) terminated unexpectedly", LD_EXE_PATH);
169        return false;
170    }
171    }
172}
173
174#endif  // RS_COMPATIBILITY_LIB
175
176const char* RsdCpuScriptImpl::BCC_EXE_PATH = "/system/bin/bcc";
177
178void* SharedLibraryUtils::loadSharedLibrary(const char *cacheDir,
179                                            const char *resName,
180                                            const char *nativeLibDir) {
181    void *loaded = nullptr;
182
183#if defined(RS_COMPATIBILITY_LIB) && defined(__LP64__)
184    std::string scriptSOName = findSharedObjectName(nativeLibDir, resName);
185#else
186    std::string scriptSOName = findSharedObjectName(cacheDir, resName);
187#endif
188
189    // We should check if we can load the library from the standard app
190    // location for shared libraries first.
191    loaded = loadSOHelper(scriptSOName.c_str(), cacheDir, resName);
192
193    if (loaded == nullptr) {
194        ALOGE("Unable to open shared library (%s): %s",
195              scriptSOName.c_str(), dlerror());
196
197#ifdef RS_COMPATIBILITY_LIB
198        // One final attempt to find the library in "/system/lib".
199        // We do this to allow bundled applications to use the compatibility
200        // library fallback path. Those applications don't have a private
201        // library path, so they need to install to the system directly.
202        // Note that this is really just a testing path.
203        std::string scriptSONameSystem("/system/lib/librs.");
204        scriptSONameSystem.append(resName);
205        scriptSONameSystem.append(".so");
206        loaded = loadSOHelper(scriptSONameSystem.c_str(), cacheDir,
207                              resName);
208        if (loaded == nullptr) {
209            ALOGE("Unable to open system shared library (%s): %s",
210                  scriptSONameSystem.c_str(), dlerror());
211        }
212#endif
213    }
214
215    return loaded;
216}
217
218void* SharedLibraryUtils::loadSOHelper(const char *origName, const char *cacheDir,
219                                       const char *resName) {
220    // Keep track of which .so libraries have been loaded. Once a library is
221    // in the set (per-process granularity), we must instead make a copy of
222    // the original shared object (randomly named .so file) and load that one
223    // instead. If we don't do this, we end up aliasing global data between
224    // the various Script instances (which are supposed to be completely
225    // independent).
226    static std::set<std::string> LoadedLibraries;
227
228    void *loaded = nullptr;
229
230    // Skip everything if we don't even have the original library available.
231    if (access(origName, F_OK) != 0) {
232        return nullptr;
233    }
234
235    // Common path is that we have not loaded this Script/library before.
236    if (LoadedLibraries.find(origName) == LoadedLibraries.end()) {
237        loaded = dlopen(origName, RTLD_NOW | RTLD_LOCAL);
238        if (loaded) {
239            LoadedLibraries.insert(origName);
240        }
241        return loaded;
242    }
243
244    std::string newName(cacheDir);
245
246    // Append RS_CACHE_DIR only if it is not found in cacheDir
247    // In driver mode, RS_CACHE_DIR is already appended to cacheDir.
248    if (newName.find(RS_CACHE_DIR) == std::string::npos) {
249        newName.append("/");
250        newName.append(RS_CACHE_DIR);
251        newName.append("/");
252    }
253
254    if (!ensureCacheDirExists(newName.c_str())) {
255        ALOGE("Could not verify or create cache dir: %s", cacheDir);
256        return nullptr;
257    }
258
259    // Construct an appropriately randomized filename for the copy.
260    newName.append("librs.");
261    newName.append(resName);
262    newName.append("#");
263    newName.append(getRandomString(6));  // 62^6 potential filename variants.
264    newName.append(".so");
265
266    int r = copyFile(newName.c_str(), origName);
267    if (r != 0) {
268        ALOGE("Could not create copy %s -> %s", origName, newName.c_str());
269        return nullptr;
270    }
271    loaded = dlopen(newName.c_str(), RTLD_NOW | RTLD_LOCAL);
272    r = unlink(newName.c_str());
273    if (r != 0) {
274        ALOGE("Could not unlink copy %s", newName.c_str());
275    }
276    if (loaded) {
277        LoadedLibraries.insert(newName.c_str());
278    }
279
280    return loaded;
281}
282
283#define MAXLINE 500
284#define MAKE_STR_HELPER(S) #S
285#define MAKE_STR(S) MAKE_STR_HELPER(S)
286#define EXPORT_VAR_STR "exportVarCount: "
287#define EXPORT_FUNC_STR "exportFuncCount: "
288#define EXPORT_FOREACH_STR "exportForEachCount: "
289#define OBJECT_SLOT_STR "objectSlotCount: "
290#define PRAGMA_STR "pragmaCount: "
291#define THREADABLE_STR "isThreadable: "
292
293// Copy up to a newline or size chars from str -> s, updating str
294// Returns s when successful and nullptr when '\0' is finally reached.
295static char* strgets(char *s, int size, const char **ppstr) {
296    if (!ppstr || !*ppstr || **ppstr == '\0' || size < 1) {
297        return nullptr;
298    }
299
300    int i;
301    for (i = 0; i < (size - 1); i++) {
302        s[i] = **ppstr;
303        (*ppstr)++;
304        if (s[i] == '\0') {
305            return s;
306        } else if (s[i] == '\n') {
307            s[i+1] = '\0';
308            return s;
309        }
310    }
311
312    // size has been exceeded.
313    s[i] = '\0';
314
315    return s;
316}
317
318ScriptExecutable* ScriptExecutable::createFromSharedObject(
319    Context* RSContext, void* sharedObj) {
320    char line[MAXLINE];
321
322    size_t varCount = 0;
323    size_t funcCount = 0;
324    size_t forEachCount = 0;
325    size_t objectSlotCount = 0;
326    size_t pragmaCount = 0;
327    bool isThreadable = true;
328
329    void** fieldAddress = nullptr;
330    bool* fieldIsObject = nullptr;
331    InvokeFunc_t* invokeFunctions = nullptr;
332    ForEachFunc_t* forEachFunctions = nullptr;
333    uint32_t* forEachSignatures = nullptr;
334    const char ** pragmaKeys = nullptr;
335    const char ** pragmaValues = nullptr;
336
337    const char *rsInfo = (const char *) dlsym(sharedObj, ".rs.info");
338
339    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
340        return nullptr;
341    }
342    if (sscanf(line, EXPORT_VAR_STR "%zu", &varCount) != 1) {
343        ALOGE("Invalid export var count!: %s", line);
344        return nullptr;
345    }
346
347    fieldAddress = new void*[varCount];
348    if (fieldAddress == nullptr) {
349        return nullptr;
350    }
351
352    fieldIsObject = new bool[varCount];
353    if (fieldIsObject == nullptr) {
354        goto error;
355    }
356
357    for (size_t i = 0; i < varCount; ++i) {
358        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
359            goto error;
360        }
361        char *c = strrchr(line, '\n');
362        if (c) {
363            *c = '\0';
364        }
365        void* addr = dlsym(sharedObj, line);
366        if (addr == nullptr) {
367            ALOGE("Failed to find variable address for %s: %s",
368                  line, dlerror());
369            // Not a critical error if we don't find a global variable.
370        }
371        fieldAddress[i] = addr;
372        fieldIsObject[i] = false;
373    }
374
375    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
376        goto error;
377    }
378    if (sscanf(line, EXPORT_FUNC_STR "%zu", &funcCount) != 1) {
379        ALOGE("Invalid export func count!: %s", line);
380        goto error;
381    }
382
383    invokeFunctions = new InvokeFunc_t[funcCount];
384    if (invokeFunctions == nullptr) {
385        goto error;
386    }
387
388    for (size_t i = 0; i < funcCount; ++i) {
389        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
390            goto error;
391        }
392        char *c = strrchr(line, '\n');
393        if (c) {
394            *c = '\0';
395        }
396
397        invokeFunctions[i] = (InvokeFunc_t) dlsym(sharedObj, line);
398        if (invokeFunctions[i] == nullptr) {
399            ALOGE("Failed to get function address for %s(): %s",
400                  line, dlerror());
401            goto error;
402        }
403    }
404
405    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
406        goto error;
407    }
408    if (sscanf(line, EXPORT_FOREACH_STR "%zu", &forEachCount) != 1) {
409        ALOGE("Invalid export forEach count!: %s", line);
410        goto error;
411    }
412
413    forEachFunctions = new ForEachFunc_t[forEachCount];
414    if (forEachFunctions == nullptr) {
415        goto error;
416    }
417
418    forEachSignatures = new uint32_t[forEachCount];
419    if (forEachSignatures == nullptr) {
420        goto error;
421    }
422
423    for (size_t i = 0; i < forEachCount; ++i) {
424        unsigned int tmpSig = 0;
425        char tmpName[MAXLINE];
426
427        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
428            goto error;
429        }
430        if (sscanf(line, "%u - %" MAKE_STR(MAXLINE) "s",
431                   &tmpSig, tmpName) != 2) {
432          ALOGE("Invalid export forEach!: %s", line);
433          goto error;
434        }
435
436        // Lookup the expanded ForEach kernel.
437        strncat(tmpName, ".expand", MAXLINE-1-strlen(tmpName));
438        forEachSignatures[i] = tmpSig;
439        forEachFunctions[i] =
440            (ForEachFunc_t) dlsym(sharedObj, tmpName);
441        if (i != 0 && forEachFunctions[i] == nullptr) {
442            // Ignore missing root.expand functions.
443            // root() is always specified at location 0.
444            ALOGE("Failed to find forEach function address for %s: %s",
445                  tmpName, dlerror());
446            goto error;
447        }
448    }
449
450    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
451        goto error;
452    }
453    if (sscanf(line, OBJECT_SLOT_STR "%zu", &objectSlotCount) != 1) {
454        ALOGE("Invalid object slot count!: %s", line);
455        goto error;
456    }
457
458    for (size_t i = 0; i < objectSlotCount; ++i) {
459        uint32_t varNum = 0;
460        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
461            goto error;
462        }
463        if (sscanf(line, "%u", &varNum) != 1) {
464            ALOGE("Invalid object slot!: %s", line);
465            goto error;
466        }
467
468        if (varNum < varCount) {
469            fieldIsObject[varNum] = true;
470        }
471    }
472
473#ifndef RS_COMPATIBILITY_LIB
474    // Do not attempt to read pragmas or isThreadable flag in compat lib path.
475    // Neither is applicable for compat lib
476
477    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
478        goto error;
479    }
480
481    if (sscanf(line, PRAGMA_STR "%zu", &pragmaCount) != 1) {
482        ALOGE("Invalid pragma count!: %s", line);
483        goto error;
484    }
485
486    pragmaKeys = new const char*[pragmaCount];
487    if (pragmaKeys == nullptr) {
488        goto error;
489    }
490
491    pragmaValues = new const char*[pragmaCount];
492    if (pragmaValues == nullptr) {
493        goto error;
494    }
495
496    bzero(pragmaKeys, sizeof(char*) * pragmaCount);
497    bzero(pragmaValues, sizeof(char*) * pragmaCount);
498
499    for (size_t i = 0; i < pragmaCount; ++i) {
500        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
501            ALOGE("Unable to read pragma at index %zu!", i);
502            goto error;
503        }
504
505        char key[MAXLINE];
506        char value[MAXLINE] = ""; // initialize in case value is empty
507
508        // pragmas can just have a key and no value.  Only check to make sure
509        // that the key is not empty
510        if (sscanf(line, "%" MAKE_STR(MAXLINE) "s - %" MAKE_STR(MAXLINE) "s",
511                   key, value) == 0 ||
512            strlen(key) == 0)
513        {
514            ALOGE("Invalid pragma value!: %s", line);
515
516            goto error;
517        }
518
519        char *pKey = new char[strlen(key)+1];
520        strcpy(pKey, key);
521        pragmaKeys[i] = pKey;
522
523        char *pValue = new char[strlen(value)+1];
524        strcpy(pValue, value);
525        pragmaValues[i] = pValue;
526        //ALOGE("Pragma %zu: Key: '%s' Value: '%s'", i, pKey, pValue);
527    }
528
529    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
530        goto error;
531    }
532
533    char tmpFlag[4];
534    if (sscanf(line, THREADABLE_STR "%4s", tmpFlag) != 1) {
535        ALOGE("Invalid threadable flag!: %s", line);
536        goto error;
537    }
538    if (strcmp(tmpFlag, "yes") == 0) {
539        isThreadable = true;
540    } else if (strcmp(tmpFlag, "no") == 0) {
541        isThreadable = false;
542    } else {
543        ALOGE("Invalid threadable flag!: %s", tmpFlag);
544        goto error;
545    }
546
547#endif  // RS_COMPATIBILITY_LIB
548
549    return new ScriptExecutable(
550        RSContext, fieldAddress, fieldIsObject, varCount,
551        invokeFunctions, funcCount,
552        forEachFunctions, forEachSignatures, forEachCount,
553        pragmaKeys, pragmaValues, pragmaCount,
554        isThreadable);
555
556error:
557
558#ifndef RS_COMPATIBILITY_LIB
559    for (size_t idx = 0; idx < pragmaCount; ++idx) {
560        delete [] pragmaKeys[idx];
561        delete [] pragmaValues[idx];
562    }
563
564    delete[] pragmaValues;
565    delete[] pragmaKeys;
566#endif  // RS_COMPATIBILITY_LIB
567
568    delete[] forEachSignatures;
569    delete[] forEachFunctions;
570    delete[] invokeFunctions;
571    delete[] fieldIsObject;
572    delete[] fieldAddress;
573
574    return nullptr;
575}
576
577}  // namespace renderscript
578}  // namespace android
579