rsCpuScript.cpp revision 584e58bb75a4d742e3a9dfcfea36eba59b38dbd9
1/*
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
7 *
8 *      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
17#include "rsCpuCore.h"
18#include "rsCpuScript.h"
19
20#ifdef RS_COMPATIBILITY_LIB
21    #include <set>
22    #include <string>
23    #include <dlfcn.h>
24    #include <stdio.h>
25    #include <stdlib.h>
26    #include <string.h>
27    #include <sys/stat.h>
28    #include <unistd.h>
29    #include <fstream>
30    #include <iostream>
31#else
32    #include <bcc/BCCContext.h>
33    #include <bcc/Config/Config.h>
34    #include <bcc/Renderscript/RSCompilerDriver.h>
35    #include <bcc/Renderscript/RSExecutable.h>
36    #include <bcc/Renderscript/RSInfo.h>
37    #include <bcinfo/MetadataExtractor.h>
38    #include <cutils/properties.h>
39
40    #include <sys/types.h>
41    #include <sys/wait.h>
42    #include <unistd.h>
43
44    #include <string>
45    #include <vector>
46#endif
47
48namespace {
49#ifdef RS_COMPATIBILITY_LIB
50
51// Create a len length string containing random characters from [A-Za-z0-9].
52static std::string getRandomString(size_t len) {
53    char buf[len + 1];
54    for (size_t i = 0; i < len; i++) {
55        uint32_t r = arc4random() & 0xffff;
56        r %= 62;
57        if (r < 26) {
58            // lowercase
59            buf[i] = 'a' + r;
60        } else if (r < 52) {
61            // uppercase
62            buf[i] = 'A' + (r - 26);
63        } else {
64            // Use a number
65            buf[i] = '0' + (r - 52);
66        }
67    }
68    buf[len] = '\0';
69    return std::string(buf);
70}
71
72// Check if a path exists and attempt to create it if it doesn't.
73static bool ensureCacheDirExists(const char *path) {
74    if (access(path, R_OK | W_OK | X_OK) == 0) {
75        // Done if we can rwx the directory
76        return true;
77    }
78    if (mkdir(path, 0700) == 0) {
79        return true;
80    }
81    return false;
82}
83
84// Copy the file named \p srcFile to \p dstFile.
85// Return 0 on success and -1 if anything wasn't copied.
86static int copyFile(const char *dstFile, const char *srcFile) {
87    std::ifstream srcStream(srcFile);
88    if (!srcStream) {
89        ALOGE("Could not verify or read source file: %s", srcFile);
90        return -1;
91    }
92    std::ofstream dstStream(dstFile);
93    if (!dstStream) {
94        ALOGE("Could not verify or write destination file: %s", dstFile);
95        return -1;
96    }
97    dstStream << srcStream.rdbuf();
98    if (!dstStream) {
99        ALOGE("Could not write destination file: %s", dstFile);
100        return -1;
101    }
102
103    srcStream.close();
104    dstStream.close();
105
106    return 0;
107}
108
109// Attempt to load the shared library from origName, but then fall back to
110// creating a copy of the shared library if necessary (to ensure instancing).
111// This function returns the dlopen()-ed handle if successful.
112static void *loadSOHelper(const char *origName, const char *cacheDir,
113                          const char *resName) {
114    // Keep track of which .so libraries have been loaded. Once a library is
115    // in the set (per-process granularity), we must instead make a copy of
116    // the original shared object (randomly named .so file) and load that one
117    // instead. If we don't do this, we end up aliasing global data between
118    // the various Script instances (which are supposed to be completely
119    // independent).
120    static std::set<std::string> LoadedLibraries;
121
122    void *loaded = nullptr;
123
124    // Skip everything if we don't even have the original library available.
125    if (access(origName, F_OK) != 0) {
126        return nullptr;
127    }
128
129    // Common path is that we have not loaded this Script/library before.
130    if (LoadedLibraries.find(origName) == LoadedLibraries.end()) {
131        loaded = dlopen(origName, RTLD_NOW | RTLD_LOCAL);
132        if (loaded) {
133            LoadedLibraries.insert(origName);
134        }
135        return loaded;
136    }
137
138    std::string newName(cacheDir);
139    newName.append("/com.android.renderscript.cache/");
140
141    if (!ensureCacheDirExists(newName.c_str())) {
142        ALOGE("Could not verify or create cache dir: %s", cacheDir);
143        return nullptr;
144    }
145
146    // Construct an appropriately randomized filename for the copy.
147    newName.append("librs.");
148    newName.append(resName);
149    newName.append("#");
150    newName.append(getRandomString(6));  // 62^6 potential filename variants.
151    newName.append(".so");
152
153    int r = copyFile(newName.c_str(), origName);
154    if (r != 0) {
155        ALOGE("Could not create copy %s -> %s", origName, newName.c_str());
156        return nullptr;
157    }
158    loaded = dlopen(newName.c_str(), RTLD_NOW | RTLD_LOCAL);
159    r = unlink(newName.c_str());
160    if (r != 0) {
161        ALOGE("Could not unlink copy %s", newName.c_str());
162    }
163    if (loaded) {
164        LoadedLibraries.insert(newName.c_str());
165    }
166
167    return loaded;
168}
169
170// Load the shared library referred to by cacheDir and resName. If we have
171// already loaded this library, we instead create a new copy (in the
172// cache dir) and then load that. We then immediately destroy the copy.
173// This is required behavior to implement script instancing for the support
174// library, since shared objects are loaded and de-duped by name only.
175static void *loadSharedLibrary(const char *cacheDir, const char *resName) {
176    void *loaded = nullptr;
177#ifndef RS_SERVER
178    std::string scriptSOName(cacheDir);
179    size_t cutPos = scriptSOName.rfind("cache");
180    if (cutPos != std::string::npos) {
181        scriptSOName.erase(cutPos);
182    } else {
183        ALOGE("Found peculiar cacheDir (missing \"cache\"): %s", cacheDir);
184    }
185    scriptSOName.append("/lib/librs.");
186#else
187    std::string scriptSOName("lib");
188#endif
189    scriptSOName.append(resName);
190    scriptSOName.append(".so");
191
192    // We should check if we can load the library from the standard app
193    // location for shared libraries first.
194    loaded = loadSOHelper(scriptSOName.c_str(), cacheDir, resName);
195
196    if (loaded == nullptr) {
197        ALOGE("Unable to open shared library (%s): %s",
198              scriptSOName.c_str(), dlerror());
199
200        // One final attempt to find the library in "/system/lib".
201        // We do this to allow bundled applications to use the compatibility
202        // library fallback path. Those applications don't have a private
203        // library path, so they need to install to the system directly.
204        // Note that this is really just a testing path.
205        std::string scriptSONameSystem("/system/lib/librs.");
206        scriptSONameSystem.append(resName);
207        scriptSONameSystem.append(".so");
208        loaded = loadSOHelper(scriptSONameSystem.c_str(), cacheDir,
209                              resName);
210        if (loaded == nullptr) {
211            ALOGE("Unable to open system shared library (%s): %s",
212                  scriptSONameSystem.c_str(), dlerror());
213        }
214    }
215
216    return loaded;
217}
218
219#else  // RS_COMPATIBILITY_LIB is not defined
220
221static bool is_force_recompile() {
222#ifdef RS_SERVER
223  return false;
224#else
225  char buf[PROPERTY_VALUE_MAX];
226
227  // Re-compile if floating point precision has been overridden.
228  property_get("debug.rs.precision", buf, "");
229  if (buf[0] != '\0') {
230    return true;
231  }
232
233  // Re-compile if debug.rs.forcerecompile is set.
234  property_get("debug.rs.forcerecompile", buf, "0");
235  if ((::strcmp(buf, "1") == 0) || (::strcmp(buf, "true") == 0)) {
236    return true;
237  } else {
238    return false;
239  }
240#endif  // RS_SERVER
241}
242
243const static char *BCC_EXE_PATH = "/system/bin/bcc";
244
245static void setCompileArguments(std::vector<const char*>* args,
246                                const std::string& bcFileName,
247                                const char* cacheDir, const char* resName,
248                                const char* core_lib, bool useRSDebugContext,
249                                const char* bccPluginName) {
250    rsAssert(cacheDir && resName && core_lib);
251    args->push_back(BCC_EXE_PATH);
252    args->push_back("-o");
253    args->push_back(resName);
254    args->push_back("-output_path");
255    args->push_back(cacheDir);
256    args->push_back("-bclib");
257    args->push_back(core_lib);
258    args->push_back("-mtriple");
259    args->push_back(DEFAULT_TARGET_TRIPLE_STRING);
260
261    // Enable workaround for A53 codegen by default.
262#if defined(__aarch64__) && !defined(DISABLE_A53_WORKAROUND)
263    args->push_back("-aarch64-fix-cortex-a53-835769");
264#endif
265
266    // Execute the bcc compiler.
267    if (useRSDebugContext) {
268        args->push_back("-rs-debug-ctx");
269    } else {
270        // Only load additional libraries for compiles that don't use
271        // the debug context.
272        if (bccPluginName && strlen(bccPluginName) > 0) {
273            args->push_back("-load");
274            args->push_back(bccPluginName);
275        }
276    }
277
278    args->push_back(bcFileName.c_str());
279    args->push_back(nullptr);
280}
281
282static bool compileBitcode(const std::string &bcFileName,
283                           const char *bitcode,
284                           size_t bitcodeSize,
285                           const char **compileArguments,
286                           const std::string &compileCommandLine) {
287    rsAssert(bitcode && bitcodeSize);
288
289    FILE *bcfile = fopen(bcFileName.c_str(), "w");
290    if (!bcfile) {
291        ALOGE("Could not write to %s", bcFileName.c_str());
292        return false;
293    }
294    size_t nwritten = fwrite(bitcode, 1, bitcodeSize, bcfile);
295    fclose(bcfile);
296    if (nwritten != bitcodeSize) {
297        ALOGE("Could not write %zu bytes to %s", bitcodeSize,
298              bcFileName.c_str());
299        return false;
300    }
301
302    pid_t pid = fork();
303
304    switch (pid) {
305    case -1: {  // Error occurred (we attempt no recovery)
306        ALOGE("Couldn't fork for bcc compiler execution");
307        return false;
308    }
309    case 0: {  // Child process
310        ALOGV("Invoking BCC with: %s", compileCommandLine.c_str());
311        execv(BCC_EXE_PATH, (char* const*)compileArguments);
312
313        ALOGE("execv() failed: %s", strerror(errno));
314        abort();
315        return false;
316    }
317    default: {  // Parent process (actual driver)
318        // Wait on child process to finish compiling the source.
319        int status = 0;
320        pid_t w = waitpid(pid, &status, 0);
321        if (w == -1) {
322            ALOGE("Could not wait for bcc compiler");
323            return false;
324        }
325
326        if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
327            return true;
328        }
329
330        ALOGE("bcc compiler terminated unexpectedly");
331        return false;
332    }
333    }
334}
335
336#endif  // !defined(RS_COMPATIBILITY_LIB)
337}  // namespace
338
339namespace android {
340namespace renderscript {
341
342#ifdef RS_COMPATIBILITY_LIB
343#define MAXLINE 500
344#define MAKE_STR_HELPER(S) #S
345#define MAKE_STR(S) MAKE_STR_HELPER(S)
346#define EXPORT_VAR_STR "exportVarCount: "
347#define EXPORT_FUNC_STR "exportFuncCount: "
348#define EXPORT_FOREACH_STR "exportForEachCount: "
349#define OBJECT_SLOT_STR "objectSlotCount: "
350
351// Copy up to a newline or size chars from str -> s, updating str
352// Returns s when successful and nullptr when '\0' is finally reached.
353static char* strgets(char *s, int size, const char **ppstr) {
354    if (!ppstr || !*ppstr || **ppstr == '\0' || size < 1) {
355        return nullptr;
356    }
357
358    int i;
359    for (i = 0; i < (size - 1); i++) {
360        s[i] = **ppstr;
361        (*ppstr)++;
362        if (s[i] == '\0') {
363            return s;
364        } else if (s[i] == '\n') {
365            s[i+1] = '\0';
366            return s;
367        }
368    }
369
370    // size has been exceeded.
371    s[i] = '\0';
372
373    return s;
374}
375#endif
376
377RsdCpuScriptImpl::RsdCpuScriptImpl(RsdCpuReferenceImpl *ctx, const Script *s) {
378    mCtx = ctx;
379    mScript = s;
380
381#ifdef RS_COMPATIBILITY_LIB
382    mScriptSO = nullptr;
383    mInvokeFunctions = nullptr;
384    mForEachFunctions = nullptr;
385    mFieldAddress = nullptr;
386    mFieldIsObject = nullptr;
387    mForEachSignatures = nullptr;
388#else
389    mCompilerDriver = nullptr;
390    mExecutable = nullptr;
391#endif
392
393
394    mRoot = nullptr;
395    mRootExpand = nullptr;
396    mInit = nullptr;
397    mFreeChildren = nullptr;
398
399
400    mBoundAllocs = nullptr;
401    mIntrinsicData = nullptr;
402    mIsThreadable = true;
403}
404
405
406bool RsdCpuScriptImpl::init(char const *resName, char const *cacheDir,
407                            uint8_t const *bitcode, size_t bitcodeSize,
408                            uint32_t flags, char const *bccPluginName) {
409    //ALOGE("rsdScriptCreate %p %p %p %p %i %i %p", rsc, resName, cacheDir, bitcode, bitcodeSize, flags, lookupFunc);
410    //ALOGE("rsdScriptInit %p %p", rsc, script);
411
412    mCtx->lockMutex();
413#ifndef RS_COMPATIBILITY_LIB
414    bool useRSDebugContext = false;
415
416    mCompilerDriver = nullptr;
417    mExecutable = nullptr;
418
419    mCompilerDriver = new bcc::RSCompilerDriver();
420    if (mCompilerDriver == nullptr) {
421        ALOGE("bcc: FAILS to create compiler driver (out of memory)");
422        mCtx->unlockMutex();
423        return false;
424    }
425
426    // Configure symbol resolvers (via compiler-rt and the RS runtime).
427    mRSRuntime.setLookupFunction(lookupRuntimeStub);
428    mRSRuntime.setContext(this);
429    mResolver.chainResolver(mCompilerRuntime);
430    mResolver.chainResolver(mRSRuntime);
431
432    // Run any compiler setup functions we have been provided with.
433    RSSetupCompilerCallback setupCompilerCallback =
434            mCtx->getSetupCompilerCallback();
435    if (setupCompilerCallback != nullptr) {
436        setupCompilerCallback(mCompilerDriver);
437    }
438
439    bcinfo::MetadataExtractor bitcodeMetadata((const char *) bitcode, bitcodeSize);
440    if (!bitcodeMetadata.extract()) {
441        ALOGE("Could not extract metadata from bitcode");
442        mCtx->unlockMutex();
443        return false;
444    }
445
446    const char* core_lib = findCoreLib(bitcodeMetadata, (const char*)bitcode, bitcodeSize);
447
448    if (mCtx->getContext()->getContextType() == RS_CONTEXT_TYPE_DEBUG) {
449        mCompilerDriver->setDebugContext(true);
450        useRSDebugContext = true;
451    }
452
453    std::string bcFileName(cacheDir);
454    bcFileName.append("/");
455    bcFileName.append(resName);
456    bcFileName.append(".bc");
457
458    std::vector<const char*> compileArguments;
459    setCompileArguments(&compileArguments, bcFileName, cacheDir, resName, core_lib,
460                        useRSDebugContext, bccPluginName);
461    // The last argument of compileArguments ia a nullptr, so remove 1 from the size.
462    std::string compileCommandLine =
463                bcc::getCommandLine(compileArguments.size() - 1, compileArguments.data());
464
465    if (!is_force_recompile()) {
466        // Load the compiled script that's in the cache, if any.
467        mExecutable = bcc::RSCompilerDriver::loadScript(cacheDir, resName, (const char*)bitcode,
468                                                        bitcodeSize, compileCommandLine.c_str(),
469                                                        mResolver);
470    }
471
472    // If we can't, it's either not there or out of date.  We compile the bit code and try loading
473    // again.
474    if (mExecutable == nullptr) {
475        if (!compileBitcode(bcFileName, (const char*)bitcode, bitcodeSize, compileArguments.data(),
476                            compileCommandLine)) {
477            ALOGE("bcc: FAILS to compile '%s'", resName);
478            mCtx->unlockMutex();
479            return false;
480        }
481        mExecutable = bcc::RSCompilerDriver::loadScript(cacheDir, resName, (const char*)bitcode,
482                                                        bitcodeSize, compileCommandLine.c_str(),
483                                                        mResolver);
484        if (mExecutable == nullptr) {
485            ALOGE("bcc: FAILS to load freshly compiled executable for '%s'", resName);
486            mCtx->unlockMutex();
487            return false;
488        }
489    }
490
491    mExecutable->setThreadable(mIsThreadable);
492    if (!mExecutable->syncInfo()) {
493        ALOGW("bcc: FAILS to synchronize the RS info file to the disk");
494    }
495
496    mRoot = reinterpret_cast<int (*)()>(mExecutable->getSymbolAddress("root"));
497    mRootExpand =
498        reinterpret_cast<int (*)()>(mExecutable->getSymbolAddress("root.expand"));
499    mInit = reinterpret_cast<void (*)()>(mExecutable->getSymbolAddress("init"));
500    mFreeChildren =
501        reinterpret_cast<void (*)()>(mExecutable->getSymbolAddress(".rs.dtor"));
502
503
504    if (bitcodeMetadata.getExportVarCount()) {
505        mBoundAllocs = new Allocation *[bitcodeMetadata.getExportVarCount()];
506        memset(mBoundAllocs, 0, sizeof(void *) * bitcodeMetadata.getExportVarCount());
507    }
508
509    for (size_t i = 0; i < bitcodeMetadata.getExportForEachSignatureCount(); i++) {
510        char* name = new char[strlen(bitcodeMetadata.getExportForEachNameList()[i]) + 1];
511        mExportedForEachFuncList.push_back(
512                    std::make_pair(name, bitcodeMetadata.getExportForEachSignatureList()[i]));
513    }
514
515#else  // RS_COMPATIBILITY_LIB is defined
516
517    mScriptSO = loadSharedLibrary(cacheDir, resName);
518
519    if (mScriptSO) {
520        char line[MAXLINE];
521        mRoot = (RootFunc_t) dlsym(mScriptSO, "root");
522        if (mRoot) {
523            //ALOGE("Found root(): %p", mRoot);
524        }
525        mRootExpand = (RootFunc_t) dlsym(mScriptSO, "root.expand");
526        if (mRootExpand) {
527            //ALOGE("Found root.expand(): %p", mRootExpand);
528        }
529        mInit = (InvokeFunc_t) dlsym(mScriptSO, "init");
530        if (mInit) {
531            //ALOGE("Found init(): %p", mInit);
532        }
533        mFreeChildren = (InvokeFunc_t) dlsym(mScriptSO, ".rs.dtor");
534        if (mFreeChildren) {
535            //ALOGE("Found .rs.dtor(): %p", mFreeChildren);
536        }
537
538        const char *rsInfo = (const char *) dlsym(mScriptSO, ".rs.info");
539        if (rsInfo) {
540            //ALOGE("Found .rs.info(): %p - %s", rsInfo, rsInfo);
541        }
542
543        size_t varCount = 0;
544        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
545            goto error;
546        }
547        if (sscanf(line, EXPORT_VAR_STR "%zu", &varCount) != 1) {
548            ALOGE("Invalid export var count!: %s", line);
549            goto error;
550        }
551
552        mExportedVariableCount = varCount;
553        //ALOGE("varCount: %zu", varCount);
554        if (varCount > 0) {
555            // Start by creating/zeroing this member, since we don't want to
556            // accidentally clean up invalid pointers later (if we error out).
557            mFieldIsObject = new bool[varCount];
558            if (mFieldIsObject == nullptr) {
559                goto error;
560            }
561            memset(mFieldIsObject, 0, varCount * sizeof(*mFieldIsObject));
562            mFieldAddress = new void*[varCount];
563            if (mFieldAddress == nullptr) {
564                goto error;
565            }
566            for (size_t i = 0; i < varCount; ++i) {
567                if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
568                    goto error;
569                }
570                char *c = strrchr(line, '\n');
571                if (c) {
572                    *c = '\0';
573                }
574                mFieldAddress[i] = dlsym(mScriptSO, line);
575                if (mFieldAddress[i] == nullptr) {
576                    ALOGE("Failed to find variable address for %s: %s",
577                          line, dlerror());
578                    // Not a critical error if we don't find a global variable.
579                }
580                else {
581                    //ALOGE("Found variable %s at %p", line,
582                    //mFieldAddress[i]);
583                }
584            }
585        }
586
587        size_t funcCount = 0;
588        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
589            goto error;
590        }
591        if (sscanf(line, EXPORT_FUNC_STR "%zu", &funcCount) != 1) {
592            ALOGE("Invalid export func count!: %s", line);
593            goto error;
594        }
595
596        mExportedFunctionCount = funcCount;
597        //ALOGE("funcCount: %zu", funcCount);
598
599        if (funcCount > 0) {
600            mInvokeFunctions = new InvokeFunc_t[funcCount];
601            if (mInvokeFunctions == nullptr) {
602                goto error;
603            }
604            for (size_t i = 0; i < funcCount; ++i) {
605                if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
606                    goto error;
607                }
608                char *c = strrchr(line, '\n');
609                if (c) {
610                    *c = '\0';
611                }
612
613                mInvokeFunctions[i] = (InvokeFunc_t) dlsym(mScriptSO, line);
614                if (mInvokeFunctions[i] == nullptr) {
615                    ALOGE("Failed to get function address for %s(): %s",
616                          line, dlerror());
617                    goto error;
618                }
619                else {
620                    //ALOGE("Found InvokeFunc_t %s at %p", line, mInvokeFunctions[i]);
621                }
622            }
623        }
624
625        size_t forEachCount = 0;
626        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
627            goto error;
628        }
629        if (sscanf(line, EXPORT_FOREACH_STR "%zu", &forEachCount) != 1) {
630            ALOGE("Invalid export forEach count!: %s", line);
631            goto error;
632        }
633
634        if (forEachCount > 0) {
635
636            mForEachSignatures = new uint32_t[forEachCount];
637            if (mForEachSignatures == nullptr) {
638                goto error;
639            }
640            mForEachFunctions = new ForEachFunc_t[forEachCount];
641            if (mForEachFunctions == nullptr) {
642                goto error;
643            }
644            for (size_t i = 0; i < forEachCount; ++i) {
645                unsigned int tmpSig = 0;
646                char tmpName[MAXLINE];
647
648                if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
649                    goto error;
650                }
651                if (sscanf(line, "%u - %" MAKE_STR(MAXLINE) "s",
652                           &tmpSig, tmpName) != 2) {
653                    ALOGE("Invalid export forEach!: %s", line);
654                    goto error;
655                }
656
657                // Lookup the expanded ForEach kernel.
658                strncat(tmpName, ".expand", MAXLINE-1-strlen(tmpName));
659                mForEachSignatures[i] = tmpSig;
660                mForEachFunctions[i] =
661                        (ForEachFunc_t) dlsym(mScriptSO, tmpName);
662                if (i != 0 && mForEachFunctions[i] == nullptr) {
663                    // Ignore missing root.expand functions.
664                    // root() is always specified at location 0.
665                    ALOGE("Failed to find forEach function address for %s: %s",
666                          tmpName, dlerror());
667                    goto error;
668                }
669                else {
670                    //ALOGE("Found forEach %s at %p", tmpName, mForEachFunctions[i]);
671                }
672            }
673        }
674
675        size_t objectSlotCount = 0;
676        if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
677            goto error;
678        }
679        if (sscanf(line, OBJECT_SLOT_STR "%zu", &objectSlotCount) != 1) {
680            ALOGE("Invalid object slot count!: %s", line);
681            goto error;
682        }
683
684        if (objectSlotCount > 0) {
685            rsAssert(varCount > 0);
686            for (size_t i = 0; i < objectSlotCount; ++i) {
687                uint32_t varNum = 0;
688                if (strgets(line, MAXLINE, &rsInfo) == nullptr) {
689                    goto error;
690                }
691                if (sscanf(line, "%u", &varNum) != 1) {
692                    ALOGE("Invalid object slot!: %s", line);
693                    goto error;
694                }
695
696                if (varNum < varCount) {
697                    mFieldIsObject[varNum] = true;
698                }
699            }
700        }
701
702        if (varCount > 0) {
703            mBoundAllocs = new Allocation *[varCount];
704            memset(mBoundAllocs, 0, varCount * sizeof(*mBoundAllocs));
705        }
706
707        if (mScriptSO == (void*)1) {
708            //rsdLookupRuntimeStub(script, "acos");
709        }
710    } else {
711        goto error;
712    }
713#endif
714    mCtx->unlockMutex();
715    return true;
716
717#ifdef RS_COMPATIBILITY_LIB
718error:
719
720    mCtx->unlockMutex();
721    delete[] mInvokeFunctions;
722    delete[] mForEachFunctions;
723    delete[] mFieldAddress;
724    delete[] mFieldIsObject;
725    delete[] mForEachSignatures;
726    delete[] mBoundAllocs;
727    if (mScriptSO) {
728        dlclose(mScriptSO);
729    }
730    return false;
731#endif
732}
733
734#ifndef RS_COMPATIBILITY_LIB
735
736#ifdef __LP64__
737#define SYSLIBPATH "/system/lib64"
738#else
739#define SYSLIBPATH "/system/lib"
740#endif
741
742const char* RsdCpuScriptImpl::findCoreLib(const bcinfo::MetadataExtractor& ME, const char* bitcode,
743                                          size_t bitcodeSize) {
744    const char* defaultLib = SYSLIBPATH"/libclcore.bc";
745
746    // If we're debugging, use the debug library.
747    if (mCtx->getContext()->getContextType() == RS_CONTEXT_TYPE_DEBUG) {
748        return SYSLIBPATH"/libclcore_debug.bc";
749    }
750
751    // If a callback has been registered to specify a library, use that.
752    RSSelectRTCallback selectRTCallback = mCtx->getSelectRTCallback();
753    if (selectRTCallback != nullptr) {
754        return selectRTCallback((const char*)bitcode, bitcodeSize);
755    }
756
757    // Check for a platform specific library
758#if defined(ARCH_ARM_HAVE_NEON) && !defined(DISABLE_CLCORE_NEON)
759    enum bcinfo::RSFloatPrecision prec = ME.getRSFloatPrecision();
760    if (prec == bcinfo::RS_FP_Relaxed) {
761        // NEON-capable ARMv7a devices can use an accelerated math library
762        // for all reduced precision scripts.
763        // ARMv8 does not use NEON, as ASIMD can be used with all precision
764        // levels.
765        return SYSLIBPATH"/libclcore_neon.bc";
766    } else {
767        return defaultLib;
768    }
769#elif defined(__i386__) || defined(__x86_64__)
770    // x86 devices will use an optimized library.
771    return SYSLIBPATH"/libclcore_x86.bc";
772#else
773    return defaultLib;
774#endif
775}
776
777#endif
778
779void RsdCpuScriptImpl::populateScript(Script *script) {
780#ifndef RS_COMPATIBILITY_LIB
781    // Copy info over to runtime
782    script->mHal.info.exportedFunctionCount = mExecutable->getExportFuncAddrs().size();
783    script->mHal.info.exportedVariableCount = mExecutable->getExportVarAddrs().size();
784    script->mHal.info.exportedForeachFuncList = &mExportedForEachFuncList[0];
785    script->mHal.info.exportedPragmaCount = mExecutable->getPragmaKeys().size();
786    script->mHal.info.exportedPragmaKeyList =
787        const_cast<const char**>(&mExecutable->getPragmaKeys().front());
788    script->mHal.info.exportedPragmaValueList =
789        const_cast<const char**>(&mExecutable->getPragmaValues().front());
790
791    if (mRootExpand) {
792        script->mHal.info.root = mRootExpand;
793    } else {
794        script->mHal.info.root = mRoot;
795    }
796#else
797    // Copy info over to runtime
798    script->mHal.info.exportedFunctionCount = mExportedFunctionCount;
799    script->mHal.info.exportedVariableCount = mExportedVariableCount;
800    script->mHal.info.exportedPragmaCount = 0;
801    script->mHal.info.exportedPragmaKeyList = 0;
802    script->mHal.info.exportedPragmaValueList = 0;
803
804    // Bug, need to stash in metadata
805    if (mRootExpand) {
806        script->mHal.info.root = mRootExpand;
807    } else {
808        script->mHal.info.root = mRoot;
809    }
810#endif
811}
812
813
814typedef void (*rs_t)(const void *, void *, const void *, uint32_t, uint32_t, uint32_t, uint32_t);
815
816void RsdCpuScriptImpl::forEachMtlsSetup(const Allocation ** ains,
817                                        uint32_t inLen,
818                                        Allocation * aout,
819                                        const void * usr, uint32_t usrLen,
820                                        const RsScriptCall *sc,
821                                        MTLaunchStruct *mtls) {
822
823    memset(mtls, 0, sizeof(MTLaunchStruct));
824
825    for (int index = inLen; --index >= 0;) {
826        const Allocation* ain = ains[index];
827
828        // possible for this to occur if IO_OUTPUT/IO_INPUT with no bound surface
829        if (ain != nullptr &&
830            (const uint8_t *)ain->mHal.drvState.lod[0].mallocPtr == nullptr) {
831
832            mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT,
833                                         "rsForEach called with null in allocations");
834            return;
835        }
836    }
837
838    if (aout &&
839        (const uint8_t *)aout->mHal.drvState.lod[0].mallocPtr == nullptr) {
840
841        mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT,
842                                     "rsForEach called with null out allocations");
843        return;
844    }
845
846    if (inLen > 0) {
847        const Allocation *ain0   = ains[0];
848        const Type       *inType = ain0->getType();
849
850        mtls->fep.dimX = inType->getDimX();
851        mtls->fep.dimY = inType->getDimY();
852        mtls->fep.dimZ = inType->getDimZ();
853
854        for (int Index = inLen; --Index >= 1;) {
855            if (!ain0->hasSameDims(ains[Index])) {
856                mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT,
857                  "Failed to launch kernel; dimensions of input and output allocations do not match.");
858
859                return;
860            }
861        }
862
863    } else if (aout != nullptr) {
864        const Type *outType = aout->getType();
865
866        mtls->fep.dimX = outType->getDimX();
867        mtls->fep.dimY = outType->getDimY();
868        mtls->fep.dimZ = outType->getDimZ();
869
870    } else {
871        mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT,
872                                     "rsForEach called with null allocations");
873        return;
874    }
875
876    if (inLen > 0 && aout != nullptr) {
877        if (!ains[0]->hasSameDims(aout)) {
878            mCtx->getContext()->setError(RS_ERROR_BAD_SCRIPT,
879              "Failed to launch kernel; dimensions of input and output allocations do not match.");
880
881            return;
882        }
883    }
884
885    if (!sc || (sc->xEnd == 0)) {
886        mtls->xEnd = mtls->fep.dimX;
887    } else {
888        rsAssert(sc->xStart < mtls->fep.dimX);
889        rsAssert(sc->xEnd <= mtls->fep.dimX);
890        rsAssert(sc->xStart < sc->xEnd);
891        mtls->xStart = rsMin(mtls->fep.dimX, sc->xStart);
892        mtls->xEnd = rsMin(mtls->fep.dimX, sc->xEnd);
893        if (mtls->xStart >= mtls->xEnd) return;
894    }
895
896    if (!sc || (sc->yEnd == 0)) {
897        mtls->yEnd = mtls->fep.dimY;
898    } else {
899        rsAssert(sc->yStart < mtls->fep.dimY);
900        rsAssert(sc->yEnd <= mtls->fep.dimY);
901        rsAssert(sc->yStart < sc->yEnd);
902        mtls->yStart = rsMin(mtls->fep.dimY, sc->yStart);
903        mtls->yEnd = rsMin(mtls->fep.dimY, sc->yEnd);
904        if (mtls->yStart >= mtls->yEnd) return;
905    }
906
907    if (!sc || (sc->zEnd == 0)) {
908        mtls->zEnd = mtls->fep.dimZ;
909    } else {
910        rsAssert(sc->zStart < mtls->fep.dimZ);
911        rsAssert(sc->zEnd <= mtls->fep.dimZ);
912        rsAssert(sc->zStart < sc->zEnd);
913        mtls->zStart = rsMin(mtls->fep.dimZ, sc->zStart);
914        mtls->zEnd = rsMin(mtls->fep.dimZ, sc->zEnd);
915        if (mtls->zStart >= mtls->zEnd) return;
916    }
917
918    mtls->xEnd     = rsMax((uint32_t)1, mtls->xEnd);
919    mtls->yEnd     = rsMax((uint32_t)1, mtls->yEnd);
920    mtls->zEnd     = rsMax((uint32_t)1, mtls->zEnd);
921    mtls->arrayEnd = rsMax((uint32_t)1, mtls->arrayEnd);
922
923    rsAssert(inLen == 0 || (ains[0]->getType()->getDimZ() == 0));
924
925    mtls->rsc        = mCtx;
926    mtls->ains       = ains;
927    mtls->aout       = aout;
928    mtls->fep.usr    = usr;
929    mtls->fep.usrLen = usrLen;
930    mtls->mSliceSize = 1;
931    mtls->mSliceNum  = 0;
932
933    mtls->fep.inPtrs    = nullptr;
934    mtls->fep.inStrides = nullptr;
935    mtls->isThreadable  = mIsThreadable;
936
937    if (inLen > 0) {
938
939        if (inLen <= RS_KERNEL_INPUT_THRESHOLD) {
940            mtls->fep.inPtrs    = (const uint8_t**)mtls->inPtrsBuff;
941            mtls->fep.inStrides = mtls->inStridesBuff;
942        } else {
943            mtls->fep.heapAllocatedArrays = true;
944
945            mtls->fep.inPtrs    = new const uint8_t*[inLen];
946            mtls->fep.inStrides = new StridePair[inLen];
947        }
948
949        mtls->fep.inLen = inLen;
950
951        for (int index = inLen; --index >= 0;) {
952            const Allocation *ain = ains[index];
953
954            mtls->fep.inPtrs[index] =
955              (const uint8_t*)ain->mHal.drvState.lod[0].mallocPtr;
956
957            mtls->fep.inStrides[index].eStride =
958              ain->getType()->getElementSizeBytes();
959            mtls->fep.inStrides[index].yStride =
960              ain->mHal.drvState.lod[0].stride;
961        }
962    }
963
964    mtls->fep.outPtr            = nullptr;
965    mtls->fep.outStride.eStride = 0;
966    mtls->fep.outStride.yStride = 0;
967    if (aout != nullptr) {
968        mtls->fep.outPtr = (uint8_t *)aout->mHal.drvState.lod[0].mallocPtr;
969
970        mtls->fep.outStride.eStride = aout->getType()->getElementSizeBytes();
971        mtls->fep.outStride.yStride = aout->mHal.drvState.lod[0].stride;
972    }
973}
974
975
976void RsdCpuScriptImpl::invokeForEach(uint32_t slot,
977                                     const Allocation ** ains,
978                                     uint32_t inLen,
979                                     Allocation * aout,
980                                     const void * usr,
981                                     uint32_t usrLen,
982                                     const RsScriptCall *sc) {
983
984    MTLaunchStruct mtls;
985
986    forEachMtlsSetup(ains, inLen, aout, usr, usrLen, sc, &mtls);
987    forEachKernelSetup(slot, &mtls);
988
989    RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
990    mCtx->launchThreads(ains, inLen, aout, sc, &mtls);
991    mCtx->setTLS(oldTLS);
992}
993
994void RsdCpuScriptImpl::forEachKernelSetup(uint32_t slot, MTLaunchStruct *mtls) {
995    mtls->script = this;
996    mtls->fep.slot = slot;
997#ifndef RS_COMPATIBILITY_LIB
998    rsAssert(slot < mExecutable->getExportForeachFuncAddrs().size());
999    mtls->kernel = reinterpret_cast<ForEachFunc_t>(
1000                      mExecutable->getExportForeachFuncAddrs()[slot]);
1001    rsAssert(mtls->kernel != nullptr);
1002    mtls->sig = mExecutable->getInfo().getExportForeachFuncs()[slot].second;
1003#else
1004    mtls->kernel = reinterpret_cast<ForEachFunc_t>(mForEachFunctions[slot]);
1005    rsAssert(mtls->kernel != nullptr);
1006    mtls->sig = mForEachSignatures[slot];
1007#endif
1008}
1009
1010int RsdCpuScriptImpl::invokeRoot() {
1011    RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
1012    int ret = mRoot();
1013    mCtx->setTLS(oldTLS);
1014    return ret;
1015}
1016
1017void RsdCpuScriptImpl::invokeInit() {
1018    if (mInit) {
1019        mInit();
1020    }
1021}
1022
1023void RsdCpuScriptImpl::invokeFreeChildren() {
1024    if (mFreeChildren) {
1025        mFreeChildren();
1026    }
1027}
1028
1029void RsdCpuScriptImpl::invokeFunction(uint32_t slot, const void *params,
1030                                      size_t paramLength) {
1031    //ALOGE("invoke %p %p %i %p %i", dc, script, slot, params, paramLength);
1032
1033    RsdCpuScriptImpl * oldTLS = mCtx->setTLS(this);
1034    reinterpret_cast<void (*)(const void *, uint32_t)>(
1035#ifndef RS_COMPATIBILITY_LIB
1036        mExecutable->getExportFuncAddrs()[slot])(params, paramLength);
1037#else
1038        mInvokeFunctions[slot])(params, paramLength);
1039#endif
1040    mCtx->setTLS(oldTLS);
1041}
1042
1043void RsdCpuScriptImpl::setGlobalVar(uint32_t slot, const void *data, size_t dataLength) {
1044    //rsAssert(!script->mFieldIsObject[slot]);
1045    //ALOGE("setGlobalVar %p %p %i %p %i", dc, script, slot, data, dataLength);
1046
1047    //if (mIntrinsicID) {
1048        //mIntrinsicFuncs.setVar(dc, script, drv->mIntrinsicData, slot, data, dataLength);
1049        //return;
1050    //}
1051
1052#ifndef RS_COMPATIBILITY_LIB
1053    int32_t *destPtr = reinterpret_cast<int32_t *>(
1054                          mExecutable->getExportVarAddrs()[slot]);
1055#else
1056    int32_t *destPtr = reinterpret_cast<int32_t *>(mFieldAddress[slot]);
1057#endif
1058    if (!destPtr) {
1059        //ALOGV("Calling setVar on slot = %i which is null", slot);
1060        return;
1061    }
1062
1063    memcpy(destPtr, data, dataLength);
1064}
1065
1066void RsdCpuScriptImpl::getGlobalVar(uint32_t slot, void *data, size_t dataLength) {
1067    //rsAssert(!script->mFieldIsObject[slot]);
1068    //ALOGE("getGlobalVar %p %p %i %p %i", dc, script, slot, data, dataLength);
1069
1070#ifndef RS_COMPATIBILITY_LIB
1071    int32_t *srcPtr = reinterpret_cast<int32_t *>(
1072                          mExecutable->getExportVarAddrs()[slot]);
1073#else
1074    int32_t *srcPtr = reinterpret_cast<int32_t *>(mFieldAddress[slot]);
1075#endif
1076    if (!srcPtr) {
1077        //ALOGV("Calling setVar on slot = %i which is null", slot);
1078        return;
1079    }
1080    memcpy(data, srcPtr, dataLength);
1081}
1082
1083
1084void RsdCpuScriptImpl::setGlobalVarWithElemDims(uint32_t slot, const void *data, size_t dataLength,
1085                                                const Element *elem,
1086                                                const uint32_t *dims, size_t dimLength) {
1087
1088#ifndef RS_COMPATIBILITY_LIB
1089    int32_t *destPtr = reinterpret_cast<int32_t *>(
1090        mExecutable->getExportVarAddrs()[slot]);
1091#else
1092    int32_t *destPtr = reinterpret_cast<int32_t *>(mFieldAddress[slot]);
1093#endif
1094    if (!destPtr) {
1095        //ALOGV("Calling setVar on slot = %i which is null", slot);
1096        return;
1097    }
1098
1099    // We want to look at dimension in terms of integer components,
1100    // but dimLength is given in terms of bytes.
1101    dimLength /= sizeof(int);
1102
1103    // Only a single dimension is currently supported.
1104    rsAssert(dimLength == 1);
1105    if (dimLength == 1) {
1106        // First do the increment loop.
1107        size_t stride = elem->getSizeBytes();
1108        const char *cVal = reinterpret_cast<const char *>(data);
1109        for (uint32_t i = 0; i < dims[0]; i++) {
1110            elem->incRefs(cVal);
1111            cVal += stride;
1112        }
1113
1114        // Decrement loop comes after (to prevent race conditions).
1115        char *oldVal = reinterpret_cast<char *>(destPtr);
1116        for (uint32_t i = 0; i < dims[0]; i++) {
1117            elem->decRefs(oldVal);
1118            oldVal += stride;
1119        }
1120    }
1121
1122    memcpy(destPtr, data, dataLength);
1123}
1124
1125void RsdCpuScriptImpl::setGlobalBind(uint32_t slot, Allocation *data) {
1126
1127    //rsAssert(!script->mFieldIsObject[slot]);
1128    //ALOGE("setGlobalBind %p %p %i %p", dc, script, slot, data);
1129
1130#ifndef RS_COMPATIBILITY_LIB
1131    int32_t *destPtr = reinterpret_cast<int32_t *>(
1132                          mExecutable->getExportVarAddrs()[slot]);
1133#else
1134    int32_t *destPtr = reinterpret_cast<int32_t *>(mFieldAddress[slot]);
1135#endif
1136    if (!destPtr) {
1137        //ALOGV("Calling setVar on slot = %i which is null", slot);
1138        return;
1139    }
1140
1141    void *ptr = nullptr;
1142    mBoundAllocs[slot] = data;
1143    if(data) {
1144        ptr = data->mHal.drvState.lod[0].mallocPtr;
1145    }
1146    memcpy(destPtr, &ptr, sizeof(void *));
1147}
1148
1149void RsdCpuScriptImpl::setGlobalObj(uint32_t slot, ObjectBase *data) {
1150
1151    //rsAssert(script->mFieldIsObject[slot]);
1152    //ALOGE("setGlobalObj %p %p %i %p", dc, script, slot, data);
1153
1154#ifndef RS_COMPATIBILITY_LIB
1155    int32_t *destPtr = reinterpret_cast<int32_t *>(
1156                          mExecutable->getExportVarAddrs()[slot]);
1157#else
1158    int32_t *destPtr = reinterpret_cast<int32_t *>(mFieldAddress[slot]);
1159#endif
1160
1161    if (!destPtr) {
1162        //ALOGV("Calling setVar on slot = %i which is null", slot);
1163        return;
1164    }
1165
1166    rsrSetObject(mCtx->getContext(), (rs_object_base *)destPtr, data);
1167}
1168
1169RsdCpuScriptImpl::~RsdCpuScriptImpl() {
1170#ifndef RS_COMPATIBILITY_LIB
1171    if (mExecutable) {
1172        std::vector<void *>::const_iterator var_addr_iter =
1173            mExecutable->getExportVarAddrs().begin();
1174        std::vector<void *>::const_iterator var_addr_end =
1175            mExecutable->getExportVarAddrs().end();
1176
1177        bcc::RSInfo::ObjectSlotListTy::const_iterator is_object_iter =
1178            mExecutable->getInfo().getObjectSlots().begin();
1179        bcc::RSInfo::ObjectSlotListTy::const_iterator is_object_end =
1180            mExecutable->getInfo().getObjectSlots().end();
1181
1182        while ((var_addr_iter != var_addr_end) &&
1183               (is_object_iter != is_object_end)) {
1184            // The field address can be nullptr if the script-side has optimized
1185            // the corresponding global variable away.
1186            rs_object_base *obj_addr =
1187                reinterpret_cast<rs_object_base *>(*var_addr_iter);
1188            if (*is_object_iter) {
1189                if (*var_addr_iter != nullptr && mCtx->getContext() != nullptr) {
1190                    rsrClearObject(mCtx->getContext(), obj_addr);
1191                }
1192            }
1193            var_addr_iter++;
1194            is_object_iter++;
1195        }
1196    }
1197
1198    if (mCompilerDriver) {
1199        delete mCompilerDriver;
1200    }
1201    if (mExecutable) {
1202        delete mExecutable;
1203    }
1204    if (mBoundAllocs) {
1205        delete[] mBoundAllocs;
1206    }
1207
1208    for (size_t i = 0; i < mExportedForEachFuncList.size(); i++) {
1209        delete[] mExportedForEachFuncList[i].first;
1210    }
1211#else
1212    if (mFieldIsObject) {
1213        for (size_t i = 0; i < mExportedVariableCount; ++i) {
1214            if (mFieldIsObject[i]) {
1215                if (mFieldAddress[i] != nullptr) {
1216                    rs_object_base *obj_addr =
1217                        reinterpret_cast<rs_object_base *>(mFieldAddress[i]);
1218                    rsrClearObject(mCtx->getContext(), obj_addr);
1219                }
1220            }
1221        }
1222    }
1223
1224    if (mInvokeFunctions) delete[] mInvokeFunctions;
1225    if (mForEachFunctions) delete[] mForEachFunctions;
1226    if (mFieldAddress) delete[] mFieldAddress;
1227    if (mFieldIsObject) delete[] mFieldIsObject;
1228    if (mForEachSignatures) delete[] mForEachSignatures;
1229    if (mBoundAllocs) delete[] mBoundAllocs;
1230    if (mScriptSO) {
1231        dlclose(mScriptSO);
1232    }
1233#endif
1234}
1235
1236Allocation * RsdCpuScriptImpl::getAllocationForPointer(const void *ptr) const {
1237    if (!ptr) {
1238        return nullptr;
1239    }
1240
1241    for (uint32_t ct=0; ct < mScript->mHal.info.exportedVariableCount; ct++) {
1242        Allocation *a = mBoundAllocs[ct];
1243        if (!a) continue;
1244        if (a->mHal.drvState.lod[0].mallocPtr == ptr) {
1245            return a;
1246        }
1247    }
1248    ALOGE("rsGetAllocation, failed to find %p", ptr);
1249    return nullptr;
1250}
1251
1252void RsdCpuScriptImpl::preLaunch(uint32_t slot, const Allocation ** ains,
1253                                 uint32_t inLen, Allocation * aout,
1254                                 const void * usr, uint32_t usrLen,
1255                                 const RsScriptCall *sc) {}
1256
1257void RsdCpuScriptImpl::postLaunch(uint32_t slot, const Allocation ** ains,
1258                                  uint32_t inLen, Allocation * aout,
1259                                  const void * usr, uint32_t usrLen,
1260                                  const RsScriptCall *sc) {}
1261
1262
1263}
1264}
1265