bump product version to 5.0.4.1
[LibreOffice.git] / sal / android / lo-bootstrap.c
blob5c47b8f6bd2f222ce8c5d5345b6d306145f9b9fe
1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #include <errno.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/stat.h>
15 #include <sys/time.h>
16 #include <time.h>
18 #include <dlfcn.h>
19 #include <fcntl.h>
20 #include <pthread.h>
21 #include <sys/mman.h>
22 #include <unistd.h>
24 #include <jni.h>
25 #include <zlib.h>
27 #include <android/log.h>
29 #include "uthash.h"
31 #include <osl/detail/android-bootstrap.h>
33 #undef LOGI
35 #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "lo-bootstrap", __VA_ARGS__))
36 #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "lo-bootstrap", __VA_ARGS__))
38 #define MAX(a,b) ((a) > (b) ? (a) : (b))
40 struct engine {
41 int dummy;
44 /* These are valid / used in all apps. */
45 const char *data_dir;
46 const char *cache_dir;
47 void *apk_file;
48 int apk_file_size;
49 JavaVM *the_java_vm;
51 /* Zip data structures */
53 /* compression methods */
54 #define STORE 0
56 struct local_file_header {
57 uint32_t signature;
58 uint16_t min_version;
59 uint16_t general_flag;
60 uint16_t compression;
61 uint16_t lastmod_time;
62 uint16_t lastmod_date;
63 uint32_t crc32;
64 uint32_t compressed_size;
65 uint32_t uncompressed_size;
66 uint16_t filename_size;
67 uint16_t extra_field_size;
68 char data[0];
69 } __attribute__((__packed__));
71 struct cdir_entry {
72 uint32_t signature;
73 uint16_t creator_version;
74 uint16_t min_version;
75 uint16_t general_flag;
76 uint16_t compression;
77 uint16_t lastmod_time;
78 uint16_t lastmod_date;
79 uint32_t crc32;
80 uint32_t compressed_size;
81 uint32_t uncompressed_size;
82 uint16_t filename_size;
83 uint16_t extra_field_size;
84 uint16_t file_comment_size;
85 uint16_t disk_num;
86 uint16_t internal_attr;
87 uint32_t external_attr;
88 uint32_t offset;
89 char data[0];
90 } __attribute__((__packed__));
92 #define CDIR_END_SIG 0x06054b50
94 struct cdir_end {
95 uint32_t signature;
96 uint16_t disk_num;
97 uint16_t cdir_disk;
98 uint16_t disk_entries;
99 uint16_t cdir_entries;
100 uint32_t cdir_size;
101 uint32_t cdir_offset;
102 uint16_t comment_size;
103 char comment[0];
104 } __attribute__((__packed__));
106 /* End of Zip data structures */
108 static struct cdir_entry *cdir_start;
109 static uint16_t cdir_entries;
111 /* Data structure to turn Zip's list in arbitrary order of
112 * hierarchical pathnames (not necessarily including entries for
113 * directories) into an actual hierarchical directory tree, so that we
114 * can iterate over directory entries properly in the dirent style
115 * functions.
118 typedef struct direntry *direntry;
120 struct direntry {
121 UT_hash_handle hh;
122 enum { REGULAR, DIRECTORY } kind;
123 int ino;
124 union {
125 struct cdir_entry *file;
126 direntry subdir;
130 struct lo_apk_dir {
131 direntry cur;
134 static direntry assets = NULL;
136 static uint32_t
137 cdir_entry_size(struct cdir_entry *entry)
139 return sizeof(*entry) +
140 letoh16(entry->filename_size) +
141 letoh16(entry->extra_field_size) +
142 letoh16(entry->file_comment_size);
146 setup_cdir(void)
148 struct cdir_end *dirend = (struct cdir_end *)((char *) apk_file + apk_file_size - sizeof(*dirend));
149 uint32_t cdir_offset;
151 while ((void *)dirend > apk_file &&
152 letoh32(dirend->signature) != CDIR_END_SIG)
153 dirend = (struct cdir_end *)((char *)dirend - 1);
154 if (letoh32(dirend->signature) != CDIR_END_SIG) {
155 LOGE("setup_cdir: Could not find end of central directory record");
156 return 0;
159 cdir_offset = letoh32(dirend->cdir_offset);
161 cdir_entries = letoh16(dirend->cdir_entries);
162 cdir_start = (struct cdir_entry *)((char *)apk_file + cdir_offset);
164 return 1;
167 static struct cdir_entry *
168 find_cdir_entry(struct cdir_entry *entry, int count, const char *name)
170 size_t name_size = strlen(name);
171 while (count--) {
172 if (letoh16(entry->filename_size) == name_size &&
173 !memcmp(entry->data, name, name_size))
174 return entry;
175 entry = (struct cdir_entry *)((char *)entry + cdir_entry_size(entry));
177 return NULL;
180 static void
181 handle_one_asset(struct cdir_entry *entry)
183 /* In the .apk there are no initial slashes */
184 const char *p = entry->data + sizeof("assets/")-1;
185 const char *z = entry->data + entry->filename_size;
186 direntry *dir = &assets;
187 static int ino = 1;
189 while (p < z) {
190 const char *q = p;
191 direntry old, new;
193 while (q < z && *q != '/')
194 q++;
195 HASH_FIND(hh, *dir, p, (unsigned)(q - p), old);
196 if (*q == '/') {
197 if (old == NULL) {
198 new = malloc(sizeof(*new));
199 new->ino = ino++;
200 new->kind = DIRECTORY;
201 new->subdir = NULL;
202 HASH_ADD_KEYPTR(hh, *dir, p, (unsigned)(q - p), new);
203 dir = &new->subdir;
204 } else {
205 dir = &old->subdir;
207 p = q + 1;
208 } else {
209 if (old == NULL) {
210 new = malloc(sizeof(*new));
211 new->ino = ino++;
212 new->kind = REGULAR;
213 new->file = entry;
214 HASH_ADD_KEYPTR(hh, *dir, p, (unsigned)(q - p), new);
215 } else {
216 LOGE("duplicate entry in apk: %.*s", entry->filename_size, entry->data);
218 p = q;
220 (void) dir;
225 setup_assets_tree(void)
227 int count = cdir_entries;
228 struct cdir_entry *entry = cdir_start;
230 while (count--) {
231 if (letoh16(entry->filename_size) >= sizeof("assets/")-1 &&
232 memcmp(entry->data, "assets/", sizeof("assets/")-1) == 0)
233 handle_one_asset(entry);
234 entry = (struct cdir_entry *)((char *)entry + cdir_entry_size(entry));
236 return 1;
239 /* The lo-native-code shared library is always loaded from Java, so this is
240 * always called by JNI first.
242 __attribute__ ((visibility("default")))
243 jint
244 JNI_OnLoad(JavaVM* vm, void* reserved)
246 (void) reserved;
248 the_java_vm = vm;
250 return JNI_VERSION_1_6;
253 // public static native boolean setup(String dataDir,
254 // String cacheDir,
255 // String apkFile)
257 __attribute__ ((visibility("default")))
258 jboolean
259 Java_org_libreoffice_android_Bootstrap_setup__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2
260 (JNIEnv* env,
261 jobject clazz,
262 jstring dataDir,
263 jstring cacheDir,
264 jstring apkFile)
266 struct stat st;
267 int fd;
268 const char *dataDirPath;
269 const char *cacheDirPath;
270 const char *apkFilePath;
272 (void) clazz;
274 dataDirPath = (*env)->GetStringUTFChars(env, dataDir, NULL);
275 data_dir = strdup(dataDirPath);
276 (*env)->ReleaseStringUTFChars(env, dataDir, dataDirPath);
278 cacheDirPath = (*env)->GetStringUTFChars(env, cacheDir, NULL);
279 cache_dir = strdup(cacheDirPath);
280 (*env)->ReleaseStringUTFChars(env, cacheDir, cacheDirPath);
282 apkFilePath = (*env)->GetStringUTFChars(env, apkFile, NULL);
284 fd = open(apkFilePath, O_RDONLY);
285 if (fd == -1) {
286 LOGE("Could not open %s", apkFilePath);
287 (*env)->ReleaseStringUTFChars(env, apkFile, apkFilePath);
288 return JNI_FALSE;
290 if (fstat(fd, &st) == -1) {
291 LOGE("Could not fstat %s", apkFilePath);
292 close(fd);
293 (*env)->ReleaseStringUTFChars(env, apkFile, apkFilePath);
294 return JNI_FALSE;
296 apk_file = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
297 close(fd);
299 if (apk_file == MAP_FAILED) {
300 LOGE("Could not mmap %s", apkFilePath);
301 (*env)->ReleaseStringUTFChars(env, apkFile, apkFilePath);
302 return JNI_FALSE;
304 apk_file_size = st.st_size;
306 (*env)->ReleaseStringUTFChars(env, apkFile, apkFilePath);
308 if (!setup_cdir())
309 return JNI_FALSE;
311 if (!setup_assets_tree())
312 return JNI_FALSE;
314 // Extract files from the .apk that can't be used mmapped directly from it
315 extract_files(UNPACK_TREE, UNPACK_TREE, 0);
316 extract_files(UNPACK_TREE_GZ, UNPACK_TREE_GZ, 1);
318 return JNI_TRUE;
321 static jboolean
322 get_jni_string_array(JNIEnv *env,
323 const char *function_and_parameter_name,
324 jobject strv,
325 int *argc,
326 const char ***argv)
328 jclass StringArray;
329 int i;
331 StringArray = (*env)->FindClass(env, "[Ljava/lang/String;");
332 if (StringArray == NULL) {
333 LOGE("Could not find String[] class");
334 return JNI_FALSE;
337 if (!(*env)->IsInstanceOf(env, strv, StringArray)) {
338 LOGE("%s is not a String[]?", function_and_parameter_name);
339 return JNI_FALSE;
342 *argc = (*env)->GetArrayLength(env, strv);
343 *argv = malloc(sizeof(char *) * (*argc+1));
345 for (i = 0; i < *argc; i++) {
346 const char *s = (*env)->GetStringUTFChars(env, (*env)->GetObjectArrayElement(env, strv, i), NULL);
347 (*argv)[i] = strdup(s);
348 (*env)->ReleaseStringUTFChars(env, (*env)->GetObjectArrayElement(env, strv, i), s);
350 (*argv)[*argc] = NULL;
352 return JNI_TRUE;
355 // public static native int getpid();
357 __attribute__ ((visibility("default")))
358 jint
359 Java_org_libreoffice_android_Bootstrap_getpid(JNIEnv* env,
360 jobject clazz)
362 (void) env;
363 (void) clazz;
365 return getpid();
368 // public static native void system(String cmdline);
370 __attribute__ ((visibility("default")))
371 void
372 Java_org_libreoffice_android_Bootstrap_system(JNIEnv* env,
373 jobject clazz,
374 jstring cmdline)
376 const char *s;
378 (void) clazz;
380 s = (*env)->GetStringUTFChars(env, cmdline, NULL);
382 LOGI("system(%s)", s);
384 system(s);
386 (*env)->ReleaseStringUTFChars(env, cmdline, s);
389 // public static native void putenv(String string);
391 __attribute__ ((visibility("default")))
392 void
393 Java_org_libreoffice_android_Bootstrap_putenv(JNIEnv* env,
394 jobject clazz,
395 jstring string)
397 const char *s;
398 char *s_copy;
400 (void) clazz;
402 s = (*env)->GetStringUTFChars(env, string, NULL);
403 s_copy = strdup(s);
405 LOGI("putenv(%s)", s_copy);
407 putenv(s_copy);
409 #if 0
411 static int beenhere=0;
412 if (!beenhere) {
413 LOGI("lo-bootstrap: Sleeping for 20 seconds, start ndk-gdb NOW if that is your intention");
414 sleep(20);
415 beenhere = 1;
418 #endif
420 (*env)->ReleaseStringUTFChars(env, string, s);
423 __attribute__ ((visibility("default")))
424 void *
425 lo_apkentry(const char *filename,
426 size_t *size)
428 struct cdir_entry *entry;
429 struct local_file_header *file;
430 void *data;
432 if (*filename == '/')
433 filename++;
435 entry = find_cdir_entry(cdir_start, cdir_entries, filename);
437 if (entry == NULL) {
438 LOGE("lo_apkentry: Could not find %s", filename);
439 return NULL;
441 file = (struct local_file_header *)((char *)apk_file + letoh32(entry->offset));
443 if (letoh16(file->compression) != STORE) {
444 LOGE("lo_apkentry: File %s is compressed", filename);
445 return NULL;
448 data = ((char *)&file->data) + letoh16(file->filename_size) + letoh16(file->extra_field_size);
449 *size = file->uncompressed_size;
451 /* LOGI("lo_apkentry(%s): %p, %d", filename, data, *size); */
453 return data;
456 __attribute__ ((visibility("default")))
457 lo_apk_dir *
458 lo_apk_opendir(const char *dirname)
460 /* In the .apk there are no initial slashes, but the parameter passed to
461 * us does have it.
463 const char *p = dirname + sizeof("/assets/")-1;
464 direntry dir = assets;
466 if (!*p) {
467 lo_apk_dir *result = malloc(sizeof(*result));
468 result->cur = assets;
469 return result;
472 while (1) {
473 const char *q = p;
474 direntry entry;
476 while (*q && *q != '/')
477 q++;
479 HASH_FIND(hh, dir, p, (unsigned)(q - p), entry);
481 if (entry == NULL && *q == '/') {
482 errno = ENOENT;
483 return NULL;
484 } else if (entry == NULL) {
485 /* Empty directories, or directories containing only "hidden"
486 * files (like the .gitignore in sc/qa/unit/qpro/indeterminate)
487 * are not present in the .apk. So we need to pretend that any
488 * directory that doesn't exist as a parent of an entry in the
489 * .apk *does* exist but is empty.
491 lo_apk_dir *result = malloc(sizeof(*result));
492 result->cur = NULL;
493 return result;
496 if (entry->kind != DIRECTORY) {
497 errno = ENOTDIR;
498 return NULL;
501 if (!q[0] || !q[1]) {
502 lo_apk_dir *result = malloc(sizeof(*result));
503 result->cur = entry->subdir;
504 return result;
507 dir = entry->subdir;
508 p = q + 1;
512 __attribute__ ((visibility("default")))
513 struct dirent *
514 lo_apk_readdir(lo_apk_dir *dirp)
516 static struct dirent result;
518 if (dirp->cur == NULL) {
519 /* LOGI("lo_apk_readdir(%p) = NULL", dirp); */
520 return NULL;
523 result.d_ino = dirp->cur->ino;
524 result.d_off = 0;
525 result.d_reclen = 0;
527 if (dirp->cur->kind == DIRECTORY)
528 result.d_type = DT_DIR;
529 else
530 result.d_type = DT_REG;
532 memcpy(result.d_name, dirp->cur->hh.key, dirp->cur->hh.keylen);
533 result.d_name[dirp->cur->hh.keylen] = '\0';
535 dirp->cur = dirp->cur->hh.next;
537 /* LOGI("lo_apk_readdir(%p) = %s:%s", dirp, result.d_type == DT_DIR ? "DIR" : "REG", result.d_name); */
539 return &result;
542 __attribute__ ((visibility("default")))
544 lo_apk_closedir(lo_apk_dir *dirp)
546 free(dirp);
548 /* LOGI("lo_apk_closedir(%p)", dirp); */
550 return 0;
553 static int
554 new_stat(const char *path,
555 struct stat *statp,
556 struct cdir_entry *entry,
557 int mode,
558 int fake_ino)
560 struct tm tm;
562 memset(statp, 0, sizeof(*statp));
563 statp->st_mode = mode | S_IRUSR;
564 statp->st_nlink = 1;
566 statp->st_uid = getuid();
567 statp->st_gid = getgid();
569 if (entry != NULL)
570 statp->st_size = entry->uncompressed_size;
571 else
572 statp->st_size = 0;
573 statp->st_blksize = 512;
574 if (statp->st_size == 0)
575 statp->st_blocks = 0;
576 else
577 statp->st_blocks = (statp->st_size - 1) / statp->st_blksize + 1;
579 statp->st_atime = time(NULL);
581 memset(&tm, 0, sizeof(tm));
582 tm.tm_sec = (letoh16(entry->lastmod_time) & 0x1F) * 2;
583 tm.tm_min = (letoh16(entry->lastmod_time) >> 5) & 0x3F;
584 tm.tm_hour = (letoh16(entry->lastmod_time) >> 11) & 0x1F;
585 tm.tm_mday = letoh16(entry->lastmod_date) & 0x1F;
586 tm.tm_mon = ((letoh16(entry->lastmod_date) >> 5) & 0x0F) - 1;
587 tm.tm_year = ((letoh16(entry->lastmod_date) >> 9) & 0x7F) + 80;
589 statp->st_mtime = mktime(&tm);
590 statp->st_ctime = statp->st_mtime;
592 statp->st_ino = fake_ino;
594 (void) path;
595 /* LOGI("lo_apk_lstat(%s) = { mode=%o, size=%lld, ino=%lld mtime=%.24s }",
596 path, statp->st_mode, statp->st_size, statp->st_ino,
597 ctime((const time_t *) &statp->st_mtime)); */
599 return 0;
602 __attribute__ ((visibility("default")))
604 lo_apk_lstat(const char *path,
605 struct stat *statp)
607 const char *pn = path;
608 int count = cdir_entries;
609 struct cdir_entry *entry = cdir_start;
610 size_t name_size;
612 if (*pn == '/') {
613 pn++;
614 if (!pn[0])
615 return new_stat(path, statp, NULL, S_IFDIR | S_IXUSR, 1);
618 name_size = strlen(pn);
619 while (count--)
621 if (letoh16(entry->filename_size) >= name_size &&
622 !memcmp(entry->data, pn, name_size) &&
623 (letoh16(entry->filename_size) == name_size || entry->data[name_size] == '/'))
624 break;
625 entry = (struct cdir_entry *)((char *)entry + cdir_entry_size(entry));
627 if (count >= 0) {
628 if (letoh16(entry->filename_size) == name_size)
629 return new_stat(path, statp, entry, S_IFREG, cdir_entries - count + 1);
630 else
631 return new_stat(path, statp, entry, S_IFDIR | S_IXUSR, cdir_entries - count + 1);
634 errno = ENOENT;
635 return -1;
638 static int
639 mkdir_p(const char *dirname)
641 char *p = malloc(strlen(dirname) + 1);
642 const char *q = dirname + 1;
643 const char *slash;
645 do {
646 slash = strchr(q, '/');
647 if (slash == NULL)
648 slash = q + strlen(q);
649 memcpy(p, dirname, slash-dirname);
650 p[slash-dirname] = '\0';
651 if (mkdir(p, 0700) == -1 && errno != EEXIST) {
652 LOGE("mkdir_p: Could not create %s: %s", p, strerror(errno));
653 free(p);
654 return 0;
656 if (*slash)
657 q = slash + 1;
658 } while (*slash);
660 free(p);
661 return 1;
664 static int
665 extract_gzipped(const char *filename,
666 const char *apkentry,
667 int size,
668 FILE *f)
670 gzFile gzfd;
671 int gzerrno;
672 int nbytes;
673 char buf[5000];
674 int total = 0;
675 char *tmpname;
676 FILE *tmp;
678 tmpname = malloc(strlen(cache_dir) + strlen("/tmp.gz") + 1);
679 strcpy(tmpname, cache_dir);
680 strcat(tmpname, "/tmp.gz");
682 tmp = fopen(tmpname, "w+");
683 unlink(tmpname);
685 if (tmp == NULL) {
686 LOGE("extract_gzipped: could not create %s: %s", tmpname, strerror(errno));
687 free(tmpname);
688 return 0;
691 if (fwrite(apkentry, size, 1, tmp) != 1) {
692 LOGE("extract_gzipped: could not write gzipped entry to %s: %s", tmpname, strerror(errno));
693 fclose(tmp);
694 free(tmpname);
695 return 0;
698 free(tmpname);
699 rewind(tmp);
701 gzfd = gzdopen(fileno(tmp), "rb");
702 if (gzfd == NULL) {
703 LOGE("extract_gzipped: gzdopen failed");
704 fclose(tmp);
705 return 0;
708 while ((nbytes = gzread(gzfd, buf, sizeof(buf))) > 0) {
709 fwrite(buf, nbytes, 1, f);
710 total += nbytes;
712 if (nbytes == -1) {
713 LOGE("extract_gzipped: Could not gzread from %s: %s", filename, gzerror(gzfd, &gzerrno));
714 return total;
716 if (gzclose(gzfd) == -1) {
717 LOGE("extract_gzipped: gzclose failed");
718 return total;
721 return total;
724 void
725 extract_files(const char *root,
726 const char *prefix,
727 int gzipped)
729 lo_apk_dir *tree = lo_apk_opendir(prefix);
730 struct dirent *dent;
732 if (tree == NULL)
733 return;
735 while ((dent = lo_apk_readdir(tree)) != NULL) {
736 if (strcmp(dent->d_name, ".") == 0 ||
737 strcmp(dent->d_name, "..") == 0)
738 continue;
740 if (dent->d_type == DT_DIR) {
741 char *subdir = malloc(strlen(prefix) + 1 + strlen(dent->d_name) + 1);
742 strcpy(subdir, prefix);
743 strcat(subdir, "/");
744 strcat(subdir, dent->d_name);
745 extract_files(root, subdir, gzipped);
746 free(subdir);
747 } else {
748 char *filename;
749 char *newfilename;
750 const char *apkentry;
751 size_t size;
752 struct stat st;
753 FILE *f;
755 filename = malloc(strlen(prefix) + 1 + strlen(dent->d_name) + 1);
756 strcpy(filename, prefix);
757 strcat(filename, "/");
758 strcat(filename, dent->d_name);
760 apkentry = lo_apkentry(filename, &size);
761 if (apkentry == NULL) {
762 LOGE("extract_files: Could not find %s in .apk", filename);
763 free(filename);
764 continue;
767 newfilename = malloc(strlen(data_dir) + 1 + strlen(prefix) - strlen(root) + strlen(dent->d_name) + 1);
768 strcpy(newfilename, data_dir);
769 strcat(newfilename, "/");
770 strcat(newfilename, prefix + strlen(root) + 1);
772 if (!mkdir_p(newfilename)) {
773 free(filename);
774 free(newfilename);
775 continue;
778 strcat(newfilename, "/");
779 strcat(newfilename, dent->d_name);
781 if (stat(newfilename, &st) == 0 &&
782 (gzipped || st.st_size == (long long) size)) {
783 free(filename);
784 free(newfilename);
785 continue;
788 f = fopen(newfilename, "w");
789 if (f == NULL) {
790 LOGE("extract_files: Could not open %s for writing: %s", newfilename, strerror(errno));
791 free(filename);
792 free(newfilename);
793 continue;
796 if (!gzipped) {
797 if (fwrite(apkentry, size, 1, f) != 1) {
798 LOGE("extract_files: Could not write %lld bytes to %s: %s", (long long) size, newfilename, strerror(errno));
799 } else {
800 LOGI("extract_files: Copied %s to %s: %lld bytes", filename, newfilename, (long long) size);
802 } else {
803 size = extract_gzipped(filename, apkentry, size, f);
804 LOGI("extract_files: Decompressed %s to %s: %lld bytes", filename, newfilename, (long long) size);
807 fclose(f);
809 free(filename);
810 free(newfilename);
813 lo_apk_closedir(tree);
816 /* Android's JNI works only to libraries loaded through Java's
817 * System.loadLibrary(), it seems. But now with just one big app-specific .so
818 * on Android, that would not be a problem, but for historical reasons, we
819 * have JNI wrappers here, and then call the VCL etc function from them. Oh
820 * well, one could say it's clean to have all the Android-specific JNI
821 * functions here in this file.
824 extern void osl_setCommandArgs(int, char **);
826 __attribute__ ((visibility("default")))
827 void
828 Java_org_libreoffice_android_Bootstrap_setCommandArgs(JNIEnv* env,
829 jobject clazz,
830 jobject argv)
832 char **c_argv;
833 int c_argc;
834 Dl_info lo_bootstrap_info;
836 (void) clazz;
838 if (!get_jni_string_array(env, "setCommandArgs :argv", argv, &c_argc, (const char ***) &c_argv))
839 return;
841 if (dladdr(Java_org_libreoffice_android_Bootstrap_setCommandArgs, &lo_bootstrap_info) != 0) {
842 char *new_argv0 = malloc(strlen(lo_bootstrap_info.dli_fname) + strlen(c_argv[0]));
843 char *slash;
844 strcpy(new_argv0, lo_bootstrap_info.dli_fname);
845 slash = strrchr(new_argv0, '/');
846 if (slash != NULL)
847 *slash = '\0';
848 slash = strrchr(new_argv0, '/');
849 if (slash != NULL)
850 strcpy(slash+1, c_argv[0]);
851 else
852 strcpy(new_argv0, c_argv[0]);
853 free(c_argv[0]);
854 c_argv[0] = new_argv0;
857 osl_setCommandArgs(c_argc, c_argv);
860 /* Code for reading lines from the pipe based on the (Apache-licensed) Android
861 * logwrapper.c
864 static int
865 read_from(int fd, const char *tag, char *buffer, int *sz, int *a, int *b, size_t sizeof_buffer)
867 int nread;
869 nread = read(fd, buffer+*b, sizeof_buffer - 1 - *b);
870 *sz = nread;
872 if (nread == -1) {
873 LOGE("redirect_thread: Reading from %d failed: %s", fd, strerror(errno));
874 close(fd);
875 return -1;
878 if (nread == 0) {
879 LOGI("redirect_thread: EOF from fd %d", fd);
880 close(fd);
881 return 0;
884 *sz += *b;
886 for (*b = 0; *b < *sz; (*b)++) {
887 if (buffer[*b] == '\n') {
888 buffer[*b] = '\0';
889 __android_log_print(ANDROID_LOG_INFO, tag, "%s", &buffer[*a]);
890 *a = *b + 1;
894 if (*a == 0 && *b == (int) sizeof_buffer - 1) {
895 // buffer is full, flush
896 buffer[*b] = '\0';
897 __android_log_print(ANDROID_LOG_INFO, tag, "%s", &buffer[*a]);
898 *b = 0;
899 } else if (*a != *b) {
900 // Keep left-overs
901 *b -= *a;
902 memmove(buffer, &buffer[*a], *b);
903 *a = 0;
904 } else {
905 *a = 0;
906 *b = 0;
909 return nread;
912 static int stdout_pipe[2], stderr_pipe[2];
914 static void *
915 redirect_thread(void *arg)
917 char buffer[2][4096];
918 int a[2] = { 0, 0 };
919 int b[2] = { 0, 0 };
920 int sz[2];
922 (void) arg;
924 while (1) {
925 fd_set readfds;
926 int nfds = 0;
928 FD_ZERO(&readfds);
929 if (stdout_pipe[0] != -1) {
930 FD_SET(stdout_pipe[0], &readfds);
931 nfds = MAX(nfds, stdout_pipe[0] + 1);
933 if (stderr_pipe[0] != -1) {
934 FD_SET(stderr_pipe[0], &readfds);
935 nfds = MAX(nfds, stderr_pipe[0] + 1);
937 if (nfds == 0) {
938 LOGI("redirect_thread: Nothing to read any more, thread exiting");
939 return NULL;
942 if (select(nfds, &readfds, NULL, NULL, NULL) == -1) {
943 LOGE("redirect_thread: select failed: %s, thread exiting", strerror(errno));
944 close(stdout_pipe[0]);
945 stdout_pipe[0] = -1;
946 close(stderr_pipe[0]);
947 stderr_pipe[0] = -1;
948 return NULL;
951 if (stdout_pipe[0] != -1 &&
952 FD_ISSET(stdout_pipe[0], &readfds)) {
953 if (read_from(stdout_pipe[0], "stdout", buffer[0], &sz[0], &a[0], &b[0], sizeof(buffer[0])) <= 0) {
954 stdout_pipe[0] = -1;
958 if (stderr_pipe[0] != -1 &&
959 FD_ISSET(stderr_pipe[0], &readfds)) {
960 if (read_from(stderr_pipe[0], "stderr", buffer[1], &sz[1], &a[1], &b[1], sizeof(buffer[1])) <= 0) {
961 stderr_pipe[0] = -1;
967 static int
968 redirect_to_null(void)
970 int null = open("/dev/null", O_WRONLY);
971 if (null == -1) {
972 LOGE("redirect_stdio: Could not open /dev/null: %s", strerror(errno));
973 /* If we can't redirect stdout or stderr to /dev/null, just close them
974 * then instead. Huh?
976 close(1);
977 close(2);
978 return 0;
980 if (dup2(null, 1) == -1) {
981 LOGE("redirect_stdio: Could not dup2 %d to 1: %s", null, strerror(errno));
982 close(null);
983 close(1);
984 close(2);
985 return 0;
987 if (dup2(null, 2) == -1) {
988 LOGE("redirect_stdio: Could not dup2 %d to 2: %s", null, strerror(errno));
989 close(null);
990 close(1);
991 close(2);
992 return 0;
994 close(null);
995 return 1;
998 __attribute__ ((visibility("default")))
999 void
1000 Java_org_libreoffice_android_Bootstrap_redirect_1stdio(JNIEnv* env,
1001 jobject clazz,
1002 jboolean state)
1004 static jboolean current = JNI_FALSE;
1005 pthread_t thread;
1006 pthread_attr_t attr;
1008 (void) env;
1009 (void) clazz;
1011 if (state == current)
1012 return;
1014 if (state == JNI_FALSE) {
1015 if (!redirect_to_null())
1016 return;
1017 } else {
1018 if (pipe(stdout_pipe) == -1) {
1019 LOGE("redirect_stdio: Could not create pipes: %s", strerror(errno));
1020 return;
1022 if (pipe(stderr_pipe) == -1) {
1023 LOGE("redirect_stdio: Could not create pipes: %s", strerror(errno));
1024 close(stdout_pipe[0]);
1025 close(stdout_pipe[1]);
1026 return;
1028 LOGI("redirect_stdio: stdout pipe: [%d,%d], stderr pipe: [%d,%d]",
1029 stdout_pipe[0], stdout_pipe[1], stderr_pipe[0], stderr_pipe[1]);
1031 if (dup2(stdout_pipe[1], 1) == -1) {
1032 LOGE("redirect_stdio: Could not dup2 %d to 1: %s", stdout_pipe[1], strerror(errno));
1033 close(stdout_pipe[0]);
1034 close(stdout_pipe[1]);
1035 close(stderr_pipe[0]);
1036 close(stderr_pipe[1]);
1037 return;
1040 if (dup2(stderr_pipe[1], 2) == -1) {
1041 LOGE("redirect_stdio: Could not dup2 %d to 2: %s", stdout_pipe[1], strerror(errno));
1042 /* stdout has already been redirected to its pipe, so redirect
1043 * it back to /dev/null
1045 redirect_to_null();
1046 close(stdout_pipe[0]);
1047 close(stdout_pipe[1]);
1048 close(stderr_pipe[0]);
1049 close(stderr_pipe[1]);
1050 return;
1052 close(stdout_pipe[1]);
1053 close(stderr_pipe[1]);
1055 if (pthread_attr_init(&attr) != 0 ||
1056 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0 ||
1057 pthread_create(&thread, &attr, redirect_thread, NULL) != 0) {
1058 LOGE("redirect_stdio: Could not create thread: %s", strerror(errno));
1059 redirect_to_null();
1060 close(stdout_pipe[0]);
1061 close(stderr_pipe[0]);
1062 return;
1065 current = state;
1066 return;
1069 __attribute__ ((visibility("default")))
1070 jlong
1071 Java_org_libreoffice_android_Bootstrap_address_1of_1direct_1byte_1buffer(JNIEnv *env,
1072 jobject bbuffer)
1074 return (jlong) (intptr_t) (*env)->GetDirectBufferAddress(env, bbuffer);
1077 __attribute__ ((visibility("default")))
1078 JavaVM *
1079 lo_get_javavm(void)
1081 return the_java_vm;
1084 __attribute__ ((visibility("default")))
1085 const char *
1086 lo_get_app_data_dir(void)
1088 return data_dir;
1091 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */