Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(220)

Side by Side Diff: content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java

Issue 2017963003: Upstream: ChildProcessLauncher connects renderer processes of WebAPKs. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Maria's comments. Created 4 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2012 The Chromium Authors. All rights reserved. 1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 package org.chromium.content.browser; 5 package org.chromium.content.browser;
6 6
7 import android.annotation.SuppressLint; 7 import android.annotation.SuppressLint;
8 import android.content.Context; 8 import android.content.Context;
9 import android.content.Intent; 9 import android.content.Intent;
10 import android.content.pm.ApplicationInfo; 10 import android.content.pm.ApplicationInfo;
(...skipping 20 matching lines...) Expand all
31 import org.chromium.content.app.ChromiumLinkerParams; 31 import org.chromium.content.app.ChromiumLinkerParams;
32 import org.chromium.content.app.DownloadProcessService; 32 import org.chromium.content.app.DownloadProcessService;
33 import org.chromium.content.app.PrivilegedProcessService; 33 import org.chromium.content.app.PrivilegedProcessService;
34 import org.chromium.content.app.SandboxedProcessService; 34 import org.chromium.content.app.SandboxedProcessService;
35 import org.chromium.content.common.ContentSwitches; 35 import org.chromium.content.common.ContentSwitches;
36 import org.chromium.content.common.IChildProcessCallback; 36 import org.chromium.content.common.IChildProcessCallback;
37 import org.chromium.content.common.SurfaceWrapper; 37 import org.chromium.content.common.SurfaceWrapper;
38 38
39 import java.io.IOException; 39 import java.io.IOException;
40 import java.util.ArrayList; 40 import java.util.ArrayList;
41 import java.util.HashMap;
41 import java.util.LinkedList; 42 import java.util.LinkedList;
42 import java.util.Map; 43 import java.util.Map;
43 import java.util.Queue; 44 import java.util.Queue;
44 import java.util.concurrent.ConcurrentHashMap; 45 import java.util.concurrent.ConcurrentHashMap;
45 46
46 /** 47 /**
47 * This class provides the method to start/stop ChildProcess called by native. 48 * This class provides the method to start/stop ChildProcess called by native.
48 */ 49 */
49 @JNINamespace("content") 50 @JNINamespace("content")
50 public class ChildProcessLauncher { 51 public class ChildProcessLauncher {
51 private static final String TAG = "ChildProcLauncher"; 52 private static final String TAG = "ChildProcLauncher";
52 53
53 static final int CALLBACK_FOR_UNKNOWN_PROCESS = 0; 54 static final int CALLBACK_FOR_UNKNOWN_PROCESS = 0;
54 static final int CALLBACK_FOR_GPU_PROCESS = 1; 55 static final int CALLBACK_FOR_GPU_PROCESS = 1;
55 static final int CALLBACK_FOR_RENDERER_PROCESS = 2; 56 static final int CALLBACK_FOR_RENDERER_PROCESS = 2;
56 static final int CALLBACK_FOR_UTILITY_PROCESS = 3; 57 static final int CALLBACK_FOR_UTILITY_PROCESS = 3;
57 static final int CALLBACK_FOR_DOWNLOAD_PROCESS = 4; 58 static final int CALLBACK_FOR_DOWNLOAD_PROCESS = 4;
58 59
59 private static class ChildConnectionAllocator { 60 private static class ChildConnectionAllocator {
60 // Connections to services. Indices of the array correspond to the servi ce numbers. 61 // Connections to services. Indices of the array correspond to the servi ce numbers.
61 private final ChildProcessConnection[] mChildProcessConnections; 62 private final ChildProcessConnection[] mChildProcessConnections;
62 63
63 // The list of free (not bound) service indices. 64 // The list of free (not bound) service indices.
64 // SHOULD BE ACCESSED WITH mConnectionLock. 65 // SHOULD BE ACCESSED WITH mConnectionLock.
65 private final ArrayList<Integer> mFreeConnectionIndices; 66 private final ArrayList<Integer> mFreeConnectionIndices;
66 private final Object mConnectionLock = new Object(); 67 private final Object mConnectionLock = new Object();
67 68
68 private Class<? extends ChildProcessService> mChildClass; 69 private Class<? extends ChildProcessService> mChildClass;
69 private final boolean mInSandbox; 70 private final boolean mInSandbox;
71 // Each Allocator keeps a queue for the pending spawn data. Once a conne ction is free, we
72 // dequeue the pending spawn data from the same allocator as the connect ion.
73 private final PendingSpawnQueue mPendingSpawnQueue = new PendingSpawnQue ue();
70 74
71 public ChildConnectionAllocator(boolean inSandbox, int numChildServices) { 75 public ChildConnectionAllocator(boolean inSandbox, int numChildServices) {
72 mChildProcessConnections = new ChildProcessConnectionImpl[numChildSe rvices]; 76 mChildProcessConnections = new ChildProcessConnectionImpl[numChildSe rvices];
73 mFreeConnectionIndices = new ArrayList<Integer>(numChildServices); 77 mFreeConnectionIndices = new ArrayList<Integer>(numChildServices);
74 for (int i = 0; i < numChildServices; i++) { 78 for (int i = 0; i < numChildServices; i++) {
75 mFreeConnectionIndices.add(i); 79 mFreeConnectionIndices.add(i);
76 } 80 }
77 mChildClass = 81 mChildClass =
78 inSandbox ? SandboxedProcessService.class : PrivilegedProces sService.class; 82 inSandbox ? SandboxedProcessService.class : PrivilegedProces sService.class;
79 mInSandbox = inSandbox; 83 mInSandbox = inSandbox;
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
118 } 122 }
119 } 123 }
120 } 124 }
121 125
122 public boolean isFreeConnectionAvailable() { 126 public boolean isFreeConnectionAvailable() {
123 synchronized (mConnectionLock) { 127 synchronized (mConnectionLock) {
124 return !mFreeConnectionIndices.isEmpty(); 128 return !mFreeConnectionIndices.isEmpty();
125 } 129 }
126 } 130 }
127 131
132 public PendingSpawnQueue getPendingSpawnQueue() {
133 return mPendingSpawnQueue;
134 }
135
128 /** @return the count of connections managed by the allocator */ 136 /** @return the count of connections managed by the allocator */
129 @VisibleForTesting 137 @VisibleForTesting
130 int allocatedConnectionsCountForTesting() { 138 int allocatedConnectionsCountForTesting() {
131 return mChildProcessConnections.length - mFreeConnectionIndices.size (); 139 return mChildProcessConnections.length - mFreeConnectionIndices.size ();
132 } 140 }
133 } 141 }
134 142
135 private static class PendingSpawnData { 143 private static class PendingSpawnData {
136 private final Context mContext; 144 private final Context mContext;
137 private final String[] mCommandLine; 145 private final String[] mCommandLine;
138 private final int mChildProcessId; 146 private final int mChildProcessId;
139 private final FileDescriptorInfo[] mFilesToBeMapped; 147 private final FileDescriptorInfo[] mFilesToBeMapped;
140 private final long mClientContext; 148 private final long mClientContext;
141 private final int mCallbackType; 149 private final int mCallbackType;
142 private final boolean mInSandbox; 150 private final boolean mInSandbox;
151 private final ChildProcessCreationParams mCreationParams;
143 152
144 private PendingSpawnData( 153 private PendingSpawnData(
145 Context context, 154 Context context,
146 String[] commandLine, 155 String[] commandLine,
147 int childProcessId, 156 int childProcessId,
148 FileDescriptorInfo[] filesToBeMapped, 157 FileDescriptorInfo[] filesToBeMapped,
149 long clientContext, 158 long clientContext,
150 int callbackType, 159 int callbackType,
151 boolean inSandbox) { 160 boolean inSandbox,
161 ChildProcessCreationParams creationParams) {
152 mContext = context; 162 mContext = context;
153 mCommandLine = commandLine; 163 mCommandLine = commandLine;
154 mChildProcessId = childProcessId; 164 mChildProcessId = childProcessId;
155 mFilesToBeMapped = filesToBeMapped; 165 mFilesToBeMapped = filesToBeMapped;
156 mClientContext = clientContext; 166 mClientContext = clientContext;
157 mCallbackType = callbackType; 167 mCallbackType = callbackType;
158 mInSandbox = inSandbox; 168 mInSandbox = inSandbox;
169 mCreationParams = creationParams;
159 } 170 }
160 171
161 private Context context() { 172 private Context context() {
162 return mContext; 173 return mContext;
163 } 174 }
164 private String[] commandLine() { 175 private String[] commandLine() {
165 return mCommandLine; 176 return mCommandLine;
166 } 177 }
167 private int childProcessId() { 178 private int childProcessId() {
168 return mChildProcessId; 179 return mChildProcessId;
169 } 180 }
170 private FileDescriptorInfo[] filesToBeMapped() { 181 private FileDescriptorInfo[] filesToBeMapped() {
171 return mFilesToBeMapped; 182 return mFilesToBeMapped;
172 } 183 }
173 private long clientContext() { 184 private long clientContext() {
174 return mClientContext; 185 return mClientContext;
175 } 186 }
176 private int callbackType() { 187 private int callbackType() {
177 return mCallbackType; 188 return mCallbackType;
178 } 189 }
179 private boolean inSandbox() { 190 private boolean inSandbox() {
180 return mInSandbox; 191 return mInSandbox;
181 } 192 }
193 private ChildProcessCreationParams getCreationParams() {
194 return mCreationParams;
195 }
182 } 196 }
183 197
184 private static class PendingSpawnQueue { 198 private static class PendingSpawnQueue {
185 // The list of pending process spawn requests and its lock. 199 // The list of pending process spawn requests and its lock.
186 // Operations on this queue must be atomical w.r.t. free connections upd ates. 200 private Queue<PendingSpawnData> mPendingSpawns = new LinkedList<PendingS pawnData>();
187 private static Queue<PendingSpawnData> sPendingSpawns =
188 new LinkedList<PendingSpawnData>();
189 static final Object sPendingSpawnsLock = new Object();
190 201
191 /** 202 /**
192 * Queue up a spawn requests to be processed once a free service is avai lable. 203 * Queue up a spawn requests to be processed once a free service is avai lable.
193 * Called when a spawn is requested while we are at the capacity. 204 * Called when a spawn is requested while we are at the capacity.
194 */ 205 */
195 public void enqueueLocked(final PendingSpawnData pendingSpawn) { 206 public void enqueue(final PendingSpawnData pendingSpawn) {
196 assert Thread.holdsLock(sPendingSpawnsLock); 207 mPendingSpawns.add(pendingSpawn);
197 sPendingSpawns.add(pendingSpawn);
198 } 208 }
199 209
200 /** 210 /**
201 * Pop the next request from the queue. Called when a free service is av ailable. 211 * Pop the next request from the queue. Called when a free service is av ailable.
202 * @return the next spawn request waiting in the queue. 212 * @return the next spawn request waiting in the queue.
203 */ 213 */
204 public PendingSpawnData dequeueLocked() { 214 public PendingSpawnData dequeue() {
205 assert Thread.holdsLock(sPendingSpawnsLock); 215 return mPendingSpawns.poll();
206 return sPendingSpawns.poll();
207 } 216 }
208 217
209 /** @return the count of pending spawns in the queue */ 218 /** @return the count of pending spawns in the queue */
210 public int sizeLocked() { 219 public int size() {
211 assert Thread.holdsLock(sPendingSpawnsLock); 220 return mPendingSpawns.size();
212 return sPendingSpawns.size();
213 } 221 }
214 } 222 }
215 223
216 private static final PendingSpawnQueue sPendingSpawnQueue = new PendingSpawn Queue(); 224 // Service class for child process.
217 225 // Map from package name to ChildConnectionAllocator.
218 // Service class for child process. As the default value it uses SandboxedPr ocessService0 and 226 private static Map<String, ChildConnectionAllocator> sSandboxedChildConnecti onAllocatorMap;
219 // PrivilegedProcessService0. 227 // As the default value it uses PrivilegedProcessService0.
220 private static ChildConnectionAllocator sSandboxedChildConnectionAllocator;
221 private static ChildConnectionAllocator sPrivilegedChildConnectionAllocator; 228 private static ChildConnectionAllocator sPrivilegedChildConnectionAllocator;
222 229
223 private static final String NUM_SANDBOXED_SERVICES_KEY = 230 private static final String NUM_SANDBOXED_SERVICES_KEY =
224 "org.chromium.content.browser.NUM_SANDBOXED_SERVICES"; 231 "org.chromium.content.browser.NUM_SANDBOXED_SERVICES";
225 private static final String NUM_PRIVILEGED_SERVICES_KEY = 232 private static final String NUM_PRIVILEGED_SERVICES_KEY =
226 "org.chromium.content.browser.NUM_PRIVILEGED_SERVICES"; 233 "org.chromium.content.browser.NUM_PRIVILEGED_SERVICES";
227 // Overrides the number of available sandboxed services. 234 // Overrides the number of available sandboxed services.
228 @VisibleForTesting 235 @VisibleForTesting
229 public static final String SWITCH_NUM_SANDBOXED_SERVICES_FOR_TESTING = "num- sandboxed-services"; 236 public static final String SWITCH_NUM_SANDBOXED_SERVICES_FOR_TESTING = "num- sandboxed-services";
230 237
231 private static int getNumberOfServices(Context context, boolean inSandbox) { 238 private static int getNumberOfServices(Context context, boolean inSandbox, S tring packageName) {
232 try { 239 try {
233 PackageManager packageManager = context.getPackageManager(); 240 PackageManager packageManager = context.getPackageManager();
234 ChildProcessCreationParams childProcessCreationParams =
235 ChildProcessCreationParams.get();
236 final String packageName = childProcessCreationParams != null
237 ? childProcessCreationParams.getPackageName() : context.getP ackageName();
238 ApplicationInfo appInfo = packageManager.getApplicationInfo(packageN ame, 241 ApplicationInfo appInfo = packageManager.getApplicationInfo(packageN ame,
239 PackageManager.GET_META_DATA); 242 PackageManager.GET_META_DATA);
240 int numServices = appInfo.metaData.getInt(inSandbox ? NUM_SANDBOXED_ SERVICES_KEY 243 int numServices = -1;
241 : NUM_PRIVILEGED_SERVICES_KEY, -1); 244 if (appInfo.metaData != null) {
245 numServices = appInfo.metaData.getInt(
246 inSandbox ? NUM_SANDBOXED_SERVICES_KEY : NUM_PRIVILEGED_ SERVICES_KEY, -1);
247 }
242 if (inSandbox 248 if (inSandbox
243 && CommandLine.getInstance().hasSwitch( 249 && CommandLine.getInstance().hasSwitch(
244 SWITCH_NUM_SANDBOXED_SERVICES_FOR_TESTING)) { 250 SWITCH_NUM_SANDBOXED_SERVICES_FOR_TESTING)) {
245 String value = CommandLine.getInstance().getSwitchValue( 251 String value = CommandLine.getInstance().getSwitchValue(
246 SWITCH_NUM_SANDBOXED_SERVICES_FOR_TESTING); 252 SWITCH_NUM_SANDBOXED_SERVICES_FOR_TESTING);
247 if (!TextUtils.isEmpty(value)) { 253 if (!TextUtils.isEmpty(value)) {
248 try { 254 try {
249 numServices = Integer.parseInt(value); 255 numServices = Integer.parseInt(value);
250 } catch (NumberFormatException e) { 256 } catch (NumberFormatException e) {
251 Log.w(TAG, "The value of --num-sandboxed-services is for matted wrongly: " 257 Log.w(TAG, "The value of --num-sandboxed-services is for matted wrongly: "
252 + value); 258 + value);
253 } 259 }
254 } 260 }
255 } 261 }
256 if (numServices < 0) { 262 if (numServices < 0) {
257 throw new RuntimeException("Illegal meta data value for number o f child services"); 263 throw new RuntimeException("Illegal meta data value for number o f child services");
258 } 264 }
259 return numServices; 265 return numServices;
260 } catch (PackageManager.NameNotFoundException e) { 266 } catch (PackageManager.NameNotFoundException e) {
261 throw new RuntimeException("Could not get application info"); 267 throw new RuntimeException("Could not get application info");
262 } 268 }
263 } 269 }
264 270
265 private static void initConnectionAllocatorsIfNecessary(Context context) { 271 private static void initConnectionAllocatorsIfNecessary(
272 Context context, boolean inSandbox, String packageName) {
266 synchronized (ChildProcessLauncher.class) { 273 synchronized (ChildProcessLauncher.class) {
267 if (sSandboxedChildConnectionAllocator == null) { 274 if (inSandbox) {
268 sSandboxedChildConnectionAllocator = 275 if (sSandboxedChildConnectionAllocatorMap == null) {
269 new ChildConnectionAllocator(true, getNumberOfServices(c ontext, true)); 276 sSandboxedChildConnectionAllocatorMap =
277 new HashMap<String, ChildConnectionAllocator>();
278 }
279 if (!sSandboxedChildConnectionAllocatorMap.containsKey(packageNa me)) {
280 Log.w(TAG, "Create a new ChildConnectionAllocator with packa ge name = %s,"
281 + " inSandbox = true",
282 packageName);
283 sSandboxedChildConnectionAllocatorMap.put(packageName,
284 new ChildConnectionAllocator(true,
285 getNumberOfServices(context, true, packageNa me)));
286 }
287 } else if (sPrivilegedChildConnectionAllocator == null) {
288 sPrivilegedChildConnectionAllocator = new ChildConnectionAllocat or(
289 false, getNumberOfServices(context, false, packageName)) ;
270 } 290 }
271 if (sPrivilegedChildConnectionAllocator == null) { 291 // TODO(pkotwicz|hanxi): Figure out when old allocators should be re moved from
272 sPrivilegedChildConnectionAllocator = 292 // {@code sSandboxedChildConnectionAllocatorMap}.
273 new ChildConnectionAllocator(false, getNumberOfServices( context, false));
274 }
275 } 293 }
276 } 294 }
277 295
278 private static ChildConnectionAllocator getConnectionAllocator(boolean inSan dbox) { 296 /**
279 return inSandbox 297 * Note: please make sure that the Allocator has been initialized before cal ling this function.
280 ? sSandboxedChildConnectionAllocator : sPrivilegedChildConnectio nAllocator; 298 * Otherwise, always calls {@link initConnectionAllocatorsIfNecessary} first .
299 */
300 private static ChildConnectionAllocator getConnectionAllocator(
301 String packageName, boolean inSandbox) {
302 if (!inSandbox) {
303 return sPrivilegedChildConnectionAllocator;
304 }
305 return sSandboxedChildConnectionAllocatorMap.get(packageName);
306 }
307
308 /**
309 * Get the PendingSpawnQueue of the Allocator. Initialize the Allocator if n eeded.
310 */
311 private static PendingSpawnQueue getPendingSpawnQueue(Context context, Strin g packageName,
312 boolean inSandbox) {
313 initConnectionAllocatorsIfNecessary(context, inSandbox, packageName);
314 return getConnectionAllocator(packageName, inSandbox).getPendingSpawnQue ue();
281 } 315 }
282 316
283 private static ChildProcessConnection allocateConnection(Context context, bo olean inSandbox, 317 private static ChildProcessConnection allocateConnection(Context context, bo olean inSandbox,
284 ChromiumLinkerParams chromiumLinkerParams, boolean alwaysInForegroun d) { 318 ChromiumLinkerParams chromiumLinkerParams, boolean alwaysInForegroun d,
319 ChildProcessCreationParams creationParams) {
285 ChildProcessConnection.DeathCallback deathCallback = 320 ChildProcessConnection.DeathCallback deathCallback =
286 new ChildProcessConnection.DeathCallback() { 321 new ChildProcessConnection.DeathCallback() {
287 @Override 322 @Override
288 public void onChildProcessDied(ChildProcessConnection connec tion) { 323 public void onChildProcessDied(ChildProcessConnection connec tion) {
289 if (connection.getPid() != 0) { 324 if (connection.getPid() != 0) {
290 stop(connection.getPid()); 325 stop(connection.getPid());
291 } else { 326 } else {
292 freeConnection(connection); 327 freeConnection(connection);
293 } 328 }
294 } 329 }
295 }; 330 };
296 initConnectionAllocatorsIfNecessary(context); 331 String packageName = creationParams != null ? creationParams.getPackageN ame()
297 return getConnectionAllocator(inSandbox).allocate(context, deathCallback , 332 : context.getPackageName();
298 chromiumLinkerParams, alwaysInForeground, ChildProcessCreationPa rams.get()); 333 initConnectionAllocatorsIfNecessary(context, inSandbox, packageName);
334 return getConnectionAllocator(packageName, inSandbox)
335 .allocate(context, deathCallback, chromiumLinkerParams, alwaysIn Foreground,
336 creationParams);
299 } 337 }
300 338
301 private static boolean sLinkerInitialized = false; 339 private static boolean sLinkerInitialized = false;
302 private static long sLinkerLoadAddress = 0; 340 private static long sLinkerLoadAddress = 0;
303 341
304 private static ChromiumLinkerParams getLinkerParamsForNewConnection() { 342 private static ChromiumLinkerParams getLinkerParamsForNewConnection() {
305 if (!sLinkerInitialized) { 343 if (!sLinkerInitialized) {
306 if (Linker.isUsed()) { 344 if (Linker.isUsed()) {
307 sLinkerLoadAddress = Linker.getInstance().getBaseLoadAddress(); 345 sLinkerLoadAddress = Linker.getInstance().getBaseLoadAddress();
308 if (sLinkerLoadAddress == 0) { 346 if (sLinkerLoadAddress == 0) {
(...skipping 13 matching lines...) Expand all
322 waitForSharedRelros, 360 waitForSharedRelros,
323 linker.getTestRunnerClassNameForTest ing(), 361 linker.getTestRunnerClassNameForTest ing(),
324 linker.getImplementationForTesting() ); 362 linker.getImplementationForTesting() );
325 } else { 363 } else {
326 return new ChromiumLinkerParams(sLinkerLoadAddress, 364 return new ChromiumLinkerParams(sLinkerLoadAddress,
327 waitForSharedRelros); 365 waitForSharedRelros);
328 } 366 }
329 } 367 }
330 368
331 private static ChildProcessConnection allocateBoundConnection(Context contex t, 369 private static ChildProcessConnection allocateBoundConnection(Context contex t,
332 String[] commandLine, boolean inSandbox, boolean alwaysInForeground) { 370 String[] commandLine, boolean inSandbox, boolean alwaysInForeground,
371 ChildProcessCreationParams creationParams) {
333 ChromiumLinkerParams chromiumLinkerParams = getLinkerParamsForNewConnect ion(); 372 ChromiumLinkerParams chromiumLinkerParams = getLinkerParamsForNewConnect ion();
334 ChildProcessConnection connection = allocateConnection(context, inSandbo x, 373 ChildProcessConnection connection = allocateConnection(
335 chromiumLinkerParams, alwaysInForeground); 374 context, inSandbox, chromiumLinkerParams, alwaysInForeground, cr eationParams);
336 if (connection != null) { 375 if (connection != null) {
337 connection.start(commandLine); 376 connection.start(commandLine);
338 377
339 if (inSandbox && !sSandboxedChildConnectionAllocator.isFreeConnectio nAvailable()) { 378 String packageName = creationParams != null ? creationParams.getPack ageName()
379 : context.getPackageName();
380 if (inSandbox && !getConnectionAllocator(packageName, inSandbox)
381 .isFreeConnectionAvailable()) {
340 // Proactively releases all the moderate bindings once all the s andboxed services 382 // Proactively releases all the moderate bindings once all the s andboxed services
341 // are allocated, which will be very likely to have some of them killed by OOM 383 // are allocated, which will be very likely to have some of them killed by OOM
342 // killer. 384 // killer.
343 sBindingManager.releaseAllModerateBindings(); 385 sBindingManager.releaseAllModerateBindings();
344 } 386 }
345 } 387 }
346 return connection; 388 return connection;
347 } 389 }
348 390
349 private static final long FREE_CONNECTION_DELAY_MILLIS = 1; 391 private static final long FREE_CONNECTION_DELAY_MILLIS = 1;
(...skipping 13 matching lines...) Expand all
363 @Override 405 @Override
364 public void run() { 406 public void run() {
365 final PendingSpawnData pendingSpawn = freeConnectionAndDequeuePe nding(conn); 407 final PendingSpawnData pendingSpawn = freeConnectionAndDequeuePe nding(conn);
366 if (pendingSpawn != null) { 408 if (pendingSpawn != null) {
367 new Thread(new Runnable() { 409 new Thread(new Runnable() {
368 @Override 410 @Override
369 public void run() { 411 public void run() {
370 startInternal(pendingSpawn.context(), pendingSpawn.c ommandLine(), 412 startInternal(pendingSpawn.context(), pendingSpawn.c ommandLine(),
371 pendingSpawn.childProcessId(), pendingSpawn. filesToBeMapped(), 413 pendingSpawn.childProcessId(), pendingSpawn. filesToBeMapped(),
372 pendingSpawn.clientContext(), pendingSpawn.c allbackType(), 414 pendingSpawn.clientContext(), pendingSpawn.c allbackType(),
373 pendingSpawn.inSandbox()); 415 pendingSpawn.inSandbox(), pendingSpawn.getCr eationParams());
374 } 416 }
375 }).start(); 417 }).start();
376 } 418 }
377 } 419 }
378 }, FREE_CONNECTION_DELAY_MILLIS); 420 }, FREE_CONNECTION_DELAY_MILLIS);
379 } 421 }
380 422
381 private static PendingSpawnData freeConnectionAndDequeuePending(ChildProcess Connection conn) { 423 private static PendingSpawnData freeConnectionAndDequeuePending(ChildProcess Connection conn) {
382 synchronized (PendingSpawnQueue.sPendingSpawnsLock) { 424 ChildConnectionAllocator allocator = getConnectionAllocator(
383 getConnectionAllocator(conn.isInSandbox()).free(conn); 425 conn.getPackageName(), conn.isInSandbox());
384 return sPendingSpawnQueue.dequeueLocked(); 426 assert allocator != null;
385 } 427 PendingSpawnQueue pendingSpawnQueue = allocator.getPendingSpawnQueue();
428 allocator.free(conn);
429 return pendingSpawnQueue.dequeue();
Maria 2016/06/07 20:41:36 So, I think the comment you deleted from the spawn
386 } 430 }
387 431
388 // Represents an invalid process handle; same as base/process/process.h kNul lProcessHandle. 432 // Represents an invalid process handle; same as base/process/process.h kNul lProcessHandle.
389 private static final int NULL_PROCESS_HANDLE = 0; 433 private static final int NULL_PROCESS_HANDLE = 0;
390 434
391 // Map from pid to ChildService connection. 435 // Map from pid to ChildService connection.
392 private static Map<Integer, ChildProcessConnection> sServiceMap = 436 private static Map<Integer, ChildProcessConnection> sServiceMap =
393 new ConcurrentHashMap<Integer, ChildProcessConnection>(); 437 new ConcurrentHashMap<Integer, ChildProcessConnection>();
394 438
395 // A pre-allocated and pre-bound connection ready for connection setup, or n ull. 439 // A pre-allocated and pre-bound connection ready for connection setup, or n ull.
(...skipping 110 matching lines...) Expand 10 before | Expand all | Expand 10 after
506 /** 550 /**
507 * Called when the embedding application is sent to background. 551 * Called when the embedding application is sent to background.
508 */ 552 */
509 public static void onSentToBackground() { 553 public static void onSentToBackground() {
510 sApplicationInForeground = false; 554 sApplicationInForeground = false;
511 sBindingManager.onSentToBackground(); 555 sBindingManager.onSentToBackground();
512 } 556 }
513 557
514 /** 558 /**
515 * Starts moderate binding management. 559 * Starts moderate binding management.
560 * Note: WebAPKs and non WebAPKs share the same moderate binding pool, so th e size of the
561 * shared moderate binding pool is always set based on the number of sandbox es processes
562 * used by Chrome.
516 * @param context Android's context. 563 * @param context Android's context.
517 * @param moderateBindingTillBackgrounded true if the BindingManager should add a moderate 564 * @param moderateBindingTillBackgrounded true if the BindingManager should add a moderate
518 * binding to a render process when it is created and remove the moderate bi nding when Chrome is 565 * binding to a render process when it is created and remove the moderate bi nding when Chrome is
519 * sent to the background. 566 * sent to the background.
520 */ 567 */
521 public static void startModerateBindingManagement( 568 public static void startModerateBindingManagement(
522 Context context, boolean moderateBindingTillBackgrounded) { 569 Context context, boolean moderateBindingTillBackgrounded) {
523 sBindingManager.startModerateBindingManagement( 570 sBindingManager.startModerateBindingManagement(context,
524 context, getNumberOfServices(context, true), moderateBindingTill Backgrounded); 571 getNumberOfServices(context, true, context.getPackageName()),
572 moderateBindingTillBackgrounded);
525 } 573 }
526 574
527 /** 575 /**
528 * Called when the embedding application is brought to foreground. 576 * Called when the embedding application is brought to foreground.
529 */ 577 */
530 public static void onBroughtToForeground() { 578 public static void onBroughtToForeground() {
531 sApplicationInForeground = true; 579 sApplicationInForeground = true;
532 sBindingManager.onBroughtToForeground(); 580 sBindingManager.onBroughtToForeground();
533 } 581 }
534 582
535 /** 583 /**
536 * Returns whether the application is currently in the foreground. 584 * Returns whether the application is currently in the foreground.
537 */ 585 */
538 static boolean isApplicationInForeground() { 586 static boolean isApplicationInForeground() {
539 return sApplicationInForeground; 587 return sApplicationInForeground;
540 } 588 }
541 589
542 /** 590 /**
543 * Should be called early in startup so the work needed to spawn the child p rocess can be done 591 * Should be called early in startup so the work needed to spawn the child p rocess can be done
544 * in parallel to other startup work. Must not be called on the UI thread. S pare connection is 592 * in parallel to other startup work. Must not be called on the UI thread. S pare connection is
545 * created in sandboxed child process. 593 * created in sandboxed child process.
546 * @param context the application context used for the connection. 594 * @param context the application context used for the connection.
547 * @param params child process creation params.
548 */ 595 */
549 public static void warmUp(Context context, ChildProcessCreationParams params ) { 596 public static void warmUp(Context context) {
550 ChildProcessCreationParams.set(params);
551 synchronized (ChildProcessLauncher.class) { 597 synchronized (ChildProcessLauncher.class) {
552 assert !ThreadUtils.runningOnUiThread(); 598 assert !ThreadUtils.runningOnUiThread();
553 if (sSpareSandboxedConnection == null) { 599 if (sSpareSandboxedConnection == null) {
554 sSpareSandboxedConnection = allocateBoundConnection(context, nul l, true, false); 600 ChildProcessCreationParams params = ChildProcessCreationParams.g et();
601 if (params != null) {
602 params = params.copy();
603 }
604 sSpareSandboxedConnection = allocateBoundConnection(context, nul l, true, false,
605 params);
555 } 606 }
556 } 607 }
557 } 608 }
558 609
559 @CalledByNative 610 @CalledByNative
560 private static FileDescriptorInfo makeFdInfo( 611 private static FileDescriptorInfo makeFdInfo(
561 int id, int fd, boolean autoClose, long offset, long size) { 612 int id, int fd, boolean autoClose, long offset, long size) {
562 ParcelFileDescriptor pFd; 613 ParcelFileDescriptor pFd;
563 if (autoClose) { 614 if (autoClose) {
564 // Adopt the FD, it will be closed when we close the ParcelFileDescr iptor. 615 // Adopt the FD, it will be closed when we close the ParcelFileDescr iptor.
(...skipping 22 matching lines...) Expand all
587 */ 638 */
588 @CalledByNative 639 @CalledByNative
589 private static void start(Context context, final String[] commandLine, int c hildProcessId, 640 private static void start(Context context, final String[] commandLine, int c hildProcessId,
590 FileDescriptorInfo[] filesToBeMapped, long clientContext) { 641 FileDescriptorInfo[] filesToBeMapped, long clientContext) {
591 assert clientContext != 0; 642 assert clientContext != 0;
592 643
593 int callbackType = CALLBACK_FOR_UNKNOWN_PROCESS; 644 int callbackType = CALLBACK_FOR_UNKNOWN_PROCESS;
594 boolean inSandbox = true; 645 boolean inSandbox = true;
595 String processType = 646 String processType =
596 ContentSwitches.getSwitchValue(commandLine, ContentSwitches.SWIT CH_PROCESS_TYPE); 647 ContentSwitches.getSwitchValue(commandLine, ContentSwitches.SWIT CH_PROCESS_TYPE);
648 ChildProcessCreationParams params = null;
597 if (ContentSwitches.SWITCH_RENDERER_PROCESS.equals(processType)) { 649 if (ContentSwitches.SWITCH_RENDERER_PROCESS.equals(processType)) {
598 callbackType = CALLBACK_FOR_RENDERER_PROCESS; 650 callbackType = CALLBACK_FOR_RENDERER_PROCESS;
651 if (ChildProcessCreationParams.get() != null) {
652 params = ChildProcessCreationParams.get().copy();
653 }
599 } else if (ContentSwitches.SWITCH_GPU_PROCESS.equals(processType)) { 654 } else if (ContentSwitches.SWITCH_GPU_PROCESS.equals(processType)) {
600 callbackType = CALLBACK_FOR_GPU_PROCESS; 655 callbackType = CALLBACK_FOR_GPU_PROCESS;
601 inSandbox = false; 656 inSandbox = false;
602 } else if (ContentSwitches.SWITCH_UTILITY_PROCESS.equals(processType)) { 657 } else if (ContentSwitches.SWITCH_UTILITY_PROCESS.equals(processType)) {
603 // We only support sandboxed right now. 658 // We only support sandboxed right now.
604 callbackType = CALLBACK_FOR_UTILITY_PROCESS; 659 callbackType = CALLBACK_FOR_UTILITY_PROCESS;
605 } else { 660 } else {
606 assert false; 661 assert false;
607 } 662 }
608 663
609 startInternal(context, commandLine, childProcessId, filesToBeMapped, cli entContext, 664 startInternal(context, commandLine, childProcessId, filesToBeMapped, cli entContext,
610 callbackType, inSandbox); 665 callbackType, inSandbox, params);
611 } 666 }
612 667
613 /** 668 /**
614 * Spawns a background download process if it hasn't been started. The downl oad process will 669 * Spawns a background download process if it hasn't been started. The downl oad process will
615 * manage its own lifecyle and can outlive chrome. 670 * manage its own lifecyle and can outlive chrome.
616 * 671 *
617 * @param context Context used to obtain the application context. 672 * @param context Context used to obtain the application context.
618 * @param commandLine The child process command line argv. 673 * @param commandLine The child process command line argv.
619 */ 674 */
620 @SuppressLint("NewApi") 675 @SuppressLint("NewApi")
(...skipping 22 matching lines...) Expand all
643 context.startService(intent); 698 context.startService(intent);
644 } 699 }
645 700
646 private static void startInternal( 701 private static void startInternal(
647 Context context, 702 Context context,
648 final String[] commandLine, 703 final String[] commandLine,
649 int childProcessId, 704 int childProcessId,
650 FileDescriptorInfo[] filesToBeMapped, 705 FileDescriptorInfo[] filesToBeMapped,
651 long clientContext, 706 long clientContext,
652 int callbackType, 707 int callbackType,
653 boolean inSandbox) { 708 boolean inSandbox,
709 ChildProcessCreationParams creationParams) {
654 try { 710 try {
655 TraceEvent.begin("ChildProcessLauncher.startInternal"); 711 TraceEvent.begin("ChildProcessLauncher.startInternal");
656 712
657 ChildProcessConnection allocatedConnection = null; 713 ChildProcessConnection allocatedConnection = null;
714 String packageName = creationParams != null ? creationParams.getPack ageName()
715 : context.getPackageName();
658 synchronized (ChildProcessLauncher.class) { 716 synchronized (ChildProcessLauncher.class) {
659 if (inSandbox) { 717 if (inSandbox && sSpareSandboxedConnection != null
718 && sSpareSandboxedConnection.getPackageName().equals(pac kageName)) {
660 allocatedConnection = sSpareSandboxedConnection; 719 allocatedConnection = sSpareSandboxedConnection;
661 sSpareSandboxedConnection = null; 720 sSpareSandboxedConnection = null;
662 } 721 }
663 } 722 }
664 if (allocatedConnection == null) { 723 if (allocatedConnection == null) {
665 boolean alwaysInForeground = false; 724 boolean alwaysInForeground = false;
666 if (callbackType == CALLBACK_FOR_GPU_PROCESS) alwaysInForeground = true; 725 if (callbackType == CALLBACK_FOR_GPU_PROCESS) alwaysInForeground = true;
667 synchronized (PendingSpawnQueue.sPendingSpawnsLock) { 726 PendingSpawnQueue pendingSpawnQueue = getPendingSpawnQueue(
668 allocatedConnection = allocateBoundConnection( 727 context, packageName, inSandbox);
669 context, commandLine, inSandbox, alwaysInForeground) ; 728 allocatedConnection = allocateBoundConnection(
670 if (allocatedConnection == null) { 729 context, commandLine, inSandbox, alwaysInForeground, cre ationParams);
671 Log.d(TAG, "Allocation of new service failed. Queuing up pending spawn."); 730 if (allocatedConnection == null) {
672 sPendingSpawnQueue.enqueueLocked(new PendingSpawnData(co ntext, commandLine, 731 Log.d(TAG, "Allocation of new service failed. Queuing up pen ding spawn.");
673 childProcessId, filesToBeMapped, clientContext, 732 pendingSpawnQueue.enqueue(new PendingSpawnData(context, comm andLine,
674 callbackType, inSandbox)); 733 childProcessId, filesToBeMapped, clientContext,
675 return; 734 callbackType, inSandbox, creationParams));
676 } 735 return;
677 } 736 }
678 } 737 }
679 738
680 Log.d(TAG, "Setting up connection to process: slot=%d", 739 Log.d(TAG, "Setting up connection to process: slot=%d",
681 allocatedConnection.getServiceNumber()); 740 allocatedConnection.getServiceNumber());
682 triggerConnectionSetup(allocatedConnection, commandLine, childProces sId, 741 triggerConnectionSetup(allocatedConnection, commandLine, childProces sId,
683 filesToBeMapped, callbackType, clientContext); 742 filesToBeMapped, callbackType, clientContext);
684 } finally { 743 } finally {
685 TraceEvent.end("ChildProcessLauncher.startInternal"); 744 TraceEvent.end("ChildProcessLauncher.startInternal");
686 } 745 }
(...skipping 154 matching lines...) Expand 10 before | Expand all | Expand 10 after
841 } 900 }
842 901
843 static void logPidWarning(int pid, String message) { 902 static void logPidWarning(int pid, String message) {
844 // This class is effectively a no-op in single process mode, so don't lo g warnings there. 903 // This class is effectively a no-op in single process mode, so don't lo g warnings there.
845 if (pid > 0 && !nativeIsSingleProcess()) { 904 if (pid > 0 && !nativeIsSingleProcess()) {
846 Log.w(TAG, "%s, pid=%d", message, pid); 905 Log.w(TAG, "%s, pid=%d", message, pid);
847 } 906 }
848 } 907 }
849 908
850 @VisibleForTesting 909 @VisibleForTesting
851 static ChildProcessConnection allocateBoundConnectionForTesting(Context cont ext) { 910 static ChildProcessConnection allocateBoundConnectionForTesting(Context cont ext,
852 return allocateBoundConnection(context, null, true, false); 911 ChildProcessCreationParams creationParams) {
912 return allocateBoundConnection(context, null, true, false, creationParam s);
853 } 913 }
854 914
855 /** 915 /**
856 * Queue up a spawn requests for testing. 916 * Queue up a spawn requests for testing.
857 */ 917 */
858 @VisibleForTesting 918 @VisibleForTesting
859 static void enqueuePendingSpawnForTesting(Context context, String[] commandL ine) { 919 static void enqueuePendingSpawnForTesting(Context context, String[] commandL ine,
860 synchronized (PendingSpawnQueue.sPendingSpawnsLock) { 920 ChildProcessCreationParams creationParams, boolean inSandbox) {
861 sPendingSpawnQueue.enqueueLocked(new PendingSpawnData(context, comma ndLine, 1, 921 PendingSpawnQueue pendingSpawnQueue = getPendingSpawnQueue(context,
862 new FileDescriptorInfo[0], 0, CALLBACK_FOR_RENDERER_PROCESS, true)); 922 creationParams.getPackageName(), inSandbox);
863 } 923 pendingSpawnQueue.enqueue(new PendingSpawnData(context, commandLine, 1,
924 new FileDescriptorInfo[0], 0, CALLBACK_FOR_RENDERER_PROCESS, tru e,
925 creationParams));
864 } 926 }
865 927
866 /** @return the count of sandboxed connections managed by the allocator */ 928 /**
929 * @return the number of sandboxed connections of given {@link packageName} managed by the
930 * allocator.
931 */
867 @VisibleForTesting 932 @VisibleForTesting
868 static int allocatedConnectionsCountForTesting(Context context) { 933 static int allocatedSandboxedConnectionsCountForTesting(Context context, Str ing packageName) {
869 initConnectionAllocatorsIfNecessary(context); 934 initConnectionAllocatorsIfNecessary(context, true, packageName);
870 return sSandboxedChildConnectionAllocator.allocatedConnectionsCountForTe sting(); 935 return sSandboxedChildConnectionAllocatorMap.get(packageName)
936 .allocatedConnectionsCountForTesting();
871 } 937 }
872 938
873 /** @return the count of services set up and working */ 939 /** @return the count of services set up and working */
874 @VisibleForTesting 940 @VisibleForTesting
875 static int connectedServicesCountForTesting() { 941 static int connectedServicesCountForTesting() {
876 return sServiceMap.size(); 942 return sServiceMap.size();
877 } 943 }
878 944
879 /** @return the count of pending spawns in the queue */ 945 /**
946 * @param context The context.
947 * @param packageName The package name of the {@link ChildProcessAlocator}.
948 * @param inSandbox Whether the connection is sandboxed.
949 * @return the count of pending spawns in the queue.
950 */
880 @VisibleForTesting 951 @VisibleForTesting
881 static int pendingSpawnsCountForTesting() { 952 static int pendingSpawnsCountForTesting(Context context, String packageName,
882 synchronized (PendingSpawnQueue.sPendingSpawnsLock) { 953 boolean inSandbox) {
883 return sPendingSpawnQueue.sizeLocked(); 954 PendingSpawnQueue pendingSpawnQueue = getPendingSpawnQueue(context, pack ageName, inSandbox);
884 } 955 return pendingSpawnQueue.size();
885 } 956 }
886 957
887 /** 958 /**
888 * Kills the child process for testing. 959 * Kills the child process for testing.
889 * @return true iff the process was killed as expected 960 * @return true iff the process was killed as expected
890 */ 961 */
891 @VisibleForTesting 962 @VisibleForTesting
892 public static boolean crashProcessForTesting(int pid) { 963 public static boolean crashProcessForTesting(int pid) {
893 if (sServiceMap.get(pid) == null) return false; 964 if (sServiceMap.get(pid) == null) return false;
894 965
895 try { 966 try {
896 ((ChildProcessConnectionImpl) sServiceMap.get(pid)).crashServiceForT esting(); 967 ((ChildProcessConnectionImpl) sServiceMap.get(pid)).crashServiceForT esting();
897 } catch (RemoteException ex) { 968 } catch (RemoteException ex) {
898 return false; 969 return false;
899 } 970 }
900 971
901 return true; 972 return true;
902 } 973 }
903 974
904 private static native void nativeOnChildProcessStarted(long clientContext, i nt pid); 975 private static native void nativeOnChildProcessStarted(long clientContext, i nt pid);
905 private static native void nativeEstablishSurfacePeer( 976 private static native void nativeEstablishSurfacePeer(
906 int pid, Surface surface, int primaryID, int secondaryID); 977 int pid, Surface surface, int primaryID, int secondaryID);
907 private static native boolean nativeIsSingleProcess(); 978 private static native boolean nativeIsSingleProcess();
908 } 979 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698