Robert Sesek | 8f8d187 | 2016-03-18 16:52:57 -0400 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2016 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package android.os; |
| 18 | |
| 19 | import android.net.LocalSocket; |
| 20 | import android.net.LocalSocketAddress; |
| 21 | import android.util.Log; |
| 22 | import com.android.internal.os.Zygote; |
| 23 | import java.io.BufferedWriter; |
| 24 | import java.io.DataInputStream; |
| 25 | import java.io.IOException; |
| 26 | import java.io.OutputStreamWriter; |
| 27 | import java.nio.charset.StandardCharsets; |
| 28 | import java.util.ArrayList; |
| 29 | import java.util.Arrays; |
| 30 | import java.util.List; |
| 31 | |
| 32 | /*package*/ class ZygoteStartFailedEx extends Exception { |
| 33 | ZygoteStartFailedEx(String s) { |
| 34 | super(s); |
| 35 | } |
| 36 | |
| 37 | ZygoteStartFailedEx(Throwable cause) { |
| 38 | super(cause); |
| 39 | } |
| 40 | |
| 41 | ZygoteStartFailedEx(String s, Throwable cause) { |
| 42 | super(s, cause); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * Maintains communication state with the zygote processes. This class is responsible |
| 48 | * for the sockets opened to the zygotes and for starting processes on behalf of the |
| 49 | * {@link android.os.Process} class. |
| 50 | * |
| 51 | * {@hide} |
| 52 | */ |
| 53 | public class ZygoteProcess { |
| 54 | private static final String LOG_TAG = "ZygoteProcess"; |
| 55 | |
| 56 | /** |
| 57 | * The name of the socket used to communicate with the primary zygote. |
| 58 | */ |
| 59 | private final String mSocket; |
| 60 | |
| 61 | /** |
| 62 | * The name of the secondary (alternate ABI) zygote socket. |
| 63 | */ |
| 64 | private final String mSecondarySocket; |
| 65 | |
| 66 | public ZygoteProcess(String primarySocket, String secondarySocket) { |
| 67 | mSocket = primarySocket; |
| 68 | mSecondarySocket = secondarySocket; |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * State for communicating with the zygote process. |
| 73 | */ |
| 74 | public static class ZygoteState { |
| 75 | final LocalSocket socket; |
| 76 | final DataInputStream inputStream; |
| 77 | final BufferedWriter writer; |
| 78 | final List<String> abiList; |
| 79 | |
| 80 | boolean mClosed; |
| 81 | |
| 82 | private ZygoteState(LocalSocket socket, DataInputStream inputStream, |
| 83 | BufferedWriter writer, List<String> abiList) { |
| 84 | this.socket = socket; |
| 85 | this.inputStream = inputStream; |
| 86 | this.writer = writer; |
| 87 | this.abiList = abiList; |
| 88 | } |
| 89 | |
| 90 | public static ZygoteState connect(String socketAddress) throws IOException { |
| 91 | DataInputStream zygoteInputStream = null; |
| 92 | BufferedWriter zygoteWriter = null; |
| 93 | final LocalSocket zygoteSocket = new LocalSocket(); |
| 94 | |
| 95 | try { |
| 96 | zygoteSocket.connect(new LocalSocketAddress(socketAddress, |
| 97 | LocalSocketAddress.Namespace.RESERVED)); |
| 98 | |
| 99 | zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream()); |
| 100 | |
| 101 | zygoteWriter = new BufferedWriter(new OutputStreamWriter( |
| 102 | zygoteSocket.getOutputStream()), 256); |
| 103 | } catch (IOException ex) { |
| 104 | try { |
| 105 | zygoteSocket.close(); |
| 106 | } catch (IOException ignore) { |
| 107 | } |
| 108 | |
| 109 | throw ex; |
| 110 | } |
| 111 | |
| 112 | String abiListString = getAbiList(zygoteWriter, zygoteInputStream); |
| 113 | Log.i("Zygote", "Process: zygote socket opened, supported ABIS: " + abiListString); |
| 114 | |
| 115 | return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter, |
| 116 | Arrays.asList(abiListString.split(","))); |
| 117 | } |
| 118 | |
| 119 | boolean matches(String abi) { |
| 120 | return abiList.contains(abi); |
| 121 | } |
| 122 | |
| 123 | public void close() { |
| 124 | try { |
| 125 | socket.close(); |
| 126 | } catch (IOException ex) { |
| 127 | Log.e(LOG_TAG,"I/O exception on routine close", ex); |
| 128 | } |
| 129 | |
| 130 | mClosed = true; |
| 131 | } |
| 132 | |
| 133 | boolean isClosed() { |
| 134 | return mClosed; |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | /** |
| 139 | * The state of the connection to the primary zygote. |
| 140 | */ |
| 141 | private ZygoteState primaryZygoteState; |
| 142 | |
| 143 | /** |
| 144 | * The state of the connection to the secondary zygote. |
| 145 | */ |
| 146 | private ZygoteState secondaryZygoteState; |
| 147 | |
| 148 | /** |
| 149 | * Start a new process. |
| 150 | * |
| 151 | * <p>If processes are enabled, a new process is created and the |
| 152 | * static main() function of a <var>processClass</var> is executed there. |
| 153 | * The process will continue running after this function returns. |
| 154 | * |
| 155 | * <p>If processes are not enabled, a new thread in the caller's |
| 156 | * process is created and main() of <var>processClass</var> called there. |
| 157 | * |
| 158 | * <p>The niceName parameter, if not an empty string, is a custom name to |
| 159 | * give to the process instead of using processClass. This allows you to |
| 160 | * make easily identifyable processes even if you are using the same base |
| 161 | * <var>processClass</var> to start them. |
| 162 | * |
| 163 | * @param processClass The class to use as the process's main entry |
| 164 | * point. |
| 165 | * @param niceName A more readable name to use for the process. |
| 166 | * @param uid The user-id under which the process will run. |
| 167 | * @param gid The group-id under which the process will run. |
| 168 | * @param gids Additional group-ids associated with the process. |
| 169 | * @param debugFlags Additional flags. |
| 170 | * @param targetSdkVersion The target SDK version for the app. |
| 171 | * @param seInfo null-ok SELinux information for the new process. |
| 172 | * @param abi non-null the ABI this app should be started with. |
| 173 | * @param instructionSet null-ok the instruction set to use. |
| 174 | * @param appDataDir null-ok the data directory of the app. |
| 175 | * @param zygoteArgs Additional arguments to supply to the zygote process. |
| 176 | * |
| 177 | * @return An object that describes the result of the attempt to start the process. |
| 178 | * @throws RuntimeException on fatal start failure |
| 179 | */ |
| 180 | public final Process.ProcessStartResult start(final String processClass, |
| 181 | final String niceName, |
| 182 | int uid, int gid, int[] gids, |
| 183 | int debugFlags, int mountExternal, |
| 184 | int targetSdkVersion, |
| 185 | String seInfo, |
| 186 | String abi, |
| 187 | String instructionSet, |
| 188 | String appDataDir, |
| 189 | String[] zygoteArgs) { |
| 190 | try { |
| 191 | return startViaZygote(processClass, niceName, uid, gid, gids, |
| 192 | debugFlags, mountExternal, targetSdkVersion, seInfo, |
| 193 | abi, instructionSet, appDataDir, zygoteArgs); |
| 194 | } catch (ZygoteStartFailedEx ex) { |
| 195 | Log.e(LOG_TAG, |
| 196 | "Starting VM process through Zygote failed"); |
| 197 | throw new RuntimeException( |
| 198 | "Starting VM process through Zygote failed", ex); |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | /** retry interval for opening a zygote socket */ |
| 203 | static final int ZYGOTE_RETRY_MILLIS = 500; |
| 204 | |
| 205 | /** |
| 206 | * Queries the zygote for the list of ABIS it supports. |
| 207 | * |
| 208 | * @throws ZygoteStartFailedEx if the query failed. |
| 209 | */ |
| 210 | private static String getAbiList(BufferedWriter writer, DataInputStream inputStream) |
| 211 | throws IOException { |
| 212 | // Each query starts with the argument count (1 in this case) |
| 213 | writer.write("1"); |
| 214 | // ... followed by a new-line. |
| 215 | writer.newLine(); |
| 216 | // ... followed by our only argument. |
| 217 | writer.write("--query-abi-list"); |
| 218 | writer.newLine(); |
| 219 | writer.flush(); |
| 220 | |
| 221 | // The response is a length prefixed stream of ASCII bytes. |
| 222 | int numBytes = inputStream.readInt(); |
| 223 | byte[] bytes = new byte[numBytes]; |
| 224 | inputStream.readFully(bytes); |
| 225 | |
| 226 | return new String(bytes, StandardCharsets.US_ASCII); |
| 227 | } |
| 228 | |
| 229 | /** |
| 230 | * Sends an argument list to the zygote process, which starts a new child |
| 231 | * and returns the child's pid. Please note: the present implementation |
| 232 | * replaces newlines in the argument list with spaces. |
| 233 | * |
| 234 | * @throws ZygoteStartFailedEx if process start failed for any reason |
| 235 | */ |
| 236 | private static Process.ProcessStartResult zygoteSendArgsAndGetResult( |
| 237 | ZygoteState zygoteState, ArrayList<String> args) |
| 238 | throws ZygoteStartFailedEx { |
| 239 | try { |
| 240 | /** |
| 241 | * See com.android.internal.os.SystemZygoteInit.readArgumentList() |
| 242 | * Presently the wire format to the zygote process is: |
| 243 | * a) a count of arguments (argc, in essence) |
| 244 | * b) a number of newline-separated argument strings equal to count |
| 245 | * |
| 246 | * After the zygote process reads these it will write the pid of |
| 247 | * the child or -1 on failure, followed by boolean to |
| 248 | * indicate whether a wrapper process was used. |
| 249 | */ |
| 250 | final BufferedWriter writer = zygoteState.writer; |
| 251 | final DataInputStream inputStream = zygoteState.inputStream; |
| 252 | |
| 253 | writer.write(Integer.toString(args.size())); |
| 254 | writer.newLine(); |
| 255 | |
| 256 | int sz = args.size(); |
| 257 | for (int i = 0; i < sz; i++) { |
| 258 | String arg = args.get(i); |
| 259 | if (arg.indexOf('\n') >= 0) { |
| 260 | throw new ZygoteStartFailedEx( |
| 261 | "embedded newlines not allowed"); |
| 262 | } |
| 263 | writer.write(arg); |
| 264 | writer.newLine(); |
| 265 | } |
| 266 | |
| 267 | writer.flush(); |
| 268 | |
| 269 | // Should there be a timeout on this? |
| 270 | Process.ProcessStartResult result = new Process.ProcessStartResult(); |
| 271 | result.pid = inputStream.readInt(); |
| 272 | if (result.pid < 0) { |
| 273 | throw new ZygoteStartFailedEx("fork() failed"); |
| 274 | } |
| 275 | result.usingWrapper = inputStream.readBoolean(); |
| 276 | return result; |
| 277 | } catch (IOException ex) { |
| 278 | zygoteState.close(); |
| 279 | throw new ZygoteStartFailedEx(ex); |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | /** |
| 284 | * Starts a new process via the zygote mechanism. |
| 285 | * |
| 286 | * @param processClass Class name whose static main() to run |
| 287 | * @param niceName 'nice' process name to appear in ps |
| 288 | * @param uid a POSIX uid that the new process should setuid() to |
| 289 | * @param gid a POSIX gid that the new process shuold setgid() to |
| 290 | * @param gids null-ok; a list of supplementary group IDs that the |
| 291 | * new process should setgroup() to. |
| 292 | * @param debugFlags Additional flags. |
| 293 | * @param targetSdkVersion The target SDK version for the app. |
| 294 | * @param seInfo null-ok SELinux information for the new process. |
| 295 | * @param abi the ABI the process should use. |
| 296 | * @param instructionSet null-ok the instruction set to use. |
| 297 | * @param appDataDir null-ok the data directory of the app. |
| 298 | * @param extraArgs Additional arguments to supply to the zygote process. |
| 299 | * @return An object that describes the result of the attempt to start the process. |
| 300 | * @throws ZygoteStartFailedEx if process start failed for any reason |
| 301 | */ |
| 302 | private Process.ProcessStartResult startViaZygote(final String processClass, |
| 303 | final String niceName, |
| 304 | final int uid, final int gid, |
| 305 | final int[] gids, |
| 306 | int debugFlags, int mountExternal, |
| 307 | int targetSdkVersion, |
| 308 | String seInfo, |
| 309 | String abi, |
| 310 | String instructionSet, |
| 311 | String appDataDir, |
| 312 | String[] extraArgs) |
| 313 | throws ZygoteStartFailedEx { |
| 314 | synchronized(Process.class) { |
| 315 | ArrayList<String> argsForZygote = new ArrayList<String>(); |
| 316 | |
| 317 | // --runtime-args, --setuid=, --setgid=, |
| 318 | // and --setgroups= must go first |
| 319 | argsForZygote.add("--runtime-args"); |
| 320 | argsForZygote.add("--setuid=" + uid); |
| 321 | argsForZygote.add("--setgid=" + gid); |
| 322 | if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) { |
| 323 | argsForZygote.add("--enable-jni-logging"); |
| 324 | } |
| 325 | if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) { |
| 326 | argsForZygote.add("--enable-safemode"); |
| 327 | } |
| 328 | if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) { |
| 329 | argsForZygote.add("--enable-debugger"); |
| 330 | } |
| 331 | if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) { |
| 332 | argsForZygote.add("--enable-checkjni"); |
| 333 | } |
| 334 | if ((debugFlags & Zygote.DEBUG_GENERATE_DEBUG_INFO) != 0) { |
| 335 | argsForZygote.add("--generate-debug-info"); |
| 336 | } |
| 337 | if ((debugFlags & Zygote.DEBUG_ALWAYS_JIT) != 0) { |
| 338 | argsForZygote.add("--always-jit"); |
| 339 | } |
| 340 | if ((debugFlags & Zygote.DEBUG_NATIVE_DEBUGGABLE) != 0) { |
| 341 | argsForZygote.add("--native-debuggable"); |
| 342 | } |
| 343 | if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) { |
| 344 | argsForZygote.add("--enable-assert"); |
| 345 | } |
| 346 | if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) { |
| 347 | argsForZygote.add("--mount-external-default"); |
| 348 | } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) { |
| 349 | argsForZygote.add("--mount-external-read"); |
| 350 | } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) { |
| 351 | argsForZygote.add("--mount-external-write"); |
| 352 | } |
| 353 | argsForZygote.add("--target-sdk-version=" + targetSdkVersion); |
| 354 | |
| 355 | //TODO optionally enable debuger |
| 356 | //argsForZygote.add("--enable-debugger"); |
| 357 | |
| 358 | // --setgroups is a comma-separated list |
| 359 | if (gids != null && gids.length > 0) { |
| 360 | StringBuilder sb = new StringBuilder(); |
| 361 | sb.append("--setgroups="); |
| 362 | |
| 363 | int sz = gids.length; |
| 364 | for (int i = 0; i < sz; i++) { |
| 365 | if (i != 0) { |
| 366 | sb.append(','); |
| 367 | } |
| 368 | sb.append(gids[i]); |
| 369 | } |
| 370 | |
| 371 | argsForZygote.add(sb.toString()); |
| 372 | } |
| 373 | |
| 374 | if (niceName != null) { |
| 375 | argsForZygote.add("--nice-name=" + niceName); |
| 376 | } |
| 377 | |
| 378 | if (seInfo != null) { |
| 379 | argsForZygote.add("--seinfo=" + seInfo); |
| 380 | } |
| 381 | |
| 382 | if (instructionSet != null) { |
| 383 | argsForZygote.add("--instruction-set=" + instructionSet); |
| 384 | } |
| 385 | |
| 386 | if (appDataDir != null) { |
| 387 | argsForZygote.add("--app-data-dir=" + appDataDir); |
| 388 | } |
| 389 | |
| 390 | argsForZygote.add(processClass); |
| 391 | |
| 392 | if (extraArgs != null) { |
| 393 | for (String arg : extraArgs) { |
| 394 | argsForZygote.add(arg); |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote); |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | /** |
| 403 | * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block |
| 404 | * and retry if the zygote is unresponsive. This method is a no-op if a connection is |
| 405 | * already open. |
| 406 | */ |
| 407 | public void establishZygoteConnectionForAbi(String abi) { |
| 408 | try { |
| 409 | openZygoteSocketIfNeeded(abi); |
| 410 | } catch (ZygoteStartFailedEx ex) { |
| 411 | throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex); |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | /** |
| 416 | * Tries to open socket to Zygote process if not already open. If |
| 417 | * already open, does nothing. May block and retry. |
| 418 | */ |
| 419 | private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx { |
| 420 | if (primaryZygoteState == null || primaryZygoteState.isClosed()) { |
| 421 | try { |
| 422 | primaryZygoteState = ZygoteState.connect(mSocket); |
| 423 | } catch (IOException ioe) { |
| 424 | throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe); |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | if (primaryZygoteState.matches(abi)) { |
| 429 | return primaryZygoteState; |
| 430 | } |
| 431 | |
| 432 | // The primary zygote didn't match. Try the secondary. |
| 433 | if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) { |
| 434 | try { |
| 435 | secondaryZygoteState = ZygoteState.connect(mSecondarySocket); |
| 436 | } catch (IOException ioe) { |
| 437 | throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe); |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | if (secondaryZygoteState.matches(abi)) { |
| 442 | return secondaryZygoteState; |
| 443 | } |
| 444 | |
| 445 | throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi); |
| 446 | } |
| 447 | } |