1 #include "CreateJavaOutputStreamAdaptor.h"
2 #include "SkData.h"
3 #include "SkMalloc.h"
4 #include "SkRefCnt.h"
5 #include "SkStream.h"
6 #include "SkTypes.h"
7 #include "Utils.h"
8 
9 #include <nativehelper/JNIHelp.h>
10 #include <log/log.h>
11 #include <memory>
12 
13 static jmethodID    gInputStream_readMethodID;
14 static jmethodID    gInputStream_skipMethodID;
15 
16 /**
17  *  Wrapper for a Java InputStream.
18  */
19 class JavaInputStreamAdaptor : public SkStream {
JavaInputStreamAdaptor(JavaVM * jvm,jobject js,jbyteArray ar,jint capacity,bool swallowExceptions)20     JavaInputStreamAdaptor(JavaVM* jvm, jobject js, jbyteArray ar, jint capacity,
21                            bool swallowExceptions)
22             : fJvm(jvm)
23             , fJavaInputStream(js)
24             , fJavaByteArray(ar)
25             , fCapacity(capacity)
26             , fBytesRead(0)
27             , fIsAtEnd(false)
28             , fSwallowExceptions(swallowExceptions) {}
29 
30 public:
Create(JNIEnv * env,jobject js,jbyteArray ar,bool swallowExceptions)31     static JavaInputStreamAdaptor* Create(JNIEnv* env, jobject js, jbyteArray ar,
32                                           bool swallowExceptions) {
33         JavaVM* jvm;
34         LOG_ALWAYS_FATAL_IF(env->GetJavaVM(&jvm) != JNI_OK);
35 
36         js = env->NewGlobalRef(js);
37         if (!js) {
38             return nullptr;
39         }
40 
41         ar = (jbyteArray) env->NewGlobalRef(ar);
42         if (!ar) {
43             env->DeleteGlobalRef(js);
44             return nullptr;
45         }
46 
47         jint capacity = env->GetArrayLength(ar);
48         return new JavaInputStreamAdaptor(jvm, js, ar, capacity, swallowExceptions);
49     }
50 
~JavaInputStreamAdaptor()51     ~JavaInputStreamAdaptor() override {
52         auto* env = android::requireEnv(fJvm);
53         env->DeleteGlobalRef(fJavaInputStream);
54         env->DeleteGlobalRef(fJavaByteArray);
55     }
56 
read(void * buffer,size_t size)57     size_t read(void* buffer, size_t size) override {
58         auto* env = android::requireEnv(fJvm);
59         if (!fSwallowExceptions && checkException(env)) {
60             // Just in case the caller did not clear from a previous exception.
61             return 0;
62         }
63         if (NULL == buffer) {
64             if (0 == size) {
65                 return 0;
66             } else {
67                 /*  InputStream.skip(n) can return <=0 but still not be at EOF
68                     If we see that value, we need to call read(), which will
69                     block if waiting for more data, or return -1 at EOF
70                  */
71                 size_t amountSkipped = 0;
72                 do {
73                     size_t amount = this->doSkip(size - amountSkipped, env);
74                     if (0 == amount) {
75                         char tmp;
76                         amount = this->doRead(&tmp, 1, env);
77                         if (0 == amount) {
78                             // if read returned 0, we're at EOF
79                             fIsAtEnd = true;
80                             break;
81                         }
82                     }
83                     amountSkipped += amount;
84                 } while (amountSkipped < size);
85                 return amountSkipped;
86             }
87         }
88         return this->doRead(buffer, size, env);
89     }
90 
isAtEnd() const91     bool isAtEnd() const override { return fIsAtEnd; }
92 
93 private:
doRead(void * buffer,size_t size,JNIEnv * env)94     size_t doRead(void* buffer, size_t size, JNIEnv* env) {
95         size_t bytesRead = 0;
96         // read the bytes
97         do {
98             jint requested = 0;
99             if (size > static_cast<size_t>(fCapacity)) {
100                 requested = fCapacity;
101             } else {
102                 // This is safe because requested is clamped to (jint)
103                 // fCapacity.
104                 requested = static_cast<jint>(size);
105             }
106 
107             jint n = env->CallIntMethod(fJavaInputStream,
108                                         gInputStream_readMethodID, fJavaByteArray, 0, requested);
109             if (checkException(env)) {
110                 SkDebugf("---- read threw an exception\n");
111                 return bytesRead;
112             }
113 
114             if (n < 0) { // n == 0 should not be possible, see InputStream read() specifications.
115                 fIsAtEnd = true;
116                 break;  // eof
117             }
118 
119             env->GetByteArrayRegion(fJavaByteArray, 0, n,
120                                     reinterpret_cast<jbyte*>(buffer));
121             if (checkException(env)) {
122                 SkDebugf("---- read:GetByteArrayRegion threw an exception\n");
123                 return bytesRead;
124             }
125 
126             buffer = (void*)((char*)buffer + n);
127             bytesRead += n;
128             size -= n;
129             fBytesRead += n;
130         } while (size != 0);
131 
132         return bytesRead;
133     }
134 
doSkip(size_t size,JNIEnv * env)135     size_t doSkip(size_t size, JNIEnv* env) {
136         jlong skipped = env->CallLongMethod(fJavaInputStream,
137                                             gInputStream_skipMethodID, (jlong)size);
138         if (checkException(env)) {
139             SkDebugf("------- skip threw an exception\n");
140             return 0;
141         }
142         if (skipped < 0) {
143             skipped = 0;
144         }
145 
146         return (size_t)skipped;
147     }
148 
checkException(JNIEnv * env)149     bool checkException(JNIEnv* env) {
150         if (!env->ExceptionCheck()) {
151             return false;
152         }
153 
154         env->ExceptionDescribe();
155         if (fSwallowExceptions) {
156             env->ExceptionClear();
157         }
158 
159         // There is no way to recover from the error, so consider the stream
160         // to be at the end.
161         fIsAtEnd = true;
162 
163         return true;
164     }
165 
166     JavaVM*     fJvm;
167     jobject     fJavaInputStream;
168     jbyteArray  fJavaByteArray;
169     const jint  fCapacity;
170     size_t      fBytesRead;
171     bool        fIsAtEnd;
172     const bool  fSwallowExceptions;
173 };
174 
CreateJavaInputStreamAdaptor(JNIEnv * env,jobject stream,jbyteArray storage,bool swallowExceptions)175 SkStream* CreateJavaInputStreamAdaptor(JNIEnv* env, jobject stream, jbyteArray storage,
176                                        bool swallowExceptions) {
177     return JavaInputStreamAdaptor::Create(env, stream, storage, swallowExceptions);
178 }
179 
adaptor_to_mem_stream(SkStream * stream)180 static SkMemoryStream* adaptor_to_mem_stream(SkStream* stream) {
181     SkASSERT(stream != NULL);
182     size_t bufferSize = 4096;
183     size_t streamLen = 0;
184     size_t len;
185     char* data = (char*)sk_malloc_throw(bufferSize);
186 
187     while ((len = stream->read(data + streamLen,
188                                bufferSize - streamLen)) != 0) {
189         streamLen += len;
190         if (streamLen == bufferSize) {
191             bufferSize *= 2;
192             data = (char*)sk_realloc_throw(data, bufferSize);
193         }
194     }
195     data = (char*)sk_realloc_throw(data, streamLen);
196 
197     SkMemoryStream* streamMem = new SkMemoryStream();
198     streamMem->setMemoryOwned(data, streamLen);
199     return streamMem;
200 }
201 
CopyJavaInputStream(JNIEnv * env,jobject stream,jbyteArray storage)202 SkStreamRewindable* CopyJavaInputStream(JNIEnv* env, jobject stream,
203                                         jbyteArray storage) {
204     std::unique_ptr<SkStream> adaptor(CreateJavaInputStreamAdaptor(env, stream, storage));
205     if (NULL == adaptor.get()) {
206         return NULL;
207     }
208     return adaptor_to_mem_stream(adaptor.get());
209 }
210 
211 ///////////////////////////////////////////////////////////////////////////////
212 
213 static jmethodID    gOutputStream_writeMethodID;
214 static jmethodID    gOutputStream_flushMethodID;
215 
216 class SkJavaOutputStream : public SkWStream {
217 public:
SkJavaOutputStream(JNIEnv * env,jobject stream,jbyteArray storage)218     SkJavaOutputStream(JNIEnv* env, jobject stream, jbyteArray storage)
219         : fEnv(env), fJavaOutputStream(stream), fJavaByteArray(storage), fBytesWritten(0) {
220         fCapacity = env->GetArrayLength(storage);
221     }
222 
bytesWritten() const223     virtual size_t bytesWritten() const {
224         return fBytesWritten;
225     }
226 
write(const void * buffer,size_t size)227     virtual bool write(const void* buffer, size_t size) {
228         JNIEnv* env = fEnv;
229         jbyteArray storage = fJavaByteArray;
230 
231         while (size > 0) {
232             jint requested = 0;
233             if (size > static_cast<size_t>(fCapacity)) {
234                 requested = fCapacity;
235             } else {
236                 // This is safe because requested is clamped to (jint)
237                 // fCapacity.
238                 requested = static_cast<jint>(size);
239             }
240 
241             env->SetByteArrayRegion(storage, 0, requested,
242                                     reinterpret_cast<const jbyte*>(buffer));
243             if (env->ExceptionCheck()) {
244                 env->ExceptionDescribe();
245                 env->ExceptionClear();
246                 SkDebugf("--- write:SetByteArrayElements threw an exception\n");
247                 return false;
248             }
249 
250             fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_writeMethodID,
251                                  storage, 0, requested);
252             if (env->ExceptionCheck()) {
253                 env->ExceptionDescribe();
254                 env->ExceptionClear();
255                 SkDebugf("------- write threw an exception\n");
256                 return false;
257             }
258 
259             buffer = (void*)((char*)buffer + requested);
260             size -= requested;
261             fBytesWritten += requested;
262         }
263         return true;
264     }
265 
flush()266     virtual void flush() {
267         fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_flushMethodID);
268     }
269 
270 private:
271     JNIEnv*     fEnv;
272     jobject     fJavaOutputStream;  // the caller owns this object
273     jbyteArray  fJavaByteArray;     // the caller owns this object
274     jint        fCapacity;
275     size_t      fBytesWritten;
276 };
277 
CreateJavaOutputStreamAdaptor(JNIEnv * env,jobject stream,jbyteArray storage)278 SkWStream* CreateJavaOutputStreamAdaptor(JNIEnv* env, jobject stream,
279                                          jbyteArray storage) {
280     return new SkJavaOutputStream(env, stream, storage);
281 }
282 
findClassCheck(JNIEnv * env,const char classname[])283 static jclass findClassCheck(JNIEnv* env, const char classname[]) {
284     jclass clazz = env->FindClass(classname);
285     SkASSERT(!env->ExceptionCheck());
286     return clazz;
287 }
288 
getMethodIDCheck(JNIEnv * env,jclass clazz,const char methodname[],const char type[])289 static jmethodID getMethodIDCheck(JNIEnv* env, jclass clazz,
290                                   const char methodname[], const char type[]) {
291     jmethodID id = env->GetMethodID(clazz, methodname, type);
292     SkASSERT(!env->ExceptionCheck());
293     return id;
294 }
295 
register_android_graphics_CreateJavaOutputStreamAdaptor(JNIEnv * env)296 int register_android_graphics_CreateJavaOutputStreamAdaptor(JNIEnv* env) {
297     jclass inputStream_Clazz = findClassCheck(env, "java/io/InputStream");
298     gInputStream_readMethodID = getMethodIDCheck(env, inputStream_Clazz, "read", "([BII)I");
299     gInputStream_skipMethodID = getMethodIDCheck(env, inputStream_Clazz, "skip", "(J)J");
300 
301     jclass outputStream_Clazz = findClassCheck(env, "java/io/OutputStream");
302     gOutputStream_writeMethodID = getMethodIDCheck(env, outputStream_Clazz, "write", "([BII)V");
303     gOutputStream_flushMethodID = getMethodIDCheck(env, outputStream_Clazz, "flush", "()V");
304 
305     return 0;
306 }
307