/* * Copyright (C) 2007, 2008 The Android Open Source Project * Copyright (C) 2012 Steven Luo * Copyright (C) 2026 SlopRoot Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Derived from jackpal/Android-Terminal-Emulator * (commit 35188f8a8b57989a4a4ec9485e11187b46be26d9): * - libtermexec/src/main/jni/process.cpp * - term/src/main/jni/termExec.cpp * Consolidated into a single pure-C JNI library for Android 2.2 (API 8) * through Android 6.0 (API 23) with no C++ runtime dependency. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef IUTF8 #define IUTF8 0040000 #endif static void throw_exception(JNIEnv *env, const char *class_name, const char *message) { jclass ex_class = (*env)->FindClass(env, class_name); if (ex_class != NULL) { (*env)->ThrowNew(env, ex_class, message != NULL ? message : ""); } } static void throw_io_exception(JNIEnv *env, int errnum, const char *fallback_msg) { const char *msg = fallback_msg; if (errnum != 0) { const char *s = strerror(errnum); if (s != NULL && strcmp(s, "Unknown error") != 0) { msg = s; } } throw_exception(env, "java/io/IOException", msg); } static char *dup_jstring_utf8(JNIEnv *env, jstring jstr) { if (jstr == NULL) { return NULL; } const char *utf = (*env)->GetStringUTFChars(env, jstr, NULL); if (utf == NULL) { return NULL; } char *copy = strdup(utf); (*env)->ReleaseStringUTFChars(env, jstr, utf); if (copy == NULL) { throw_exception(env, "java/lang/OutOfMemoryError", "Out of memory duplicating string"); } return copy; } static void free_string_array(char **arr) { if (arr == NULL) { return; } for (char **p = arr; *p != NULL; ++p) { free(*p); } free(arr); } static char **extract_string_array(JNIEnv *env, jobjectArray jarr) { if (jarr == NULL) { return NULL; } jsize size = (*env)->GetArrayLength(env, jarr); if (size <= 0) { return NULL; } char **out = (char **)calloc((size_t)size + 1, sizeof(char *)); if (out == NULL) { throw_exception(env, "java/lang/OutOfMemoryError", "Out of memory allocating string array"); return NULL; } for (jsize i = 0; i < size; ++i) { jstring elem = (jstring)(*env)->GetObjectArrayElement(env, jarr, i); if (elem == NULL) { free_string_array(out); throw_exception(env, "java/lang/NullPointerException", "Null entry in string array"); return NULL; } char *copy = dup_jstring_utf8(env, elem); (*env)->DeleteLocalRef(env, elem); if (copy == NULL) { free_string_array(out); return NULL; } out[i] = copy; } out[size] = NULL; return out; } static int parse_fd_number(const char *s) { if (s == NULL || *s < '0' || *s > '9') { return -1; } int val = 0; while (*s >= '0' && *s <= '9') { if (val > 100000) { return -1; } val = val * 10 + (*s - '0'); s++; } return val; } static void reset_child_signals(void) { sigset_t empty_mask; memset(&empty_mask, 0, sizeof(empty_mask)); sigprocmask(SIG_SETMASK, &empty_mask, NULL); static const int reset_sigs[] = { SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGTERM, SIGCHLD, SIGTSTP, SIGTTIN, SIGTTOU }; struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_DFL; for (size_t i = 0; i < sizeof(reset_sigs) / sizeof(reset_sigs[0]); ++i) { sigaction(reset_sigs[i], &sa, NULL); } } static int create_subprocess(JNIEnv *env, const char *cmd, char *const argv[], char *const envp[], int master_fd) { char devname[64]; int unlock = 0; unsigned int ptn = 0; if (master_fd < 0) { throw_io_exception(env, EBADF, "Invalid PTY master descriptor"); return -1; } fcntl(master_fd, F_SETFD, FD_CLOEXEC); /* Unlock slave PTY and resolve /dev/pts/ directly via Linux devpts ioctls. * Avoids early-Bionic ptsname_r return-value quirks while staying compatible * with Android 2.2 (API 8) through modern kernels. */ if (ioctl(master_fd, TIOCSPTLCK, &unlock) != 0) { throw_io_exception(env, errno, "TIOCSPTLCK failed on /dev/ptmx"); return -1; } if (ioctl(master_fd, TIOCGPTN, &ptn) != 0) { throw_io_exception(env, errno, "TIOCGPTN failed on /dev/ptmx"); return -1; } snprintf(devname, sizeof(devname), "/dev/pts/%u", ptn); /* Query properties fd and fd upper bound before fork() so the child does no * heap allocation or non-async-signal-safe libc calls after fork(). */ int properties_fd = parse_fd_number(getenv("ANDROID_PROPERTY_WORKSPACE")); int max_fd = 1024; struct rlimit rl; if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_cur > 0) { if (rl.rlim_cur > 8192) { max_fd = 8192; } else { max_fd = (int)rl.rlim_cur; } } if (max_fd < 256) { max_fd = 256; } pid_t pid = fork(); if (pid < 0) { throw_io_exception(env, errno, "fork failed"); return -1; } if (pid == 0) { reset_child_signals(); if (setsid() < 0) { _exit(127); } int pts = open(devname, O_RDWR | O_NOCTTY); if (pts < 0) { _exit(127); } if (ioctl(pts, TIOCSCTTY, 0) != 0) { _exit(127); } if (dup2(pts, STDIN_FILENO) < 0 || dup2(pts, STDOUT_FILENO) < 0 || dup2(pts, STDERR_FILENO) < 0) { _exit(127); } for (int fd = STDERR_FILENO + 1; fd < max_fd; ++fd) { if (fd != properties_fd) { close(fd); } } if (pts > STDERR_FILENO && pts >= max_fd) { close(pts); } if (envp != NULL) { execve(cmd, argv, envp); } else { execv(cmd, argv); } _exit(127); } return (int)pid; } JNIEXPORT jint JNICALL Java_jackpal_androidterm_TermExec_createSubprocessInternal( JNIEnv *env, jclass clazz, jstring cmd, jobjectArray args, jobjectArray envVars, jint masterFd) { (void)clazz; char *cmd_c = dup_jstring_utf8(env, cmd); if (cmd_c == NULL) { if (!(*env)->ExceptionCheck(env)) { throw_exception(env, "java/lang/IllegalArgumentException", "Command must not be null"); } return -1; } char **argv = extract_string_array(env, args); if ((*env)->ExceptionCheck(env)) { free(cmd_c); return -1; } if (argv == NULL) { argv = (char **)calloc(2, sizeof(char *)); if (argv == NULL) { free(cmd_c); throw_exception(env, "java/lang/OutOfMemoryError", "Out of memory allocating argv"); return -1; } argv[0] = strdup(cmd_c); if (argv[0] == NULL) { free(argv); free(cmd_c); throw_exception(env, "java/lang/OutOfMemoryError", "Out of memory duplicating argv[0]"); return -1; } argv[1] = NULL; } char **envp = extract_string_array(env, envVars); if ((*env)->ExceptionCheck(env)) { free_string_array(argv); free(cmd_c); return -1; } int pid = create_subprocess(env, cmd_c, argv, envp, (int)masterFd); free_string_array(envp); free_string_array(argv); free(cmd_c); return (jint)pid; } JNIEXPORT jint JNICALL Java_jackpal_androidterm_TermExec_waitFor( JNIEnv *env, jclass clazz, jint procId) { (void)env; (void)clazz; int status = 0; pid_t r; do { r = waitpid((pid_t)procId, &status, 0); } while (r < 0 && errno == EINTR); if (r < 0) { return -1; } if (WIFEXITED(status)) { return (jint)WEXITSTATUS(status); } if (WIFSIGNALED(status)) { return (jint)(128 + WTERMSIG(status)); } return -1; } JNIEXPORT void JNICALL Java_jackpal_androidterm_TermExec_sendSignal( JNIEnv *env, jclass clazz, jint procId, jint sig) { (void)env; (void)clazz; kill((pid_t)procId, (int)sig); } JNIEXPORT void JNICALL Java_jackpal_androidterm_TermExec_setPtyWindowSizeInternal( JNIEnv *env, jclass clazz, jint fd, jint row, jint col, jint xpixel, jint ypixel) { (void)clazz; struct winsize sz; sz.ws_row = (unsigned short)(row > 0 ? row : 1); sz.ws_col = (unsigned short)(col > 0 ? col : 1); sz.ws_xpixel = (unsigned short)(xpixel >= 0 ? xpixel : 0); sz.ws_ypixel = (unsigned short)(ypixel >= 0 ? ypixel : 0); if (ioctl((int)fd, TIOCSWINSZ, &sz) == -1) { throw_io_exception(env, errno, "Failed to issue TIOCSWINSZ ioctl"); } } /* Direct TCGETS / TCSETS ioctls match upstream termExec.cpp for legacy Bionic compatibility. */ JNIEXPORT void JNICALL Java_jackpal_androidterm_TermExec_setPtyUTF8ModeInternal( JNIEnv *env, jclass clazz, jint fd, jboolean utf8Mode) { (void)clazz; struct termios tios; if (ioctl((int)fd, TCGETS, &tios) != 0) { throw_io_exception(env, errno, "Failed to get terminal attributes"); return; } if (utf8Mode) { tios.c_iflag |= IUTF8; } else { tios.c_iflag &= (tcflag_t)(~IUTF8); } if (ioctl((int)fd, TCSETS, &tios) != 0) { throw_io_exception(env, errno, "Failed to set terminal UTF-8 mode"); } }