Debian Codegraph @

Android/testbed/app/src/main/c/main_activity.c

raw
1 #include <android/log.h>
2 #include <errno.h>
3 #include <jni.h>
4 #include <pthread.h>
5 #include <Python.h>
6 #include <signal.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <unistd.h>
10
11
12 static void throw_runtime_exception(JNIEnv *env, const char *message) {
13 (*env)->ThrowNew(
14 env,
15 (*env)->FindClass(env, "java/lang/RuntimeException"),
16 message);
17 }
18
19 static void throw_errno(JNIEnv *env, const char *error_prefix) {
20 char error_message[1024];
21 snprintf(error_message, sizeof(error_message),
22 "%s: %s", error_prefix, strerror(errno));
23 throw_runtime_exception(env, error_message);
24 }
25
26
27 // --- Stdio redirection ------------------------------------------------------
28
29 // Most apps won't need this, because the Python-level sys.stdout and sys.stderr
30 // are redirected to the Android logcat by Python itself. However, in the
31 // testbed it's useful to redirect the native streams as well, to debug problems
32 // in the Python startup or redirection process.
33 //
34 // Based on
35 // https://github.com/beeware/briefcase-android-gradle-template/blob/v0.3.11/%7B%7B%20cookiecutter.safe_formal_name%20%7D%7D/app/src/main/cpp/native-lib.cpp
36
37 typedef struct {
38 FILE *file;
39 int fd;
40 android_LogPriority priority;
41 char *tag;
42 int pipe[2];
43 } StreamInfo;
44
45 // The FILE member can't be initialized here because stdout and stderr are not
46 // compile-time constants. Instead, it's initialized immediately before the
47 // redirection.
48 static StreamInfo STREAMS[] = {
49 {NULL, STDOUT_FILENO, ANDROID_LOG_INFO, "native.stdout", {-1, -1}},
50 {NULL, STDERR_FILENO, ANDROID_LOG_WARN, "native.stderr", {-1, -1}},
51 {NULL, -1, ANDROID_LOG_UNKNOWN, NULL, {-1, -1}},
52 };
53
54 // The maximum length of a log message in bytes, including the level marker and
55 // tag, is defined as LOGGER_ENTRY_MAX_PAYLOAD in
56 // platform/system/logging/liblog/include/log/log.h. As of API level 30, messages
57 // longer than this will be be truncated by logcat. This limit has already been
58 // reduced at least once in the history of Android (from 4076 to 4068 between API
59 // level 23 and 26), so leave some headroom.
60 static const int MAX_BYTES_PER_WRITE = 4000;
61
62 static void *redirection_thread(void *arg) {
63 StreamInfo *si = (StreamInfo*)arg;
64 ssize_t read_size;
65 char buf[MAX_BYTES_PER_WRITE];
66 while ((read_size = read(si->pipe[0], buf, sizeof buf - 1)) > 0) {
67 buf[read_size] = '\0'; /* add null-terminator */
68 __android_log_write(si->priority, si->tag, buf);
69 }
70 return 0;
71 }
72
73 static char *redirect_stream(StreamInfo *si) {
74 /* make the FILE unbuffered, to ensure messages are never lost */
75 if (setvbuf(si->file, 0, _IONBF, 0)) {
76 return "setvbuf";
77 }
78
79 /* create the pipe and redirect the file descriptor */
80 if (pipe(si->pipe)) {
81 return "pipe";
82 }
83 if (dup2(si->pipe[1], si->fd) == -1) {
84 return "dup2";
85 }
86
87 /* start the logging thread */
88 pthread_t thr;
89 if ((errno = pthread_create(&thr, 0, redirection_thread, si))) {
90 return "pthread_create";
91 }
92 if ((errno = pthread_detach(thr))) {
93 return "pthread_detach";
94 }
95 return 0;
96 }
97
98 JNIEXPORT void JNICALL Java_org_python_testbed_PythonTestRunner_redirectStdioToLogcat(
99 JNIEnv *env, jobject obj
100 ) {
101 STREAMS[0].file = stdout;
102 STREAMS[1].file = stderr;
103 for (StreamInfo *si = STREAMS; si->file; si++) {
104 char *error_prefix;
105 if ((error_prefix = redirect_stream(si))) {
106 throw_errno(env, error_prefix);
107 return;
108 }
109 }
110 }
111
112
113 // --- Python initialization ---------------------------------------------------
114
115 static char *init_signals() {
116 // Some tests use SIGUSR1, but that's blocked by default in an Android app in
117 // order to make it available to `sigwait` in the Signal Catcher thread.
118 // (https://cs.android.com/android/platform/superproject/+/android14-qpr3-release:art/runtime/signal_catcher.cc).
119 // That thread's functionality is only useful for debugging the JVM, so disabling
120 // it should not weaken the tests.
121 //
122 // There's no safe way of stopping the thread completely (#123982), but simply
123 // unblocking SIGUSR1 is enough to fix most tests.
124 //
125 // However, in tests that generate multiple different signals in quick
126 // succession, it's possible for SIGUSR1 to arrive while the main thread is busy
127 // running the C-level handler for a different signal. In that case, the SIGUSR1
128 // may be sent to the Signal Catcher thread instead, which will generate a log
129 // message containing the text "reacting to signal".
130 //
131 // Such tests may need to be changed in one of the following ways:
132 // * Use a signal other than SIGUSR1 (e.g. test_stress_delivery_simultaneous in
133 // test_signal.py).
134 // * Send the signal to a specific thread rather than the whole process (e.g.
135 // test_signals in test_threadsignals.py.
136 sigset_t set;
137 if (sigemptyset(&set)) {
138 return "sigemptyset";
139 }
140 if (sigaddset(&set, SIGUSR1)) {
141 return "sigaddset";
142 }
143 if ((errno = pthread_sigmask(SIG_UNBLOCK, &set, NULL))) {
144 return "pthread_sigmask";
145 }
146 return NULL;
147 }
148
149 static void throw_status(JNIEnv *env, PyStatus status) {
150 throw_runtime_exception(env, status.err_msg ? status.err_msg : "");
151 }
152
153 JNIEXPORT int JNICALL Java_org_python_testbed_PythonTestRunner_runPython(
154 JNIEnv *env, jobject obj, jstring home, jarray args
155 ) {
156 const char *home_utf8 = (*env)->GetStringUTFChars(env, home, NULL);
157 char cwd[PATH_MAX];
158 snprintf(cwd, sizeof(cwd), "%s/%s", home_utf8, "cwd");
159 if (chdir(cwd)) {
160 throw_errno(env, "chdir");
161 return 1;
162 }
163
164 char *error_prefix;
165 if ((error_prefix = init_signals())) {
166 throw_errno(env, error_prefix);
167 return 1;
168 }
169
170 PyConfig config;
171 PyStatus status;
172 PyConfig_InitPythonConfig(&config);
173
174 jsize argc = (*env)->GetArrayLength(env, args);
175 const char *argv[argc + 1];
176 for (int i = 0; i < argc; i++) {
177 jobject arg = (*env)->GetObjectArrayElement(env, args, i);
178 argv[i] = (*env)->GetStringUTFChars(env, arg, NULL);
179 }
180 argv[argc] = NULL;
181
182 // PyConfig_SetBytesArgv "must be called before other methods, since the
183 // preinitialization configuration depends on command line arguments"
184 if (PyStatus_Exception(status = PyConfig_SetBytesArgv(&config, argc, (char**)argv))) {
185 throw_status(env, status);
186 return 1;
187 }
188
189 status = PyConfig_SetBytesString(&config, &config.home, home_utf8);
190 if (PyStatus_Exception(status)) {
191 throw_status(env, status);
192 return 1;
193 }
194
195 status = Py_InitializeFromConfig(&config);
196 if (PyStatus_Exception(status)) {
197 throw_status(env, status);
198 return 1;
199 }
200
201 return Py_RunMain();
202 }