1/* 2 * Copyright (C) 2006 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 17package dalvik.system; 18 19import java.io.File; 20 21/** 22 * Provides hooks for the zygote to call back into the runtime to perform 23 * parent or child specific initialization.. 24 * 25 * @hide 26 */ 27public final class ZygoteHooks { 28 private long token; 29 30 /** 31 * Called by the zygote prior to every fork. Each call to {@code preFork} 32 * is followed by a matching call to {@link #postForkChild(int)} on the child 33 * process and {@link #postForkCommon()} on both the parent and the child 34 * process. {@code postForkCommon} is called after {@code postForkChild} in 35 * the child process. 36 */ 37 public void preFork() { 38 Daemons.stop(); 39 waitUntilAllThreadsStopped(); 40 token = nativePreFork(); 41 } 42 43 /** 44 * Called by the zygote in the child process after every fork. The debug 45 * flags from {@code debugFlags} are applied to the child process. The string 46 * {@code instructionSet} determines whether to use a native bridge. 47 */ 48 public void postForkChild(int debugFlags, String instructionSet) { 49 nativePostForkChild(token, debugFlags, instructionSet); 50 } 51 52 /** 53 * Called by the zygote in both the parent and child processes after 54 * every fork. In the child process, this method is called after 55 * {@code postForkChild}. 56 */ 57 public void postForkCommon() { 58 Daemons.start(); 59 } 60 61 private static native long nativePreFork(); 62 private static native void nativePostForkChild(long token, int debugFlags, 63 String instructionSet); 64 65 /** 66 * We must not fork until we're single-threaded again. Wait until /proc shows we're 67 * down to just one thread. 68 */ 69 private static void waitUntilAllThreadsStopped() { 70 File tasks = new File("/proc/self/task"); 71 while (tasks.list().length > 1) { 72 try { 73 // Experimentally, booting and playing about with a stingray, I never saw us 74 // go round this loop more than once with a 10ms sleep. 75 Thread.sleep(10); 76 } catch (InterruptedException ignored) { 77 } 78 } 79 } 80} 81