1 /*
2  * Copyright (C) 2013 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 <malloc.h>
18 #include <string.h>
19 #include <pthread.h>
20 
21 #include "RenderScript.h"
22 #include "rsCppStructs.h"
23 #include "rsCppInternal.h"
24 
25 #include <dlfcn.h>
26 #include <unistd.h>
27 
28 #if !defined(RS_SERVER) && !defined(RS_COMPATIBILITY_LIB) && defined(HAVE_ANDROID_OS)
29 #include <cutils/properties.h>
30 #else
31 #include "rsCompatibilityLib.h"
32 #endif
33 
34 
35 using namespace android;
36 using namespace RSC;
37 
38 bool RS::gInitialized = false;
39 bool RS::usingNative = false;
40 pthread_mutex_t RS::gInitMutex = PTHREAD_MUTEX_INITIALIZER;
41 dispatchTable* RS::dispatch = nullptr;
42 static int gInitError = 0;
43 
RS()44 RS::RS() {
45     mDev = nullptr;
46     mContext = nullptr;
47     mErrorFunc = nullptr;
48     mMessageFunc = nullptr;
49     mMessageRun = false;
50     mInit = false;
51     mCurrentError = RS_SUCCESS;
52 
53     memset(&mElements, 0, sizeof(mElements));
54     memset(&mSamplers, 0, sizeof(mSamplers));
55 }
56 
~RS()57 RS::~RS() {
58     if (mInit == true) {
59         mMessageRun = false;
60 
61         if (mContext) {
62             RS::dispatch->ContextDeinitToClient(mContext);
63 
64             void *res = nullptr;
65             int status = pthread_join(mMessageThreadId, &res);
66 
67             RS::dispatch->ContextDestroy(mContext);
68             mContext = nullptr;
69         }
70         if (mDev) {
71             RS::dispatch->DeviceDestroy(mDev);
72             mDev = nullptr;
73         }
74     }
75 }
76 
init(const char * name,uint32_t flags)77 bool RS::init(const char * name, uint32_t flags) {
78     return RS::init(name, RS_VERSION, flags);
79 }
80 
81 // this will only open API 19+ libRS
82 // because that's when we changed libRS to extern "C" entry points
loadSO(const char * filename,int targetApi)83 static bool loadSO(const char* filename, int targetApi) {
84     void* handle = dlopen(filename, RTLD_LAZY | RTLD_LOCAL);
85     if (handle == nullptr) {
86         ALOGV("couldn't dlopen %s, %s", filename, dlerror());
87         return false;
88     }
89 
90     if (loadSymbols(handle, *RS::dispatch, targetApi) == false) {
91         ALOGV("%s init failed!", filename);
92         return false;
93     }
94     //ALOGE("Successfully loaded %s", filename);
95     return true;
96 }
97 
getProp(const char * str)98 static uint32_t getProp(const char *str) {
99 #if !defined(__LP64__) && !defined(RS_SERVER) && defined(HAVE_ANDROID_OS)
100     char buf[256];
101     property_get(str, buf, "0");
102     return atoi(buf);
103 #else
104     return 0;
105 #endif
106 }
107 
initDispatch(int targetApi)108 bool RS::initDispatch(int targetApi) {
109     pthread_mutex_lock(&gInitMutex);
110     if (gInitError) {
111         goto error;
112     } else if (gInitialized) {
113         pthread_mutex_unlock(&gInitMutex);
114         return true;
115     }
116 
117     RS::dispatch = new dispatchTable;
118 
119     // attempt to load libRS, load libRSSupport on failure
120     // if property is set, proceed directly to libRSSupport
121     if (getProp("debug.rs.forcecompat") == 0) {
122         usingNative = loadSO("libRS.so", targetApi);
123     }
124     if (usingNative == false) {
125         if (loadSO("libRSSupport.so", targetApi) == false) {
126             ALOGE("Failed to load libRS.so and libRSSupport.so");
127             goto error;
128         }
129     }
130 
131     gInitialized = true;
132 
133     pthread_mutex_unlock(&gInitMutex);
134     return true;
135 
136  error:
137     gInitError = 1;
138     pthread_mutex_unlock(&gInitMutex);
139     return false;
140 }
141 
init(const char * name,int targetApi,uint32_t flags)142 bool RS::init(const char * name, int targetApi, uint32_t flags) {
143     if (mInit) {
144         return true;
145     }
146 
147     if (initDispatch(targetApi) == false) {
148         ALOGE("Couldn't initialize dispatch table");
149         return false;
150     }
151 
152     uint32_t nameLen = strlen(name);
153     if (nameLen > PATH_MAX) {
154         ALOGE("The path to the cache directory is too long");
155         return false;
156     }
157     memcpy(mCacheDir, name, nameLen);
158     mCacheDir[nameLen] = 0; //add the null character even if the user does not.
159     mCacheDirLen = nameLen + 1;
160 
161     mDev = RS::dispatch->DeviceCreate();
162     if (mDev == 0) {
163         ALOGE("Device creation failed");
164         return false;
165     }
166 
167     if (flags & ~(RS_CONTEXT_SYNCHRONOUS | RS_CONTEXT_LOW_LATENCY |
168                   RS_CONTEXT_LOW_POWER | RS_CONTEXT_WAIT_FOR_ATTACH)) {
169         ALOGE("Invalid flags passed");
170         return false;
171     }
172 
173     mContext = RS::dispatch->ContextCreate(mDev, 0, targetApi, RS_CONTEXT_TYPE_NORMAL, flags);
174     if (mContext == 0) {
175         ALOGE("Context creation failed");
176         return false;
177     }
178 
179     pid_t mNativeMessageThreadId;
180 
181     int status = pthread_create(&mMessageThreadId, nullptr, threadProc, this);
182     if (status) {
183         ALOGE("Failed to start RS message thread.");
184         return false;
185     }
186     // Wait for the message thread to be active.
187     while (!mMessageRun) {
188         usleep(1000);
189     }
190 
191     mInit = true;
192 
193     return true;
194 }
195 
throwError(RSError error,const char * errMsg)196 void RS::throwError(RSError error, const char *errMsg) {
197     if (mCurrentError == RS_SUCCESS) {
198         mCurrentError = error;
199         ALOGE("RS CPP error: %s", errMsg);
200     } else {
201         ALOGE("RS CPP error (masked by previous error): %s", errMsg);
202     }
203 }
204 
getError()205 RSError RS::getError() {
206     return mCurrentError;
207 }
208 
209 
threadProc(void * vrsc)210 void * RS::threadProc(void *vrsc) {
211     RS *rs = static_cast<RS *>(vrsc);
212     size_t rbuf_size = 256;
213     void * rbuf = malloc(rbuf_size);
214 
215     RS::dispatch->ContextInitToClient(rs->mContext);
216     rs->mMessageRun = true;
217 
218     while (rs->mMessageRun) {
219         size_t receiveLen = 0;
220         uint32_t usrID = 0;
221         uint32_t subID = 0;
222         RsMessageToClientType r = RS::dispatch->ContextPeekMessage(rs->mContext,
223                                                                    &receiveLen, sizeof(receiveLen),
224                                                                    &usrID, sizeof(usrID));
225 
226         if (receiveLen >= rbuf_size) {
227             rbuf_size = receiveLen + 32;
228             rbuf = realloc(rbuf, rbuf_size);
229         }
230         if (!rbuf) {
231             ALOGE("RS::message handler realloc error %zu", rbuf_size);
232             // No clean way to recover now?
233         }
234         RS::dispatch->ContextGetMessage(rs->mContext, rbuf, rbuf_size, &receiveLen, sizeof(receiveLen),
235                             &subID, sizeof(subID));
236 
237         switch(r) {
238         case RS_MESSAGE_TO_CLIENT_ERROR:
239             ALOGE("RS Error %s", (const char *)rbuf);
240             rs->throwError(RS_ERROR_RUNTIME_ERROR, "Error returned from runtime");
241             if(rs->mMessageFunc != nullptr) {
242                 rs->mErrorFunc(usrID, (const char *)rbuf);
243             }
244             break;
245         case RS_MESSAGE_TO_CLIENT_NONE:
246         case RS_MESSAGE_TO_CLIENT_EXCEPTION:
247         case RS_MESSAGE_TO_CLIENT_RESIZE:
248             // teardown. But we want to avoid starving other threads during
249             // teardown by yielding until the next line in the destructor can
250             // execute to set mRun = false. Note that the FIFO sends an
251             // empty NONE message when it reaches its destructor.
252             usleep(1000);
253             break;
254         case RS_MESSAGE_TO_CLIENT_USER:
255             if(rs->mMessageFunc != nullptr) {
256                 rs->mMessageFunc(usrID, rbuf, receiveLen);
257             } else {
258                 ALOGE("Received a message from the script with no message handler installed.");
259             }
260             break;
261 
262         default:
263             ALOGE("RS unknown message type %i", r);
264         }
265     }
266 
267     if (rbuf) {
268         free(rbuf);
269     }
270     ALOGV("RS Message thread exiting.");
271     return nullptr;
272 }
273 
setErrorHandler(ErrorHandlerFunc_t func)274 void RS::setErrorHandler(ErrorHandlerFunc_t func) {
275     mErrorFunc = func;
276 }
277 
setMessageHandler(MessageHandlerFunc_t func)278 void RS::setMessageHandler(MessageHandlerFunc_t func) {
279     mMessageFunc  = func;
280 }
281 
finish()282 void RS::finish() {
283     RS::dispatch->ContextFinish(mContext);
284 }
285