Debian Codegraph @

src/core/util_platforms.cpp

raw symbols SCIP
1 /*----------------------------------------------------------------------------
2 ChucK Strongly-timed Audio Programming Language
3 Compiler and Virtual Machine
4
5 Copyright (c) 2003 Ge Wang and Perry R. Cook. All rights reserved.
6 http://chuck.stanford.edu/
7 http://chuck.cs.princeton.edu/
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
22 U.S.A.
23 -----------------------------------------------------------------------------*/
24
25 //-----------------------------------------------------------------------------
26 // name: util_platforms.cpp
27 // desc: platform-specific utilities, e.g., for Android and various
28 //
29 // author: Andriy Kunitsyn ([email protected]) | original ChuckAndroid
30 // Ge Wang (https://ccrma.stanford.edu/~ge/)
31 // date: Summer 2021
32 //-----------------------------------------------------------------------------
33 #include "util_platforms.h"
34 #include "util_string.h"
35 #include "chuck_errmsg.h"
36
37 #include <stdio.h>
38 #include <string.h>
39 #include <sys/stat.h>
40
41
42 #ifdef __PLATFORM_WINDOWS__
43
44 #ifndef __CHUNREAL_ENGINE__
45 #include <windows.h> // for win32_tmpfile()
46 #else
47 // 1.5.0.0 (ge) | #chunreal
48 // unreal engine on windows disallows including windows.h
49 #include "Windows/MinWindows.h"
50 #endif // #ifndef __CHUNREAL_ENGINE__
51 #include <io.h> // for _isatty()
52
53 #else // not windows
54
55 #include <unistd.h>
56 #include <sys/ioctl.h>
57 #include <sys/time.h>
58
59 #endif // #ifdef __PLATFORM_WINDOWS__
60
61
62
63 //-----------------------------------------------------------------------------
64 // name: ck_openFileAutoExt()
65 // desc: open a file by name, first as is, and if needed concatenateing ".ck"
66 // this potentially modifies the contents of fname
67 //-----------------------------------------------------------------------------
68 FILE * ck_openFileAutoExt( std::string & filenameMutable,
69 const std::string & extension )
70 {
71 #ifdef __ANDROID__
72 if( strncmp(filenameMutable.c_str(), "jar:", strlen("jar:")) == 0 )
73 {
74 int fd = 0;
75 if( !ChuckAndroid::copyJARURLFileToTemporary(filenameMutable.c_str(), &fd) )
76 {
77 EM_error2( 0, "unable to download from JAR URL: %s", filenameMutable.c_str() );
78 return NULL;
79 }
80 return fdopen(fd, "rb");
81 }
82 #endif // __ANDROID__
83
84 // try opening
85 FILE * fd = fopen( filenameMutable.c_str(), "rb" );
86 // file open?
87 if( !fd )
88 {
89 // check if filename has extension, ignoring case
90 if( !extension_matches( filenameMutable, extension, TRUE ) )
91 {
92 // concat
93 std::string tryThis = filenameMutable + extension;
94 // try opening again
95 fd = fopen( tryThis.c_str(), "rb" );
96 // if successful update filename
97 filenameMutable = tryThis;
98 }
99 }
100
101 return fd;
102 }
103
104
105
106
107 //-----------------------------------------------------------------------------
108 // name: win32_tmpfile()
109 // desc: replacement for broken tmpfile() on Windows Vista + 7
110 //-----------------------------------------------------------------------------
111 #ifdef __PLATFORM_WINDOWS__
112 FILE * win32_tmpfile()
113 {
114 char tmp_path[MAX_PATH];
115 char file_path[MAX_PATH];
116 FILE * file = NULL;
117
118 #ifndef __CHUNREAL_ENGINE__
119 if( GetTempPath(256, tmp_path) == 0 )
120 #else
121 // 1.5.0.0 (ge) | #chunreal explicit call ASCII version
122 if( GetTempPathA(256, tmp_path) == 0 )
123 #endif
124 return NULL;
125
126 #ifndef __CHUNREAL_ENGINE__
127 if( GetTempFileName(tmp_path, "mA", 0, file_path) == 0 )
128 #else
129 // 1.5.0.0 (ge) | #chunreal explicit call ASCII version
130 if( GetTempFileNameA(tmp_path, "mA", 0, file_path) == 0 )
131 #endif
132 return NULL;
133
134 file = fopen( file_path, "wb+D" );
135
136 return file;
137 }
138 #endif // #ifdef __PLATFORM_WINDOWS__
139
140
141
142
143 //-----------------------------------------------------------------------------
144 // name: ck_configANSI_ESCcodes() | 1.5.0.5 (ge) added
145 // desc: do any platform-specific setup to enable ANSI escape codes
146 //-----------------------------------------------------------------------------
147 t_CKBOOL ck_configANSI_ESCcodes()
148 {
149 #ifndef __PLATFORM_WINDOWS__
150 #else
151 // get stderr handle; do this first as chuck tends to write to stderr
152 HANDLE winStderr = GetStdHandle( STD_ERROR_HANDLE );
153 // check handle
154 if( winStderr == NULL || winStderr == INVALID_HANDLE_VALUE ) return FALSE;
155 // set windows console mode to process escape sequences + enable color terminal output
156 SetConsoleMode( winStderr, ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING );
157
158 // get stdout handle
159 HANDLE winStdout = GetStdHandle( STD_OUTPUT_HANDLE );
160 // check handle
161 if( winStdout == NULL || winStdout == INVALID_HANDLE_VALUE ) return FALSE;
162 // set windows console mode to process escape sequences + enable color terminal output
163 SetConsoleMode( winStdout, ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING );
164 #endif
165
166 return TRUE;
167 }
168
169
170
171
172 //-----------------------------------------------------------------------------
173 // name: ck_isatty() | 1.5.0.5 (ge) added
174 // desc: are we output to a TTY (teletype, character by character)
175 // (vs say a file stream; helpful for determining if we should
176 // suppress printing ANSI escapes codes, e.g., color codes
177 // to the output stream
178 //-----------------------------------------------------------------------------
179 t_CKBOOL ck_isatty( int fd )
180 {
181 #if defined(__PLATFORM_WINDOWS__)
182 return _isatty( fd ) != 0;
183 #else
184 return isatty( fd ) != 0;
185 #endif
186 }
187 //-----------------------------------------------------------------------------
188 // get a general sense if currently outputting to TTY
189 //-----------------------------------------------------------------------------
190 t_CKBOOL ck_isatty()
191 {
192 // let's test stderr, since much of chuck operates over it
193 #if defined(__PLATFORM_WINDOWS__)
194 return ck_isatty( _fileno(stderr) );
195 #elif defined(__PLATFORM_EMSCRIPTEN__)
196 // emscripten always seems to return TRUE for isatty()
197 // but then ioctl() does not seem to be working / implemented
198 // so returning FALSE for now | use chuck param TTY_WIDTH_HINT
199 return FALSE;
200 #else
201 return ck_isatty( fileno(stderr) );
202 #endif
203 }
204
205
206
207
208 // current dfeault
209 static t_CKUINT g_ttywidth_default = 80;
210 //-----------------------------------------------------------------------------
211 // name: ck_ttywidth() | 1.5.0.5 (ge) added
212 // desc: get TTY terminal width, or CK_DEFAULT_TTY_WIDTH if not TTY
213 //-----------------------------------------------------------------------------
214 t_CKUINT ck_ttywidth()
215 {
216 // return default if not TTY
217 if( !ck_isatty() ) return g_ttywidth_default;
218
219 #ifndef __PLATFORM_WINDOWS__
220 // a struct to hold return value
221 struct winsize w;
222 // zero out, as ioctl() can return 0 but not modify w (et tu emscripten?)
223 memset( &w, 0, sizeof(w) );
224 // get the window size
225 if( ioctl( fileno(stderr), TIOCGWINSZ, &w ) != 0 ) { goto error; }
226 // return
227 return w.ws_col;
228 #else
229 // get windows handle to stderr
230 HANDLE hStderr = GetStdHandle( STD_ERROR_HANDLE );
231 // console buffer info
232 CONSOLE_SCREEN_BUFFER_INFO info;
233 // get screen buffer info
234 if( !GetConsoleScreenBufferInfo( hStderr, &info ) ) { goto error; }
235 // return width
236 return info.dwSize.X;
237 #endif
238
239 error:
240 return g_ttywidth_default;
241 }
242
243
244
245
246 //-----------------------------------------------------------------------------
247 // set default TTY width
248 //-----------------------------------------------------------------------------
249 void ck_ttywidth_setdefault( t_CKUINT width )
250 {
251 g_ttywidth_default = width;
252 }
253 //-----------------------------------------------------------------------------
254 // get default TTY width
255 //-----------------------------------------------------------------------------
256 t_CKUINT ck_ttywidth_default()
257 {
258 return g_ttywidth_default;
259 }
260
261
262
263
264 //-----------------------------------------------------------------------------
265 // name: android_tmpfile()
266 // desc: replacement for broken tmpfile() on Android
267 //-----------------------------------------------------------------------------
268 #ifdef __ANDROID__
269 FILE * android_tmpfile()
270 {
271 return ChuckAndroid::getTemporaryFile();
272 }
273 #endif
274
275
276
277
278 //-----------------------------------------------------------------------------
279 // name: android_tmpfile()
280 // desc: replacement for broken tmpfile() on Android
281 //-----------------------------------------------------------------------------
282 FILE * ck_tmpfile()
283 {
284 FILE * fd = NULL;
285 #ifdef __PLATFORM_WINDOWS__
286 fd = win32_tmpfile();
287 #elif defined (__ANDROID__)
288 fd = android_tmpfile();
289 #else
290 fd = tmpfile();
291 #endif
292
293 return fd;
294 }
295
296
297
298
299 //-----------------------------------------------------------------------------
300 // name: ck_isdir()
301 // desc: check if file is a directory
302 //-----------------------------------------------------------------------------
303 t_CKBOOL ck_isdir( const std::string & path )
304 {
305 // shuttle
306 struct stat fs;
307 // stat the path and check flag (is path not there, also returns false)
308 return (stat( path.c_str(), &fs )==0 && fs.st_mode & S_IFDIR);
309 }
310
311
312
313
314 //-----------------------------------------------------------------------------
315 // name: ck_fileexists()
316 // desc: check if file exists
317 //-----------------------------------------------------------------------------
318 t_CKBOOL ck_fileexists( const std::string & path )
319 {
320 // shuttle
321 struct stat fs;
322 // stat the path; 0 means success
323 return ( stat( path.c_str(), &fs ) == 0 );
324 }
325
326
327
328 #ifdef __PLATFORM_WINDOWS__
329 //-----------------------------------------------------------------------------
330 // name: win32_getline()
331 // desc: C getline using a FILE descriptor
332 // thanks be to random people on the internet
333 // https://stackoverflow.com/questions/735126/are-there-alternate-implementations-of-gnu-getline-interface/735472#735472
334 // using version from Song "from Malaysia": "Better Answer with no Bug Here:"
335 //-----------------------------------------------------------------------------
336 size_t win32_getline( char ** lineptr, size_t * n, FILE * stream )
337 {
338 char * bufptr = NULL;
339 char * p = bufptr;
340 size_t size;
341 int c;
342
343 if( lineptr == NULL )
344 {
345 return -1;
346 }
347 if( stream == NULL )
348 {
349 return -1;
350 }
351 if( n == NULL )
352 {
353 return -1;
354 }
355 bufptr = *lineptr;
356 size = *n;
357
358 c = fgetc( stream );
359 if( c == EOF )
360 {
361 return -1;
362 }
363 if( bufptr == NULL )
364 {
365 bufptr = (char *)malloc( 128 );
366 if( bufptr == NULL )
367 {
368 return -1;
369 }
370 size = 128;
371 }
372 p = bufptr;
373 while( c != EOF )
374 {
375 if( (p - bufptr) > (size - 1) )
376 {
377 size = size + 128;
378 bufptr = (char *)realloc( bufptr, size );
379 if( bufptr == NULL )
380 {
381 return -1;
382 }
383 p = bufptr + (size - 128);
384 }
385 *p++ = c;
386 if( c == '\n' )
387 {
388 break;
389 }
390 c = fgetc( stream );
391 }
392
393 *p++ = '\0';
394 *lineptr = bufptr;
395 *n = size;
396
397 return p - bufptr - 1;
398 }
399 #endif // __PLATFORM_WIN32
400
401
402
403
404
405 //-----------------------------------------------------------------------------
406 // name: ck_getline()
407 // desc: redirect for c edition of getline
408 //-----------------------------------------------------------------------------
409 size_t ck_getline( char ** lineptr, size_t * n, FILE * stream )
410 {
411 #ifndef __PLATFORM_WINDOWS__
412 return getline( lineptr, n, stream );
413 #else
414 return win32_getline( lineptr, n, stream );
415 #endif
416 }
417
418
419
420
421 //-----------------------------------------------------------------------------
422 // name: ck_usleep()
423 // desc: usleep in microseconds
424 //-----------------------------------------------------------------------------
425 void ck_usleep( t_CKUINT microseconds )
426 {
427 #if defined(__PLATFORM_WINDOWS__) && !defined(usleep)
428 #ifndef __CHUNREAL_ENGINE__
429 Sleep( microseconds / 1000 <= 0 ? 1 : microseconds / 1000 );
430 #else
431 // 1.5.0.0 (ge) | #chunreal
432 FPlatformProcess::Sleep( microseconds/1000000.0f <= 0 ? .001 : microseconds/1000000.0f );
433 #endif // #ifndef __UNREAL_ENGINE__
434 #else
435 // call system usleep
436 usleep( (useconds_t)microseconds );
437 #endif
438 }
439
440
441
442
443 //-----------------------------------------------------------------------------
444 // FYI timeval is defined in sys/time.h (non-windows)
445 // FYI timeval is defined in winsock.h AND winsock2.h (windows)
446 // including winsock.h BEFORE winsock2.h could result in compiler errors
447 // (but not vice versa)
448 //-----------------------------------------------------------------------------
449 // typedef struct timeval { long tv_sec; long tv_usec; } timeval;
450 //-----------------------------------------------------------------------------
451 // name: ck_gettimeofday()
452 // desc: get underlying operating system absolute time
453 //-----------------------------------------------------------------------------
454 int ck_gettimeofday( long * tv_sec, long * tv_usec, void * tzp )
455 {
456 // zero out
457 *tv_sec = 0;
458 *tv_usec = 0;
459
460 #ifndef __PLATFORM_WINDOWS__
461 // timeval
462 timeval tv;
463 // call on through
464 #ifdef __ANDROID__
465 int retval = gettimeofday( &tv, (struct timezone *)tzp );
466 #else
467 int retval = gettimeofday( &tv, tzp );
468 #endif
469 // check it
470 if( retval ) return retval;
471 // set return values
472 *tv_sec = tv.tv_sec;
473 *tv_usec = tv.tv_usec;
474 // return (success code)
475 return retval;
476
477 #else // windows
478 // NOTE: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
479 // This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)
480 // until 00:00:00 January 1, 1970
481 static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL);
482
483 SYSTEMTIME system_time;
484 FILETIME file_time;
485 uint64_t time;
486
487 GetSystemTime( &system_time );
488 SystemTimeToFileTime( &system_time, &file_time );
489 time = ((uint64_t)file_time.dwLowDateTime ) ;
490 time += ((uint64_t)file_time.dwHighDateTime) << 32;
491
492 *tv_sec = (long)((time - EPOCH) / 10000000L);
493 *tv_usec = (long)(system_time.wMilliseconds * 1000);
494
495 // return success
496 return 0;
497 #endif
498 }
499
500
501
502
503 //-----------------------------------------------------------------------------
504 #if defined(__PLATFORM_APPLE__) && !defined(__CHIP_MODE__)
505 //-----------------------------------------------------------------------------
506 #include <sys/types.h>
507 #include <sys/sysctl.h>
508 #include <mach/mach.h>
509 #include <mach/mach_time.h> // for mach_absolute_time | 1.5.0.5
510
511
512 //-----------------------------------------------------------------------------
513 // name: ck_darwin_version()
514 // desc: get darwin release version (also see ck_macOS_version())
515 // https://stackoverflow.com/questions/11072804/how-do-i-determine-the-os-version-at-runtime-in-os-x-or-ios-without-using-gesta
516 //-----------------------------------------------------------------------------
517 ck_OSVersion ck_darwin_version()
518 {
519 // version
520 ck_OSVersion ver;
521
522 // get darwin release number
523 char str[256];
524 size_t size = sizeof(str);
525 // get darwin kernel release version
526 // note: sysctl() is supported on macOS; no longer in linux kernels
527 int ret = sysctlbyname( "kern.osrelease", str, &size, NULL, 0 );
528
529 // error
530 if( ret ) return ver;
531
532 // read it in
533 sscanf( str, "%hd.%hd.%hd", &ver.major, &ver.minor, &ver.patch );
534
535 // return version
536 return ver;
537 }
538
539
540 //-----------------------------------------------------------------------------
541 // name: ck_macOS_version()
542 // desc: get macOS release version
543 // note: alternative for Gestalt() which is deprecated
544 // https://stackoverflow.com/questions/11072804/how-do-i-determine-the-os-version-at-runtime-in-os-x-or-ios-without-using-gesta
545 // https://en.wikipedia.org/wiki/Darwin_(operating_system)
546 // Darwin operating system version to macOS release version
547 // 25.x.x. macOS 16.x.x Tahoe
548 // 24.x.x. macOS 15.x.x Sequoia
549 // 23.x.x. macOS 14.x.x Sonoma
550 // 22.x.x. macOS 13.x.x Ventura
551 // 21.x.x. macOS 12.x.x Monterey
552 // 20.x.x. macOS 11.x.x Big Sur
553 // 19.x.x. macOS 10.15.x Catalina
554 // 18.x.x. macOS 10.14.x Mojave
555 // 17.x.x. macOS 10.13.x High Sierra
556 // 16.x.x macOS 10.12.x Sierra
557 // 15.x.x OS X 10.11.x El Capitan
558 // 14.x.x OS X 10.10.x Yosemite
559 // 13.x.x OS X 10.9.x Mavericks
560 // 12.x.x OS X 10.8.x Mountain Lion
561 // 11.x.x OS X 10.7.x Lion
562 // 10.x.x OS X 10.6.x Snow Leopard
563 // 9.x.x OS X 10.5.x Leopard
564 // 8.x.x OS X 10.4.x Tiger
565 // 7.x.x OS X 10.3.x Panther
566 // 6.x.x OS X 10.2.x Jaguar
567 // 5.x OS X 10.1.x Puma
568 // 4.x OS X 10.0.x Cheetah
569 //-----------------------------------------------------------------------------
570 ck_OSVersion ck_macOS_version()
571 {
572 // version
573 ck_OSVersion ver;
574
575 // first try to get macOS release number directly
576 // FYI this may not work in older versions, circa before 2018
577 char str[256];
578 size_t size = sizeof(str);
579 // get darwin kernel release version
580 // note: sysctl() is supported on macOS; no longer in linux kernels
581 int ret = sysctlbyname( "kern.osproductversion", str, &size, NULL, 0 );
582
583 // success
584 if( ret == 0 )
585 {
586 // read it in
587 sscanf( str, "%hd.%hd.%hd", &ver.major, &ver.minor, &ver.patch );
588 // done
589 return ver;
590 }
591
592 // fall back -- get darwin version and our own conversion
593 // FYI darwin minor version could be off by 1 due to security patches
594 ver = ck_darwin_version();
595
596 // test
597 if( ver.major < 4 ) // before 10.1.x Puma
598 {
599 // reset to 0
600 ver.reset();
601 // return 0 version
602 return ver;
603 }
604
605 // convert to macOS release number
606 if( ver.major <= 19 )
607 {
608 // still in OS X era
609 ver.minor = ver.major - 4;
610 ver.major = 10;
611 }
612 else
613 {
614 // hopefully this is future proof; depends on Apple release versioning
615 ver.major = ver.major - 9;
616 }
617
618 // return version
619 return ver;
620 }
621
622
623 //-----------------------------------------------------------------------------
624 // name: str()
625 // desc: get version as string
626 //-----------------------------------------------------------------------------
627 std::string ck_OSVersion::str()
628 {
629 return ck_itoa(major) + "." + ck_itoa(minor) + "." + ck_itoa(patch);
630 }
631
632
633 //-----------------------------------------------------------------------------
634 // name: ck_macOS_uptime() | 1.5.0.5 (ge) added
635 // desc: return macOS uptime
636 // note: replacement for UpTime(), which is deprecated
637 // https://stackoverflow.com/questions/47168914/absolutetonanoseconds-uptime-deprecated
638 // https://opensource.apple.com/source/Libc/Libc-1158.1.2/gen/clock_gettime.c.auto.html
639 // clock_gettime_nsec_np(CLOCK_UPTIME_RAW) doesn't seem be the same as UpTime
640 // at least on apple silicon macOS 13 (Ventura)
641 //-----------------------------------------------------------------------------
642 AbsoluteTime ck_macOS_uptime()
643 {
644 uint64_t mt = mach_absolute_time();
645 AbsoluteTime at;
646 at.hi = (uint32_t)(mt << 32);
647 at.lo = (uint32_t)(mt & 0xffffffff);
648 return at;
649 }
650
651
652 /*
653 static void testUpTime()
654 {
655 uint64_t mt = mach_absolute_time();
656 AbsoluteTime at = UpTime();
657 uint64_t t = ((uint64_t)at.hi << 32) + at.lo;
658
659 AbsoluteTime at2;
660 at2.hi = mt >> 32;
661 at2.lo = mt & 0xffffffff;
662 uint64_t t2 = ((uint64_t)at2.hi << 32) + at2.lo;
663
664 cerr << "TIME:" << clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000 << " mach: " << mt << " UpTime: " << t2 << endl;
665 }
666 */
667
668
669 #endif // #if defined(__PLATFORM_APPLE__) && !defined(__CHIP_MODE__)
670
671
672
673
674 //-----------------------------------------------------------------------------
675 #ifdef __ANDROID__
676 //-----------------------------------------------------------------------------
677 #include <jni.h>
678 #include <fcntl.h>
679 #include <unistd.h>
680 #include <string>
681
682 static JavaVM * jvm_instance = NULL;
683
684 JNIEXPORT jint JNICALL JNI_OnLoad( JavaVM * vm, void * reserved )
685 {
686 jvm_instance = vm;
687
688 return JNI_VERSION_1_6;
689 }
690
691 JavaVM * ChuckAndroid::getJVM()
692 {
693 return jvm_instance;
694 }
695
696 //-----------------------------------------------------------------------------
697 // name: class JNIEnvWrapper
698 // desc: Wrapper around JNIEnv. Serves three purposes:
699 // - releases JNIEnv and Java objects in RAII fashion
700 // - removes the need to get method IDs
701 // - throws JNIEnvWrapperException exception on Java exceptions
702 //-----------------------------------------------------------------------------
703 class JNIEnvWrapper
704 {
705 public:
706 JNIEnvWrapper(JavaVM * jvm);
707 ~JNIEnvWrapper();
708
709 bool IsValid() const;
710
711 jclass FindClass(const char * class_signature);
712 jobject ConstructNewObject(jclass constructed_class,
713 const char * constructor_signature, jobject param_1);
714 jobject CallObjectMethod(jobject callee, jclass callee_class,
715 const char * method_name, const char * method_signature);
716 jobject CallObjectMethod(jobject callee, jclass callee_class,
717 const char * method_name, const char * method_signature,
718 jobject param_1);
719 jobject CallStaticObjectMethod(jclass callee_class,
720 const char * method_name, const char * method_signature);
721 jobject CallStaticObjectMethod(jclass callee_class,
722 const char * method_name, const char * method_signature,
723 jobject param_1);
724 jobject CallStaticObjectMethod(jclass callee_class,
725 const char * method_name, const char * method_signature,
726 jobject param_1, jobject param_2, jobject param_3);
727 jint CallIntMethod(jobject callee, jclass callee_class,
728 const char * method_name, const char * method_signature,
729 jobject param_1);
730 void CallVoidMethod(jobject callee, jclass callee_class,
731 const char * method_name, const char * method_signature);
732
733 jstring NewStringUTF(const char * utf8_string);
734 const char * GetStringUTFChars(jstring string);
735 void ReleaseStringUTFChars(jstring string, const char * utf8_chars);
736 jbyteArray NewByteArray(size_t size);
737 jbyte * GetByteArrayElements(jbyteArray java_array);
738 void ReleaseByteArrayElements(jbyteArray java_array, jbyte * native_array);
739
740 private:
741 void ThrowOnJavaException();
742 JavaVM * m_jvm = NULL;
743 JNIEnv * m_env = NULL;
744 bool m_needs_detaching = false;
745 };
746
747 class JNIEnvWrapperException {};
748
749 JNIEnvWrapper::JNIEnvWrapper(JavaVM * jvm)
750 : m_jvm(jvm)
751 {
752 int reason = jvm->GetEnv((void **)&m_env, JNI_VERSION_1_6);
753 if( reason != JNI_OK && reason != JNI_EDETACHED )
754 {
755 m_env = NULL;
756 return;
757 }
758 if( reason == JNI_EDETACHED )
759 {
760 if( jvm->AttachCurrentThread(&m_env, NULL) != 0 )
761 {
762 m_env = NULL;
763 return;
764 }
765 m_needs_detaching = true;
766 }
767 if( m_env->PushLocalFrame(32) != 0 )
768 {
769 if( m_needs_detaching )
770 {
771 m_jvm->DetachCurrentThread();
772 }
773 m_env = NULL;
774 }
775 }
776
777 JNIEnvWrapper::~JNIEnvWrapper()
778 {
779 if( m_env == NULL )
780 {
781 return;
782 }
783 m_env->PopLocalFrame(NULL);
784 if( m_needs_detaching )
785 {
786 m_jvm->DetachCurrentThread();
787 }
788 }
789
790 bool JNIEnvWrapper::IsValid() const
791 {
792 return m_env != NULL;
793 }
794
795 void JNIEnvWrapper::ThrowOnJavaException()
796 {
797 if( m_env->ExceptionCheck() )
798 {
799 m_env->ExceptionDescribe();
800 m_env->ExceptionClear();
801 throw JNIEnvWrapperException();
802 }
803 }
804
805 jclass JNIEnvWrapper::FindClass(const char * class_signature)
806 {
807 jclass ret = m_env->FindClass(class_signature);
808 ThrowOnJavaException();
809 return ret;
810 }
811
812 jobject JNIEnvWrapper::ConstructNewObject(jclass constructed_class,
813 const char * constructor_signature, jobject param_1)
814 {
815 jmethodID method_id = m_env->GetMethodID(constructed_class,
816 "<init>", constructor_signature);
817 ThrowOnJavaException();
818 jobject ret = m_env->NewObject(constructed_class, method_id,
819 param_1);
820 ThrowOnJavaException();
821 return ret;
822 }
823
824 jobject JNIEnvWrapper::CallObjectMethod(jobject callee, jclass callee_class,
825 const char * method_name, const char * method_signature)
826 {
827 jmethodID method_id = m_env->GetMethodID(callee_class,
828 method_name, method_signature);
829 ThrowOnJavaException();
830 jobject ret = m_env->CallObjectMethod(callee, method_id);
831 ThrowOnJavaException();
832 return ret;
833 }
834
835 jobject JNIEnvWrapper::CallObjectMethod(jobject callee, jclass callee_class,
836 const char * method_name, const char * method_signature,
837 jobject param_1)
838 {
839 jmethodID method_id = m_env->GetMethodID(callee_class,
840 method_name, method_signature);
841 ThrowOnJavaException();
842 jobject ret = m_env->CallObjectMethod(callee, method_id, param_1);
843 ThrowOnJavaException();
844 return ret;
845 }
846
847 jobject JNIEnvWrapper::CallStaticObjectMethod(jclass callee_class,
848 const char * method_name, const char * method_signature)
849 {
850 jmethodID method_id = m_env->GetStaticMethodID(callee_class,
851 method_name, method_signature);
852 ThrowOnJavaException();
853 jobject ret = m_env->CallStaticObjectMethod(callee_class, method_id);
854 ThrowOnJavaException();
855
856 return ret;
857 }
858
859 jobject JNIEnvWrapper::CallStaticObjectMethod(jclass callee_class,
860 const char * method_name, const char * method_signature, jobject param_1)
861 {
862 jmethodID method_id = m_env->GetStaticMethodID(callee_class,
863 method_name, method_signature);
864 ThrowOnJavaException();
865 jobject ret = m_env->CallStaticObjectMethod(callee_class,
866 method_id, param_1);
867 ThrowOnJavaException();
868
869 return ret;
870 }
871
872 jobject JNIEnvWrapper::CallStaticObjectMethod(jclass callee_class,
873 const char * method_name, const char * method_signature, jobject param_1,
874 jobject param_2, jobject param_3)
875 {
876 jmethodID method_id = m_env->GetStaticMethodID(callee_class,
877 method_name, method_signature);
878 ThrowOnJavaException();
879 jobject ret = m_env->CallStaticObjectMethod(callee_class, method_id,
880 param_1, param_2, param_3);
881 ThrowOnJavaException();
882
883 return ret;
884 }
885
886 jint JNIEnvWrapper::CallIntMethod(jobject callee, jclass callee_class,
887 const char * method_name, const char * method_signature, jobject param_1)
888 {
889 jmethodID method_id = m_env->GetMethodID(callee_class,
890 method_name, method_signature);
891 ThrowOnJavaException();
892 jint ret = m_env->CallIntMethod(callee, method_id, param_1);
893 ThrowOnJavaException();
894 return ret;
895 }
896
897 void JNIEnvWrapper::CallVoidMethod(jobject callee, jclass callee_class,
898 const char * method_name, const char * method_signature)
899 {
900 jmethodID method_id = m_env->GetMethodID(callee_class,
901 method_name, method_signature);
902 ThrowOnJavaException();
903 m_env->CallVoidMethod(callee, method_id);
904 ThrowOnJavaException();
905 }
906
907 jstring JNIEnvWrapper::NewStringUTF(const char * utf8_string)
908 {
909 jstring ret = m_env->NewStringUTF(utf8_string);
910 ThrowOnJavaException();
911
912 return ret;
913 }
914
915 const char * JNIEnvWrapper::GetStringUTFChars(jstring string)
916 {
917 return m_env->GetStringUTFChars(string, NULL);
918 }
919
920 void JNIEnvWrapper::ReleaseStringUTFChars(jstring string, const char * utf8_chars)
921 {
922 m_env->ReleaseStringUTFChars(string, utf8_chars);
923 }
924
925 jbyteArray JNIEnvWrapper::NewByteArray(size_t size)
926 {
927 jbyteArray ret = m_env->NewByteArray(size);
928 ThrowOnJavaException();
929
930 return ret;
931 }
932
933 jbyte * JNIEnvWrapper::GetByteArrayElements(jbyteArray java_array)
934 {
935 return m_env->GetByteArrayElements(java_array, NULL);
936 }
937
938 void JNIEnvWrapper::ReleaseByteArrayElements(jbyteArray java_array,
939 jbyte * native_array)
940 {
941 m_env->ReleaseByteArrayElements(java_array, native_array, 0);
942 }
943
944 static std::string GetTemporaryFilePath(JNIEnvWrapper& jni)
945 {
946 // context = android.app.ActivityThread.currentActivityThread().getApplication()
947 jclass thread_class = jni.FindClass("android/app/ActivityThread");
948 jobject current_thread = jni.CallStaticObjectMethod(thread_class,
949 "currentActivityThread", "()Landroid/app/ActivityThread;");
950 jobject context = jni.CallObjectMethod(current_thread, thread_class,
951 "getApplication", "()Landroid/app/Application;");
952
953 // cache_dir = context.getCacheDir()
954 jclass context_class = jni.FindClass("android/content/Context");
955 jobject cache_dir = jni.CallObjectMethod(context, context_class,
956 "getCacheDir", "()Ljava/io/File;");
957
958 // temp_file = java.io.File.createTempFile("chuck_temp", "", cache_dir)
959 jclass file_class = jni.FindClass("java/io/File");
960 jobject temp_file = jni.CallStaticObjectMethod(file_class, "createTempFile",
961 "(Ljava/lang/String;Ljava/lang/String;Ljava/io/File;)Ljava/io/File;",
962 jni.NewStringUTF("chuck_temp"), jni.NewStringUTF(""), cache_dir);
963
964 // temp_file_path = temp_file.getPath()
965 jstring temp_file_path = (jstring)jni.CallObjectMethod(temp_file,
966 file_class, "getPath", "()Ljava/lang/String;");
967
968 const char * path_chars = jni.GetStringUTFChars(temp_file_path);
969 std::string ret = path_chars;
970 jni.ReleaseStringUTFChars(temp_file_path, path_chars);
971
972 return ret;
973 }
974
975 FILE * ChuckAndroid::getTemporaryFile() noexcept
976 {
977 JavaVM * jvm = getJVM();
978 if( !jvm )
979 {
980 return NULL;
981 }
982 JNIEnvWrapper jni(jvm);
983 if( !jni.IsValid() )
984 {
985 return NULL;
986 }
987
988 try
989 {
990 const std::string temp_path = GetTemporaryFilePath(jni);
991 return fopen(temp_path.c_str(), "wb+");
992 }
993 catch (JNIEnvWrapperException)
994 {
995 return NULL;
996 }
997 }
998
999 bool ChuckAndroid::copyJARURLFileToTemporary(const char * jar_url, int * fd)
1000 noexcept
1001 {
1002 JavaVM * jvm = getJVM();
1003 if( !jvm )
1004 {
1005 return false;
1006 }
1007 JNIEnvWrapper jni(jvm);
1008 if( !jni.IsValid() )
1009 {
1010 return false;
1011 }
1012
1013 int ret = 0;
1014 try
1015 {
1016 const std::string temp_path = GetTemporaryFilePath(jni);
1017 ret = open(temp_path.c_str(), O_RDWR | O_CREAT, 0600);
1018 if( ret == -1 )
1019 {
1020 return false;
1021 }
1022 // do not pollute temp directory
1023 if( unlink(temp_path.c_str()) == -1 )
1024 {
1025 return false;
1026 }
1027
1028 // url = new java.net.URL(jar_url)
1029 jclass url_class = jni.FindClass("java/net/URL");
1030 jobject url = jni.ConstructNewObject(url_class,
1031 "(Ljava/lang/String;)V", jni.NewStringUTF(jar_url));
1032
1033 // connection = url.openConnection()
1034 jobject connection = jni.CallObjectMethod(url, url_class,
1035 "openConnection", "()Ljava/net/URLConnection;");
1036
1037 // jar_file = (java.net.JarURLConnection)connection.getJarFile()
1038 jclass jar_url_connection_class = jni.FindClass(
1039 "java/net/JarURLConnection");
1040 jobject jar_file = jni.CallObjectMethod(connection,
1041 jar_url_connection_class, "getJarFile",
1042 "()Ljava/util/jar/JarFile;");
1043
1044 // jar_entry = connection.getJarEntry()
1045 jobject jar_entry = jni.CallObjectMethod(connection,
1046 jar_url_connection_class, "getJarEntry",
1047 "()Ljava/util/jar/JarEntry;");
1048
1049 // input_stream = jar_file.getInputStream(jar_entry)
1050 jclass jar_file_class = jni.FindClass("java/util/jar/JarFile");
1051 jobject input_stream = jni.CallObjectMethod(jar_file, jar_file_class,
1052 "getInputStream", "(Ljava/util/zip/ZipEntry;)Ljava/io/InputStream;",
1053 jar_entry);
1054
1055 // buffer = new byte[8 * 1024]
1056 jbyteArray java_buffer = jni.NewByteArray(8 * 1024);
1057 // s = input_stream.read(buffer)
1058 jclass input_stream_class = jni.FindClass("java/io/InputStream");
1059 jint s = 0;
1060 while( true )
1061 {
1062 s = jni.CallIntMethod(input_stream, input_stream_class, "read",
1063 "([B)I", java_buffer);
1064 if( s < 0 )
1065 {
1066 break;
1067 }
1068 jbyte * native_buffer = jni.GetByteArrayElements(java_buffer);
1069 size_t written = 0;
1070 while( written < s )
1071 {
1072 ssize_t written_now = write(ret, native_buffer + written,
1073 s - written);
1074 if( written_now < 0 )
1075 {
1076 close(ret);
1077 return false;
1078 }
1079 written += written_now;
1080 }
1081 jni.ReleaseByteArrayElements(java_buffer, native_buffer);
1082 }
1083
1084 // jar_file.close()
1085 jni.CallVoidMethod(jar_file, jar_file_class, "close", "()V");
1086 }
1087 catch (JNIEnvWrapperException)
1088 {
1089 if( ret != -1 )
1090 {
1091 close(ret);
1092 }
1093 return false;
1094 }
1095
1096 lseek(ret, 0, SEEK_SET);
1097 *fd = ret;
1098 return true;
1099 }
1100
1101
1102
1103
1104 #endif // __ANDROID__