1 #define LOG_TAG "GraphicsJNI"
2 
3 #include <unistd.h>
4 #include <sys/mman.h>
5 
6 #include "jni.h"
7 #include "JNIHelp.h"
8 #include "GraphicsJNI.h"
9 
10 #include "Canvas.h"
11 #include "SkCanvas.h"
12 #include "SkDevice.h"
13 #include "SkMath.h"
14 #include "SkRegion.h"
15 #include <android_runtime/AndroidRuntime.h>
16 #include <cutils/ashmem.h>
17 
18 #include <Caches.h>
19 #include <TextureCache.h>
20 
doThrowNPE(JNIEnv * env)21 void doThrowNPE(JNIEnv* env) {
22     jniThrowNullPointerException(env, NULL);
23 }
24 
doThrowAIOOBE(JNIEnv * env)25 void doThrowAIOOBE(JNIEnv* env) {
26     jniThrowException(env, "java/lang/ArrayIndexOutOfBoundsException", NULL);
27 }
28 
doThrowRE(JNIEnv * env,const char * msg)29 void doThrowRE(JNIEnv* env, const char* msg) {
30     jniThrowRuntimeException(env, msg);
31 }
32 
doThrowIAE(JNIEnv * env,const char * msg)33 void doThrowIAE(JNIEnv* env, const char* msg) {
34     jniThrowException(env, "java/lang/IllegalArgumentException", msg);
35 }
36 
doThrowISE(JNIEnv * env,const char * msg)37 void doThrowISE(JNIEnv* env, const char* msg) {
38     jniThrowException(env, "java/lang/IllegalStateException", msg);
39 }
40 
doThrowOOME(JNIEnv * env,const char * msg)41 void doThrowOOME(JNIEnv* env, const char* msg) {
42     jniThrowException(env, "java/lang/OutOfMemoryError", msg);
43 }
44 
doThrowIOE(JNIEnv * env,const char * msg)45 void doThrowIOE(JNIEnv* env, const char* msg) {
46     jniThrowException(env, "java/io/IOException", msg);
47 }
48 
hasException(JNIEnv * env)49 bool GraphicsJNI::hasException(JNIEnv *env) {
50     if (env->ExceptionCheck() != 0) {
51         ALOGE("*** Uncaught exception returned from Java call!\n");
52         env->ExceptionDescribe();
53         return true;
54     }
55     return false;
56 }
57 
58 ///////////////////////////////////////////////////////////////////////////////
59 
AutoJavaFloatArray(JNIEnv * env,jfloatArray array,int minLength,JNIAccess access)60 AutoJavaFloatArray::AutoJavaFloatArray(JNIEnv* env, jfloatArray array,
61                                        int minLength, JNIAccess access)
62 : fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
63     SkASSERT(env);
64     if (array) {
65         fLen = env->GetArrayLength(array);
66         if (fLen < minLength) {
67             sk_throw();
68         }
69         fPtr = env->GetFloatArrayElements(array, NULL);
70     }
71     fReleaseMode = (access == kRO_JNIAccess) ? JNI_ABORT : 0;
72 }
73 
~AutoJavaFloatArray()74 AutoJavaFloatArray::~AutoJavaFloatArray() {
75     if (fPtr) {
76         fEnv->ReleaseFloatArrayElements(fArray, fPtr, fReleaseMode);
77     }
78 }
79 
AutoJavaIntArray(JNIEnv * env,jintArray array,int minLength)80 AutoJavaIntArray::AutoJavaIntArray(JNIEnv* env, jintArray array,
81                                        int minLength)
82 : fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
83     SkASSERT(env);
84     if (array) {
85         fLen = env->GetArrayLength(array);
86         if (fLen < minLength) {
87             sk_throw();
88         }
89         fPtr = env->GetIntArrayElements(array, NULL);
90     }
91 }
92 
~AutoJavaIntArray()93 AutoJavaIntArray::~AutoJavaIntArray() {
94     if (fPtr) {
95         fEnv->ReleaseIntArrayElements(fArray, fPtr, 0);
96     }
97 }
98 
AutoJavaShortArray(JNIEnv * env,jshortArray array,int minLength,JNIAccess access)99 AutoJavaShortArray::AutoJavaShortArray(JNIEnv* env, jshortArray array,
100                                        int minLength, JNIAccess access)
101 : fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
102     SkASSERT(env);
103     if (array) {
104         fLen = env->GetArrayLength(array);
105         if (fLen < minLength) {
106             sk_throw();
107         }
108         fPtr = env->GetShortArrayElements(array, NULL);
109     }
110     fReleaseMode = (access == kRO_JNIAccess) ? JNI_ABORT : 0;
111 }
112 
~AutoJavaShortArray()113 AutoJavaShortArray::~AutoJavaShortArray() {
114     if (fPtr) {
115         fEnv->ReleaseShortArrayElements(fArray, fPtr, fReleaseMode);
116     }
117 }
118 
AutoJavaByteArray(JNIEnv * env,jbyteArray array,int minLength)119 AutoJavaByteArray::AutoJavaByteArray(JNIEnv* env, jbyteArray array,
120                                        int minLength)
121 : fEnv(env), fArray(array), fPtr(NULL), fLen(0) {
122     SkASSERT(env);
123     if (array) {
124         fLen = env->GetArrayLength(array);
125         if (fLen < minLength) {
126             sk_throw();
127         }
128         fPtr = env->GetByteArrayElements(array, NULL);
129     }
130 }
131 
~AutoJavaByteArray()132 AutoJavaByteArray::~AutoJavaByteArray() {
133     if (fPtr) {
134         fEnv->ReleaseByteArrayElements(fArray, fPtr, 0);
135     }
136 }
137 
138 ///////////////////////////////////////////////////////////////////////////////
139 
140 static jclass   gRect_class;
141 static jfieldID gRect_leftFieldID;
142 static jfieldID gRect_topFieldID;
143 static jfieldID gRect_rightFieldID;
144 static jfieldID gRect_bottomFieldID;
145 
146 static jclass   gRectF_class;
147 static jfieldID gRectF_leftFieldID;
148 static jfieldID gRectF_topFieldID;
149 static jfieldID gRectF_rightFieldID;
150 static jfieldID gRectF_bottomFieldID;
151 
152 static jclass   gPoint_class;
153 static jfieldID gPoint_xFieldID;
154 static jfieldID gPoint_yFieldID;
155 
156 static jclass   gPointF_class;
157 static jfieldID gPointF_xFieldID;
158 static jfieldID gPointF_yFieldID;
159 
160 static jclass   gBitmap_class;
161 static jfieldID gBitmap_nativePtr;
162 static jmethodID gBitmap_constructorMethodID;
163 static jmethodID gBitmap_reinitMethodID;
164 static jmethodID gBitmap_getAllocationByteCountMethodID;
165 
166 static jclass   gBitmapConfig_class;
167 static jfieldID gBitmapConfig_nativeInstanceID;
168 
169 static jclass   gBitmapRegionDecoder_class;
170 static jmethodID gBitmapRegionDecoder_constructorMethodID;
171 
172 static jclass   gCanvas_class;
173 static jfieldID gCanvas_nativeInstanceID;
174 
175 static jclass   gPicture_class;
176 static jfieldID gPicture_nativeInstanceID;
177 
178 static jclass   gRegion_class;
179 static jfieldID gRegion_nativeInstanceID;
180 static jmethodID gRegion_constructorMethodID;
181 
182 static jclass    gByte_class;
183 static jobject   gVMRuntime;
184 static jclass    gVMRuntime_class;
185 static jmethodID gVMRuntime_newNonMovableArray;
186 static jmethodID gVMRuntime_addressOf;
187 
188 ///////////////////////////////////////////////////////////////////////////////
189 
get_jrect(JNIEnv * env,jobject obj,int * L,int * T,int * R,int * B)190 void GraphicsJNI::get_jrect(JNIEnv* env, jobject obj, int* L, int* T, int* R, int* B)
191 {
192     SkASSERT(env->IsInstanceOf(obj, gRect_class));
193 
194     *L = env->GetIntField(obj, gRect_leftFieldID);
195     *T = env->GetIntField(obj, gRect_topFieldID);
196     *R = env->GetIntField(obj, gRect_rightFieldID);
197     *B = env->GetIntField(obj, gRect_bottomFieldID);
198 }
199 
set_jrect(JNIEnv * env,jobject obj,int L,int T,int R,int B)200 void GraphicsJNI::set_jrect(JNIEnv* env, jobject obj, int L, int T, int R, int B)
201 {
202     SkASSERT(env->IsInstanceOf(obj, gRect_class));
203 
204     env->SetIntField(obj, gRect_leftFieldID, L);
205     env->SetIntField(obj, gRect_topFieldID, T);
206     env->SetIntField(obj, gRect_rightFieldID, R);
207     env->SetIntField(obj, gRect_bottomFieldID, B);
208 }
209 
jrect_to_irect(JNIEnv * env,jobject obj,SkIRect * ir)210 SkIRect* GraphicsJNI::jrect_to_irect(JNIEnv* env, jobject obj, SkIRect* ir)
211 {
212     SkASSERT(env->IsInstanceOf(obj, gRect_class));
213 
214     ir->set(env->GetIntField(obj, gRect_leftFieldID),
215             env->GetIntField(obj, gRect_topFieldID),
216             env->GetIntField(obj, gRect_rightFieldID),
217             env->GetIntField(obj, gRect_bottomFieldID));
218     return ir;
219 }
220 
irect_to_jrect(const SkIRect & ir,JNIEnv * env,jobject obj)221 void GraphicsJNI::irect_to_jrect(const SkIRect& ir, JNIEnv* env, jobject obj)
222 {
223     SkASSERT(env->IsInstanceOf(obj, gRect_class));
224 
225     env->SetIntField(obj, gRect_leftFieldID, ir.fLeft);
226     env->SetIntField(obj, gRect_topFieldID, ir.fTop);
227     env->SetIntField(obj, gRect_rightFieldID, ir.fRight);
228     env->SetIntField(obj, gRect_bottomFieldID, ir.fBottom);
229 }
230 
jrectf_to_rect(JNIEnv * env,jobject obj,SkRect * r)231 SkRect* GraphicsJNI::jrectf_to_rect(JNIEnv* env, jobject obj, SkRect* r)
232 {
233     SkASSERT(env->IsInstanceOf(obj, gRectF_class));
234 
235     r->set(env->GetFloatField(obj, gRectF_leftFieldID),
236            env->GetFloatField(obj, gRectF_topFieldID),
237            env->GetFloatField(obj, gRectF_rightFieldID),
238            env->GetFloatField(obj, gRectF_bottomFieldID));
239     return r;
240 }
241 
jrect_to_rect(JNIEnv * env,jobject obj,SkRect * r)242 SkRect* GraphicsJNI::jrect_to_rect(JNIEnv* env, jobject obj, SkRect* r)
243 {
244     SkASSERT(env->IsInstanceOf(obj, gRect_class));
245 
246     r->set(SkIntToScalar(env->GetIntField(obj, gRect_leftFieldID)),
247            SkIntToScalar(env->GetIntField(obj, gRect_topFieldID)),
248            SkIntToScalar(env->GetIntField(obj, gRect_rightFieldID)),
249            SkIntToScalar(env->GetIntField(obj, gRect_bottomFieldID)));
250     return r;
251 }
252 
rect_to_jrectf(const SkRect & r,JNIEnv * env,jobject obj)253 void GraphicsJNI::rect_to_jrectf(const SkRect& r, JNIEnv* env, jobject obj)
254 {
255     SkASSERT(env->IsInstanceOf(obj, gRectF_class));
256 
257     env->SetFloatField(obj, gRectF_leftFieldID, SkScalarToFloat(r.fLeft));
258     env->SetFloatField(obj, gRectF_topFieldID, SkScalarToFloat(r.fTop));
259     env->SetFloatField(obj, gRectF_rightFieldID, SkScalarToFloat(r.fRight));
260     env->SetFloatField(obj, gRectF_bottomFieldID, SkScalarToFloat(r.fBottom));
261 }
262 
jpoint_to_ipoint(JNIEnv * env,jobject obj,SkIPoint * point)263 SkIPoint* GraphicsJNI::jpoint_to_ipoint(JNIEnv* env, jobject obj, SkIPoint* point)
264 {
265     SkASSERT(env->IsInstanceOf(obj, gPoint_class));
266 
267     point->set(env->GetIntField(obj, gPoint_xFieldID),
268                env->GetIntField(obj, gPoint_yFieldID));
269     return point;
270 }
271 
ipoint_to_jpoint(const SkIPoint & ir,JNIEnv * env,jobject obj)272 void GraphicsJNI::ipoint_to_jpoint(const SkIPoint& ir, JNIEnv* env, jobject obj)
273 {
274     SkASSERT(env->IsInstanceOf(obj, gPoint_class));
275 
276     env->SetIntField(obj, gPoint_xFieldID, ir.fX);
277     env->SetIntField(obj, gPoint_yFieldID, ir.fY);
278 }
279 
jpointf_to_point(JNIEnv * env,jobject obj,SkPoint * point)280 SkPoint* GraphicsJNI::jpointf_to_point(JNIEnv* env, jobject obj, SkPoint* point)
281 {
282     SkASSERT(env->IsInstanceOf(obj, gPointF_class));
283 
284     point->set(env->GetIntField(obj, gPointF_xFieldID),
285                env->GetIntField(obj, gPointF_yFieldID));
286     return point;
287 }
288 
point_to_jpointf(const SkPoint & r,JNIEnv * env,jobject obj)289 void GraphicsJNI::point_to_jpointf(const SkPoint& r, JNIEnv* env, jobject obj)
290 {
291     SkASSERT(env->IsInstanceOf(obj, gPointF_class));
292 
293     env->SetFloatField(obj, gPointF_xFieldID, SkScalarToFloat(r.fX));
294     env->SetFloatField(obj, gPointF_yFieldID, SkScalarToFloat(r.fY));
295 }
296 
297 // This enum must keep these int values, to match the int values
298 // in the java Bitmap.Config enum.
299 enum LegacyBitmapConfig {
300     kNo_LegacyBitmapConfig          = 0,
301     kA8_LegacyBitmapConfig          = 1,
302     kIndex8_LegacyBitmapConfig      = 2,
303     kRGB_565_LegacyBitmapConfig     = 3,
304     kARGB_4444_LegacyBitmapConfig   = 4,
305     kARGB_8888_LegacyBitmapConfig   = 5,
306 
307     kLastEnum_LegacyBitmapConfig = kARGB_8888_LegacyBitmapConfig
308 };
309 
colorTypeToLegacyBitmapConfig(SkColorType colorType)310 jint GraphicsJNI::colorTypeToLegacyBitmapConfig(SkColorType colorType) {
311     switch (colorType) {
312         case kN32_SkColorType:
313             return kARGB_8888_LegacyBitmapConfig;
314         case kARGB_4444_SkColorType:
315             return kARGB_4444_LegacyBitmapConfig;
316         case kRGB_565_SkColorType:
317             return kRGB_565_LegacyBitmapConfig;
318         case kIndex_8_SkColorType:
319             return kIndex8_LegacyBitmapConfig;
320         case kAlpha_8_SkColorType:
321             return kA8_LegacyBitmapConfig;
322         case kUnknown_SkColorType:
323         default:
324             break;
325     }
326     return kNo_LegacyBitmapConfig;
327 }
328 
legacyBitmapConfigToColorType(jint legacyConfig)329 SkColorType GraphicsJNI::legacyBitmapConfigToColorType(jint legacyConfig) {
330     const uint8_t gConfig2ColorType[] = {
331         kUnknown_SkColorType,
332         kAlpha_8_SkColorType,
333         kIndex_8_SkColorType,
334         kRGB_565_SkColorType,
335         kARGB_4444_SkColorType,
336         kN32_SkColorType
337     };
338 
339     if (legacyConfig < 0 || legacyConfig > kLastEnum_LegacyBitmapConfig) {
340         legacyConfig = kNo_LegacyBitmapConfig;
341     }
342     return static_cast<SkColorType>(gConfig2ColorType[legacyConfig]);
343 }
344 
getBitmap(JNIEnv * env,jobject bitmap)345 android::Bitmap* GraphicsJNI::getBitmap(JNIEnv* env, jobject bitmap) {
346     SkASSERT(env);
347     SkASSERT(bitmap);
348     SkASSERT(env->IsInstanceOf(bitmap, gBitmap_class));
349     jlong bitmapHandle = env->GetLongField(bitmap, gBitmap_nativePtr);
350     android::Bitmap* b = reinterpret_cast<android::Bitmap*>(bitmapHandle);
351     SkASSERT(b);
352     return b;
353 }
354 
getSkBitmap(JNIEnv * env,jobject bitmap,SkBitmap * outBitmap)355 void GraphicsJNI::getSkBitmap(JNIEnv* env, jobject bitmap, SkBitmap* outBitmap) {
356     getBitmap(env, bitmap)->getSkBitmap(outBitmap);
357 }
358 
refSkPixelRef(JNIEnv * env,jobject bitmap)359 SkPixelRef* GraphicsJNI::refSkPixelRef(JNIEnv* env, jobject bitmap) {
360     return getBitmap(env, bitmap)->refPixelRef();
361 }
362 
getNativeBitmapColorType(JNIEnv * env,jobject jconfig)363 SkColorType GraphicsJNI::getNativeBitmapColorType(JNIEnv* env, jobject jconfig) {
364     SkASSERT(env);
365     if (NULL == jconfig) {
366         return kUnknown_SkColorType;
367     }
368     SkASSERT(env->IsInstanceOf(jconfig, gBitmapConfig_class));
369     int c = env->GetIntField(jconfig, gBitmapConfig_nativeInstanceID);
370     return legacyBitmapConfigToColorType(c);
371 }
372 
getNativeCanvas(JNIEnv * env,jobject canvas)373 android::Canvas* GraphicsJNI::getNativeCanvas(JNIEnv* env, jobject canvas) {
374     SkASSERT(env);
375     SkASSERT(canvas);
376     SkASSERT(env->IsInstanceOf(canvas, gCanvas_class));
377     jlong canvasHandle = env->GetLongField(canvas, gCanvas_nativeInstanceID);
378     if (!canvasHandle) {
379         return NULL;
380     }
381     return reinterpret_cast<android::Canvas*>(canvasHandle);
382 }
383 
getNativeRegion(JNIEnv * env,jobject region)384 SkRegion* GraphicsJNI::getNativeRegion(JNIEnv* env, jobject region)
385 {
386     SkASSERT(env);
387     SkASSERT(region);
388     SkASSERT(env->IsInstanceOf(region, gRegion_class));
389     jlong regionHandle = env->GetLongField(region, gRegion_nativeInstanceID);
390     SkRegion* r = reinterpret_cast<SkRegion*>(regionHandle);
391     SkASSERT(r);
392     return r;
393 }
394 
395 ///////////////////////////////////////////////////////////////////////////////////////////
396 
397 // Assert that bitmap's SkAlphaType is consistent with isPremultiplied.
assert_premultiplied(const SkImageInfo & info,bool isPremultiplied)398 static void assert_premultiplied(const SkImageInfo& info, bool isPremultiplied) {
399     // kOpaque_SkAlphaType and kIgnore_SkAlphaType mean that isPremultiplied is
400     // irrelevant. This just tests to ensure that the SkAlphaType is not
401     // opposite of isPremultiplied.
402     if (isPremultiplied) {
403         SkASSERT(info.alphaType() != kUnpremul_SkAlphaType);
404     } else {
405         SkASSERT(info.alphaType() != kPremul_SkAlphaType);
406     }
407 }
408 
createBitmap(JNIEnv * env,android::Bitmap * bitmap,int bitmapCreateFlags,jbyteArray ninePatchChunk,jobject ninePatchInsets,int density)409 jobject GraphicsJNI::createBitmap(JNIEnv* env, android::Bitmap* bitmap,
410         int bitmapCreateFlags, jbyteArray ninePatchChunk, jobject ninePatchInsets,
411         int density) {
412     bool isMutable = bitmapCreateFlags & kBitmapCreateFlag_Mutable;
413     bool isPremultiplied = bitmapCreateFlags & kBitmapCreateFlag_Premultiplied;
414     // The caller needs to have already set the alpha type properly, so the
415     // native SkBitmap stays in sync with the Java Bitmap.
416     assert_premultiplied(bitmap->info(), isPremultiplied);
417 
418     jobject obj = env->NewObject(gBitmap_class, gBitmap_constructorMethodID,
419             reinterpret_cast<jlong>(bitmap), bitmap->javaByteArray(),
420             bitmap->width(), bitmap->height(), density, isMutable, isPremultiplied,
421             ninePatchChunk, ninePatchInsets);
422     hasException(env); // For the side effect of logging.
423     return obj;
424 }
425 
reinitBitmap(JNIEnv * env,jobject javaBitmap,const SkImageInfo & info,bool isPremultiplied)426 void GraphicsJNI::reinitBitmap(JNIEnv* env, jobject javaBitmap, const SkImageInfo& info,
427         bool isPremultiplied)
428 {
429     // The caller needs to have already set the alpha type properly, so the
430     // native SkBitmap stays in sync with the Java Bitmap.
431     assert_premultiplied(info, isPremultiplied);
432 
433     env->CallVoidMethod(javaBitmap, gBitmap_reinitMethodID,
434             info.width(), info.height(), isPremultiplied);
435 }
436 
getBitmapAllocationByteCount(JNIEnv * env,jobject javaBitmap)437 int GraphicsJNI::getBitmapAllocationByteCount(JNIEnv* env, jobject javaBitmap)
438 {
439     return env->CallIntMethod(javaBitmap, gBitmap_getAllocationByteCountMethodID);
440 }
441 
createBitmapRegionDecoder(JNIEnv * env,SkBitmapRegionDecoder * bitmap)442 jobject GraphicsJNI::createBitmapRegionDecoder(JNIEnv* env, SkBitmapRegionDecoder* bitmap)
443 {
444     SkASSERT(bitmap != NULL);
445 
446     jobject obj = env->NewObject(gBitmapRegionDecoder_class,
447             gBitmapRegionDecoder_constructorMethodID,
448             reinterpret_cast<jlong>(bitmap));
449     hasException(env); // For the side effect of logging.
450     return obj;
451 }
452 
createRegion(JNIEnv * env,SkRegion * region)453 jobject GraphicsJNI::createRegion(JNIEnv* env, SkRegion* region)
454 {
455     SkASSERT(region != NULL);
456     jobject obj = env->NewObject(gRegion_class, gRegion_constructorMethodID,
457                                  reinterpret_cast<jlong>(region), 0);
458     hasException(env); // For the side effect of logging.
459     return obj;
460 }
461 
vm2env(JavaVM * vm)462 static JNIEnv* vm2env(JavaVM* vm)
463 {
464     JNIEnv* env = NULL;
465     if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || NULL == env)
466     {
467         SkDebugf("------- [%p] vm->GetEnv() failed\n", vm);
468         sk_throw();
469     }
470     return env;
471 }
472 
473 ///////////////////////////////////////////////////////////////////////////////
474 
computeAllocationSize(const SkBitmap & bitmap,size_t * size)475 static bool computeAllocationSize(const SkBitmap& bitmap, size_t* size) {
476     int32_t rowBytes32 = SkToS32(bitmap.rowBytes());
477     int64_t bigSize = (int64_t)bitmap.height() * rowBytes32;
478     if (rowBytes32 < 0 || !sk_64_isS32(bigSize)) {
479         return false; // allocation will be too large
480     }
481 
482     *size = sk_64_asS32(bigSize);
483     return true;
484 }
485 
allocateJavaPixelRef(JNIEnv * env,SkBitmap * bitmap,SkColorTable * ctable)486 android::Bitmap* GraphicsJNI::allocateJavaPixelRef(JNIEnv* env, SkBitmap* bitmap,
487                                              SkColorTable* ctable) {
488     const SkImageInfo& info = bitmap->info();
489     if (info.fColorType == kUnknown_SkColorType) {
490         doThrowIAE(env, "unknown bitmap configuration");
491         return NULL;
492     }
493 
494     size_t size;
495     if (!computeAllocationSize(*bitmap, &size)) {
496         return NULL;
497     }
498 
499     // we must respect the rowBytes value already set on the bitmap instead of
500     // attempting to compute our own.
501     const size_t rowBytes = bitmap->rowBytes();
502 
503     jbyteArray arrayObj = (jbyteArray) env->CallObjectMethod(gVMRuntime,
504                                                              gVMRuntime_newNonMovableArray,
505                                                              gByte_class, size);
506     if (env->ExceptionCheck() != 0) {
507         return NULL;
508     }
509     SkASSERT(arrayObj);
510     jbyte* addr = (jbyte*) env->CallLongMethod(gVMRuntime, gVMRuntime_addressOf, arrayObj);
511     if (env->ExceptionCheck() != 0) {
512         return NULL;
513     }
514     SkASSERT(addr);
515     android::Bitmap* wrapper = new android::Bitmap(env, arrayObj, (void*) addr,
516             info, rowBytes, ctable);
517     wrapper->getSkBitmap(bitmap);
518     // since we're already allocated, we lockPixels right away
519     // HeapAllocator behaves this way too
520     bitmap->lockPixels();
521 
522     return wrapper;
523 }
524 
525 struct AndroidPixelRefContext {
526     int32_t stableID;
527 };
528 
allocatePixelsReleaseProc(void * ptr,void * ctx)529 static void allocatePixelsReleaseProc(void* ptr, void* ctx) {
530     AndroidPixelRefContext* context = (AndroidPixelRefContext*)ctx;
531     if (android::uirenderer::Caches::hasInstance()) {
532          android::uirenderer::Caches::getInstance().textureCache.releaseTexture(context->stableID);
533     }
534 
535     sk_free(ptr);
536     delete context;
537 }
538 
allocatePixels(JNIEnv * env,SkBitmap * bitmap,SkColorTable * ctable)539 bool GraphicsJNI::allocatePixels(JNIEnv* env, SkBitmap* bitmap, SkColorTable* ctable) {
540     const SkImageInfo& info = bitmap->info();
541     if (info.fColorType == kUnknown_SkColorType) {
542         doThrowIAE(env, "unknown bitmap configuration");
543         return NULL;
544     }
545 
546     size_t size;
547     if (!computeAllocationSize(*bitmap, &size)) {
548         return false;
549     }
550 
551     // we must respect the rowBytes value already set on the bitmap instead of
552     // attempting to compute our own.
553     const size_t rowBytes = bitmap->rowBytes();
554 
555     void* addr = sk_malloc_flags(size, 0);
556     if (NULL == addr) {
557         return false;
558     }
559 
560     AndroidPixelRefContext* context = new AndroidPixelRefContext;
561     SkMallocPixelRef* pr = SkMallocPixelRef::NewWithProc(info, rowBytes, ctable, addr,
562                                                          &allocatePixelsReleaseProc, context);
563     if (!pr) {
564         delete context;
565         return false;
566     }
567 
568     // set the stableID in the context so that it can be used later in
569     // allocatePixelsReleaseProc to remove the texture from the cache.
570     context->stableID = pr->getStableID();
571 
572     bitmap->setPixelRef(pr)->unref();
573     // since we're already allocated, we can lockPixels right away
574     bitmap->lockPixels();
575 
576     return true;
577 }
578 
allocateAshmemPixelRef(JNIEnv * env,SkBitmap * bitmap,SkColorTable * ctable)579 android::Bitmap* GraphicsJNI::allocateAshmemPixelRef(JNIEnv* env, SkBitmap* bitmap,
580                                                      SkColorTable* ctable) {
581     int fd;
582 
583     const SkImageInfo& info = bitmap->info();
584     if (info.fColorType == kUnknown_SkColorType) {
585         doThrowIAE(env, "unknown bitmap configuration");
586         return nullptr;
587     }
588 
589     size_t size;
590     if (!computeAllocationSize(*bitmap, &size)) {
591         return nullptr;
592     }
593 
594     // we must respect the rowBytes value already set on the bitmap instead of
595     // attempting to compute our own.
596     const size_t rowBytes = bitmap->rowBytes();
597 
598     // Create new ashmem region with read/write priv
599     fd = ashmem_create_region("bitmap", size);
600     if (fd < 0) {
601         return nullptr;
602     }
603 
604     void* addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
605     if (addr == MAP_FAILED) {
606         close(fd);
607         return nullptr;
608     }
609 
610     if (ashmem_set_prot_region(fd, PROT_READ) < 0) {
611         munmap(addr, size);
612         close(fd);
613         return nullptr;
614     }
615 
616     android::Bitmap* wrapper = new android::Bitmap(addr, fd, info, rowBytes, ctable);
617     wrapper->getSkBitmap(bitmap);
618     // since we're already allocated, we lockPixels right away
619     // HeapAllocator behaves this way too
620     bitmap->lockPixels();
621 
622     return wrapper;
623 }
624 
mapAshmemPixelRef(JNIEnv * env,SkBitmap * bitmap,SkColorTable * ctable,int fd,void * addr,bool readOnly)625 android::Bitmap* GraphicsJNI::mapAshmemPixelRef(JNIEnv* env, SkBitmap* bitmap,
626         SkColorTable* ctable, int fd, void* addr, bool readOnly) {
627     const SkImageInfo& info = bitmap->info();
628     if (info.fColorType == kUnknown_SkColorType) {
629         doThrowIAE(env, "unknown bitmap configuration");
630         return nullptr;
631     }
632 
633     if (!addr) {
634         // Map existing ashmem region if not already mapped.
635         int flags = readOnly ? (PROT_READ) : (PROT_READ | PROT_WRITE);
636         addr = mmap(NULL, ashmem_get_size_region(fd), flags, MAP_SHARED, fd, 0);
637         if (addr == MAP_FAILED) {
638             return nullptr;
639         }
640     }
641 
642     // we must respect the rowBytes value already set on the bitmap instead of
643     // attempting to compute our own.
644     const size_t rowBytes = bitmap->rowBytes();
645 
646     android::Bitmap* wrapper = new android::Bitmap(addr, fd, info, rowBytes, ctable);
647     wrapper->getSkBitmap(bitmap);
648     if (readOnly) {
649         bitmap->pixelRef()->setImmutable();
650     }
651     // since we're already allocated, we lockPixels right away
652     // HeapAllocator behaves this way too
653     bitmap->lockPixels();
654 
655     return wrapper;
656 }
657 
658 ///////////////////////////////////////////////////////////////////////////////
659 
JavaPixelAllocator(JNIEnv * env)660 JavaPixelAllocator::JavaPixelAllocator(JNIEnv* env) {
661     LOG_ALWAYS_FATAL_IF(env->GetJavaVM(&mJavaVM) != JNI_OK,
662             "env->GetJavaVM failed");
663 }
664 
~JavaPixelAllocator()665 JavaPixelAllocator::~JavaPixelAllocator() {
666     if (mStorage) {
667         mStorage->detachFromJava();
668     }
669 }
670 
allocPixelRef(SkBitmap * bitmap,SkColorTable * ctable)671 bool JavaPixelAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
672     JNIEnv* env = vm2env(mJavaVM);
673 
674     mStorage = GraphicsJNI::allocateJavaPixelRef(env, bitmap, ctable);
675     return mStorage != nullptr;
676 }
677 
678 ////////////////////////////////////////////////////////////////////////////////
679 
AshmemPixelAllocator(JNIEnv * env)680 AshmemPixelAllocator::AshmemPixelAllocator(JNIEnv *env) {
681     LOG_ALWAYS_FATAL_IF(env->GetJavaVM(&mJavaVM) != JNI_OK,
682             "env->GetJavaVM failed");
683 }
684 
~AshmemPixelAllocator()685 AshmemPixelAllocator::~AshmemPixelAllocator() {
686     if (mStorage) {
687         mStorage->detachFromJava();
688     }
689 }
690 
allocPixelRef(SkBitmap * bitmap,SkColorTable * ctable)691 bool AshmemPixelAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
692     JNIEnv* env = vm2env(mJavaVM);
693     mStorage = GraphicsJNI::allocateAshmemPixelRef(env, bitmap, ctable);
694     return mStorage != nullptr;
695 }
696 
697 ////////////////////////////////////////////////////////////////////////////////
698 
make_globalref(JNIEnv * env,const char classname[])699 static jclass make_globalref(JNIEnv* env, const char classname[])
700 {
701     jclass c = env->FindClass(classname);
702     SkASSERT(c);
703     return (jclass) env->NewGlobalRef(c);
704 }
705 
getFieldIDCheck(JNIEnv * env,jclass clazz,const char fieldname[],const char type[])706 static jfieldID getFieldIDCheck(JNIEnv* env, jclass clazz,
707                                 const char fieldname[], const char type[])
708 {
709     jfieldID id = env->GetFieldID(clazz, fieldname, type);
710     SkASSERT(id);
711     return id;
712 }
713 
register_android_graphics_Graphics(JNIEnv * env)714 int register_android_graphics_Graphics(JNIEnv* env)
715 {
716     jmethodID m;
717     jclass c;
718 
719     gRect_class = make_globalref(env, "android/graphics/Rect");
720     gRect_leftFieldID = getFieldIDCheck(env, gRect_class, "left", "I");
721     gRect_topFieldID = getFieldIDCheck(env, gRect_class, "top", "I");
722     gRect_rightFieldID = getFieldIDCheck(env, gRect_class, "right", "I");
723     gRect_bottomFieldID = getFieldIDCheck(env, gRect_class, "bottom", "I");
724 
725     gRectF_class = make_globalref(env, "android/graphics/RectF");
726     gRectF_leftFieldID = getFieldIDCheck(env, gRectF_class, "left", "F");
727     gRectF_topFieldID = getFieldIDCheck(env, gRectF_class, "top", "F");
728     gRectF_rightFieldID = getFieldIDCheck(env, gRectF_class, "right", "F");
729     gRectF_bottomFieldID = getFieldIDCheck(env, gRectF_class, "bottom", "F");
730 
731     gPoint_class = make_globalref(env, "android/graphics/Point");
732     gPoint_xFieldID = getFieldIDCheck(env, gPoint_class, "x", "I");
733     gPoint_yFieldID = getFieldIDCheck(env, gPoint_class, "y", "I");
734 
735     gPointF_class = make_globalref(env, "android/graphics/PointF");
736     gPointF_xFieldID = getFieldIDCheck(env, gPointF_class, "x", "F");
737     gPointF_yFieldID = getFieldIDCheck(env, gPointF_class, "y", "F");
738 
739     gBitmap_class = make_globalref(env, "android/graphics/Bitmap");
740     gBitmap_nativePtr = getFieldIDCheck(env, gBitmap_class, "mNativePtr", "J");
741     gBitmap_constructorMethodID = env->GetMethodID(gBitmap_class, "<init>", "(J[BIIIZZ[BLandroid/graphics/NinePatch$InsetStruct;)V");
742     gBitmap_reinitMethodID = env->GetMethodID(gBitmap_class, "reinit", "(IIZ)V");
743     gBitmap_getAllocationByteCountMethodID = env->GetMethodID(gBitmap_class, "getAllocationByteCount", "()I");
744     gBitmapRegionDecoder_class = make_globalref(env, "android/graphics/BitmapRegionDecoder");
745     gBitmapRegionDecoder_constructorMethodID = env->GetMethodID(gBitmapRegionDecoder_class, "<init>", "(J)V");
746 
747     gBitmapConfig_class = make_globalref(env, "android/graphics/Bitmap$Config");
748     gBitmapConfig_nativeInstanceID = getFieldIDCheck(env, gBitmapConfig_class,
749                                                      "nativeInt", "I");
750 
751     gCanvas_class = make_globalref(env, "android/graphics/Canvas");
752     gCanvas_nativeInstanceID = getFieldIDCheck(env, gCanvas_class, "mNativeCanvasWrapper", "J");
753 
754     gPicture_class = make_globalref(env, "android/graphics/Picture");
755     gPicture_nativeInstanceID = getFieldIDCheck(env, gPicture_class, "mNativePicture", "J");
756 
757     gRegion_class = make_globalref(env, "android/graphics/Region");
758     gRegion_nativeInstanceID = getFieldIDCheck(env, gRegion_class, "mNativeRegion", "J");
759     gRegion_constructorMethodID = env->GetMethodID(gRegion_class, "<init>",
760         "(JI)V");
761 
762     c = env->FindClass("java/lang/Byte");
763     gByte_class = (jclass) env->NewGlobalRef(
764         env->GetStaticObjectField(c, env->GetStaticFieldID(c, "TYPE", "Ljava/lang/Class;")));
765 
766     gVMRuntime_class = make_globalref(env, "dalvik/system/VMRuntime");
767     m = env->GetStaticMethodID(gVMRuntime_class, "getRuntime", "()Ldalvik/system/VMRuntime;");
768     gVMRuntime = env->NewGlobalRef(env->CallStaticObjectMethod(gVMRuntime_class, m));
769     gVMRuntime_newNonMovableArray = env->GetMethodID(gVMRuntime_class, "newNonMovableArray",
770                                                      "(Ljava/lang/Class;I)Ljava/lang/Object;");
771     gVMRuntime_addressOf = env->GetMethodID(gVMRuntime_class, "addressOf", "(Ljava/lang/Object;)J");
772 
773     return 0;
774 }
775