rsCpuExecutable.cpp revision aa6757ffc1b23d771566439c3179fdbc1e5ba569
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#define CHECKSUM_STR "buildChecksum: "
293
294// Copy up to a newline or size chars from str -> s, updating str
295// Returns s when successful and nullptr when '\0' is finally reached.
296static char* strgets(char *s, int size, const char **ppstr) {
297    if (!ppstr || !*ppstr || **ppstr == '\0' || size < 1) {
298        return nullptr;
299    }
300
301    int i;
302    for (i = 0; i < (size - 1); i++) {
303        s[i] = **ppstr;
304        (*ppstr)++;
305        if (s[i] == '\0') {
306            return s;
307        } else if (s[i] == '\n') {
308            s[i+1] = '\0';
309            return s;
310        }
311    }
312
313    // size has been exceeded.
314    s[i] = '\0';
315
316    return s;
317}
318
319ScriptExecutable* ScriptExecutable::createFromSharedObject(
320    Context* RSContext, void* sharedObj) {
321    char line[MAXLINE];
322
323    size_t varCount = 0;
324    size_t funcCount = 0;
325    size_t forEachCount = 0;
326    size_t objectSlotCount = 0;
327    size_t pragmaCount = 0;
328    bool isThreadable = true;
329
330    void** fieldAddress = nullptr;
331    bool* fieldIsObject = nullptr;
332    InvokeFunc_t* invokeFunctions = nullptr;
333    ForEachFunc_t* forEachFunctions = nullptr;
334    uint32_t* forEachSignatures = nullptr;
335    const char ** pragmaKeys = nullptr;
336    const char ** pragmaValues = nullptr;
337    char *checksum = nullptr;
338
339    const char *rsInfo = (const char *) dlsym(sharedObj, ".rs.info");
340
341    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
342        return nullptr;
343    }
344    if (sscanf(line, EXPORT_VAR_STR "%zu", &varCount) != 1) {
345        ALOGE("Invalid export var count!: %s", line);
346        return nullptr;
347    }
348
349    fieldAddress = new void*[varCount];
350    if (fieldAddress == nullptr) {
351        return nullptr;
352    }
353
354    fieldIsObject = new bool[varCount];
355    if (fieldIsObject == nullptr) {
356        goto error;
357    }
358
359    for (size_t i = 0; i < varCount; ++i) {
360        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
361            goto error;
362        }
363        char *c = strrchr(line, '\n');
364        if (c) {
365            *c = '\0';
366        }
367        void* addr = dlsym(sharedObj, line);
368        if (addr == nullptr) {
369            ALOGE("Failed to find variable address for %s: %s",
370                  line, dlerror());
371            // Not a critical error if we don't find a global variable.
372        }
373        fieldAddress[i] = addr;
374        fieldIsObject[i] = false;
375    }
376
377    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
378        goto error;
379    }
380    if (sscanf(line, EXPORT_FUNC_STR "%zu", &funcCount) != 1) {
381        ALOGE("Invalid export func count!: %s", line);
382        goto error;
383    }
384
385    invokeFunctions = new InvokeFunc_t[funcCount];
386    if (invokeFunctions == nullptr) {
387        goto error;
388    }
389
390    for (size_t i = 0; i < funcCount; ++i) {
391        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
392            goto error;
393        }
394        char *c = strrchr(line, '\n');
395        if (c) {
396            *c = '\0';
397        }
398
399        invokeFunctions[i] = (InvokeFunc_t) dlsym(sharedObj, line);
400        if (invokeFunctions[i] == nullptr) {
401            ALOGE("Failed to get function address for %s(): %s",
402                  line, dlerror());
403            goto error;
404        }
405    }
406
407    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
408        goto error;
409    }
410    if (sscanf(line, EXPORT_FOREACH_STR "%zu", &forEachCount) != 1) {
411        ALOGE("Invalid export forEach count!: %s", line);
412        goto error;
413    }
414
415    forEachFunctions = new ForEachFunc_t[forEachCount];
416    if (forEachFunctions == nullptr) {
417        goto error;
418    }
419
420    forEachSignatures = new uint32_t[forEachCount];
421    if (forEachSignatures == nullptr) {
422        goto error;
423    }
424
425    for (size_t i = 0; i < forEachCount; ++i) {
426        unsigned int tmpSig = 0;
427        char tmpName[MAXLINE];
428
429        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
430            goto error;
431        }
432        if (sscanf(line, "%u - %" MAKE_STR(MAXLINE) "s",
433                   &tmpSig, tmpName) != 2) {
434          ALOGE("Invalid export forEach!: %s", line);
435          goto error;
436        }
437
438        // Lookup the expanded ForEach kernel.
439        strncat(tmpName, ".expand", MAXLINE-1-strlen(tmpName));
440        forEachSignatures[i] = tmpSig;
441        forEachFunctions[i] =
442            (ForEachFunc_t) dlsym(sharedObj, tmpName);
443        if (i != 0 && forEachFunctions[i] == nullptr) {
444            // Ignore missing root.expand functions.
445            // root() is always specified at location 0.
446            ALOGE("Failed to find forEach function address for %s: %s",
447                  tmpName, dlerror());
448            goto error;
449        }
450    }
451
452    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
453        goto error;
454    }
455    if (sscanf(line, OBJECT_SLOT_STR "%zu", &objectSlotCount) != 1) {
456        ALOGE("Invalid object slot count!: %s", line);
457        goto error;
458    }
459
460    for (size_t i = 0; i < objectSlotCount; ++i) {
461        uint32_t varNum = 0;
462        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
463            goto error;
464        }
465        if (sscanf(line, "%u", &varNum) != 1) {
466            ALOGE("Invalid object slot!: %s", line);
467            goto error;
468        }
469
470        if (varNum < varCount) {
471            fieldIsObject[varNum] = true;
472        }
473    }
474
475#ifndef RS_COMPATIBILITY_LIB
476    // Do not attempt to read pragmas or isThreadable flag in compat lib path.
477    // Neither is applicable for compat lib
478
479    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
480        goto error;
481    }
482
483    if (sscanf(line, PRAGMA_STR "%zu", &pragmaCount) != 1) {
484        ALOGE("Invalid pragma count!: %s", line);
485        goto error;
486    }
487
488    pragmaKeys = new const char*[pragmaCount];
489    if (pragmaKeys == nullptr) {
490        goto error;
491    }
492
493    pragmaValues = new const char*[pragmaCount];
494    if (pragmaValues == nullptr) {
495        goto error;
496    }
497
498    bzero(pragmaKeys, sizeof(char*) * pragmaCount);
499    bzero(pragmaValues, sizeof(char*) * pragmaCount);
500
501    for (size_t i = 0; i < pragmaCount; ++i) {
502        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
503            ALOGE("Unable to read pragma at index %zu!", i);
504            goto error;
505        }
506
507        char key[MAXLINE];
508        char value[MAXLINE] = ""; // initialize in case value is empty
509
510        // pragmas can just have a key and no value.  Only check to make sure
511        // that the key is not empty
512        if (sscanf(line, "%" MAKE_STR(MAXLINE) "s - %" MAKE_STR(MAXLINE) "s",
513                   key, value) == 0 ||
514            strlen(key) == 0)
515        {
516            ALOGE("Invalid pragma value!: %s", line);
517
518            goto error;
519        }
520
521        char *pKey = new char[strlen(key)+1];
522        strcpy(pKey, key);
523        pragmaKeys[i] = pKey;
524
525        char *pValue = new char[strlen(value)+1];
526        strcpy(pValue, value);
527        pragmaValues[i] = pValue;
528        //ALOGE("Pragma %zu: Key: '%s' Value: '%s'", i, pKey, pValue);
529    }
530
531    if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
532        goto error;
533    }
534
535    char tmpFlag[4];
536    if (sscanf(line, THREADABLE_STR "%4s", tmpFlag) != 1) {
537        ALOGE("Invalid threadable flag!: %s", line);
538        goto error;
539    }
540    if (strcmp(tmpFlag, "yes") == 0) {
541        isThreadable = true;
542    } else if (strcmp(tmpFlag, "no") == 0) {
543        isThreadable = false;
544    } else {
545        ALOGE("Invalid threadable flag!: %s", tmpFlag);
546        goto error;
547    }
548
549    if (strgets(line, MAXLINE, &rsInfo) != nullptr) {
550        if (strncmp(line, CHECKSUM_STR, strlen(CHECKSUM_STR)) != 0) {
551            ALOGE("Invalid checksum flag!: %s", line);
552            goto error;
553        }
554
555        // consume trailing newline character
556        char *c = strrchr(line, '\n');
557        if (c) {
558            *c = '\0';
559        }
560
561        char *checksumStart = &line[strlen(CHECKSUM_STR)];
562        checksum = new char[strlen(checksumStart) + 1];
563        strcpy(checksum, checksumStart);
564    }
565    else {
566        goto error;
567    }
568
569#endif  // RS_COMPATIBILITY_LIB
570
571    return new ScriptExecutable(
572        RSContext, fieldAddress, fieldIsObject, varCount,
573        invokeFunctions, funcCount,
574        forEachFunctions, forEachSignatures, forEachCount,
575        pragmaKeys, pragmaValues, pragmaCount,
576        isThreadable, checksum);
577
578error:
579
580#ifndef RS_COMPATIBILITY_LIB
581    delete[] checksum;
582
583    for (size_t idx = 0; idx < pragmaCount; ++idx) {
584        delete [] pragmaKeys[idx];
585        delete [] pragmaValues[idx];
586    }
587
588    delete[] pragmaValues;
589    delete[] pragmaKeys;
590#endif  // RS_COMPATIBILITY_LIB
591
592    delete[] forEachSignatures;
593    delete[] forEachFunctions;
594    delete[] invokeFunctions;
595    delete[] fieldIsObject;
596    delete[] fieldAddress;
597
598    return nullptr;
599}
600
601}  // namespace renderscript
602}  // namespace android
603