rsScriptC.cpp revision 140a7acade66ab5d1f3dc55803a3a65a71f3f86c
1/*
2 * Copyright (C) 2009-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 "rsContext.h"
18#include "rsScriptC.h"
19
20#ifndef RS_COMPATIBILITY_LIB
21#ifndef ANDROID_RS_SERIALIZE
22#include <bcinfo/BitcodeTranslator.h>
23#include <bcinfo/BitcodeWrapper.h>
24#endif
25#endif
26
27#if !defined(RS_SERVER) && !defined(RS_COMPATIBILITY_LIB)
28#include "utils/Timers.h"
29#endif
30
31#include "cutils/trace.h"
32
33#include <sys/stat.h>
34
35using namespace android;
36using namespace android::renderscript;
37
38#define GET_TLS()  Context::ScriptTLSStruct * tls = \
39    (Context::ScriptTLSStruct *)pthread_getspecific(Context::gThreadTLSKey); \
40    Context * rsc = tls->mContext; \
41    ScriptC * sc = (ScriptC *) tls->mScript
42
43ScriptC::ScriptC(Context *rsc) : Script(rsc) {
44#ifndef RS_COMPATIBILITY_LIB
45#ifndef ANDROID_RS_SERIALIZE
46    BT = NULL;
47#endif
48#endif
49}
50
51ScriptC::~ScriptC() {
52#ifndef RS_COMPATIBILITY_LIB
53#ifndef ANDROID_RS_SERIALIZE
54    if (BT) {
55        delete BT;
56        BT = NULL;
57    }
58#endif
59#endif
60    if (mInitialized) {
61        mRSC->mHal.funcs.script.invokeFreeChildren(mRSC, this);
62        mRSC->mHal.funcs.script.destroy(mRSC, this);
63    }
64}
65
66#ifndef RS_COMPATIBILITY_LIB
67bool ScriptC::createCacheDir(const char *cacheDir) {
68    String8 cacheDirString, currentDir;
69    struct stat statBuf;
70    int statReturn = stat(cacheDir, &statBuf);
71    if (!statReturn) {
72        return true;
73    }
74
75    // String8 path functions strip leading /'s
76    // insert if necessary
77    if (cacheDir[0] == '/') {
78        currentDir += "/";
79    }
80
81    cacheDirString.setPathName(cacheDir);
82
83    while (cacheDirString.length()) {
84        currentDir += (cacheDirString.walkPath(&cacheDirString));
85        statReturn = stat(currentDir.string(), &statBuf);
86        if (statReturn) {
87            if (errno == ENOENT) {
88                if (mkdir(currentDir.string(), S_IRUSR | S_IWUSR | S_IXUSR)) {
89                    ALOGE("Couldn't create cache directory: %s",
90                          currentDir.string());
91                    ALOGE("Error: %s", strerror(errno));
92                    return false;
93                }
94            } else {
95                ALOGE("Stat error: %s", strerror(errno));
96                return false;
97            }
98        }
99        currentDir += "/";
100    }
101    return true;
102}
103#endif
104
105void ScriptC::setupScript(Context *rsc) {
106#ifndef RS_SERVER
107    mEnviroment.mStartTimeMillis
108                = nanoseconds_to_milliseconds(systemTime(SYSTEM_TIME_MONOTONIC));
109#endif
110
111    for (uint32_t ct=0; ct < mHal.info.exportedVariableCount; ct++) {
112        if (mSlots[ct].get() && !mTypes[ct].get()) {
113            mTypes[ct].set(mSlots[ct]->getType());
114        }
115
116        if (!mTypes[ct].get())
117            continue;
118        rsc->mHal.funcs.script.setGlobalBind(rsc, this, ct, mSlots[ct].get());
119    }
120}
121
122void ScriptC::setupGLState(Context *rsc) {
123#ifndef RS_COMPATIBILITY_LIB
124    if (mEnviroment.mFragmentStore.get()) {
125        rsc->setProgramStore(mEnviroment.mFragmentStore.get());
126    }
127    if (mEnviroment.mFragment.get()) {
128        rsc->setProgramFragment(mEnviroment.mFragment.get());
129    }
130    if (mEnviroment.mVertex.get()) {
131        rsc->setProgramVertex(mEnviroment.mVertex.get());
132    }
133    if (mEnviroment.mRaster.get()) {
134        rsc->setProgramRaster(mEnviroment.mRaster.get());
135    }
136#endif
137}
138
139uint32_t ScriptC::run(Context *rsc) {
140    if (mHal.info.root == NULL) {
141        rsc->setError(RS_ERROR_BAD_SCRIPT, "Attempted to run bad script");
142        return 0;
143    }
144
145    setupGLState(rsc);
146    setupScript(rsc);
147
148    uint32_t ret = 0;
149
150    if (rsc->props.mLogScripts) {
151        ALOGV("%p ScriptC::run invoking root,  ptr %p", rsc, mHal.info.root);
152    }
153
154    ret = rsc->mHal.funcs.script.invokeRoot(rsc, this);
155
156    if (rsc->props.mLogScripts) {
157        ALOGV("%p ScriptC::run invoking complete, ret=%i", rsc, ret);
158    }
159
160    return ret;
161}
162
163
164void ScriptC::runForEach(Context *rsc,
165                         uint32_t slot,
166                         const Allocation * ain,
167                         Allocation * aout,
168                         const void * usr,
169                         size_t usrBytes,
170                         const RsScriptCall *sc) {
171    // Trace this function call.
172    // To avoid overhead, we only build the string, if tracing is actually
173    // enabled.
174    String8 *AString = NULL;
175    const char *String = "";
176    if (ATRACE_ENABLED()) {
177        AString = new String8("runForEach_");
178        AString->append(mHal.info.exportedForeachFuncList[slot].first);
179        String = AString->string();
180    }
181    ATRACE_NAME(String);
182    (void)String;
183
184    Context::PushState ps(rsc);
185
186    setupGLState(rsc);
187    setupScript(rsc);
188    rsc->mHal.funcs.script.invokeForEach(rsc, this, slot, ain, aout, usr, usrBytes, sc);
189
190    if (AString)
191        delete AString;
192}
193
194void ScriptC::Invoke(Context *rsc, uint32_t slot, const void *data, size_t len) {
195    ATRACE_CALL();
196
197    if (slot >= mHal.info.exportedFunctionCount) {
198        rsc->setError(RS_ERROR_BAD_SCRIPT, "Calling invoke on bad script");
199        return;
200    }
201    setupScript(rsc);
202
203    if (rsc->props.mLogScripts) {
204        ALOGV("%p ScriptC::Invoke invoking slot %i,  ptr %p", rsc, slot, this);
205    }
206    rsc->mHal.funcs.script.invokeFunction(rsc, this, slot, data, len);
207}
208
209ScriptCState::ScriptCState() {
210}
211
212ScriptCState::~ScriptCState() {
213}
214
215/*
216static void* symbolLookup(void* pContext, char const* name) {
217    const ScriptCState::SymbolTable_t *sym;
218    ScriptC *s = (ScriptC *)pContext;
219    if (!strcmp(name, "__isThreadable")) {
220      return (void*) s->mHal.info.isThreadable;
221    } else if (!strcmp(name, "__clearThreadable")) {
222      s->mHal.info.isThreadable = false;
223      return NULL;
224    }
225    sym = ScriptCState::lookupSymbol(name);
226    if (!sym) {
227        sym = ScriptCState::lookupSymbolCL(name);
228    }
229    if (!sym) {
230        sym = ScriptCState::lookupSymbolGL(name);
231    }
232    if (sym) {
233        s->mHal.info.isThreadable &= sym->threadable;
234        return sym->mPtr;
235    }
236    ALOGE("ScriptC sym lookup failed for %s", name);
237    return NULL;
238}
239*/
240
241#if 0
242extern const char rs_runtime_lib_bc[];
243extern unsigned rs_runtime_lib_bc_size;
244#endif
245
246bool ScriptC::runCompiler(Context *rsc,
247                          const char *resName,
248                          const char *cacheDir,
249                          const uint8_t *bitcode,
250                          size_t bitcodeLen) {
251    ATRACE_CALL();
252    //ALOGE("runCompiler %p %p %p %p %p %i", rsc, this, resName, cacheDir, bitcode, bitcodeLen);
253#ifndef RS_COMPATIBILITY_LIB
254#ifndef ANDROID_RS_SERIALIZE
255    uint32_t sdkVersion = 0;
256    bcinfo::BitcodeWrapper bcWrapper((const char *)bitcode, bitcodeLen);
257    if (!bcWrapper.unwrap()) {
258        ALOGE("Bitcode is not in proper container format (raw or wrapper)");
259        return false;
260    }
261
262    if (bcWrapper.getBCFileType() == bcinfo::BC_WRAPPER) {
263        sdkVersion = bcWrapper.getTargetAPI();
264    }
265
266    if (sdkVersion == 0) {
267        // This signals that we didn't have a wrapper containing information
268        // about the bitcode.
269        sdkVersion = rsc->getTargetSdkVersion();
270    }
271
272    if (BT) {
273        delete BT;
274    }
275    BT = new bcinfo::BitcodeTranslator((const char *)bitcode, bitcodeLen,
276                                       sdkVersion);
277    if (!BT->translate()) {
278        ALOGE("Failed to translate bitcode from version: %u", sdkVersion);
279        delete BT;
280        BT = NULL;
281        return false;
282    }
283    bitcode = (const uint8_t *) BT->getTranslatedBitcode();
284    bitcodeLen = BT->getTranslatedBitcodeSize();
285#endif
286
287    if (!cacheDir) {
288        // MUST BE FIXED BEFORE ANYTHING USING C++ API IS RELEASED
289        cacheDir = getenv("EXTERNAL_STORAGE");
290        ALOGV("Cache dir changed to %s", cacheDir);
291    }
292
293    // ensure that cache dir exists
294    if (cacheDir && !createCacheDir(cacheDir)) {
295      return false;
296    }
297#endif
298
299    if (!rsc->mHal.funcs.script.init(rsc, this, resName, cacheDir, bitcode, bitcodeLen, 0)) {
300        return false;
301    }
302
303    mInitialized = true;
304#ifndef RS_COMPATIBILITY_LIB
305    mEnviroment.mFragment.set(rsc->getDefaultProgramFragment());
306    mEnviroment.mVertex.set(rsc->getDefaultProgramVertex());
307    mEnviroment.mFragmentStore.set(rsc->getDefaultProgramStore());
308    mEnviroment.mRaster.set(rsc->getDefaultProgramRaster());
309#endif
310
311    rsc->mHal.funcs.script.invokeInit(rsc, this);
312
313    for (size_t i=0; i < mHal.info.exportedPragmaCount; ++i) {
314        const char * key = mHal.info.exportedPragmaKeyList[i];
315        const char * value = mHal.info.exportedPragmaValueList[i];
316        //ALOGE("pragma %s %s", keys[i], values[i]);
317        if (!strcmp(key, "version")) {
318            if (!strcmp(value, "1")) {
319                continue;
320            }
321            ALOGE("Invalid version pragma value: %s\n", value);
322            return false;
323        }
324
325#ifndef RS_COMPATIBILITY_LIB
326        if (!strcmp(key, "stateVertex")) {
327            if (!strcmp(value, "default")) {
328                continue;
329            }
330            if (!strcmp(value, "parent")) {
331                mEnviroment.mVertex.clear();
332                continue;
333            }
334            ALOGE("Unrecognized value %s passed to stateVertex", value);
335            return false;
336        }
337
338        if (!strcmp(key, "stateRaster")) {
339            if (!strcmp(value, "default")) {
340                continue;
341            }
342            if (!strcmp(value, "parent")) {
343                mEnviroment.mRaster.clear();
344                continue;
345            }
346            ALOGE("Unrecognized value %s passed to stateRaster", value);
347            return false;
348        }
349
350        if (!strcmp(key, "stateFragment")) {
351            if (!strcmp(value, "default")) {
352                continue;
353            }
354            if (!strcmp(value, "parent")) {
355                mEnviroment.mFragment.clear();
356                continue;
357            }
358            ALOGE("Unrecognized value %s passed to stateFragment", value);
359            return false;
360        }
361
362        if (!strcmp(key, "stateStore")) {
363            if (!strcmp(value, "default")) {
364                continue;
365            }
366            if (!strcmp(value, "parent")) {
367                mEnviroment.mFragmentStore.clear();
368                continue;
369            }
370            ALOGE("Unrecognized value %s passed to stateStore", value);
371            return false;
372        }
373#endif
374
375    }
376
377    mSlots = new ObjectBaseRef<Allocation>[mHal.info.exportedVariableCount];
378    mTypes = new ObjectBaseRef<const Type>[mHal.info.exportedVariableCount];
379
380    return true;
381}
382
383namespace android {
384namespace renderscript {
385
386RsScript rsi_ScriptCCreate(Context *rsc,
387                           const char *resName, size_t resName_length,
388                           const char *cacheDir, size_t cacheDir_length,
389                           const char *text, size_t text_length)
390{
391    ScriptC *s = new ScriptC(rsc);
392
393    if (!s->runCompiler(rsc, resName, cacheDir, (uint8_t *)text, text_length)) {
394        // Error during compile, destroy s and return null.
395        ObjectBase::checkDelete(s);
396        return NULL;
397    }
398
399    s->incUserRef();
400    return s;
401}
402
403}
404}
405