blob: b85cf2cf24956c532f278b515cd3b8f25d98eae3 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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 com.android.server;
18
19import com.android.internal.app.ResolverActivity;
20import com.android.internal.util.FastXmlSerializer;
21import com.android.internal.util.XmlUtils;
22
23import org.xmlpull.v1.XmlPullParser;
24import org.xmlpull.v1.XmlPullParserException;
25import org.xmlpull.v1.XmlSerializer;
26
27import android.app.ActivityManagerNative;
28import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070033import android.content.IntentSender;
34import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.pm.ActivityInfo;
36import android.content.pm.ApplicationInfo;
37import android.content.pm.ComponentInfo;
38import android.content.pm.IPackageDataObserver;
39import android.content.pm.IPackageDeleteObserver;
40import android.content.pm.IPackageInstallObserver;
41import android.content.pm.IPackageManager;
42import android.content.pm.IPackageStatsObserver;
43import android.content.pm.InstrumentationInfo;
44import android.content.pm.PackageInfo;
45import android.content.pm.PackageManager;
46import android.content.pm.PackageStats;
47import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
48import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
49import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
50import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
51import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
52import android.content.pm.PackageParser;
53import android.content.pm.PermissionInfo;
54import android.content.pm.PermissionGroupInfo;
55import android.content.pm.ProviderInfo;
56import android.content.pm.ResolveInfo;
57import android.content.pm.ServiceInfo;
58import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.net.Uri;
60import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070061import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.Bundle;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -070063import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.HandlerThread;
65import android.os.Parcel;
66import android.os.RemoteException;
67import android.os.Environment;
68import android.os.FileObserver;
69import android.os.FileUtils;
70import android.os.Handler;
71import android.os.ParcelFileDescriptor;
72import android.os.Process;
73import android.os.ServiceManager;
74import android.os.SystemClock;
75import android.os.SystemProperties;
76import android.util.*;
77import android.view.Display;
78import android.view.WindowManager;
79
80import java.io.File;
81import java.io.FileDescriptor;
82import java.io.FileInputStream;
83import java.io.FileNotFoundException;
84import java.io.FileOutputStream;
85import java.io.FileReader;
86import java.io.FilenameFilter;
87import java.io.IOException;
88import java.io.InputStream;
89import java.io.PrintWriter;
90import java.util.ArrayList;
91import java.util.Arrays;
92import java.util.Collections;
93import java.util.Comparator;
94import java.util.Enumeration;
95import java.util.HashMap;
96import java.util.HashSet;
97import java.util.Iterator;
98import java.util.List;
99import java.util.Map;
100import java.util.Set;
101import java.util.zip.ZipEntry;
102import java.util.zip.ZipFile;
103import java.util.zip.ZipOutputStream;
104
105class PackageManagerService extends IPackageManager.Stub {
106 private static final String TAG = "PackageManager";
107 private static final boolean DEBUG_SETTINGS = false;
108 private static final boolean DEBUG_PREFERRED = false;
109
110 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
111 private static final int RADIO_UID = Process.PHONE_UID;
112 private static final int FIRST_APPLICATION_UID =
113 Process.FIRST_APPLICATION_UID;
114 private static final int MAX_APPLICATION_UIDS = 1000;
115
116 private static final boolean SHOW_INFO = false;
117
118 private static final boolean GET_CERTIFICATES = true;
119
120 private static final int REMOVE_EVENTS =
121 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
122 private static final int ADD_EVENTS =
123 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
124
125 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
126
127 static final int SCAN_MONITOR = 1<<0;
128 static final int SCAN_NO_DEX = 1<<1;
129 static final int SCAN_FORCE_DEX = 1<<2;
130 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
131 static final int SCAN_FORWARD_LOCKED = 1<<4;
The Android Open Source Project10592532009-03-18 17:39:46 -0700132 static final int SCAN_NEW_INSTALL = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
134 static final int LOG_BOOT_PROGRESS_PMS_START = 3060;
135 static final int LOG_BOOT_PROGRESS_PMS_SYSTEM_SCAN_START = 3070;
136 static final int LOG_BOOT_PROGRESS_PMS_DATA_SCAN_START = 3080;
137 static final int LOG_BOOT_PROGRESS_PMS_SCAN_END = 3090;
138 static final int LOG_BOOT_PROGRESS_PMS_READY = 3100;
139
140 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
141 Process.THREAD_PRIORITY_BACKGROUND);
142 final Handler mHandler;
143
Dianne Hackborn851a5412009-05-08 12:06:44 -0700144 final int mSdkVersion = Build.VERSION.SDK_INT;
145 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
146 ? null : Build.VERSION.CODENAME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
148 final Context mContext;
149 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700150 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 final DisplayMetrics mMetrics;
152 final int mDefParseFlags;
153 final String[] mSeparateProcesses;
154
155 // This is where all application persistent data goes.
156 final File mAppDataDir;
157
158 // This is the object monitoring the framework dir.
159 final FileObserver mFrameworkInstallObserver;
160
161 // This is the object monitoring the system app dir.
162 final FileObserver mSystemInstallObserver;
163
164 // This is the object monitoring mAppInstallDir.
165 final FileObserver mAppInstallObserver;
166
167 // This is the object monitoring mDrmAppPrivateInstallDir.
168 final FileObserver mDrmAppInstallObserver;
169
170 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
171 // LOCK HELD. Can be called with mInstallLock held.
172 final Installer mInstaller;
173
174 final File mFrameworkDir;
175 final File mSystemAppDir;
176 final File mAppInstallDir;
177
178 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
179 // apps.
180 final File mDrmAppPrivateInstallDir;
181
182 // ----------------------------------------------------------------
183
184 // Lock for state used when installing and doing other long running
185 // operations. Methods that must be called with this lock held have
186 // the prefix "LI".
187 final Object mInstallLock = new Object();
188
189 // These are the directories in the 3rd party applications installed dir
190 // that we have currently loaded packages from. Keys are the application's
191 // installed zip file (absolute codePath), and values are Package.
192 final HashMap<String, PackageParser.Package> mAppDirs =
193 new HashMap<String, PackageParser.Package>();
194
195 // Information for the parser to write more useful error messages.
196 File mScanningPath;
197 int mLastScanError;
198
199 final int[] mOutPermissions = new int[3];
200
201 // ----------------------------------------------------------------
202
203 // Keys are String (package name), values are Package. This also serves
204 // as the lock for the global state. Methods that must be called with
205 // this lock held have the prefix "LP".
206 final HashMap<String, PackageParser.Package> mPackages =
207 new HashMap<String, PackageParser.Package>();
208
209 final Settings mSettings;
210 boolean mRestoredSettings;
211 boolean mReportedUidError;
212
213 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
214 int[] mGlobalGids;
215
216 // These are the built-in uid -> permission mappings that were read from the
217 // etc/permissions.xml file.
218 final SparseArray<HashSet<String>> mSystemPermissions =
219 new SparseArray<HashSet<String>>();
220
221 // These are the built-in shared libraries that were read from the
222 // etc/permissions.xml file.
223 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
224
225 // All available activities, for your resolving pleasure.
226 final ActivityIntentResolver mActivities =
227 new ActivityIntentResolver();
228
229 // All available receivers, for your resolving pleasure.
230 final ActivityIntentResolver mReceivers =
231 new ActivityIntentResolver();
232
233 // All available services, for your resolving pleasure.
234 final ServiceIntentResolver mServices = new ServiceIntentResolver();
235
236 // Keys are String (provider class name), values are Provider.
237 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
238 new HashMap<ComponentName, PackageParser.Provider>();
239
240 // Mapping from provider base names (first directory in content URI codePath)
241 // to the provider information.
242 final HashMap<String, PackageParser.Provider> mProviders =
243 new HashMap<String, PackageParser.Provider>();
244
245 // Mapping from instrumentation class names to info about them.
246 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
247 new HashMap<ComponentName, PackageParser.Instrumentation>();
248
249 // Mapping from permission names to info about them.
250 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
251 new HashMap<String, PackageParser.PermissionGroup>();
252
Dianne Hackborn854060af2009-07-09 18:14:31 -0700253 // Broadcast actions that are only available to the system.
254 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 boolean mSystemReady;
257 boolean mSafeMode;
258 boolean mHasSystemUidErrors;
259
260 ApplicationInfo mAndroidApplication;
261 final ActivityInfo mResolveActivity = new ActivityInfo();
262 final ResolveInfo mResolveInfo = new ResolveInfo();
263 ComponentName mResolveComponentName;
264 PackageParser.Package mPlatformPackage;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700265 private boolean mCompatibilityModeEnabled = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 public static final IPackageManager main(Context context, boolean factoryTest) {
268 PackageManagerService m = new PackageManagerService(context, factoryTest);
269 ServiceManager.addService("package", m);
270 return m;
271 }
272
273 static String[] splitString(String str, char sep) {
274 int count = 1;
275 int i = 0;
276 while ((i=str.indexOf(sep, i)) >= 0) {
277 count++;
278 i++;
279 }
280
281 String[] res = new String[count];
282 i=0;
283 count = 0;
284 int lastI=0;
285 while ((i=str.indexOf(sep, i)) >= 0) {
286 res[count] = str.substring(lastI, i);
287 count++;
288 i++;
289 lastI = i;
290 }
291 res[count] = str.substring(lastI, str.length());
292 return res;
293 }
294
295 public PackageManagerService(Context context, boolean factoryTest) {
296 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_START,
297 SystemClock.uptimeMillis());
298
299 if (mSdkVersion <= 0) {
300 Log.w(TAG, "**** ro.build.version.sdk not set!");
301 }
302
303 mContext = context;
304 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700305 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 mMetrics = new DisplayMetrics();
307 mSettings = new Settings();
308 mSettings.addSharedUserLP("android.uid.system",
309 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
310 mSettings.addSharedUserLP("android.uid.phone",
311 MULTIPLE_APPLICATION_UIDS
312 ? RADIO_UID : FIRST_APPLICATION_UID,
313 ApplicationInfo.FLAG_SYSTEM);
314
315 String separateProcesses = SystemProperties.get("debug.separate_processes");
316 if (separateProcesses != null && separateProcesses.length() > 0) {
317 if ("*".equals(separateProcesses)) {
318 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
319 mSeparateProcesses = null;
320 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
321 } else {
322 mDefParseFlags = 0;
323 mSeparateProcesses = separateProcesses.split(",");
324 Log.w(TAG, "Running with debug.separate_processes: "
325 + separateProcesses);
326 }
327 } else {
328 mDefParseFlags = 0;
329 mSeparateProcesses = null;
330 }
331
332 Installer installer = new Installer();
333 // Little hacky thing to check if installd is here, to determine
334 // whether we are running on the simulator and thus need to take
335 // care of building the /data file structure ourself.
336 // (apparently the sim now has a working installer)
337 if (installer.ping() && Process.supportsProcesses()) {
338 mInstaller = installer;
339 } else {
340 mInstaller = null;
341 }
342
343 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
344 Display d = wm.getDefaultDisplay();
345 d.getMetrics(mMetrics);
346
347 synchronized (mInstallLock) {
348 synchronized (mPackages) {
349 mHandlerThread.start();
350 mHandler = new Handler(mHandlerThread.getLooper());
351
352 File dataDir = Environment.getDataDirectory();
353 mAppDataDir = new File(dataDir, "data");
354 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
355
356 if (mInstaller == null) {
357 // Make sure these dirs exist, when we are running in
358 // the simulator.
359 // Make a wide-open directory for random misc stuff.
360 File miscDir = new File(dataDir, "misc");
361 miscDir.mkdirs();
362 mAppDataDir.mkdirs();
363 mDrmAppPrivateInstallDir.mkdirs();
364 }
365
366 readPermissions();
367
368 mRestoredSettings = mSettings.readLP();
369 long startTime = SystemClock.uptimeMillis();
370
371 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
372 startTime);
373
374 int scanMode = SCAN_MONITOR;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700375 if (mNoDexOpt) {
376 Log.w(TAG, "Running ENG build: no pre-dexopt!");
377 scanMode |= SCAN_NO_DEX;
378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379
380 final HashSet<String> libFiles = new HashSet<String>();
381
382 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
383
384 if (mInstaller != null) {
385 /**
386 * Out of paranoia, ensure that everything in the boot class
387 * path has been dexed.
388 */
389 String bootClassPath = System.getProperty("java.boot.class.path");
390 if (bootClassPath != null) {
391 String[] paths = splitString(bootClassPath, ':');
392 for (int i=0; i<paths.length; i++) {
393 try {
394 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
395 libFiles.add(paths[i]);
396 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
397 }
398 } catch (FileNotFoundException e) {
399 Log.w(TAG, "Boot class path not found: " + paths[i]);
400 } catch (IOException e) {
401 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
402 }
403 }
404 } else {
405 Log.w(TAG, "No BOOTCLASSPATH found!");
406 }
407
408 /**
409 * Also ensure all external libraries have had dexopt run on them.
410 */
411 if (mSharedLibraries.size() > 0) {
412 Iterator<String> libs = mSharedLibraries.values().iterator();
413 while (libs.hasNext()) {
414 String lib = libs.next();
415 try {
416 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
417 libFiles.add(lib);
418 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
419 }
420 } catch (FileNotFoundException e) {
421 Log.w(TAG, "Library not found: " + lib);
422 } catch (IOException e) {
423 Log.w(TAG, "Exception reading library: " + lib, e);
424 }
425 }
426 }
427
428 // Gross hack for now: we know this file doesn't contain any
429 // code, so don't dexopt it to avoid the resulting log spew.
430 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
431
432 /**
433 * And there are a number of commands implemented in Java, which
434 * we currently need to do the dexopt on so that they can be
435 * run from a non-root shell.
436 */
437 String[] frameworkFiles = mFrameworkDir.list();
438 if (frameworkFiles != null && mInstaller != null) {
439 for (int i=0; i<frameworkFiles.length; i++) {
440 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
441 String path = libPath.getPath();
442 // Skip the file if we alrady did it.
443 if (libFiles.contains(path)) {
444 continue;
445 }
446 // Skip the file if it is not a type we want to dexopt.
447 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
448 continue;
449 }
450 try {
451 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
452 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
453 }
454 } catch (FileNotFoundException e) {
455 Log.w(TAG, "Jar not found: " + path);
456 } catch (IOException e) {
457 Log.w(TAG, "Exception reading jar: " + path, e);
458 }
459 }
460 }
461 }
462
463 mFrameworkInstallObserver = new AppDirObserver(
464 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
465 mFrameworkInstallObserver.startWatching();
466 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
467 scanMode | SCAN_NO_DEX);
468 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
469 mSystemInstallObserver = new AppDirObserver(
470 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
471 mSystemInstallObserver.startWatching();
472 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
473 mAppInstallDir = new File(dataDir, "app");
474 if (mInstaller == null) {
475 // Make sure these dirs exist, when we are running in
476 // the simulator.
477 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
478 }
479 //look for any incomplete package installations
480 ArrayList<String> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
481 //clean up list
482 for(int i = 0; i < deletePkgsList.size(); i++) {
483 //clean up here
484 cleanupInstallFailedPackage(deletePkgsList.get(i));
485 }
486 //delete tmp files
487 deleteTempPackageFiles();
488
489 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_DATA_SCAN_START,
490 SystemClock.uptimeMillis());
491 mAppInstallObserver = new AppDirObserver(
492 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
493 mAppInstallObserver.startWatching();
494 scanDirLI(mAppInstallDir, 0, scanMode);
495
496 mDrmAppInstallObserver = new AppDirObserver(
497 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
498 mDrmAppInstallObserver.startWatching();
499 scanDirLI(mDrmAppPrivateInstallDir, 0, scanMode);
500
501 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_SCAN_END,
502 SystemClock.uptimeMillis());
503 Log.i(TAG, "Time to scan packages: "
504 + ((SystemClock.uptimeMillis()-startTime)/1000f)
505 + " seconds");
506
507 updatePermissionsLP();
508
509 mSettings.writeLP();
510
511 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_READY,
512 SystemClock.uptimeMillis());
513
514 // Now after opening every single application zip, make sure they
515 // are all flushed. Not really needed, but keeps things nice and
516 // tidy.
517 Runtime.getRuntime().gc();
518 } // synchronized (mPackages)
519 } // synchronized (mInstallLock)
520 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 @Override
523 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
524 throws RemoteException {
525 try {
526 return super.onTransact(code, data, reply, flags);
527 } catch (RuntimeException e) {
528 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
529 Log.e(TAG, "Package Manager Crash", e);
530 }
531 throw e;
532 }
533 }
534
535 void cleanupInstallFailedPackage(String packageName) {
536 if (mInstaller != null) {
537 int retCode = mInstaller.remove(packageName);
538 if (retCode < 0) {
539 Log.w(TAG, "Couldn't remove app data directory for package: "
540 + packageName + ", retcode=" + retCode);
541 }
542 } else {
543 //for emulator
544 PackageParser.Package pkg = mPackages.get(packageName);
545 File dataDir = new File(pkg.applicationInfo.dataDir);
546 dataDir.delete();
547 }
548 mSettings.removePackageLP(packageName);
549 }
550
551 void readPermissions() {
552 // Read permissions from .../etc/permission directory.
553 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
554 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
555 Log.w(TAG, "No directory " + libraryDir + ", skipping");
556 return;
557 }
558 if (!libraryDir.canRead()) {
559 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
560 return;
561 }
562
563 // Iterate over the files in the directory and scan .xml files
564 for (File f : libraryDir.listFiles()) {
565 // We'll read platform.xml last
566 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
567 continue;
568 }
569
570 if (!f.getPath().endsWith(".xml")) {
571 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
572 continue;
573 }
574 if (!f.canRead()) {
575 Log.w(TAG, "Permissions library file " + f + " cannot be read");
576 continue;
577 }
578
579 readPermissionsFromXml(f);
580 }
581
582 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
583 final File permFile = new File(Environment.getRootDirectory(),
584 "etc/permissions/platform.xml");
585 readPermissionsFromXml(permFile);
586 }
587
588 private void readPermissionsFromXml(File permFile) {
589 FileReader permReader = null;
590 try {
591 permReader = new FileReader(permFile);
592 } catch (FileNotFoundException e) {
593 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
594 return;
595 }
596
597 try {
598 XmlPullParser parser = Xml.newPullParser();
599 parser.setInput(permReader);
600
601 XmlUtils.beginDocument(parser, "permissions");
602
603 while (true) {
604 XmlUtils.nextElement(parser);
605 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
606 break;
607 }
608
609 String name = parser.getName();
610 if ("group".equals(name)) {
611 String gidStr = parser.getAttributeValue(null, "gid");
612 if (gidStr != null) {
613 int gid = Integer.parseInt(gidStr);
614 mGlobalGids = appendInt(mGlobalGids, gid);
615 } else {
616 Log.w(TAG, "<group> without gid at "
617 + parser.getPositionDescription());
618 }
619
620 XmlUtils.skipCurrentTag(parser);
621 continue;
622 } else if ("permission".equals(name)) {
623 String perm = parser.getAttributeValue(null, "name");
624 if (perm == null) {
625 Log.w(TAG, "<permission> without name at "
626 + parser.getPositionDescription());
627 XmlUtils.skipCurrentTag(parser);
628 continue;
629 }
630 perm = perm.intern();
631 readPermission(parser, perm);
632
633 } else if ("assign-permission".equals(name)) {
634 String perm = parser.getAttributeValue(null, "name");
635 if (perm == null) {
636 Log.w(TAG, "<assign-permission> without name at "
637 + parser.getPositionDescription());
638 XmlUtils.skipCurrentTag(parser);
639 continue;
640 }
641 String uidStr = parser.getAttributeValue(null, "uid");
642 if (uidStr == null) {
643 Log.w(TAG, "<assign-permission> without uid at "
644 + parser.getPositionDescription());
645 XmlUtils.skipCurrentTag(parser);
646 continue;
647 }
648 int uid = Process.getUidForName(uidStr);
649 if (uid < 0) {
650 Log.w(TAG, "<assign-permission> with unknown uid \""
651 + uidStr + "\" at "
652 + parser.getPositionDescription());
653 XmlUtils.skipCurrentTag(parser);
654 continue;
655 }
656 perm = perm.intern();
657 HashSet<String> perms = mSystemPermissions.get(uid);
658 if (perms == null) {
659 perms = new HashSet<String>();
660 mSystemPermissions.put(uid, perms);
661 }
662 perms.add(perm);
663 XmlUtils.skipCurrentTag(parser);
664
665 } else if ("library".equals(name)) {
666 String lname = parser.getAttributeValue(null, "name");
667 String lfile = parser.getAttributeValue(null, "file");
668 if (lname == null) {
669 Log.w(TAG, "<library> without name at "
670 + parser.getPositionDescription());
671 } else if (lfile == null) {
672 Log.w(TAG, "<library> without file at "
673 + parser.getPositionDescription());
674 } else {
675 Log.i(TAG, "Got library " + lname + " in " + lfile);
676 this.mSharedLibraries.put(lname, lfile);
677 }
678 XmlUtils.skipCurrentTag(parser);
679 continue;
680
681 } else {
682 XmlUtils.skipCurrentTag(parser);
683 continue;
684 }
685
686 }
687 } catch (XmlPullParserException e) {
688 Log.w(TAG, "Got execption parsing permissions.", e);
689 } catch (IOException e) {
690 Log.w(TAG, "Got execption parsing permissions.", e);
691 }
692 }
693
694 void readPermission(XmlPullParser parser, String name)
695 throws IOException, XmlPullParserException {
696
697 name = name.intern();
698
699 BasePermission bp = mSettings.mPermissions.get(name);
700 if (bp == null) {
701 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
702 mSettings.mPermissions.put(name, bp);
703 }
704 int outerDepth = parser.getDepth();
705 int type;
706 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
707 && (type != XmlPullParser.END_TAG
708 || parser.getDepth() > outerDepth)) {
709 if (type == XmlPullParser.END_TAG
710 || type == XmlPullParser.TEXT) {
711 continue;
712 }
713
714 String tagName = parser.getName();
715 if ("group".equals(tagName)) {
716 String gidStr = parser.getAttributeValue(null, "gid");
717 if (gidStr != null) {
718 int gid = Process.getGidForName(gidStr);
719 bp.gids = appendInt(bp.gids, gid);
720 } else {
721 Log.w(TAG, "<group> without gid at "
722 + parser.getPositionDescription());
723 }
724 }
725 XmlUtils.skipCurrentTag(parser);
726 }
727 }
728
729 static int[] appendInt(int[] cur, int val) {
730 if (cur == null) {
731 return new int[] { val };
732 }
733 final int N = cur.length;
734 for (int i=0; i<N; i++) {
735 if (cur[i] == val) {
736 return cur;
737 }
738 }
739 int[] ret = new int[N+1];
740 System.arraycopy(cur, 0, ret, 0, N);
741 ret[N] = val;
742 return ret;
743 }
744
745 static int[] appendInts(int[] cur, int[] add) {
746 if (add == null) return cur;
747 if (cur == null) return add;
748 final int N = add.length;
749 for (int i=0; i<N; i++) {
750 cur = appendInt(cur, add[i]);
751 }
752 return cur;
753 }
754
755 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
756 final PackageSetting ps = (PackageSetting)p.mExtras;
757 if (ps == null) {
758 return null;
759 }
760 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
761 return PackageParser.generatePackageInfo(p, gp.gids, flags);
762 }
763
764 public PackageInfo getPackageInfo(String packageName, int flags) {
765 synchronized (mPackages) {
766 PackageParser.Package p = mPackages.get(packageName);
767 if (Config.LOGV) Log.v(
768 TAG, "getApplicationInfo " + packageName
769 + ": " + p);
770 if (p != null) {
771 return generatePackageInfo(p, flags);
772 }
773 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
774 return generatePackageInfoFromSettingsLP(packageName, flags);
775 }
776 }
777 return null;
778 }
779
780 public int getPackageUid(String packageName) {
781 synchronized (mPackages) {
782 PackageParser.Package p = mPackages.get(packageName);
783 if(p != null) {
784 return p.applicationInfo.uid;
785 }
786 PackageSetting ps = mSettings.mPackages.get(packageName);
787 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
788 return -1;
789 }
790 p = ps.pkg;
791 return p != null ? p.applicationInfo.uid : -1;
792 }
793 }
794
795 public int[] getPackageGids(String packageName) {
796 synchronized (mPackages) {
797 PackageParser.Package p = mPackages.get(packageName);
798 if (Config.LOGV) Log.v(
799 TAG, "getApplicationInfo " + packageName
800 + ": " + p);
801 if (p != null) {
802 final PackageSetting ps = (PackageSetting)p.mExtras;
803 final SharedUserSetting suid = ps.sharedUser;
804 return suid != null ? suid.gids : ps.gids;
805 }
806 }
807 // stupid thing to indicate an error.
808 return new int[0];
809 }
810
811 public PermissionInfo getPermissionInfo(String name, int flags) {
812 synchronized (mPackages) {
813 final BasePermission p = mSettings.mPermissions.get(name);
814 if (p != null && p.perm != null) {
815 return PackageParser.generatePermissionInfo(p.perm, flags);
816 }
817 return null;
818 }
819 }
820
821 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
822 synchronized (mPackages) {
823 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
824 for (BasePermission p : mSettings.mPermissions.values()) {
825 if (group == null) {
826 if (p.perm.info.group == null) {
827 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
828 }
829 } else {
830 if (group.equals(p.perm.info.group)) {
831 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
832 }
833 }
834 }
835
836 if (out.size() > 0) {
837 return out;
838 }
839 return mPermissionGroups.containsKey(group) ? out : null;
840 }
841 }
842
843 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
844 synchronized (mPackages) {
845 return PackageParser.generatePermissionGroupInfo(
846 mPermissionGroups.get(name), flags);
847 }
848 }
849
850 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
851 synchronized (mPackages) {
852 final int N = mPermissionGroups.size();
853 ArrayList<PermissionGroupInfo> out
854 = new ArrayList<PermissionGroupInfo>(N);
855 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
856 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
857 }
858 return out;
859 }
860 }
861
862 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
863 PackageSetting ps = mSettings.mPackages.get(packageName);
864 if(ps != null) {
865 if(ps.pkg == null) {
866 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
867 if(pInfo != null) {
868 return pInfo.applicationInfo;
869 }
870 return null;
871 }
872 return PackageParser.generateApplicationInfo(ps.pkg, flags);
873 }
874 return null;
875 }
876
877 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
878 PackageSetting ps = mSettings.mPackages.get(packageName);
879 if(ps != null) {
880 if(ps.pkg == null) {
881 ps.pkg = new PackageParser.Package(packageName);
882 ps.pkg.applicationInfo.packageName = packageName;
883 }
884 return generatePackageInfo(ps.pkg, flags);
885 }
886 return null;
887 }
888
889 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
890 synchronized (mPackages) {
891 PackageParser.Package p = mPackages.get(packageName);
892 if (Config.LOGV) Log.v(
893 TAG, "getApplicationInfo " + packageName
894 + ": " + p);
895 if (p != null) {
896 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700897 ApplicationInfo appInfo = PackageParser.generateApplicationInfo(p, flags);
898 if (!mCompatibilityModeEnabled) {
899 appInfo.disableCompatibilityMode();
900 }
901 return appInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
903 if ("android".equals(packageName)||"system".equals(packageName)) {
904 return mAndroidApplication;
905 }
906 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
907 return generateApplicationInfoFromSettingsLP(packageName, flags);
908 }
909 }
910 return null;
911 }
912
913
914 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
915 mContext.enforceCallingOrSelfPermission(
916 android.Manifest.permission.CLEAR_APP_CACHE, null);
917 // Queue up an async operation since clearing cache may take a little while.
918 mHandler.post(new Runnable() {
919 public void run() {
920 mHandler.removeCallbacks(this);
921 int retCode = -1;
922 if (mInstaller != null) {
923 retCode = mInstaller.freeCache(freeStorageSize);
924 if (retCode < 0) {
925 Log.w(TAG, "Couldn't clear application caches");
926 }
927 } //end if mInstaller
928 if (observer != null) {
929 try {
930 observer.onRemoveCompleted(null, (retCode >= 0));
931 } catch (RemoteException e) {
932 Log.w(TAG, "RemoveException when invoking call back");
933 }
934 }
935 }
936 });
937 }
938
Suchi Amalapurapubc806f62009-06-17 15:18:19 -0700939 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -0700940 mContext.enforceCallingOrSelfPermission(
941 android.Manifest.permission.CLEAR_APP_CACHE, null);
942 // Queue up an async operation since clearing cache may take a little while.
943 mHandler.post(new Runnable() {
944 public void run() {
945 mHandler.removeCallbacks(this);
946 int retCode = -1;
947 if (mInstaller != null) {
948 retCode = mInstaller.freeCache(freeStorageSize);
949 if (retCode < 0) {
950 Log.w(TAG, "Couldn't clear application caches");
951 }
952 }
953 if(pi != null) {
954 try {
955 // Callback via pending intent
956 int code = (retCode >= 0) ? 1 : 0;
957 pi.sendIntent(null, code, null,
958 null, null);
959 } catch (SendIntentException e1) {
960 Log.i(TAG, "Failed to send pending intent");
961 }
962 }
963 }
964 });
965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966
967 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
968 synchronized (mPackages) {
969 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700970
971 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700973 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 }
975 if (mResolveComponentName.equals(component)) {
976 return mResolveActivity;
977 }
978 }
979 return null;
980 }
981
982 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
983 synchronized (mPackages) {
984 PackageParser.Activity a = mReceivers.mActivities.get(component);
985 if (Config.LOGV) Log.v(
986 TAG, "getReceiverInfo " + component + ": " + a);
987 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
988 return PackageParser.generateActivityInfo(a, flags);
989 }
990 }
991 return null;
992 }
993
994 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
995 synchronized (mPackages) {
996 PackageParser.Service s = mServices.mServices.get(component);
997 if (Config.LOGV) Log.v(
998 TAG, "getServiceInfo " + component + ": " + s);
999 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1000 return PackageParser.generateServiceInfo(s, flags);
1001 }
1002 }
1003 return null;
1004 }
1005
1006 public String[] getSystemSharedLibraryNames() {
1007 Set<String> libSet;
1008 synchronized (mPackages) {
1009 libSet = mSharedLibraries.keySet();
1010 }
1011 int size = libSet.size();
1012 if (size > 0) {
1013 String[] libs = new String[size];
1014 libSet.toArray(libs);
1015 return libs;
1016 }
1017 return null;
1018 }
1019
1020 public int checkPermission(String permName, String pkgName) {
1021 synchronized (mPackages) {
1022 PackageParser.Package p = mPackages.get(pkgName);
1023 if (p != null && p.mExtras != null) {
1024 PackageSetting ps = (PackageSetting)p.mExtras;
1025 if (ps.sharedUser != null) {
1026 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1027 return PackageManager.PERMISSION_GRANTED;
1028 }
1029 } else if (ps.grantedPermissions.contains(permName)) {
1030 return PackageManager.PERMISSION_GRANTED;
1031 }
1032 }
1033 }
1034 return PackageManager.PERMISSION_DENIED;
1035 }
1036
1037 public int checkUidPermission(String permName, int uid) {
1038 synchronized (mPackages) {
1039 Object obj = mSettings.getUserIdLP(uid);
1040 if (obj != null) {
1041 if (obj instanceof SharedUserSetting) {
1042 SharedUserSetting sus = (SharedUserSetting)obj;
1043 if (sus.grantedPermissions.contains(permName)) {
1044 return PackageManager.PERMISSION_GRANTED;
1045 }
1046 } else if (obj instanceof PackageSetting) {
1047 PackageSetting ps = (PackageSetting)obj;
1048 if (ps.grantedPermissions.contains(permName)) {
1049 return PackageManager.PERMISSION_GRANTED;
1050 }
1051 }
1052 } else {
1053 HashSet<String> perms = mSystemPermissions.get(uid);
1054 if (perms != null && perms.contains(permName)) {
1055 return PackageManager.PERMISSION_GRANTED;
1056 }
1057 }
1058 }
1059 return PackageManager.PERMISSION_DENIED;
1060 }
1061
1062 private BasePermission findPermissionTreeLP(String permName) {
1063 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1064 if (permName.startsWith(bp.name) &&
1065 permName.length() > bp.name.length() &&
1066 permName.charAt(bp.name.length()) == '.') {
1067 return bp;
1068 }
1069 }
1070 return null;
1071 }
1072
1073 private BasePermission checkPermissionTreeLP(String permName) {
1074 if (permName != null) {
1075 BasePermission bp = findPermissionTreeLP(permName);
1076 if (bp != null) {
1077 if (bp.uid == Binder.getCallingUid()) {
1078 return bp;
1079 }
1080 throw new SecurityException("Calling uid "
1081 + Binder.getCallingUid()
1082 + " is not allowed to add to permission tree "
1083 + bp.name + " owned by uid " + bp.uid);
1084 }
1085 }
1086 throw new SecurityException("No permission tree found for " + permName);
1087 }
1088
1089 public boolean addPermission(PermissionInfo info) {
1090 synchronized (mPackages) {
1091 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1092 throw new SecurityException("Label must be specified in permission");
1093 }
1094 BasePermission tree = checkPermissionTreeLP(info.name);
1095 BasePermission bp = mSettings.mPermissions.get(info.name);
1096 boolean added = bp == null;
1097 if (added) {
1098 bp = new BasePermission(info.name, tree.sourcePackage,
1099 BasePermission.TYPE_DYNAMIC);
1100 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1101 throw new SecurityException(
1102 "Not allowed to modify non-dynamic permission "
1103 + info.name);
1104 }
1105 bp.perm = new PackageParser.Permission(tree.perm.owner,
1106 new PermissionInfo(info));
1107 bp.perm.info.packageName = tree.perm.info.packageName;
1108 bp.uid = tree.uid;
1109 if (added) {
1110 mSettings.mPermissions.put(info.name, bp);
1111 }
1112 mSettings.writeLP();
1113 return added;
1114 }
1115 }
1116
1117 public void removePermission(String name) {
1118 synchronized (mPackages) {
1119 checkPermissionTreeLP(name);
1120 BasePermission bp = mSettings.mPermissions.get(name);
1121 if (bp != null) {
1122 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1123 throw new SecurityException(
1124 "Not allowed to modify non-dynamic permission "
1125 + name);
1126 }
1127 mSettings.mPermissions.remove(name);
1128 mSettings.writeLP();
1129 }
1130 }
1131 }
1132
Dianne Hackborn854060af2009-07-09 18:14:31 -07001133 public boolean isProtectedBroadcast(String actionName) {
1134 synchronized (mPackages) {
1135 return mProtectedBroadcasts.contains(actionName);
1136 }
1137 }
1138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 public int checkSignatures(String pkg1, String pkg2) {
1140 synchronized (mPackages) {
1141 PackageParser.Package p1 = mPackages.get(pkg1);
1142 PackageParser.Package p2 = mPackages.get(pkg2);
1143 if (p1 == null || p1.mExtras == null
1144 || p2 == null || p2.mExtras == null) {
1145 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1146 }
1147 return checkSignaturesLP(p1, p2);
1148 }
1149 }
1150
1151 int checkSignaturesLP(PackageParser.Package p1, PackageParser.Package p2) {
1152 if (p1.mSignatures == null) {
1153 return p2.mSignatures == null
1154 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1155 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1156 }
1157 if (p2.mSignatures == null) {
1158 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1159 }
1160 final int N1 = p1.mSignatures.length;
1161 final int N2 = p2.mSignatures.length;
1162 for (int i=0; i<N1; i++) {
1163 boolean match = false;
1164 for (int j=0; j<N2; j++) {
1165 if (p1.mSignatures[i].equals(p2.mSignatures[j])) {
1166 match = true;
1167 break;
1168 }
1169 }
1170 if (!match) {
1171 return PackageManager.SIGNATURE_NO_MATCH;
1172 }
1173 }
1174 return PackageManager.SIGNATURE_MATCH;
1175 }
1176
1177 public String[] getPackagesForUid(int uid) {
1178 synchronized (mPackages) {
1179 Object obj = mSettings.getUserIdLP(uid);
1180 if (obj instanceof SharedUserSetting) {
1181 SharedUserSetting sus = (SharedUserSetting)obj;
1182 final int N = sus.packages.size();
1183 String[] res = new String[N];
1184 Iterator<PackageSetting> it = sus.packages.iterator();
1185 int i=0;
1186 while (it.hasNext()) {
1187 res[i++] = it.next().name;
1188 }
1189 return res;
1190 } else if (obj instanceof PackageSetting) {
1191 PackageSetting ps = (PackageSetting)obj;
1192 return new String[] { ps.name };
1193 }
1194 }
1195 return null;
1196 }
1197
1198 public String getNameForUid(int uid) {
1199 synchronized (mPackages) {
1200 Object obj = mSettings.getUserIdLP(uid);
1201 if (obj instanceof SharedUserSetting) {
1202 SharedUserSetting sus = (SharedUserSetting)obj;
1203 return sus.name + ":" + sus.userId;
1204 } else if (obj instanceof PackageSetting) {
1205 PackageSetting ps = (PackageSetting)obj;
1206 return ps.name;
1207 }
1208 }
1209 return null;
1210 }
1211
1212 public int getUidForSharedUser(String sharedUserName) {
1213 if(sharedUserName == null) {
1214 return -1;
1215 }
1216 synchronized (mPackages) {
1217 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1218 if(suid == null) {
1219 return -1;
1220 }
1221 return suid.userId;
1222 }
1223 }
1224
1225 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1226 int flags) {
1227 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001228 return chooseBestActivity(intent, resolvedType, flags, query);
1229 }
1230
Mihai Predaeae850c2009-05-13 10:13:48 +02001231 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1232 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 if (query != null) {
1234 final int N = query.size();
1235 if (N == 1) {
1236 return query.get(0);
1237 } else if (N > 1) {
1238 // If there is more than one activity with the same priority,
1239 // then let the user decide between them.
1240 ResolveInfo r0 = query.get(0);
1241 ResolveInfo r1 = query.get(1);
1242 if (false) {
1243 System.out.println(r0.activityInfo.name +
1244 "=" + r0.priority + " vs " +
1245 r1.activityInfo.name +
1246 "=" + r1.priority);
1247 }
1248 // If the first activity has a higher priority, or a different
1249 // default, then it is always desireable to pick it.
1250 if (r0.priority != r1.priority
1251 || r0.preferredOrder != r1.preferredOrder
1252 || r0.isDefault != r1.isDefault) {
1253 return query.get(0);
1254 }
1255 // If we have saved a preference for a preferred activity for
1256 // this Intent, use that.
1257 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1258 flags, query, r0.priority);
1259 if (ri != null) {
1260 return ri;
1261 }
1262 return mResolveInfo;
1263 }
1264 }
1265 return null;
1266 }
1267
1268 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1269 int flags, List<ResolveInfo> query, int priority) {
1270 synchronized (mPackages) {
1271 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1272 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001273 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1275 if (prefs != null && prefs.size() > 0) {
1276 // First figure out how good the original match set is.
1277 // We will only allow preferred activities that came
1278 // from the same match quality.
1279 int match = 0;
1280 final int N = query.size();
1281 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1282 for (int j=0; j<N; j++) {
1283 ResolveInfo ri = query.get(j);
1284 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1285 + ": 0x" + Integer.toHexString(match));
1286 if (ri.match > match) match = ri.match;
1287 }
1288 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1289 + Integer.toHexString(match));
1290 match &= IntentFilter.MATCH_CATEGORY_MASK;
1291 final int M = prefs.size();
1292 for (int i=0; i<M; i++) {
1293 PreferredActivity pa = prefs.get(i);
1294 if (pa.mMatch != match) {
1295 continue;
1296 }
1297 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1298 if (DEBUG_PREFERRED) {
1299 Log.v(TAG, "Got preferred activity:");
1300 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1301 }
1302 if (ai != null) {
1303 for (int j=0; j<N; j++) {
1304 ResolveInfo ri = query.get(j);
1305 if (!ri.activityInfo.applicationInfo.packageName
1306 .equals(ai.applicationInfo.packageName)) {
1307 continue;
1308 }
1309 if (!ri.activityInfo.name.equals(ai.name)) {
1310 continue;
1311 }
1312
1313 // Okay we found a previously set preferred app.
1314 // If the result set is different from when this
1315 // was created, we need to clear it and re-ask the
1316 // user their preference.
1317 if (!pa.sameSet(query, priority)) {
1318 Log.i(TAG, "Result set changed, dropping preferred activity for "
1319 + intent + " type " + resolvedType);
1320 mSettings.mPreferredActivities.removeFilter(pa);
1321 return null;
1322 }
1323
1324 // Yay!
1325 return ri;
1326 }
1327 }
1328 }
1329 }
1330 }
1331 return null;
1332 }
1333
1334 public List<ResolveInfo> queryIntentActivities(Intent intent,
1335 String resolvedType, int flags) {
1336 ComponentName comp = intent.getComponent();
1337 if (comp != null) {
1338 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1339 ActivityInfo ai = getActivityInfo(comp, flags);
1340 if (ai != null) {
1341 ResolveInfo ri = new ResolveInfo();
1342 ri.activityInfo = ai;
1343 list.add(ri);
1344 }
1345 return list;
1346 }
1347
1348 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001349 String pkgName = intent.getPackage();
1350 if (pkgName == null) {
1351 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1352 resolvedType, flags);
1353 }
1354 PackageParser.Package pkg = mPackages.get(pkgName);
1355 if (pkg != null) {
1356 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1357 resolvedType, flags, pkg.activities);
1358 }
1359 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
1361 }
1362
1363 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1364 Intent[] specifics, String[] specificTypes, Intent intent,
1365 String resolvedType, int flags) {
1366 final String resultsAction = intent.getAction();
1367
1368 List<ResolveInfo> results = queryIntentActivities(
1369 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1370 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1371
1372 int specificsPos = 0;
1373 int N;
1374
1375 // todo: note that the algorithm used here is O(N^2). This
1376 // isn't a problem in our current environment, but if we start running
1377 // into situations where we have more than 5 or 10 matches then this
1378 // should probably be changed to something smarter...
1379
1380 // First we go through and resolve each of the specific items
1381 // that were supplied, taking care of removing any corresponding
1382 // duplicate items in the generic resolve list.
1383 if (specifics != null) {
1384 for (int i=0; i<specifics.length; i++) {
1385 final Intent sintent = specifics[i];
1386 if (sintent == null) {
1387 continue;
1388 }
1389
1390 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1391 String action = sintent.getAction();
1392 if (resultsAction != null && resultsAction.equals(action)) {
1393 // If this action was explicitly requested, then don't
1394 // remove things that have it.
1395 action = null;
1396 }
1397 ComponentName comp = sintent.getComponent();
1398 ResolveInfo ri = null;
1399 ActivityInfo ai = null;
1400 if (comp == null) {
1401 ri = resolveIntent(
1402 sintent,
1403 specificTypes != null ? specificTypes[i] : null,
1404 flags);
1405 if (ri == null) {
1406 continue;
1407 }
1408 if (ri == mResolveInfo) {
1409 // ACK! Must do something better with this.
1410 }
1411 ai = ri.activityInfo;
1412 comp = new ComponentName(ai.applicationInfo.packageName,
1413 ai.name);
1414 } else {
1415 ai = getActivityInfo(comp, flags);
1416 if (ai == null) {
1417 continue;
1418 }
1419 }
1420
1421 // Look for any generic query activities that are duplicates
1422 // of this specific one, and remove them from the results.
1423 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1424 N = results.size();
1425 int j;
1426 for (j=specificsPos; j<N; j++) {
1427 ResolveInfo sri = results.get(j);
1428 if ((sri.activityInfo.name.equals(comp.getClassName())
1429 && sri.activityInfo.applicationInfo.packageName.equals(
1430 comp.getPackageName()))
1431 || (action != null && sri.filter.matchAction(action))) {
1432 results.remove(j);
1433 if (Config.LOGV) Log.v(
1434 TAG, "Removing duplicate item from " + j
1435 + " due to specific " + specificsPos);
1436 if (ri == null) {
1437 ri = sri;
1438 }
1439 j--;
1440 N--;
1441 }
1442 }
1443
1444 // Add this specific item to its proper place.
1445 if (ri == null) {
1446 ri = new ResolveInfo();
1447 ri.activityInfo = ai;
1448 }
1449 results.add(specificsPos, ri);
1450 ri.specificIndex = i;
1451 specificsPos++;
1452 }
1453 }
1454
1455 // Now we go through the remaining generic results and remove any
1456 // duplicate actions that are found here.
1457 N = results.size();
1458 for (int i=specificsPos; i<N-1; i++) {
1459 final ResolveInfo rii = results.get(i);
1460 if (rii.filter == null) {
1461 continue;
1462 }
1463
1464 // Iterate over all of the actions of this result's intent
1465 // filter... typically this should be just one.
1466 final Iterator<String> it = rii.filter.actionsIterator();
1467 if (it == null) {
1468 continue;
1469 }
1470 while (it.hasNext()) {
1471 final String action = it.next();
1472 if (resultsAction != null && resultsAction.equals(action)) {
1473 // If this action was explicitly requested, then don't
1474 // remove things that have it.
1475 continue;
1476 }
1477 for (int j=i+1; j<N; j++) {
1478 final ResolveInfo rij = results.get(j);
1479 if (rij.filter != null && rij.filter.hasAction(action)) {
1480 results.remove(j);
1481 if (Config.LOGV) Log.v(
1482 TAG, "Removing duplicate item from " + j
1483 + " due to action " + action + " at " + i);
1484 j--;
1485 N--;
1486 }
1487 }
1488 }
1489
1490 // If the caller didn't request filter information, drop it now
1491 // so we don't have to marshall/unmarshall it.
1492 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1493 rii.filter = null;
1494 }
1495 }
1496
1497 // Filter out the caller activity if so requested.
1498 if (caller != null) {
1499 N = results.size();
1500 for (int i=0; i<N; i++) {
1501 ActivityInfo ainfo = results.get(i).activityInfo;
1502 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1503 && caller.getClassName().equals(ainfo.name)) {
1504 results.remove(i);
1505 break;
1506 }
1507 }
1508 }
1509
1510 // If the caller didn't request filter information,
1511 // drop them now so we don't have to
1512 // marshall/unmarshall it.
1513 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1514 N = results.size();
1515 for (int i=0; i<N; i++) {
1516 results.get(i).filter = null;
1517 }
1518 }
1519
1520 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1521 return results;
1522 }
1523
1524 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1525 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001526 ComponentName comp = intent.getComponent();
1527 if (comp != null) {
1528 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1529 ActivityInfo ai = getReceiverInfo(comp, flags);
1530 if (ai != null) {
1531 ResolveInfo ri = new ResolveInfo();
1532 ri.activityInfo = ai;
1533 list.add(ri);
1534 }
1535 return list;
1536 }
1537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001539 String pkgName = intent.getPackage();
1540 if (pkgName == null) {
1541 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1542 resolvedType, flags);
1543 }
1544 PackageParser.Package pkg = mPackages.get(pkgName);
1545 if (pkg != null) {
1546 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1547 resolvedType, flags, pkg.receivers);
1548 }
1549 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551 }
1552
1553 public ResolveInfo resolveService(Intent intent, String resolvedType,
1554 int flags) {
1555 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1556 flags);
1557 if (query != null) {
1558 if (query.size() >= 1) {
1559 // If there is more than one service with the same priority,
1560 // just arbitrarily pick the first one.
1561 return query.get(0);
1562 }
1563 }
1564 return null;
1565 }
1566
1567 public List<ResolveInfo> queryIntentServices(Intent intent,
1568 String resolvedType, int flags) {
1569 ComponentName comp = intent.getComponent();
1570 if (comp != null) {
1571 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1572 ServiceInfo si = getServiceInfo(comp, flags);
1573 if (si != null) {
1574 ResolveInfo ri = new ResolveInfo();
1575 ri.serviceInfo = si;
1576 list.add(ri);
1577 }
1578 return list;
1579 }
1580
1581 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001582 String pkgName = intent.getPackage();
1583 if (pkgName == null) {
1584 return (List<ResolveInfo>)mServices.queryIntent(intent,
1585 resolvedType, flags);
1586 }
1587 PackageParser.Package pkg = mPackages.get(pkgName);
1588 if (pkg != null) {
1589 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1590 resolvedType, flags, pkg.services);
1591 }
1592 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 }
1594 }
1595
1596 public List<PackageInfo> getInstalledPackages(int flags) {
1597 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1598
1599 synchronized (mPackages) {
1600 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1601 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1602 while (i.hasNext()) {
1603 final PackageSetting ps = i.next();
1604 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1605 if(psPkg != null) {
1606 finalList.add(psPkg);
1607 }
1608 }
1609 }
1610 else {
1611 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1612 while (i.hasNext()) {
1613 final PackageParser.Package p = i.next();
1614 if (p.applicationInfo != null) {
1615 PackageInfo pi = generatePackageInfo(p, flags);
1616 if(pi != null) {
1617 finalList.add(pi);
1618 }
1619 }
1620 }
1621 }
1622 }
1623 return finalList;
1624 }
1625
1626 public List<ApplicationInfo> getInstalledApplications(int flags) {
1627 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1628 synchronized(mPackages) {
1629 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1630 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1631 while (i.hasNext()) {
1632 final PackageSetting ps = i.next();
1633 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1634 if(ai != null) {
1635 finalList.add(ai);
1636 }
1637 }
1638 }
1639 else {
1640 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1641 while (i.hasNext()) {
1642 final PackageParser.Package p = i.next();
1643 if (p.applicationInfo != null) {
1644 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1645 if(ai != null) {
1646 finalList.add(ai);
1647 }
1648 }
1649 }
1650 }
1651 }
1652 return finalList;
1653 }
1654
1655 public List<ApplicationInfo> getPersistentApplications(int flags) {
1656 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1657
1658 synchronized (mPackages) {
1659 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1660 while (i.hasNext()) {
1661 PackageParser.Package p = i.next();
1662 if (p.applicationInfo != null
1663 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
1664 && (!mSafeMode || (p.applicationInfo.flags
1665 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1666 finalList.add(p.applicationInfo);
1667 }
1668 }
1669 }
1670
1671 return finalList;
1672 }
1673
1674 public ProviderInfo resolveContentProvider(String name, int flags) {
1675 synchronized (mPackages) {
1676 final PackageParser.Provider provider = mProviders.get(name);
1677 return provider != null
1678 && mSettings.isEnabledLP(provider.info, flags)
1679 && (!mSafeMode || (provider.info.applicationInfo.flags
1680 &ApplicationInfo.FLAG_SYSTEM) != 0)
1681 ? PackageParser.generateProviderInfo(provider, flags)
1682 : null;
1683 }
1684 }
1685
1686 public void querySyncProviders(List outNames, List outInfo) {
1687 synchronized (mPackages) {
1688 Iterator<Map.Entry<String, PackageParser.Provider>> i
1689 = mProviders.entrySet().iterator();
1690
1691 while (i.hasNext()) {
1692 Map.Entry<String, PackageParser.Provider> entry = i.next();
1693 PackageParser.Provider p = entry.getValue();
1694
1695 if (p.syncable
1696 && (!mSafeMode || (p.info.applicationInfo.flags
1697 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1698 outNames.add(entry.getKey());
1699 outInfo.add(PackageParser.generateProviderInfo(p, 0));
1700 }
1701 }
1702 }
1703 }
1704
1705 public List<ProviderInfo> queryContentProviders(String processName,
1706 int uid, int flags) {
1707 ArrayList<ProviderInfo> finalList = null;
1708
1709 synchronized (mPackages) {
1710 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
1711 while (i.hasNext()) {
1712 PackageParser.Provider p = i.next();
1713 if (p.info.authority != null
1714 && (processName == null ||
1715 (p.info.processName.equals(processName)
1716 && p.info.applicationInfo.uid == uid))
1717 && mSettings.isEnabledLP(p.info, flags)
1718 && (!mSafeMode || (p.info.applicationInfo.flags
1719 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1720 if (finalList == null) {
1721 finalList = new ArrayList<ProviderInfo>(3);
1722 }
1723 finalList.add(PackageParser.generateProviderInfo(p,
1724 flags));
1725 }
1726 }
1727 }
1728
1729 if (finalList != null) {
1730 Collections.sort(finalList, mProviderInitOrderSorter);
1731 }
1732
1733 return finalList;
1734 }
1735
1736 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
1737 int flags) {
1738 synchronized (mPackages) {
1739 final PackageParser.Instrumentation i = mInstrumentation.get(name);
1740 return PackageParser.generateInstrumentationInfo(i, flags);
1741 }
1742 }
1743
1744 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
1745 int flags) {
1746 ArrayList<InstrumentationInfo> finalList =
1747 new ArrayList<InstrumentationInfo>();
1748
1749 synchronized (mPackages) {
1750 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
1751 while (i.hasNext()) {
1752 PackageParser.Instrumentation p = i.next();
1753 if (targetPackage == null
1754 || targetPackage.equals(p.info.targetPackage)) {
1755 finalList.add(PackageParser.generateInstrumentationInfo(p,
1756 flags));
1757 }
1758 }
1759 }
1760
1761 return finalList;
1762 }
1763
1764 private void scanDirLI(File dir, int flags, int scanMode) {
1765 Log.d(TAG, "Scanning app dir " + dir);
1766
1767 String[] files = dir.list();
1768
1769 int i;
1770 for (i=0; i<files.length; i++) {
1771 File file = new File(dir, files[i]);
1772 PackageParser.Package pkg = scanPackageLI(file, file, file,
1773 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
1774 }
1775 }
1776
1777 private static void reportSettingsProblem(int priority, String msg) {
1778 try {
1779 File dataDir = Environment.getDataDirectory();
1780 File systemDir = new File(dataDir, "system");
1781 File fname = new File(systemDir, "uiderrors.txt");
1782 FileOutputStream out = new FileOutputStream(fname, true);
1783 PrintWriter pw = new PrintWriter(out);
1784 pw.println(msg);
1785 pw.close();
1786 FileUtils.setPermissions(
1787 fname.toString(),
1788 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
1789 -1, -1);
1790 } catch (java.io.IOException e) {
1791 }
1792 Log.println(priority, TAG, msg);
1793 }
1794
1795 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
1796 PackageParser.Package pkg, File srcFile, int parseFlags) {
1797 if (GET_CERTIFICATES) {
1798 if (ps == null || !ps.codePath.equals(srcFile)
1799 || ps.getTimeStamp() != srcFile.lastModified()) {
1800 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
1801 if (!pp.collectCertificates(pkg, parseFlags)) {
1802 mLastScanError = pp.getParseError();
1803 return false;
1804 }
1805 }
1806 }
1807 return true;
1808 }
1809
1810 /*
1811 * Scan a package and return the newly parsed package.
1812 * Returns null in case of errors and the error code is stored in mLastScanError
1813 */
1814 private PackageParser.Package scanPackageLI(File scanFile,
1815 File destCodeFile, File destResourceFile, int parseFlags,
1816 int scanMode) {
1817 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
1818 parseFlags |= mDefParseFlags;
1819 PackageParser pp = new PackageParser(scanFile.getPath());
1820 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackborn851a5412009-05-08 12:06:44 -07001821 pp.setSdkVersion(mSdkVersion, mSdkCodename);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 final PackageParser.Package pkg = pp.parsePackage(scanFile,
1823 destCodeFile.getAbsolutePath(), mMetrics, parseFlags);
1824 if (pkg == null) {
1825 mLastScanError = pp.getParseError();
1826 return null;
1827 }
1828 PackageSetting ps;
1829 PackageSetting updatedPkg;
1830 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07001831 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
1833 }
1834 if (updatedPkg != null) {
1835 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
1836 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
1837 }
1838 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
1839 // Check for updated system applications here
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07001840 if (updatedPkg != null) {
1841 if ((ps != null) && (!ps.codePath.getPath().equals(scanFile.getPath()))) {
1842 if (pkg.mVersionCode <= ps.versionCode) {
1843 // The system package has been updated and the code path does not match
1844 // Ignore entry. Just return
1845 Log.w(TAG, "Package:" + pkg.packageName +
1846 " has been updated. Ignoring the one from path:"+scanFile);
1847 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
1848 return null;
1849 } else {
1850 // Delete the older apk pointed to by ps
1851 deletePackageResourcesLI(ps.name, ps.codePathString, ps.resourcePathString);
1852 mSettings.enableSystemPackageLP(ps.name);
1853 }
1854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856 }
1857 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
1858 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
1859 return null;
1860 }
1861 // The apk is forward locked (not public) if its code and resources
1862 // are kept in different files.
1863 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
1864 scanMode |= SCAN_FORWARD_LOCKED;
1865 }
1866 // Note that we invoke the following method only if we are about to unpack an application
1867 return scanPackageLI(scanFile, destCodeFile, destResourceFile,
1868 pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
1869 }
1870
1871 private static String fixProcessName(String defProcessName,
1872 String processName, int uid) {
1873 if (processName == null) {
1874 return defProcessName;
1875 }
1876 return processName;
1877 }
1878
1879 private boolean verifySignaturesLP(PackageSetting pkgSetting,
1880 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
1881 if (pkg.mSignatures != null) {
1882 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
1883 updateSignature)) {
1884 Log.e(TAG, "Package " + pkg.packageName
1885 + " signatures do not match the previously installed version; ignoring!");
1886 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
1887 return false;
1888 }
1889
1890 if (pkgSetting.sharedUser != null) {
1891 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
1892 pkg.mSignatures, updateSignature)) {
1893 Log.e(TAG, "Package " + pkg.packageName
1894 + " has no signatures that match those in shared user "
1895 + pkgSetting.sharedUser.name + "; ignoring!");
1896 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
1897 return false;
1898 }
1899 }
1900 } else {
1901 pkg.mSignatures = pkgSetting.signatures.mSignatures;
1902 }
1903 return true;
1904 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001905
1906 public boolean performDexOpt(String packageName) {
1907 if (!mNoDexOpt) {
1908 return false;
1909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001911 PackageParser.Package p;
1912 synchronized (mPackages) {
1913 p = mPackages.get(packageName);
1914 if (p == null || p.mDidDexOpt) {
1915 return false;
1916 }
1917 }
1918 synchronized (mInstallLock) {
1919 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
1920 }
1921 }
1922
1923 static final int DEX_OPT_SKIPPED = 0;
1924 static final int DEX_OPT_PERFORMED = 1;
1925 static final int DEX_OPT_FAILED = -1;
1926
1927 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
1928 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07001929 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001930 String path = pkg.mScanPath;
1931 int ret = 0;
1932 try {
1933 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
1934 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
1935 !pkg.mForwardLocked);
1936 pkg.mDidDexOpt = true;
1937 performed = true;
1938 }
1939 } catch (FileNotFoundException e) {
1940 Log.w(TAG, "Apk not found for dexopt: " + path);
1941 ret = -1;
1942 } catch (IOException e) {
1943 Log.w(TAG, "Exception reading apk: " + path, e);
1944 ret = -1;
1945 }
1946 if (ret < 0) {
1947 //error from installer
1948 return DEX_OPT_FAILED;
1949 }
1950 }
1951
1952 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
1953 }
1954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 private PackageParser.Package scanPackageLI(
1956 File scanFile, File destCodeFile, File destResourceFile,
1957 PackageParser.Package pkg, int parseFlags, int scanMode) {
1958
1959 mScanningPath = scanFile;
1960 if (pkg == null) {
1961 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
1962 return null;
1963 }
1964
1965 final String pkgName = pkg.applicationInfo.packageName;
1966 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
1967 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
1968 }
1969
1970 if (pkgName.equals("android")) {
1971 synchronized (mPackages) {
1972 if (mAndroidApplication != null) {
1973 Log.w(TAG, "*************************************************");
1974 Log.w(TAG, "Core android package being redefined. Skipping.");
1975 Log.w(TAG, " file=" + mScanningPath);
1976 Log.w(TAG, "*************************************************");
1977 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
1978 return null;
1979 }
1980
1981 // Set up information for our fall-back user intent resolution
1982 // activity.
1983 mPlatformPackage = pkg;
1984 pkg.mVersionCode = mSdkVersion;
1985 mAndroidApplication = pkg.applicationInfo;
1986 mResolveActivity.applicationInfo = mAndroidApplication;
1987 mResolveActivity.name = ResolverActivity.class.getName();
1988 mResolveActivity.packageName = mAndroidApplication.packageName;
1989 mResolveActivity.processName = mAndroidApplication.processName;
1990 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
1991 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1992 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
1993 mResolveActivity.exported = true;
1994 mResolveActivity.enabled = true;
1995 mResolveInfo.activityInfo = mResolveActivity;
1996 mResolveInfo.priority = 0;
1997 mResolveInfo.preferredOrder = 0;
1998 mResolveInfo.match = 0;
1999 mResolveComponentName = new ComponentName(
2000 mAndroidApplication.packageName, mResolveActivity.name);
2001 }
2002 }
2003
2004 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2005 TAG, "Scanning package " + pkgName);
2006 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2007 Log.w(TAG, "*************************************************");
2008 Log.w(TAG, "Application package " + pkgName
2009 + " already installed. Skipping duplicate.");
2010 Log.w(TAG, "*************************************************");
2011 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2012 return null;
2013 }
2014
2015 SharedUserSetting suid = null;
2016 PackageSetting pkgSetting = null;
2017
2018 boolean removeExisting = false;
2019
2020 synchronized (mPackages) {
2021 // Check all shared libraries and map to their actual file path.
2022 if (pkg.usesLibraryFiles != null) {
2023 for (int i=0; i<pkg.usesLibraryFiles.length; i++) {
2024 String file = mSharedLibraries.get(pkg.usesLibraryFiles[i]);
2025 if (file == null) {
2026 Log.e(TAG, "Package " + pkg.packageName
2027 + " requires unavailable shared library "
2028 + pkg.usesLibraryFiles[i] + "; ignoring!");
2029 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2030 return null;
2031 }
2032 pkg.usesLibraryFiles[i] = file;
2033 }
2034 }
2035
2036 if (pkg.mSharedUserId != null) {
2037 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2038 pkg.applicationInfo.flags, true);
2039 if (suid == null) {
2040 Log.w(TAG, "Creating application package " + pkgName
2041 + " for shared user failed");
2042 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2043 return null;
2044 }
2045 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2046 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2047 + suid.userId + "): packages=" + suid.packages);
2048 }
2049 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002050
2051 // Just create the setting, don't add it yet. For already existing packages
2052 // the PkgSetting exists already and doesn't have to be created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
2054 destResourceFile, pkg.applicationInfo.flags, true, false);
2055 if (pkgSetting == null) {
2056 Log.w(TAG, "Creating application package " + pkgName + " failed");
2057 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2058 return null;
2059 }
2060 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
2061 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2062 }
2063
2064 pkg.applicationInfo.uid = pkgSetting.userId;
2065 pkg.mExtras = pkgSetting;
2066
2067 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
2068 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2069 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2070 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2071 return null;
2072 }
2073 // The signature has changed, but this package is in the system
2074 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002075 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 // However... if this package is part of a shared user, but it
2077 // doesn't match the signature of the shared user, let's fail.
2078 // What this means is that you can't change the signatures
2079 // associated with an overall shared user, which doesn't seem all
2080 // that unreasonable.
2081 if (pkgSetting.sharedUser != null) {
2082 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2083 pkg.mSignatures, false)) {
2084 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2085 return null;
2086 }
2087 }
2088 removeExisting = true;
2089 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002090
2091 // Verify that this new package doesn't have any content providers
2092 // that conflict with existing packages. Only do this if the
2093 // package isn't already installed, since we don't want to break
2094 // things that are installed.
2095 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2096 int N = pkg.providers.size();
2097 int i;
2098 for (i=0; i<N; i++) {
2099 PackageParser.Provider p = pkg.providers.get(i);
2100 String names[] = p.info.authority.split(";");
2101 for (int j = 0; j < names.length; j++) {
2102 if (mProviders.containsKey(names[j])) {
2103 PackageParser.Provider other = mProviders.get(names[j]);
2104 Log.w(TAG, "Can't install because provider name " + names[j] +
2105 " (in package " + pkg.applicationInfo.packageName +
2106 ") is already used by "
2107 + ((other != null && other.component != null)
2108 ? other.component.getPackageName() : "?"));
2109 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2110 return null;
2111 }
2112 }
2113 }
2114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 }
2116
2117 if (removeExisting) {
2118 if (mInstaller != null) {
2119 int ret = mInstaller.remove(pkgName);
2120 if (ret != 0) {
2121 String msg = "System package " + pkg.packageName
2122 + " could not have data directory erased after signature change.";
2123 reportSettingsProblem(Log.WARN, msg);
2124 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2125 return null;
2126 }
2127 }
2128 Log.w(TAG, "System package " + pkg.packageName
2129 + " signature changed: existing data removed.");
2130 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2131 }
2132
2133 long scanFileTime = scanFile.lastModified();
2134 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2135 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2136 pkg.applicationInfo.processName = fixProcessName(
2137 pkg.applicationInfo.packageName,
2138 pkg.applicationInfo.processName,
2139 pkg.applicationInfo.uid);
2140 pkg.applicationInfo.publicSourceDir = pkgSetting.resourcePathString;
2141
2142 File dataPath;
2143 if (mPlatformPackage == pkg) {
2144 // The system package is special.
2145 dataPath = new File (Environment.getDataDirectory(), "system");
2146 pkg.applicationInfo.dataDir = dataPath.getPath();
2147 } else {
2148 // This is a normal package, need to make its data directory.
2149 dataPath = new File(mAppDataDir, pkgName);
2150 if (dataPath.exists()) {
2151 mOutPermissions[1] = 0;
2152 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2153 if (mOutPermissions[1] == pkg.applicationInfo.uid
2154 || !Process.supportsProcesses()) {
2155 pkg.applicationInfo.dataDir = dataPath.getPath();
2156 } else {
2157 boolean recovered = false;
2158 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2159 // If this is a system app, we can at least delete its
2160 // current data so the application will still work.
2161 if (mInstaller != null) {
2162 int ret = mInstaller.remove(pkgName);
2163 if(ret >= 0) {
2164 // Old data gone!
2165 String msg = "System package " + pkg.packageName
2166 + " has changed from uid: "
2167 + mOutPermissions[1] + " to "
2168 + pkg.applicationInfo.uid + "; old data erased";
2169 reportSettingsProblem(Log.WARN, msg);
2170 recovered = true;
2171
2172 // And now re-install the app.
2173 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2174 pkg.applicationInfo.uid);
2175 if (ret == -1) {
2176 // Ack should not happen!
2177 msg = "System package " + pkg.packageName
2178 + " could not have data directory re-created after delete.";
2179 reportSettingsProblem(Log.WARN, msg);
2180 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2181 return null;
2182 }
2183 }
2184 }
2185 if (!recovered) {
2186 mHasSystemUidErrors = true;
2187 }
2188 }
2189 if (!recovered) {
2190 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2191 + pkg.applicationInfo.uid + "/fs_"
2192 + mOutPermissions[1];
2193 String msg = "Package " + pkg.packageName
2194 + " has mismatched uid: "
2195 + mOutPermissions[1] + " on disk, "
2196 + pkg.applicationInfo.uid + " in settings";
2197 synchronized (mPackages) {
2198 if (!mReportedUidError) {
2199 mReportedUidError = true;
2200 msg = msg + "; read messages:\n"
2201 + mSettings.getReadMessagesLP();
2202 }
2203 reportSettingsProblem(Log.ERROR, msg);
2204 }
2205 }
2206 }
2207 pkg.applicationInfo.dataDir = dataPath.getPath();
2208 } else {
2209 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2210 Log.v(TAG, "Want this data dir: " + dataPath);
2211 //invoke installer to do the actual installation
2212 if (mInstaller != null) {
2213 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2214 pkg.applicationInfo.uid);
2215 if(ret < 0) {
2216 // Error from installer
2217 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2218 return null;
2219 }
2220 } else {
2221 dataPath.mkdirs();
2222 if (dataPath.exists()) {
2223 FileUtils.setPermissions(
2224 dataPath.toString(),
2225 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2226 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2227 }
2228 }
2229 if (dataPath.exists()) {
2230 pkg.applicationInfo.dataDir = dataPath.getPath();
2231 } else {
2232 Log.w(TAG, "Unable to create data directory: " + dataPath);
2233 pkg.applicationInfo.dataDir = null;
2234 }
2235 }
2236 }
2237
2238 // Perform shared library installation and dex validation and
2239 // optimization, if this is not a system app.
2240 if (mInstaller != null) {
2241 String path = scanFile.getPath();
2242 if (scanFileNewer) {
2243 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002244 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2245 if (err != PackageManager.INSTALL_SUCCEEDED) {
2246 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 return null;
2248 }
2249 }
2250
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002251 pkg.mForwardLocked = (scanMode&SCAN_FORWARD_LOCKED) != 0;
2252 pkg.mScanPath = path;
2253
2254 if ((scanMode&SCAN_NO_DEX) == 0) {
2255 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2257 return null;
2258 }
2259 }
2260 }
2261
2262 if (mFactoryTest && pkg.requestedPermissions.contains(
2263 android.Manifest.permission.FACTORY_TEST)) {
2264 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2265 }
2266
2267 if ((scanMode&SCAN_MONITOR) != 0) {
2268 pkg.mPath = destCodeFile.getAbsolutePath();
2269 mAppDirs.put(pkg.mPath, pkg);
2270 }
2271
2272 synchronized (mPackages) {
2273 // We don't expect installation to fail beyond this point
2274 // Add the new setting to mSettings
2275 mSettings.insertPackageSettingLP(pkgSetting, pkg.packageName, suid);
2276 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002277 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 int N = pkg.providers.size();
2279 StringBuilder r = null;
2280 int i;
2281 for (i=0; i<N; i++) {
2282 PackageParser.Provider p = pkg.providers.get(i);
2283 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2284 p.info.processName, pkg.applicationInfo.uid);
2285 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2286 p.info.name), p);
2287 p.syncable = p.info.isSyncable;
2288 String names[] = p.info.authority.split(";");
2289 p.info.authority = null;
2290 for (int j = 0; j < names.length; j++) {
2291 if (j == 1 && p.syncable) {
2292 // We only want the first authority for a provider to possibly be
2293 // syncable, so if we already added this provider using a different
2294 // authority clear the syncable flag. We copy the provider before
2295 // changing it because the mProviders object contains a reference
2296 // to a provider that we don't want to change.
2297 // Only do this for the second authority since the resulting provider
2298 // object can be the same for all future authorities for this provider.
2299 p = new PackageParser.Provider(p);
2300 p.syncable = false;
2301 }
2302 if (!mProviders.containsKey(names[j])) {
2303 mProviders.put(names[j], p);
2304 if (p.info.authority == null) {
2305 p.info.authority = names[j];
2306 } else {
2307 p.info.authority = p.info.authority + ";" + names[j];
2308 }
2309 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2310 Log.d(TAG, "Registered content provider: " + names[j] +
2311 ", className = " + p.info.name +
2312 ", isSyncable = " + p.info.isSyncable);
2313 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002314 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 Log.w(TAG, "Skipping provider name " + names[j] +
2316 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002317 "): name already used by "
2318 + ((other != null && other.component != null)
2319 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 }
2321 }
2322 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2323 if (r == null) {
2324 r = new StringBuilder(256);
2325 } else {
2326 r.append(' ');
2327 }
2328 r.append(p.info.name);
2329 }
2330 }
2331 if (r != null) {
2332 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2333 }
2334
2335 N = pkg.services.size();
2336 r = null;
2337 for (i=0; i<N; i++) {
2338 PackageParser.Service s = pkg.services.get(i);
2339 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2340 s.info.processName, pkg.applicationInfo.uid);
2341 mServices.addService(s);
2342 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2343 if (r == null) {
2344 r = new StringBuilder(256);
2345 } else {
2346 r.append(' ');
2347 }
2348 r.append(s.info.name);
2349 }
2350 }
2351 if (r != null) {
2352 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2353 }
2354
2355 N = pkg.receivers.size();
2356 r = null;
2357 for (i=0; i<N; i++) {
2358 PackageParser.Activity a = pkg.receivers.get(i);
2359 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2360 a.info.processName, pkg.applicationInfo.uid);
2361 mReceivers.addActivity(a, "receiver");
2362 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2363 if (r == null) {
2364 r = new StringBuilder(256);
2365 } else {
2366 r.append(' ');
2367 }
2368 r.append(a.info.name);
2369 }
2370 }
2371 if (r != null) {
2372 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2373 }
2374
2375 N = pkg.activities.size();
2376 r = null;
2377 for (i=0; i<N; i++) {
2378 PackageParser.Activity a = pkg.activities.get(i);
2379 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2380 a.info.processName, pkg.applicationInfo.uid);
2381 mActivities.addActivity(a, "activity");
2382 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2383 if (r == null) {
2384 r = new StringBuilder(256);
2385 } else {
2386 r.append(' ');
2387 }
2388 r.append(a.info.name);
2389 }
2390 }
2391 if (r != null) {
2392 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2393 }
2394
2395 N = pkg.permissionGroups.size();
2396 r = null;
2397 for (i=0; i<N; i++) {
2398 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2399 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2400 if (cur == null) {
2401 mPermissionGroups.put(pg.info.name, pg);
2402 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2403 if (r == null) {
2404 r = new StringBuilder(256);
2405 } else {
2406 r.append(' ');
2407 }
2408 r.append(pg.info.name);
2409 }
2410 } else {
2411 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2412 + pg.info.packageName + " ignored: original from "
2413 + cur.info.packageName);
2414 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2415 if (r == null) {
2416 r = new StringBuilder(256);
2417 } else {
2418 r.append(' ');
2419 }
2420 r.append("DUP:");
2421 r.append(pg.info.name);
2422 }
2423 }
2424 }
2425 if (r != null) {
2426 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2427 }
2428
2429 N = pkg.permissions.size();
2430 r = null;
2431 for (i=0; i<N; i++) {
2432 PackageParser.Permission p = pkg.permissions.get(i);
2433 HashMap<String, BasePermission> permissionMap =
2434 p.tree ? mSettings.mPermissionTrees
2435 : mSettings.mPermissions;
2436 p.group = mPermissionGroups.get(p.info.group);
2437 if (p.info.group == null || p.group != null) {
2438 BasePermission bp = permissionMap.get(p.info.name);
2439 if (bp == null) {
2440 bp = new BasePermission(p.info.name, p.info.packageName,
2441 BasePermission.TYPE_NORMAL);
2442 permissionMap.put(p.info.name, bp);
2443 }
2444 if (bp.perm == null) {
2445 if (bp.sourcePackage == null
2446 || bp.sourcePackage.equals(p.info.packageName)) {
2447 BasePermission tree = findPermissionTreeLP(p.info.name);
2448 if (tree == null
2449 || tree.sourcePackage.equals(p.info.packageName)) {
2450 bp.perm = p;
2451 bp.uid = pkg.applicationInfo.uid;
2452 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2453 if (r == null) {
2454 r = new StringBuilder(256);
2455 } else {
2456 r.append(' ');
2457 }
2458 r.append(p.info.name);
2459 }
2460 } else {
2461 Log.w(TAG, "Permission " + p.info.name + " from package "
2462 + p.info.packageName + " ignored: base tree "
2463 + tree.name + " is from package "
2464 + tree.sourcePackage);
2465 }
2466 } else {
2467 Log.w(TAG, "Permission " + p.info.name + " from package "
2468 + p.info.packageName + " ignored: original from "
2469 + bp.sourcePackage);
2470 }
2471 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2472 if (r == null) {
2473 r = new StringBuilder(256);
2474 } else {
2475 r.append(' ');
2476 }
2477 r.append("DUP:");
2478 r.append(p.info.name);
2479 }
2480 } else {
2481 Log.w(TAG, "Permission " + p.info.name + " from package "
2482 + p.info.packageName + " ignored: no group "
2483 + p.group);
2484 }
2485 }
2486 if (r != null) {
2487 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2488 }
2489
2490 N = pkg.instrumentation.size();
2491 r = null;
2492 for (i=0; i<N; i++) {
2493 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2494 a.info.packageName = pkg.applicationInfo.packageName;
2495 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2496 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2497 a.info.dataDir = pkg.applicationInfo.dataDir;
2498 mInstrumentation.put(a.component, a);
2499 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2500 if (r == null) {
2501 r = new StringBuilder(256);
2502 } else {
2503 r.append(' ');
2504 }
2505 r.append(a.info.name);
2506 }
2507 }
2508 if (r != null) {
2509 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2510 }
2511
Dianne Hackborn854060af2009-07-09 18:14:31 -07002512 if (pkg.protectedBroadcasts != null) {
2513 N = pkg.protectedBroadcasts.size();
2514 for (i=0; i<N; i++) {
2515 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
2516 }
2517 }
2518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 pkgSetting.setTimeStamp(scanFileTime);
2520 }
2521
2522 return pkg;
2523 }
2524
Dianne Hackbornb1811182009-05-21 15:45:42 -07002525 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
2526 File dataPath, File scanFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002528 final String sharedLibraryABI = Build.CPU_ABI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 final String apkLibraryDirectory = "lib/" + sharedLibraryABI + "/";
2530 final String apkSharedLibraryPrefix = apkLibraryDirectory + "lib";
2531 final String sharedLibrarySuffix = ".so";
Dianne Hackbornb1811182009-05-21 15:45:42 -07002532 boolean hasNativeCode = false;
2533 boolean installedNativeCode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 try {
2535 ZipFile zipFile = new ZipFile(scanFile);
2536 Enumeration<ZipEntry> entries =
2537 (Enumeration<ZipEntry>) zipFile.entries();
2538
2539 while (entries.hasMoreElements()) {
2540 ZipEntry entry = entries.nextElement();
2541 if (entry.isDirectory()) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002542 if (!hasNativeCode && entry.getName().startsWith("lib")) {
2543 hasNativeCode = true;
2544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 continue;
2546 }
2547 String entryName = entry.getName();
Dianne Hackbornb1811182009-05-21 15:45:42 -07002548 if (entryName.startsWith("lib/")) {
2549 hasNativeCode = true;
2550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 if (! (entryName.startsWith(apkSharedLibraryPrefix)
2552 && entryName.endsWith(sharedLibrarySuffix))) {
2553 continue;
2554 }
2555 String libFileName = entryName.substring(
2556 apkLibraryDirectory.length());
2557 if (libFileName.contains("/")
2558 || (!FileUtils.isFilenameSafe(new File(libFileName)))) {
2559 continue;
2560 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002561
2562 installedNativeCode = true;
2563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
2565 File.separator + libFileName;
2566 File sharedLibraryFile = new File(sharedLibraryFilePath);
2567 if (! sharedLibraryFile.exists() ||
2568 sharedLibraryFile.length() != entry.getSize() ||
2569 sharedLibraryFile.lastModified() != entry.getTime()) {
2570 if (Config.LOGD) {
2571 Log.d(TAG, "Caching shared lib " + entry.getName());
2572 }
2573 if (mInstaller == null) {
2574 sharedLibraryDir.mkdir();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 }
2576 cacheSharedLibLI(pkg, zipFile, entry, sharedLibraryDir,
2577 sharedLibraryFile);
2578 }
2579 }
2580 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002581 Log.w(TAG, "Failed to cache package shared libs", e);
2582 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002584
2585 if (hasNativeCode && !installedNativeCode) {
2586 Log.w(TAG, "Install failed: .apk has native code but none for arch "
2587 + Build.CPU_ABI);
2588 return PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
2589 }
2590
2591 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 }
2593
2594 private void cacheSharedLibLI(PackageParser.Package pkg,
2595 ZipFile zipFile, ZipEntry entry,
2596 File sharedLibraryDir,
2597 File sharedLibraryFile) throws IOException {
2598 InputStream inputStream = zipFile.getInputStream(entry);
2599 try {
2600 File tempFile = File.createTempFile("tmp", "tmp", sharedLibraryDir);
2601 String tempFilePath = tempFile.getPath();
2602 // XXX package manager can't change owner, so the lib files for
2603 // now need to be left as world readable and owned by the system.
2604 if (! FileUtils.copyToFile(inputStream, tempFile) ||
2605 ! tempFile.setLastModified(entry.getTime()) ||
2606 FileUtils.setPermissions(tempFilePath,
2607 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
2608 |FileUtils.S_IROTH, -1, -1) != 0 ||
2609 ! tempFile.renameTo(sharedLibraryFile)) {
2610 // Failed to properly write file.
2611 tempFile.delete();
2612 throw new IOException("Couldn't create cached shared lib "
2613 + sharedLibraryFile + " in " + sharedLibraryDir);
2614 }
2615 } finally {
2616 inputStream.close();
2617 }
2618 }
2619
2620 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
2621 if (chatty && Config.LOGD) Log.d(
2622 TAG, "Removing package " + pkg.applicationInfo.packageName );
2623
2624 synchronized (mPackages) {
2625 if (pkg.mPreferredOrder > 0) {
2626 mSettings.mPreferredPackages.remove(pkg);
2627 pkg.mPreferredOrder = 0;
2628 updatePreferredIndicesLP();
2629 }
2630
2631 clearPackagePreferredActivitiesLP(pkg.packageName);
2632
2633 mPackages.remove(pkg.applicationInfo.packageName);
2634 if (pkg.mPath != null) {
2635 mAppDirs.remove(pkg.mPath);
2636 }
2637
2638 PackageSetting ps = (PackageSetting)pkg.mExtras;
2639 if (ps != null && ps.sharedUser != null) {
2640 // XXX don't do this until the data is removed.
2641 if (false) {
2642 ps.sharedUser.packages.remove(ps);
2643 if (ps.sharedUser.packages.size() == 0) {
2644 // Remove.
2645 }
2646 }
2647 }
2648
2649 int N = pkg.providers.size();
2650 StringBuilder r = null;
2651 int i;
2652 for (i=0; i<N; i++) {
2653 PackageParser.Provider p = pkg.providers.get(i);
2654 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
2655 p.info.name));
2656 if (p.info.authority == null) {
2657
2658 /* The is another ContentProvider with this authority when
2659 * this app was installed so this authority is null,
2660 * Ignore it as we don't have to unregister the provider.
2661 */
2662 continue;
2663 }
2664 String names[] = p.info.authority.split(";");
2665 for (int j = 0; j < names.length; j++) {
2666 if (mProviders.get(names[j]) == p) {
2667 mProviders.remove(names[j]);
2668 if (chatty && Config.LOGD) Log.d(
2669 TAG, "Unregistered content provider: " + names[j] +
2670 ", className = " + p.info.name +
2671 ", isSyncable = " + p.info.isSyncable);
2672 }
2673 }
2674 if (chatty) {
2675 if (r == null) {
2676 r = new StringBuilder(256);
2677 } else {
2678 r.append(' ');
2679 }
2680 r.append(p.info.name);
2681 }
2682 }
2683 if (r != null) {
2684 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2685 }
2686
2687 N = pkg.services.size();
2688 r = null;
2689 for (i=0; i<N; i++) {
2690 PackageParser.Service s = pkg.services.get(i);
2691 mServices.removeService(s);
2692 if (chatty) {
2693 if (r == null) {
2694 r = new StringBuilder(256);
2695 } else {
2696 r.append(' ');
2697 }
2698 r.append(s.info.name);
2699 }
2700 }
2701 if (r != null) {
2702 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2703 }
2704
2705 N = pkg.receivers.size();
2706 r = null;
2707 for (i=0; i<N; i++) {
2708 PackageParser.Activity a = pkg.receivers.get(i);
2709 mReceivers.removeActivity(a, "receiver");
2710 if (chatty) {
2711 if (r == null) {
2712 r = new StringBuilder(256);
2713 } else {
2714 r.append(' ');
2715 }
2716 r.append(a.info.name);
2717 }
2718 }
2719 if (r != null) {
2720 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2721 }
2722
2723 N = pkg.activities.size();
2724 r = null;
2725 for (i=0; i<N; i++) {
2726 PackageParser.Activity a = pkg.activities.get(i);
2727 mActivities.removeActivity(a, "activity");
2728 if (chatty) {
2729 if (r == null) {
2730 r = new StringBuilder(256);
2731 } else {
2732 r.append(' ');
2733 }
2734 r.append(a.info.name);
2735 }
2736 }
2737 if (r != null) {
2738 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2739 }
2740
2741 N = pkg.permissions.size();
2742 r = null;
2743 for (i=0; i<N; i++) {
2744 PackageParser.Permission p = pkg.permissions.get(i);
2745 boolean tree = false;
2746 BasePermission bp = mSettings.mPermissions.get(p.info.name);
2747 if (bp == null) {
2748 tree = true;
2749 bp = mSettings.mPermissionTrees.get(p.info.name);
2750 }
2751 if (bp != null && bp.perm == p) {
2752 if (bp.type != BasePermission.TYPE_BUILTIN) {
2753 if (tree) {
2754 mSettings.mPermissionTrees.remove(p.info.name);
2755 } else {
2756 mSettings.mPermissions.remove(p.info.name);
2757 }
2758 } else {
2759 bp.perm = null;
2760 }
2761 if (chatty) {
2762 if (r == null) {
2763 r = new StringBuilder(256);
2764 } else {
2765 r.append(' ');
2766 }
2767 r.append(p.info.name);
2768 }
2769 }
2770 }
2771 if (r != null) {
2772 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2773 }
2774
2775 N = pkg.instrumentation.size();
2776 r = null;
2777 for (i=0; i<N; i++) {
2778 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2779 mInstrumentation.remove(a.component);
2780 if (chatty) {
2781 if (r == null) {
2782 r = new StringBuilder(256);
2783 } else {
2784 r.append(' ');
2785 }
2786 r.append(a.info.name);
2787 }
2788 }
2789 if (r != null) {
2790 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2791 }
2792 }
2793 }
2794
2795 private static final boolean isPackageFilename(String name) {
2796 return name != null && name.endsWith(".apk");
2797 }
2798
2799 private void updatePermissionsLP() {
2800 // Make sure there are no dangling permission trees.
2801 Iterator<BasePermission> it = mSettings.mPermissionTrees
2802 .values().iterator();
2803 while (it.hasNext()) {
2804 BasePermission bp = it.next();
2805 if (bp.perm == null) {
2806 Log.w(TAG, "Removing dangling permission tree: " + bp.name
2807 + " from package " + bp.sourcePackage);
2808 it.remove();
2809 }
2810 }
2811
2812 // Make sure all dynamic permissions have been assigned to a package,
2813 // and make sure there are no dangling permissions.
2814 it = mSettings.mPermissions.values().iterator();
2815 while (it.hasNext()) {
2816 BasePermission bp = it.next();
2817 if (bp.type == BasePermission.TYPE_DYNAMIC) {
2818 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
2819 + bp.name + " pkg=" + bp.sourcePackage
2820 + " info=" + bp.pendingInfo);
2821 if (bp.perm == null && bp.pendingInfo != null) {
2822 BasePermission tree = findPermissionTreeLP(bp.name);
2823 if (tree != null) {
2824 bp.perm = new PackageParser.Permission(tree.perm.owner,
2825 new PermissionInfo(bp.pendingInfo));
2826 bp.perm.info.packageName = tree.perm.info.packageName;
2827 bp.perm.info.name = bp.name;
2828 bp.uid = tree.uid;
2829 }
2830 }
2831 }
2832 if (bp.perm == null) {
2833 Log.w(TAG, "Removing dangling permission: " + bp.name
2834 + " from package " + bp.sourcePackage);
2835 it.remove();
2836 }
2837 }
2838
2839 // Now update the permissions for all packages, in particular
2840 // replace the granted permissions of the system packages.
2841 for (PackageParser.Package pkg : mPackages.values()) {
2842 grantPermissionsLP(pkg, false);
2843 }
2844 }
2845
2846 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
2847 final PackageSetting ps = (PackageSetting)pkg.mExtras;
2848 if (ps == null) {
2849 return;
2850 }
2851 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2852 boolean addedPermission = false;
2853
2854 if (replace) {
2855 ps.permissionsFixed = false;
2856 if (gp == ps) {
2857 gp.grantedPermissions.clear();
2858 gp.gids = mGlobalGids;
2859 }
2860 }
2861
2862 if (gp.gids == null) {
2863 gp.gids = mGlobalGids;
2864 }
2865
2866 final int N = pkg.requestedPermissions.size();
2867 for (int i=0; i<N; i++) {
2868 String name = pkg.requestedPermissions.get(i);
2869 BasePermission bp = mSettings.mPermissions.get(name);
2870 PackageParser.Permission p = bp != null ? bp.perm : null;
2871 if (false) {
2872 if (gp != ps) {
2873 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
2874 + ": " + p);
2875 }
2876 }
2877 if (p != null) {
2878 final String perm = p.info.name;
2879 boolean allowed;
2880 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
2881 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
2882 allowed = true;
2883 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
2884 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
2885 allowed = (checkSignaturesLP(p.owner, pkg)
2886 == PackageManager.SIGNATURE_MATCH)
2887 || (checkSignaturesLP(mPlatformPackage, pkg)
2888 == PackageManager.SIGNATURE_MATCH);
2889 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
2890 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
2891 // For updated system applications, the signatureOrSystem permission
2892 // is granted only if it had been defined by the original application.
2893 if ((pkg.applicationInfo.flags
2894 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
2895 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
2896 if(sysPs.grantedPermissions.contains(perm)) {
2897 allowed = true;
2898 } else {
2899 allowed = false;
2900 }
2901 } else {
2902 allowed = true;
2903 }
2904 }
2905 }
2906 } else {
2907 allowed = false;
2908 }
2909 if (false) {
2910 if (gp != ps) {
2911 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
2912 }
2913 }
2914 if (allowed) {
2915 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
2916 && ps.permissionsFixed) {
2917 // If this is an existing, non-system package, then
2918 // we can't add any new permissions to it.
2919 if (!gp.loadedPermissions.contains(perm)) {
2920 allowed = false;
Dianne Hackborna96cbb42009-05-13 15:06:13 -07002921 // Except... if this is a permission that was added
2922 // to the platform (note: need to only do this when
2923 // updating the platform).
2924 final int NP = PackageParser.NEW_PERMISSIONS.length;
2925 for (int ip=0; ip<NP; ip++) {
2926 final PackageParser.NewPermissionInfo npi
2927 = PackageParser.NEW_PERMISSIONS[ip];
2928 if (npi.name.equals(perm)
2929 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
2930 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07002931 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborna96cbb42009-05-13 15:06:13 -07002932 + pkg.packageName);
2933 break;
2934 }
2935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 }
2937 }
2938 if (allowed) {
2939 if (!gp.grantedPermissions.contains(perm)) {
2940 addedPermission = true;
2941 gp.grantedPermissions.add(perm);
2942 gp.gids = appendInts(gp.gids, bp.gids);
2943 }
2944 } else {
2945 Log.w(TAG, "Not granting permission " + perm
2946 + " to package " + pkg.packageName
2947 + " because it was previously installed without");
2948 }
2949 } else {
2950 Log.w(TAG, "Not granting permission " + perm
2951 + " to package " + pkg.packageName
2952 + " (protectionLevel=" + p.info.protectionLevel
2953 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
2954 + ")");
2955 }
2956 } else {
2957 Log.w(TAG, "Unknown permission " + name
2958 + " in package " + pkg.packageName);
2959 }
2960 }
2961
2962 if ((addedPermission || replace) && !ps.permissionsFixed &&
2963 (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2964 // This is the first that we have heard about this package, so the
2965 // permissions we have now selected are fixed until explicitly
2966 // changed.
2967 ps.permissionsFixed = true;
2968 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
2969 }
2970 }
2971
2972 private final class ActivityIntentResolver
2973 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02002974 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02002976 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 }
2978
Mihai Preda074edef2009-05-18 17:13:31 +02002979 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02002981 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2983 }
2984
Mihai Predaeae850c2009-05-13 10:13:48 +02002985 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
2986 ArrayList<PackageParser.Activity> packageActivities) {
2987 if (packageActivities == null) {
2988 return null;
2989 }
2990 mFlags = flags;
2991 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
2992 int N = packageActivities.size();
2993 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
2994 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02002995
2996 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02002997 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02002998 intentFilters = packageActivities.get(i).intents;
2999 if (intentFilters != null && intentFilters.size() > 0) {
3000 listCut.add(intentFilters);
3001 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003002 }
3003 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3004 }
3005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 public final void addActivity(PackageParser.Activity a, String type) {
3007 mActivities.put(a.component, a);
3008 if (SHOW_INFO || Config.LOGV) Log.v(
3009 TAG, " " + type + " " +
3010 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3011 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3012 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003013 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3015 if (SHOW_INFO || Config.LOGV) {
3016 Log.v(TAG, " IntentFilter:");
3017 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3018 }
3019 if (!intent.debugCheck()) {
3020 Log.w(TAG, "==> For Activity " + a.info.name);
3021 }
3022 addFilter(intent);
3023 }
3024 }
3025
3026 public final void removeActivity(PackageParser.Activity a, String type) {
3027 mActivities.remove(a.component);
3028 if (SHOW_INFO || Config.LOGV) Log.v(
3029 TAG, " " + type + " " +
3030 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3031 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3032 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003033 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3035 if (SHOW_INFO || Config.LOGV) {
3036 Log.v(TAG, " IntentFilter:");
3037 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3038 }
3039 removeFilter(intent);
3040 }
3041 }
3042
3043 @Override
3044 protected boolean allowFilterResult(
3045 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3046 ActivityInfo filterAi = filter.activity.info;
3047 for (int i=dest.size()-1; i>=0; i--) {
3048 ActivityInfo destAi = dest.get(i).activityInfo;
3049 if (destAi.name == filterAi.name
3050 && destAi.packageName == filterAi.packageName) {
3051 return false;
3052 }
3053 }
3054 return true;
3055 }
3056
3057 @Override
3058 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3059 int match) {
3060 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3061 return null;
3062 }
3063 final PackageParser.Activity activity = info.activity;
3064 if (mSafeMode && (activity.info.applicationInfo.flags
3065 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3066 return null;
3067 }
3068 final ResolveInfo res = new ResolveInfo();
3069 res.activityInfo = PackageParser.generateActivityInfo(activity,
3070 mFlags);
3071 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3072 res.filter = info;
3073 }
3074 res.priority = info.getPriority();
3075 res.preferredOrder = activity.owner.mPreferredOrder;
3076 //System.out.println("Result: " + res.activityInfo.className +
3077 // " = " + res.priority);
3078 res.match = match;
3079 res.isDefault = info.hasDefault;
3080 res.labelRes = info.labelRes;
3081 res.nonLocalizedLabel = info.nonLocalizedLabel;
3082 res.icon = info.icon;
3083 return res;
3084 }
3085
3086 @Override
3087 protected void sortResults(List<ResolveInfo> results) {
3088 Collections.sort(results, mResolvePrioritySorter);
3089 }
3090
3091 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003092 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003094 out.print(prefix); out.print(
3095 Integer.toHexString(System.identityHashCode(filter.activity)));
3096 out.print(' ');
3097 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 }
3099
3100// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3101// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3102// final List<ResolveInfo> retList = Lists.newArrayList();
3103// while (i.hasNext()) {
3104// final ResolveInfo resolveInfo = i.next();
3105// if (isEnabledLP(resolveInfo.activityInfo)) {
3106// retList.add(resolveInfo);
3107// }
3108// }
3109// return retList;
3110// }
3111
3112 // Keys are String (activity class name), values are Activity.
3113 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3114 = new HashMap<ComponentName, PackageParser.Activity>();
3115 private int mFlags;
3116 }
3117
3118 private final class ServiceIntentResolver
3119 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003120 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003122 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 }
3124
Mihai Preda074edef2009-05-18 17:13:31 +02003125 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003127 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003128 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3129 }
3130
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003131 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3132 ArrayList<PackageParser.Service> packageServices) {
3133 if (packageServices == null) {
3134 return null;
3135 }
3136 mFlags = flags;
3137 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3138 int N = packageServices.size();
3139 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3140 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3141
3142 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3143 for (int i = 0; i < N; ++i) {
3144 intentFilters = packageServices.get(i).intents;
3145 if (intentFilters != null && intentFilters.size() > 0) {
3146 listCut.add(intentFilters);
3147 }
3148 }
3149 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3150 }
3151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 public final void addService(PackageParser.Service s) {
3153 mServices.put(s.component, s);
3154 if (SHOW_INFO || Config.LOGV) Log.v(
3155 TAG, " " + (s.info.nonLocalizedLabel != null
3156 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3157 if (SHOW_INFO || Config.LOGV) Log.v(
3158 TAG, " Class=" + s.info.name);
3159 int NI = s.intents.size();
3160 int j;
3161 for (j=0; j<NI; j++) {
3162 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3163 if (SHOW_INFO || Config.LOGV) {
3164 Log.v(TAG, " IntentFilter:");
3165 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3166 }
3167 if (!intent.debugCheck()) {
3168 Log.w(TAG, "==> For Service " + s.info.name);
3169 }
3170 addFilter(intent);
3171 }
3172 }
3173
3174 public final void removeService(PackageParser.Service s) {
3175 mServices.remove(s.component);
3176 if (SHOW_INFO || Config.LOGV) Log.v(
3177 TAG, " " + (s.info.nonLocalizedLabel != null
3178 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3179 if (SHOW_INFO || Config.LOGV) Log.v(
3180 TAG, " Class=" + s.info.name);
3181 int NI = s.intents.size();
3182 int j;
3183 for (j=0; j<NI; j++) {
3184 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3185 if (SHOW_INFO || Config.LOGV) {
3186 Log.v(TAG, " IntentFilter:");
3187 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3188 }
3189 removeFilter(intent);
3190 }
3191 }
3192
3193 @Override
3194 protected boolean allowFilterResult(
3195 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3196 ServiceInfo filterSi = filter.service.info;
3197 for (int i=dest.size()-1; i>=0; i--) {
3198 ServiceInfo destAi = dest.get(i).serviceInfo;
3199 if (destAi.name == filterSi.name
3200 && destAi.packageName == filterSi.packageName) {
3201 return false;
3202 }
3203 }
3204 return true;
3205 }
3206
3207 @Override
3208 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3209 int match) {
3210 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3211 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3212 return null;
3213 }
3214 final PackageParser.Service service = info.service;
3215 if (mSafeMode && (service.info.applicationInfo.flags
3216 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3217 return null;
3218 }
3219 final ResolveInfo res = new ResolveInfo();
3220 res.serviceInfo = PackageParser.generateServiceInfo(service,
3221 mFlags);
3222 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3223 res.filter = filter;
3224 }
3225 res.priority = info.getPriority();
3226 res.preferredOrder = service.owner.mPreferredOrder;
3227 //System.out.println("Result: " + res.activityInfo.className +
3228 // " = " + res.priority);
3229 res.match = match;
3230 res.isDefault = info.hasDefault;
3231 res.labelRes = info.labelRes;
3232 res.nonLocalizedLabel = info.nonLocalizedLabel;
3233 res.icon = info.icon;
3234 return res;
3235 }
3236
3237 @Override
3238 protected void sortResults(List<ResolveInfo> results) {
3239 Collections.sort(results, mResolvePrioritySorter);
3240 }
3241
3242 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003243 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003245 out.print(prefix); out.print(
3246 Integer.toHexString(System.identityHashCode(filter.service)));
3247 out.print(' ');
3248 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 }
3250
3251// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3252// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3253// final List<ResolveInfo> retList = Lists.newArrayList();
3254// while (i.hasNext()) {
3255// final ResolveInfo resolveInfo = (ResolveInfo) i;
3256// if (isEnabledLP(resolveInfo.serviceInfo)) {
3257// retList.add(resolveInfo);
3258// }
3259// }
3260// return retList;
3261// }
3262
3263 // Keys are String (activity class name), values are Activity.
3264 private final HashMap<ComponentName, PackageParser.Service> mServices
3265 = new HashMap<ComponentName, PackageParser.Service>();
3266 private int mFlags;
3267 };
3268
3269 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3270 new Comparator<ResolveInfo>() {
3271 public int compare(ResolveInfo r1, ResolveInfo r2) {
3272 int v1 = r1.priority;
3273 int v2 = r2.priority;
3274 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3275 if (v1 != v2) {
3276 return (v1 > v2) ? -1 : 1;
3277 }
3278 v1 = r1.preferredOrder;
3279 v2 = r2.preferredOrder;
3280 if (v1 != v2) {
3281 return (v1 > v2) ? -1 : 1;
3282 }
3283 if (r1.isDefault != r2.isDefault) {
3284 return r1.isDefault ? -1 : 1;
3285 }
3286 v1 = r1.match;
3287 v2 = r2.match;
3288 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3289 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3290 }
3291 };
3292
3293 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3294 new Comparator<ProviderInfo>() {
3295 public int compare(ProviderInfo p1, ProviderInfo p2) {
3296 final int v1 = p1.initOrder;
3297 final int v2 = p2.initOrder;
3298 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3299 }
3300 };
3301
3302 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3303 IActivityManager am = ActivityManagerNative.getDefault();
3304 if (am != null) {
3305 try {
3306 final Intent intent = new Intent(action,
3307 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3308 if (extras != null) {
3309 intent.putExtras(extras);
3310 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003311 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 am.broadcastIntent(
3313 null, intent,
3314 null, null, 0, null, null, null, false, false);
3315 } catch (RemoteException ex) {
3316 }
3317 }
3318 }
3319
3320 private final class AppDirObserver extends FileObserver {
3321 public AppDirObserver(String path, int mask, boolean isrom) {
3322 super(path, mask);
3323 mRootDir = path;
3324 mIsRom = isrom;
3325 }
3326
3327 public void onEvent(int event, String path) {
3328 String removedPackage = null;
3329 int removedUid = -1;
3330 String addedPackage = null;
3331 int addedUid = -1;
3332
3333 synchronized (mInstallLock) {
3334 String fullPathStr = null;
3335 File fullPath = null;
3336 if (path != null) {
3337 fullPath = new File(mRootDir, path);
3338 fullPathStr = fullPath.getPath();
3339 }
3340
3341 if (Config.LOGV) Log.v(
3342 TAG, "File " + fullPathStr + " changed: "
3343 + Integer.toHexString(event));
3344
3345 if (!isPackageFilename(path)) {
3346 if (Config.LOGV) Log.v(
3347 TAG, "Ignoring change of non-package file: " + fullPathStr);
3348 return;
3349 }
3350
3351 if ((event&REMOVE_EVENTS) != 0) {
3352 synchronized (mInstallLock) {
3353 PackageParser.Package p = mAppDirs.get(fullPathStr);
3354 if (p != null) {
3355 removePackageLI(p, true);
3356 removedPackage = p.applicationInfo.packageName;
3357 removedUid = p.applicationInfo.uid;
3358 }
3359 }
3360 }
3361
3362 if ((event&ADD_EVENTS) != 0) {
3363 PackageParser.Package p = mAppDirs.get(fullPathStr);
3364 if (p == null) {
3365 p = scanPackageLI(fullPath, fullPath, fullPath,
3366 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3367 PackageParser.PARSE_CHATTY |
3368 PackageParser.PARSE_MUST_BE_APK,
3369 SCAN_MONITOR);
3370 if (p != null) {
3371 synchronized (mPackages) {
3372 grantPermissionsLP(p, false);
3373 }
3374 addedPackage = p.applicationInfo.packageName;
3375 addedUid = p.applicationInfo.uid;
3376 }
3377 }
3378 }
3379
3380 synchronized (mPackages) {
3381 mSettings.writeLP();
3382 }
3383 }
3384
3385 if (removedPackage != null) {
3386 Bundle extras = new Bundle(1);
3387 extras.putInt(Intent.EXTRA_UID, removedUid);
3388 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3389 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3390 }
3391 if (addedPackage != null) {
3392 Bundle extras = new Bundle(1);
3393 extras.putInt(Intent.EXTRA_UID, addedUid);
3394 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3395 }
3396 }
3397
3398 private final String mRootDir;
3399 private final boolean mIsRom;
3400 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02003401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 /* Called when a downloaded package installation has been confirmed by the user */
3403 public void installPackage(
3404 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazskic64322c2009-04-28 15:26:38 +02003405 installPackage(packageURI, observer, flags, null);
3406 }
3407
3408 /* Called when a downloaded package installation has been confirmed by the user */
3409 public void installPackage(
3410 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3411 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 mContext.enforceCallingOrSelfPermission(
3413 android.Manifest.permission.INSTALL_PACKAGES, null);
Jacek Surazskic64322c2009-04-28 15:26:38 +02003414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 // Queue up an async operation since the package installation may take a little while.
3416 mHandler.post(new Runnable() {
3417 public void run() {
3418 mHandler.removeCallbacks(this);
3419 PackageInstalledInfo res;
3420 synchronized (mInstallLock) {
Jacek Surazskic64322c2009-04-28 15:26:38 +02003421 res = installPackageLI(packageURI, flags, true, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 }
3423 if (observer != null) {
3424 try {
3425 observer.packageInstalled(res.name, res.returnCode);
3426 } catch (RemoteException e) {
3427 Log.i(TAG, "Observer no longer exists.");
3428 }
3429 }
3430 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3431 // call appears in the synchronized block above.
3432 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3433 res.removedInfo.sendBroadcast(false, true);
3434 Bundle extras = new Bundle(1);
3435 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003436 final boolean update = res.removedInfo.removedPackage != null;
3437 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3439 }
3440 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3441 res.pkg.applicationInfo.packageName,
3442 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003443 if (update) {
3444 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3445 res.pkg.applicationInfo.packageName,
3446 extras);
3447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
3449 Runtime.getRuntime().gc();
3450 }
3451 });
3452 }
3453
3454 class PackageInstalledInfo {
3455 String name;
3456 int uid;
3457 PackageParser.Package pkg;
3458 int returnCode;
3459 PackageRemovedInfo removedInfo;
3460 }
3461
3462 /*
3463 * Install a non-existing package.
3464 */
3465 private void installNewPackageLI(String pkgName,
3466 File tmpPackageFile,
3467 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003468 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003469 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 // Remember this for later, in case we need to rollback this install
3471 boolean dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3472 res.name = pkgName;
3473 synchronized(mPackages) {
3474 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(destFilePath)) {
3475 // Don't allow installation over an existing package with the same name.
3476 Log.w(TAG, "Attempt to re-install " + pkgName
3477 + " without first uninstalling.");
3478 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3479 return;
3480 }
3481 }
3482 if (destPackageFile.exists()) {
3483 // It's safe to do this because we know (from the above check) that the file
3484 // isn't currently used for an installed package.
3485 destPackageFile.delete();
3486 }
3487 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3488 PackageParser.Package newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3489 destResourceFile, pkg, 0,
3490 SCAN_MONITOR | SCAN_FORCE_DEX
3491 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003492 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3493 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 if (newPackage == null) {
3495 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3496 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3497 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3498 }
3499 } else {
3500 updateSettingsLI(pkgName, tmpPackageFile,
3501 destFilePath, destPackageFile,
3502 destResourceFile, pkg,
3503 newPackage,
3504 true,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003505 forwardLocked,
3506 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 res);
3508 // delete the partially installed application. the data directory will have to be
3509 // restored if it was already existing
3510 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3511 // remove package from internal structures. Note that we want deletePackageX to
3512 // delete the package data and cache directories that it created in
3513 // scanPackageLocked, unless those directories existed before we even tried to
3514 // install.
3515 deletePackageLI(
3516 pkgName, true,
3517 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3518 res.removedInfo);
3519 }
3520 }
3521 }
3522
3523 private void replacePackageLI(String pkgName,
3524 File tmpPackageFile,
3525 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003526 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003527 String installerPackageName, PackageInstalledInfo res) {
3528
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003529 PackageParser.Package oldPackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 // First find the old package info and check signatures
3531 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003532 oldPackage = mPackages.get(pkgName);
3533 if(checkSignaturesLP(pkg, oldPackage) != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3535 return;
3536 }
3537 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003538 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 if(sysPkg) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003540 replaceSystemPackageLI(oldPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003542 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003543 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 } else {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003545 replaceNonSystemPackageLI(oldPackage, tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003546 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003547 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 }
3549 }
3550
3551 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
3552 File tmpPackageFile,
3553 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003554 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003555 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 PackageParser.Package newPackage = null;
3557 String pkgName = deletedPackage.packageName;
3558 boolean deletedPkg = true;
3559 boolean updatedSettings = false;
Jacek Surazskic64322c2009-04-28 15:26:38 +02003560
3561 String oldInstallerPackageName = null;
3562 synchronized (mPackages) {
3563 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3564 }
3565
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003566 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 // First delete the existing package while retaining the data directory
3568 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3569 res.removedInfo)) {
3570 // If the existing package was'nt successfully deleted
3571 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3572 deletedPkg = false;
3573 } else {
3574 // Successfully deleted the old package. Now proceed with re-installation
3575 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3576 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3577 destResourceFile, pkg, parseFlags,
3578 SCAN_MONITOR | SCAN_FORCE_DEX
3579 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003580 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3581 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 if (newPackage == null) {
3583 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3584 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3585 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3586 }
3587 } else {
3588 updateSettingsLI(pkgName, tmpPackageFile,
3589 destFilePath, destPackageFile,
3590 destResourceFile, pkg,
3591 newPackage,
3592 true,
3593 forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003594 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 res);
3596 updatedSettings = true;
3597 }
3598 }
3599
3600 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3601 // If we deleted an exisiting package, the old source and resource files that we
3602 // were keeping around in case we needed them (see below) can now be deleted
3603 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
3604 final ApplicationInfo installedPackageAppInfo =
3605 newPackage.applicationInfo;
3606 if (!deletedPackageAppInfo.sourceDir
3607 .equals(installedPackageAppInfo.sourceDir)) {
3608 new File(deletedPackageAppInfo.sourceDir).delete();
3609 }
3610 if (!deletedPackageAppInfo.publicSourceDir
3611 .equals(installedPackageAppInfo.publicSourceDir)) {
3612 new File(deletedPackageAppInfo.publicSourceDir).delete();
3613 }
3614 //update signature on the new package setting
3615 //this should always succeed, since we checked the
3616 //signature earlier.
3617 synchronized(mPackages) {
3618 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
3619 parseFlags, true);
3620 }
3621 } else {
3622 // remove package from internal structures. Note that we want deletePackageX to
3623 // delete the package data and cache directories that it created in
3624 // scanPackageLocked, unless those directories existed before we even tried to
3625 // install.
3626 if(updatedSettings) {
3627 deletePackageLI(
3628 pkgName, true,
3629 PackageManager.DONT_DELETE_DATA,
3630 res.removedInfo);
3631 }
3632 // Since we failed to install the new package we need to restore the old
3633 // package that we deleted.
3634 if(deletedPkg) {
3635 installPackageLI(
3636 Uri.fromFile(new File(deletedPackage.mPath)),
3637 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003638 ? PackageManager.INSTALL_FORWARD_LOCK
Jacek Surazskic64322c2009-04-28 15:26:38 +02003639 : 0, false, oldInstallerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 }
3641 }
3642 }
3643
3644 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
3645 File tmpPackageFile,
3646 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003647 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003648 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 PackageParser.Package newPackage = null;
3650 boolean updatedSettings = false;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003651 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 PackageParser.PARSE_IS_SYSTEM;
3653 String packageName = deletedPackage.packageName;
3654 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3655 if (packageName == null) {
3656 Log.w(TAG, "Attempt to delete null packageName.");
3657 return;
3658 }
3659 PackageParser.Package oldPkg;
3660 PackageSetting oldPkgSetting;
3661 synchronized (mPackages) {
3662 oldPkg = mPackages.get(packageName);
3663 oldPkgSetting = mSettings.mPackages.get(packageName);
3664 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
3665 (oldPkgSetting == null)) {
3666 Log.w(TAG, "Could'nt find package:"+packageName+" information");
3667 return;
3668 }
3669 }
3670 res.removedInfo.uid = oldPkg.applicationInfo.uid;
3671 res.removedInfo.removedPackage = packageName;
3672 // Remove existing system package
3673 removePackageLI(oldPkg, true);
3674 synchronized (mPackages) {
3675 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
3676 }
3677
3678 // Successfully disabled the old package. Now proceed with re-installation
3679 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3680 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3681 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3682 destResourceFile, pkg, parseFlags,
3683 SCAN_MONITOR | SCAN_FORCE_DEX
3684 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003685 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3686 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 if (newPackage == null) {
3688 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3689 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3690 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3691 }
3692 } else {
3693 updateSettingsLI(packageName, tmpPackageFile,
3694 destFilePath, destPackageFile,
3695 destResourceFile, pkg,
3696 newPackage,
3697 true,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003698 forwardLocked,
3699 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 res);
3701 updatedSettings = true;
3702 }
3703
3704 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3705 //update signature on the new package setting
3706 //this should always succeed, since we checked the
3707 //signature earlier.
3708 synchronized(mPackages) {
3709 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
3710 parseFlags, true);
3711 }
3712 } else {
3713 // Re installation failed. Restore old information
3714 // Remove new pkg information
Dianne Hackborna96cbb42009-05-13 15:06:13 -07003715 if (newPackage != null) {
3716 removePackageLI(newPackage, true);
3717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 // Add back the old system package
3719 scanPackageLI(oldPkgSetting.codePath, oldPkgSetting.codePath,
3720 oldPkgSetting.resourcePath,
3721 oldPkg, parseFlags,
3722 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07003723 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 // Restore the old system information in Settings
3725 synchronized(mPackages) {
3726 if(updatedSettings) {
3727 mSettings.enableSystemPackageLP(packageName);
Jacek Surazskic64322c2009-04-28 15:26:38 +02003728 mSettings.setInstallerPackageName(packageName,
3729 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 }
3731 mSettings.writeLP();
3732 }
3733 }
3734 }
3735
3736 private void updateSettingsLI(String pkgName, File tmpPackageFile,
3737 String destFilePath, File destPackageFile,
3738 File destResourceFile,
3739 PackageParser.Package pkg,
3740 PackageParser.Package newPackage,
3741 boolean replacingExistingPackage,
3742 boolean forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003743 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 synchronized (mPackages) {
3745 //write settings. the installStatus will be incomplete at this stage.
3746 //note that the new package setting would have already been
3747 //added to mPackages. It hasn't been persisted yet.
3748 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
3749 mSettings.writeLP();
3750 }
3751
3752 int retCode = 0;
3753 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
3754 retCode = mInstaller.movedex(tmpPackageFile.toString(),
3755 destPackageFile.toString());
3756 if (retCode != 0) {
3757 Log.e(TAG, "Couldn't rename dex file: " + destPackageFile);
3758 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3759 return;
3760 }
3761 }
3762 // XXX There are probably some big issues here: upon doing
3763 // the rename, we have reached the point of no return (the
3764 // original .apk is gone!), so we can't fail. Yet... we can.
3765 if (!tmpPackageFile.renameTo(destPackageFile)) {
3766 Log.e(TAG, "Couldn't move package file to: " + destPackageFile);
3767 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3768 } else {
3769 res.returnCode = setPermissionsLI(pkgName, newPackage, destFilePath,
3770 destResourceFile,
3771 forwardLocked);
3772 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3773 return;
3774 } else {
3775 Log.d(TAG, "New package installed in " + destPackageFile);
3776 }
3777 }
3778 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3779 if (mInstaller != null) {
3780 mInstaller.rmdex(tmpPackageFile.getPath());
3781 }
3782 }
3783
3784 synchronized (mPackages) {
3785 grantPermissionsLP(newPackage, true);
3786 res.name = pkgName;
3787 res.uid = newPackage.applicationInfo.uid;
3788 res.pkg = newPackage;
3789 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazskic64322c2009-04-28 15:26:38 +02003790 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3792 //to update install status
3793 mSettings.writeLP();
3794 }
3795 }
3796
The Android Open Source Project10592532009-03-18 17:39:46 -07003797 private PackageInstalledInfo installPackageLI(Uri pPackageURI,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003798 int pFlags, boolean newInstall, String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 File tmpPackageFile = null;
3800 String pkgName = null;
3801 boolean forwardLocked = false;
3802 boolean replacingExistingPackage = false;
3803 // Result object to be returned
3804 PackageInstalledInfo res = new PackageInstalledInfo();
3805 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3806 res.uid = -1;
3807 res.pkg = null;
3808 res.removedInfo = new PackageRemovedInfo();
3809
3810 main_flow: try {
3811 tmpPackageFile = createTempPackageFile();
3812 if (tmpPackageFile == null) {
3813 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3814 break main_flow;
3815 }
3816 tmpPackageFile.deleteOnExit(); // paranoia
3817 if (pPackageURI.getScheme().equals("file")) {
3818 final File srcPackageFile = new File(pPackageURI.getPath());
3819 // We copy the source package file to a temp file and then rename it to the
3820 // destination file in order to eliminate a window where the package directory
3821 // scanner notices the new package file but it's not completely copied yet.
3822 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
3823 Log.e(TAG, "Couldn't copy package file to temp file.");
3824 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3825 break main_flow;
3826 }
3827 } else if (pPackageURI.getScheme().equals("content")) {
3828 ParcelFileDescriptor fd;
3829 try {
3830 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
3831 } catch (FileNotFoundException e) {
3832 Log.e(TAG, "Couldn't open file descriptor from download service.");
3833 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3834 break main_flow;
3835 }
3836 if (fd == null) {
3837 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
3838 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3839 break main_flow;
3840 }
3841 if (Config.LOGV) {
3842 Log.v(TAG, "Opened file descriptor from download service.");
3843 }
3844 ParcelFileDescriptor.AutoCloseInputStream
3845 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
3846 // We copy the source package file to a temp file and then rename it to the
3847 // destination file in order to eliminate a window where the package directory
3848 // scanner notices the new package file but it's not completely copied yet.
3849 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
3850 Log.e(TAG, "Couldn't copy package stream to temp file.");
3851 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3852 break main_flow;
3853 }
3854 } else {
3855 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
3856 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_URI;
3857 break main_flow;
3858 }
3859 pkgName = PackageParser.parsePackageName(
3860 tmpPackageFile.getAbsolutePath(), 0);
3861 if (pkgName == null) {
3862 Log.e(TAG, "Couldn't find a package name in : " + tmpPackageFile);
3863 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3864 break main_flow;
3865 }
3866 res.name = pkgName;
3867 //initialize some variables before installing pkg
3868 final String pkgFileName = pkgName + ".apk";
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003869 final File destDir = ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 ? mDrmAppPrivateInstallDir
3871 : mAppInstallDir;
3872 final File destPackageFile = new File(destDir, pkgFileName);
3873 final String destFilePath = destPackageFile.getAbsolutePath();
3874 File destResourceFile;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003875 if ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 final String publicZipFileName = pkgName + ".zip";
3877 destResourceFile = new File(mAppInstallDir, publicZipFileName);
3878 forwardLocked = true;
3879 } else {
3880 destResourceFile = destPackageFile;
3881 }
3882 // Retrieve PackageSettings and parse package
3883 int parseFlags = PackageParser.PARSE_CHATTY;
3884 parseFlags |= mDefParseFlags;
3885 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
3886 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackborn851a5412009-05-08 12:06:44 -07003887 pp.setSdkVersion(mSdkVersion, mSdkCodename);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
3889 destPackageFile.getAbsolutePath(), mMetrics, parseFlags);
3890 if (pkg == null) {
3891 res.returnCode = pp.getParseError();
3892 break main_flow;
3893 }
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003894 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
3895 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
3896 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
3897 break main_flow;
3898 }
3899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
3901 res.returnCode = pp.getParseError();
3902 break main_flow;
3903 }
3904
3905 synchronized (mPackages) {
3906 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003907 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 && mPackages.containsKey(pkgName)) {
3909 replacingExistingPackage = true;
3910 }
3911 }
3912
3913 if(replacingExistingPackage) {
3914 replacePackageLI(pkgName,
3915 tmpPackageFile,
3916 destFilePath, destPackageFile, destResourceFile,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003917 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 res);
3919 } else {
3920 installNewPackageLI(pkgName,
3921 tmpPackageFile,
3922 destFilePath, destPackageFile, destResourceFile,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003923 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 res);
3925 }
3926 } finally {
3927 if (tmpPackageFile != null && tmpPackageFile.exists()) {
3928 tmpPackageFile.delete();
3929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003931 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 }
3933
3934 private int setPermissionsLI(String pkgName,
3935 PackageParser.Package newPackage,
3936 String destFilePath,
3937 File destResourceFile,
3938 boolean forwardLocked) {
3939 int retCode;
3940 if (forwardLocked) {
3941 try {
3942 extractPublicFiles(newPackage, destResourceFile);
3943 } catch (IOException e) {
3944 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
3945 " forward-locked app.");
3946 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3947 } finally {
3948 //TODO clean up the extracted public files
3949 }
3950 if (mInstaller != null) {
3951 retCode = mInstaller.setForwardLockPerm(pkgName,
3952 newPackage.applicationInfo.uid);
3953 } else {
3954 final int filePermissions =
3955 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
3956 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1,
3957 newPackage.applicationInfo.uid);
3958 }
3959 } else {
3960 final int filePermissions =
3961 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
3962 |FileUtils.S_IROTH;
3963 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1, -1);
3964 }
3965 if (retCode != 0) {
3966 Log.e(TAG, "Couldn't set new package file permissions for " + destFilePath
3967 + ". The return code was: " + retCode);
3968 }
3969 return PackageManager.INSTALL_SUCCEEDED;
3970 }
3971
3972 private boolean isForwardLocked(PackageParser.Package deletedPackage) {
3973 final ApplicationInfo applicationInfo = deletedPackage.applicationInfo;
3974 return applicationInfo.sourceDir.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath());
3975 }
3976
3977 private void extractPublicFiles(PackageParser.Package newPackage,
3978 File publicZipFile) throws IOException {
3979 final ZipOutputStream publicZipOutStream =
3980 new ZipOutputStream(new FileOutputStream(publicZipFile));
3981 final ZipFile privateZip = new ZipFile(newPackage.mPath);
3982
3983 // Copy manifest, resources.arsc and res directory to public zip
3984
3985 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
3986 while (privateZipEntries.hasMoreElements()) {
3987 final ZipEntry zipEntry = privateZipEntries.nextElement();
3988 final String zipEntryName = zipEntry.getName();
3989 if ("AndroidManifest.xml".equals(zipEntryName)
3990 || "resources.arsc".equals(zipEntryName)
3991 || zipEntryName.startsWith("res/")) {
3992 try {
3993 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
3994 } catch (IOException e) {
3995 try {
3996 publicZipOutStream.close();
3997 throw e;
3998 } finally {
3999 publicZipFile.delete();
4000 }
4001 }
4002 }
4003 }
4004
4005 publicZipOutStream.close();
4006 FileUtils.setPermissions(
4007 publicZipFile.getAbsolutePath(),
4008 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4009 -1, -1);
4010 }
4011
4012 private static void copyZipEntry(ZipEntry zipEntry,
4013 ZipFile inZipFile,
4014 ZipOutputStream outZipStream) throws IOException {
4015 byte[] buffer = new byte[4096];
4016 int num;
4017
4018 ZipEntry newEntry;
4019 if (zipEntry.getMethod() == ZipEntry.STORED) {
4020 // Preserve the STORED method of the input entry.
4021 newEntry = new ZipEntry(zipEntry);
4022 } else {
4023 // Create a new entry so that the compressed len is recomputed.
4024 newEntry = new ZipEntry(zipEntry.getName());
4025 }
4026 outZipStream.putNextEntry(newEntry);
4027
4028 InputStream data = inZipFile.getInputStream(zipEntry);
4029 while ((num = data.read(buffer)) > 0) {
4030 outZipStream.write(buffer, 0, num);
4031 }
4032 outZipStream.flush();
4033 }
4034
4035 private void deleteTempPackageFiles() {
4036 FilenameFilter filter = new FilenameFilter() {
4037 public boolean accept(File dir, String name) {
4038 return name.startsWith("vmdl") && name.endsWith(".tmp");
4039 }
4040 };
4041 String tmpFilesList[] = mAppInstallDir.list(filter);
4042 if(tmpFilesList == null) {
4043 return;
4044 }
4045 for(int i = 0; i < tmpFilesList.length; i++) {
4046 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4047 tmpFile.delete();
4048 }
4049 }
4050
4051 private File createTempPackageFile() {
4052 File tmpPackageFile;
4053 try {
4054 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
4055 } catch (IOException e) {
4056 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4057 return null;
4058 }
4059 try {
4060 FileUtils.setPermissions(
4061 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4062 -1, -1);
4063 } catch (IOException e) {
4064 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4065 return null;
4066 }
4067 return tmpPackageFile;
4068 }
4069
4070 public void deletePackage(final String packageName,
4071 final IPackageDeleteObserver observer,
4072 final int flags) {
4073 mContext.enforceCallingOrSelfPermission(
4074 android.Manifest.permission.DELETE_PACKAGES, null);
4075 // Queue up an async operation since the package deletion may take a little while.
4076 mHandler.post(new Runnable() {
4077 public void run() {
4078 mHandler.removeCallbacks(this);
4079 final boolean succeded = deletePackageX(packageName, true, true, flags);
4080 if (observer != null) {
4081 try {
4082 observer.packageDeleted(succeded);
4083 } catch (RemoteException e) {
4084 Log.i(TAG, "Observer no longer exists.");
4085 } //end catch
4086 } //end if
4087 } //end run
4088 });
4089 }
4090
4091 /**
4092 * This method is an internal method that could be get invoked either
4093 * to delete an installed package or to clean up a failed installation.
4094 * After deleting an installed package, a broadcast is sent to notify any
4095 * listeners that the package has been installed. For cleaning up a failed
4096 * installation, the broadcast is not necessary since the package's
4097 * installation wouldn't have sent the initial broadcast either
4098 * The key steps in deleting a package are
4099 * deleting the package information in internal structures like mPackages,
4100 * deleting the packages base directories through installd
4101 * updating mSettings to reflect current status
4102 * persisting settings for later use
4103 * sending a broadcast if necessary
4104 */
4105
4106 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4107 boolean deleteCodeAndResources, int flags) {
4108 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004109 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110
4111 synchronized (mInstallLock) {
4112 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4113 }
4114
4115 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004116 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4117 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4118
4119 // If the removed package was a system update, the old system packaged
4120 // was re-enabled; we need to broadcast this information
4121 if (systemUpdate) {
4122 Bundle extras = new Bundle(1);
4123 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4124 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4125
4126 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4127 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 }
4130 return res;
4131 }
4132
4133 static class PackageRemovedInfo {
4134 String removedPackage;
4135 int uid = -1;
4136 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004137 boolean isRemovedPackageSystemUpdate = false;
4138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 void sendBroadcast(boolean fullRemove, boolean replacing) {
4140 Bundle extras = new Bundle(1);
4141 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4142 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4143 if (replacing) {
4144 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4145 }
4146 if (removedPackage != null) {
4147 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4148 }
4149 if (removedUid >= 0) {
4150 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4151 }
4152 }
4153 }
4154
4155 /*
4156 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4157 * flag is not set, the data directory is removed as well.
4158 * make sure this flag is set for partially installed apps. If not its meaningless to
4159 * delete a partially installed application.
4160 */
4161 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
4162 int flags) {
4163 String packageName = p.packageName;
4164 outInfo.removedPackage = packageName;
4165 removePackageLI(p, true);
4166 // Retrieve object to delete permissions for shared user later on
4167 PackageSetting deletedPs;
4168 synchronized (mPackages) {
4169 deletedPs = mSettings.mPackages.get(packageName);
4170 }
4171 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
4172 if (mInstaller != null) {
4173 int retCode = mInstaller.remove(packageName);
4174 if (retCode < 0) {
4175 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4176 + packageName + ", retcode=" + retCode);
4177 // we don't consider this to be a failure of the core package deletion
4178 }
4179 } else {
4180 //for emulator
4181 PackageParser.Package pkg = mPackages.get(packageName);
4182 File dataDir = new File(pkg.applicationInfo.dataDir);
4183 dataDir.delete();
4184 }
4185 synchronized (mPackages) {
4186 outInfo.removedUid = mSettings.removePackageLP(packageName);
4187 }
4188 }
4189 synchronized (mPackages) {
4190 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4191 // remove permissions associated with package
4192 mSettings.updateSharedUserPerms (deletedPs);
4193 }
4194 // Save settings now
4195 mSettings.writeLP ();
4196 }
4197 }
4198
4199 /*
4200 * Tries to delete system package.
4201 */
4202 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004203 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 ApplicationInfo applicationInfo = p.applicationInfo;
4205 //applicable for non-partially installed applications only
4206 if (applicationInfo == null) {
4207 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4208 return false;
4209 }
4210 PackageSetting ps = null;
4211 // Confirm if the system package has been updated
4212 // An updated system app can be deleted. This will also have to restore
4213 // the system pkg from system partition
4214 synchronized (mPackages) {
4215 ps = mSettings.getDisabledSystemPkg(p.packageName);
4216 }
4217 if (ps == null) {
4218 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4219 return false;
4220 } else {
4221 Log.i(TAG, "Deleting system pkg from data partition");
4222 }
4223 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004224 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004225 boolean deleteCodeAndResources = false;
4226 if (ps.versionCode < p.mVersionCode) {
4227 // Delete code and resources for downgrades
4228 deleteCodeAndResources = true;
4229 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4230 flags &= ~PackageManager.DONT_DELETE_DATA;
4231 }
4232 } else {
4233 // Preserve data by setting flag
4234 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4235 flags |= PackageManager.DONT_DELETE_DATA;
4236 }
4237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4239 if (!ret) {
4240 return false;
4241 }
4242 synchronized (mPackages) {
4243 // Reinstate the old system package
4244 mSettings.enableSystemPackageLP(p.packageName);
4245 }
4246 // Install the system package
4247 PackageParser.Package newPkg = scanPackageLI(ps.codePath, ps.codePath, ps.resourcePath,
4248 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
4249 SCAN_MONITOR);
4250
4251 if (newPkg == null) {
4252 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4253 return false;
4254 }
4255 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07004256 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 mSettings.writeLP();
4258 }
4259 return true;
4260 }
4261
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004262 private void deletePackageResourcesLI(String packageName,
4263 String sourceDir, String publicSourceDir) {
4264 File sourceFile = new File(sourceDir);
4265 if (!sourceFile.exists()) {
4266 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4267 }
4268 // Delete application's code and resources
4269 sourceFile.delete();
4270 final File publicSourceFile = new File(publicSourceDir);
4271 if (publicSourceFile.exists()) {
4272 publicSourceFile.delete();
4273 }
4274 if (mInstaller != null) {
4275 int retCode = mInstaller.rmdex(sourceFile.toString());
4276 if (retCode < 0) {
4277 Log.w(TAG, "Couldn't remove dex file for package: "
4278 + packageName + " at location " + sourceFile.toString() + ", retcode=" + retCode);
4279 // we don't consider this to be a failure of the core package deletion
4280 }
4281 }
4282 }
4283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4285 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4286 ApplicationInfo applicationInfo = p.applicationInfo;
4287 if (applicationInfo == null) {
4288 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4289 return false;
4290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 outInfo.uid = applicationInfo.uid;
4292
4293 // Delete package data from internal structures and also remove data if flag is set
4294 removePackageDataLI(p, outInfo, flags);
4295
4296 // Delete application code and resources
4297 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004298 deletePackageResourcesLI(applicationInfo.packageName,
4299 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 }
4301 return true;
4302 }
4303
4304 /*
4305 * This method handles package deletion in general
4306 */
4307 private boolean deletePackageLI(String packageName,
4308 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4309 if (packageName == null) {
4310 Log.w(TAG, "Attempt to delete null packageName.");
4311 return false;
4312 }
4313 PackageParser.Package p;
4314 boolean dataOnly = false;
4315 synchronized (mPackages) {
4316 p = mPackages.get(packageName);
4317 if (p == null) {
4318 //this retrieves partially installed apps
4319 dataOnly = true;
4320 PackageSetting ps = mSettings.mPackages.get(packageName);
4321 if (ps == null) {
4322 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4323 return false;
4324 }
4325 p = ps.pkg;
4326 }
4327 }
4328 if (p == null) {
4329 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4330 return false;
4331 }
4332
4333 if (dataOnly) {
4334 // Delete application data first
4335 removePackageDataLI(p, outInfo, flags);
4336 return true;
4337 }
4338 // At this point the package should have ApplicationInfo associated with it
4339 if (p.applicationInfo == null) {
4340 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4341 return false;
4342 }
4343 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4344 Log.i(TAG, "Removing system package:"+p.packageName);
4345 // When an updated system application is deleted we delete the existing resources as well and
4346 // fall back to existing code in system partition
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004347 return deleteSystemPackageLI(p, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348 }
4349 Log.i(TAG, "Removing non-system package:"+p.packageName);
4350 return deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
4351 }
4352
4353 public void clearApplicationUserData(final String packageName,
4354 final IPackageDataObserver observer) {
4355 mContext.enforceCallingOrSelfPermission(
4356 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4357 // Queue up an async operation since the package deletion may take a little while.
4358 mHandler.post(new Runnable() {
4359 public void run() {
4360 mHandler.removeCallbacks(this);
4361 final boolean succeeded;
4362 synchronized (mInstallLock) {
4363 succeeded = clearApplicationUserDataLI(packageName);
4364 }
4365 if (succeeded) {
4366 // invoke DeviceStorageMonitor's update method to clear any notifications
4367 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4368 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4369 if (dsm != null) {
4370 dsm.updateMemory();
4371 }
4372 }
4373 if(observer != null) {
4374 try {
4375 observer.onRemoveCompleted(packageName, succeeded);
4376 } catch (RemoteException e) {
4377 Log.i(TAG, "Observer no longer exists.");
4378 }
4379 } //end if observer
4380 } //end run
4381 });
4382 }
4383
4384 private boolean clearApplicationUserDataLI(String packageName) {
4385 if (packageName == null) {
4386 Log.w(TAG, "Attempt to delete null packageName.");
4387 return false;
4388 }
4389 PackageParser.Package p;
4390 boolean dataOnly = false;
4391 synchronized (mPackages) {
4392 p = mPackages.get(packageName);
4393 if(p == null) {
4394 dataOnly = true;
4395 PackageSetting ps = mSettings.mPackages.get(packageName);
4396 if((ps == null) || (ps.pkg == null)) {
4397 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4398 return false;
4399 }
4400 p = ps.pkg;
4401 }
4402 }
4403 if(!dataOnly) {
4404 //need to check this only for fully installed applications
4405 if (p == null) {
4406 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4407 return false;
4408 }
4409 final ApplicationInfo applicationInfo = p.applicationInfo;
4410 if (applicationInfo == null) {
4411 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4412 return false;
4413 }
4414 }
4415 if (mInstaller != null) {
4416 int retCode = mInstaller.clearUserData(packageName);
4417 if (retCode < 0) {
4418 Log.w(TAG, "Couldn't remove cache files for package: "
4419 + packageName);
4420 return false;
4421 }
4422 }
4423 return true;
4424 }
4425
4426 public void deleteApplicationCacheFiles(final String packageName,
4427 final IPackageDataObserver observer) {
4428 mContext.enforceCallingOrSelfPermission(
4429 android.Manifest.permission.DELETE_CACHE_FILES, null);
4430 // Queue up an async operation since the package deletion may take a little while.
4431 mHandler.post(new Runnable() {
4432 public void run() {
4433 mHandler.removeCallbacks(this);
4434 final boolean succeded;
4435 synchronized (mInstallLock) {
4436 succeded = deleteApplicationCacheFilesLI(packageName);
4437 }
4438 if(observer != null) {
4439 try {
4440 observer.onRemoveCompleted(packageName, succeded);
4441 } catch (RemoteException e) {
4442 Log.i(TAG, "Observer no longer exists.");
4443 }
4444 } //end if observer
4445 } //end run
4446 });
4447 }
4448
4449 private boolean deleteApplicationCacheFilesLI(String packageName) {
4450 if (packageName == null) {
4451 Log.w(TAG, "Attempt to delete null packageName.");
4452 return false;
4453 }
4454 PackageParser.Package p;
4455 synchronized (mPackages) {
4456 p = mPackages.get(packageName);
4457 }
4458 if (p == null) {
4459 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4460 return false;
4461 }
4462 final ApplicationInfo applicationInfo = p.applicationInfo;
4463 if (applicationInfo == null) {
4464 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4465 return false;
4466 }
4467 if (mInstaller != null) {
4468 int retCode = mInstaller.deleteCacheFiles(packageName);
4469 if (retCode < 0) {
4470 Log.w(TAG, "Couldn't remove cache files for package: "
4471 + packageName);
4472 return false;
4473 }
4474 }
4475 return true;
4476 }
4477
4478 public void getPackageSizeInfo(final String packageName,
4479 final IPackageStatsObserver observer) {
4480 mContext.enforceCallingOrSelfPermission(
4481 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4482 // Queue up an async operation since the package deletion may take a little while.
4483 mHandler.post(new Runnable() {
4484 public void run() {
4485 mHandler.removeCallbacks(this);
4486 PackageStats lStats = new PackageStats(packageName);
4487 final boolean succeded;
4488 synchronized (mInstallLock) {
4489 succeded = getPackageSizeInfoLI(packageName, lStats);
4490 }
4491 if(observer != null) {
4492 try {
4493 observer.onGetStatsCompleted(lStats, succeded);
4494 } catch (RemoteException e) {
4495 Log.i(TAG, "Observer no longer exists.");
4496 }
4497 } //end if observer
4498 } //end run
4499 });
4500 }
4501
4502 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4503 if (packageName == null) {
4504 Log.w(TAG, "Attempt to get size of null packageName.");
4505 return false;
4506 }
4507 PackageParser.Package p;
4508 boolean dataOnly = false;
4509 synchronized (mPackages) {
4510 p = mPackages.get(packageName);
4511 if(p == null) {
4512 dataOnly = true;
4513 PackageSetting ps = mSettings.mPackages.get(packageName);
4514 if((ps == null) || (ps.pkg == null)) {
4515 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4516 return false;
4517 }
4518 p = ps.pkg;
4519 }
4520 }
4521 String publicSrcDir = null;
4522 if(!dataOnly) {
4523 final ApplicationInfo applicationInfo = p.applicationInfo;
4524 if (applicationInfo == null) {
4525 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4526 return false;
4527 }
4528 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4529 }
4530 if (mInstaller != null) {
4531 int res = mInstaller.getSizeInfo(packageName, p.mPath,
4532 publicSrcDir, pStats);
4533 if (res < 0) {
4534 return false;
4535 } else {
4536 return true;
4537 }
4538 }
4539 return true;
4540 }
4541
4542
4543 public void addPackageToPreferred(String packageName) {
4544 mContext.enforceCallingOrSelfPermission(
4545 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4546
4547 synchronized (mPackages) {
4548 PackageParser.Package p = mPackages.get(packageName);
4549 if (p == null) {
4550 return;
4551 }
4552 PackageSetting ps = (PackageSetting)p.mExtras;
4553 if (ps != null) {
4554 mSettings.mPreferredPackages.remove(ps);
4555 mSettings.mPreferredPackages.add(0, ps);
4556 updatePreferredIndicesLP();
4557 mSettings.writeLP();
4558 }
4559 }
4560 }
4561
4562 public void removePackageFromPreferred(String packageName) {
4563 mContext.enforceCallingOrSelfPermission(
4564 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4565
4566 synchronized (mPackages) {
4567 PackageParser.Package p = mPackages.get(packageName);
4568 if (p == null) {
4569 return;
4570 }
4571 if (p.mPreferredOrder > 0) {
4572 PackageSetting ps = (PackageSetting)p.mExtras;
4573 if (ps != null) {
4574 mSettings.mPreferredPackages.remove(ps);
4575 p.mPreferredOrder = 0;
4576 updatePreferredIndicesLP();
4577 mSettings.writeLP();
4578 }
4579 }
4580 }
4581 }
4582
4583 private void updatePreferredIndicesLP() {
4584 final ArrayList<PackageSetting> pkgs
4585 = mSettings.mPreferredPackages;
4586 final int N = pkgs.size();
4587 for (int i=0; i<N; i++) {
4588 pkgs.get(i).pkg.mPreferredOrder = N - i;
4589 }
4590 }
4591
4592 public List<PackageInfo> getPreferredPackages(int flags) {
4593 synchronized (mPackages) {
4594 final ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
4595 final ArrayList<PackageSetting> pref = mSettings.mPreferredPackages;
4596 final int N = pref.size();
4597 for (int i=0; i<N; i++) {
4598 res.add(generatePackageInfo(pref.get(i).pkg, flags));
4599 }
4600 return res;
4601 }
4602 }
4603
4604 public void addPreferredActivity(IntentFilter filter, int match,
4605 ComponentName[] set, ComponentName activity) {
4606 mContext.enforceCallingOrSelfPermission(
4607 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4608
4609 synchronized (mPackages) {
4610 Log.i(TAG, "Adding preferred activity " + activity + ":");
4611 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4612 mSettings.mPreferredActivities.addFilter(
4613 new PreferredActivity(filter, match, set, activity));
4614 mSettings.writeLP();
4615 }
4616 }
4617
Satish Sampath8dbe6122009-06-02 23:35:54 +01004618 public void replacePreferredActivity(IntentFilter filter, int match,
4619 ComponentName[] set, ComponentName activity) {
4620 mContext.enforceCallingOrSelfPermission(
4621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4622 if (filter.countActions() != 1) {
4623 throw new IllegalArgumentException(
4624 "replacePreferredActivity expects filter to have only 1 action.");
4625 }
4626 if (filter.countCategories() != 1) {
4627 throw new IllegalArgumentException(
4628 "replacePreferredActivity expects filter to have only 1 category.");
4629 }
4630 if (filter.countDataAuthorities() != 0
4631 || filter.countDataPaths() != 0
4632 || filter.countDataSchemes() != 0
4633 || filter.countDataTypes() != 0) {
4634 throw new IllegalArgumentException(
4635 "replacePreferredActivity expects filter to have no data authorities, " +
4636 "paths, schemes or types.");
4637 }
4638 synchronized (mPackages) {
4639 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4640 String action = filter.getAction(0);
4641 String category = filter.getCategory(0);
4642 while (it.hasNext()) {
4643 PreferredActivity pa = it.next();
4644 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
4645 it.remove();
4646 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
4647 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4648 }
4649 }
4650 addPreferredActivity(filter, match, set, activity);
4651 }
4652 }
4653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 public void clearPackagePreferredActivities(String packageName) {
4655 mContext.enforceCallingOrSelfPermission(
4656 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4657
4658 synchronized (mPackages) {
4659 if (clearPackagePreferredActivitiesLP(packageName)) {
4660 mSettings.writeLP();
4661 }
4662 }
4663 }
4664
4665 boolean clearPackagePreferredActivitiesLP(String packageName) {
4666 boolean changed = false;
4667 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4668 while (it.hasNext()) {
4669 PreferredActivity pa = it.next();
4670 if (pa.mActivity.getPackageName().equals(packageName)) {
4671 it.remove();
4672 changed = true;
4673 }
4674 }
4675 return changed;
4676 }
4677
4678 public int getPreferredActivities(List<IntentFilter> outFilters,
4679 List<ComponentName> outActivities, String packageName) {
4680
4681 int num = 0;
4682 synchronized (mPackages) {
4683 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4684 while (it.hasNext()) {
4685 PreferredActivity pa = it.next();
4686 if (packageName == null
4687 || pa.mActivity.getPackageName().equals(packageName)) {
4688 if (outFilters != null) {
4689 outFilters.add(new IntentFilter(pa));
4690 }
4691 if (outActivities != null) {
4692 outActivities.add(pa.mActivity);
4693 }
4694 }
4695 }
4696 }
4697
4698 return num;
4699 }
4700
4701 public void setApplicationEnabledSetting(String appPackageName,
4702 int newState, int flags) {
4703 setEnabledSetting(appPackageName, null, newState, flags);
4704 }
4705
4706 public void setComponentEnabledSetting(ComponentName componentName,
4707 int newState, int flags) {
4708 setEnabledSetting(componentName.getPackageName(),
4709 componentName.getClassName(), newState, flags);
4710 }
4711
4712 private void setEnabledSetting(
4713 final String packageNameStr, String classNameStr, int newState, final int flags) {
4714 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
4715 || newState == COMPONENT_ENABLED_STATE_ENABLED
4716 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
4717 throw new IllegalArgumentException("Invalid new component state: "
4718 + newState);
4719 }
4720 PackageSetting pkgSetting;
4721 final int uid = Binder.getCallingUid();
4722 final int permission = mContext.checkCallingPermission(
4723 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
4724 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4725 int packageUid = -1;
4726 synchronized (mPackages) {
4727 pkgSetting = mSettings.mPackages.get(packageNameStr);
4728 if (pkgSetting == null) {
4729 if (classNameStr == null) {
4730 throw new IllegalArgumentException(
4731 "Unknown package: " + packageNameStr);
4732 }
4733 throw new IllegalArgumentException(
4734 "Unknown component: " + packageNameStr
4735 + "/" + classNameStr);
4736 }
4737 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4738 throw new SecurityException(
4739 "Permission Denial: attempt to change component state from pid="
4740 + Binder.getCallingPid()
4741 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
4742 }
4743 packageUid = pkgSetting.userId;
4744 if (classNameStr == null) {
4745 // We're dealing with an application/package level state change
4746 pkgSetting.enabled = newState;
4747 } else {
4748 // We're dealing with a component level state change
4749 switch (newState) {
4750 case COMPONENT_ENABLED_STATE_ENABLED:
4751 pkgSetting.enableComponentLP(classNameStr);
4752 break;
4753 case COMPONENT_ENABLED_STATE_DISABLED:
4754 pkgSetting.disableComponentLP(classNameStr);
4755 break;
4756 case COMPONENT_ENABLED_STATE_DEFAULT:
4757 pkgSetting.restoreComponentLP(classNameStr);
4758 break;
4759 default:
4760 Log.e(TAG, "Invalid new component state: " + newState);
4761 }
4762 }
4763 mSettings.writeLP();
4764 }
4765
4766 long callingId = Binder.clearCallingIdentity();
4767 try {
4768 Bundle extras = new Bundle(2);
4769 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP,
4770 (flags&PackageManager.DONT_KILL_APP) != 0);
4771 extras.putInt(Intent.EXTRA_UID, packageUid);
4772 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageNameStr, extras);
4773 } finally {
4774 Binder.restoreCallingIdentity(callingId);
4775 }
4776 }
4777
Jacek Surazskic64322c2009-04-28 15:26:38 +02004778 public String getInstallerPackageName(String packageName) {
4779 synchronized (mPackages) {
4780 PackageSetting pkg = mSettings.mPackages.get(packageName);
4781 if (pkg == null) {
4782 throw new IllegalArgumentException("Unknown package: " + packageName);
4783 }
4784 return pkg.installerPackageName;
4785 }
4786 }
4787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 public int getApplicationEnabledSetting(String appPackageName) {
4789 synchronized (mPackages) {
4790 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
4791 if (pkg == null) {
4792 throw new IllegalArgumentException("Unknown package: " + appPackageName);
4793 }
4794 return pkg.enabled;
4795 }
4796 }
4797
4798 public int getComponentEnabledSetting(ComponentName componentName) {
4799 synchronized (mPackages) {
4800 final String packageNameStr = componentName.getPackageName();
4801 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
4802 if (pkg == null) {
4803 throw new IllegalArgumentException("Unknown component: " + componentName);
4804 }
4805 final String classNameStr = componentName.getClassName();
4806 return pkg.currentEnabledStateLP(classNameStr);
4807 }
4808 }
4809
4810 public void enterSafeMode() {
4811 if (!mSystemReady) {
4812 mSafeMode = true;
4813 }
4814 }
4815
4816 public void systemReady() {
4817 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07004818
4819 // Read the compatibilty setting when the system is ready.
4820 mCompatibilityModeEnabled = android.provider.Settings.System.getInt(
4821 mContext.getContentResolver(),
4822 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
4823 if (DEBUG_SETTINGS) {
4824 Log.d(TAG, "compatibility mode:" + mCompatibilityModeEnabled);
4825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 }
4827
4828 public boolean isSafeMode() {
4829 return mSafeMode;
4830 }
4831
4832 public boolean hasSystemUidErrors() {
4833 return mHasSystemUidErrors;
4834 }
4835
4836 static String arrayToString(int[] array) {
4837 StringBuffer buf = new StringBuffer(128);
4838 buf.append('[');
4839 if (array != null) {
4840 for (int i=0; i<array.length; i++) {
4841 if (i > 0) buf.append(", ");
4842 buf.append(array[i]);
4843 }
4844 }
4845 buf.append(']');
4846 return buf.toString();
4847 }
4848
4849 @Override
4850 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4851 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4852 != PackageManager.PERMISSION_GRANTED) {
4853 pw.println("Permission Denial: can't dump ActivityManager from from pid="
4854 + Binder.getCallingPid()
4855 + ", uid=" + Binder.getCallingUid()
4856 + " without permission "
4857 + android.Manifest.permission.DUMP);
4858 return;
4859 }
4860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004861 synchronized (mPackages) {
4862 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004863 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 pw.println(" ");
4865 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004866 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 pw.println(" ");
4868 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004869 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 pw.println(" ");
4871 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004872 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004873 pw.println(" ");
4874 pw.println("Preferred Packages:");
4875 {
4876 for (PackageSetting ps : mSettings.mPreferredPackages) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004877 pw.print(" "); pw.println(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004878 }
4879 }
4880 pw.println(" ");
4881 pw.println("Permissions:");
4882 {
4883 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004884 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
4885 pw.print(Integer.toHexString(System.identityHashCode(p)));
4886 pw.println("):");
4887 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
4888 pw.print(" uid="); pw.print(p.uid);
4889 pw.print(" gids="); pw.print(arrayToString(p.gids));
4890 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 }
4892 }
4893 pw.println(" ");
4894 pw.println("Packages:");
4895 {
4896 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004897 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
4898 pw.print(Integer.toHexString(System.identityHashCode(ps)));
4899 pw.println("):");
4900 pw.print(" userId="); pw.print(ps.userId);
4901 pw.print(" gids="); pw.println(arrayToString(ps.gids));
4902 pw.print(" sharedUser="); pw.println(ps.sharedUser);
4903 pw.print(" pkg="); pw.println(ps.pkg);
4904 pw.print(" codePath="); pw.println(ps.codePathString);
4905 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004906 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004907 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004909 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
4910 pw.print(" signatures="); pw.println(ps.signatures);
4911 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
4912 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
4913 pw.print(" installStatus="); pw.print(ps.installStatus);
4914 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 if (ps.disabledComponents.size() > 0) {
4916 pw.println(" disabledComponents:");
4917 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004918 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004919 }
4920 }
4921 if (ps.enabledComponents.size() > 0) {
4922 pw.println(" enabledComponents:");
4923 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004924 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 }
4926 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004927 if (ps.grantedPermissions.size() > 0) {
4928 pw.println(" grantedPermissions:");
4929 for (String s : ps.grantedPermissions) {
4930 pw.print(" "); pw.println(s);
4931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004932 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004933 if (ps.loadedPermissions.size() > 0) {
4934 pw.println(" loadedPermissions:");
4935 for (String s : ps.loadedPermissions) {
4936 pw.print(" "); pw.println(s);
4937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004938 }
4939 }
4940 }
4941 pw.println(" ");
4942 pw.println("Shared Users:");
4943 {
4944 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004945 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
4946 pw.print(Integer.toHexString(System.identityHashCode(su)));
4947 pw.println("):");
4948 pw.print(" userId="); pw.print(su.userId);
4949 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004950 pw.println(" grantedPermissions:");
4951 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004952 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 }
4954 pw.println(" loadedPermissions:");
4955 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004956 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 }
4958 }
4959 }
4960 pw.println(" ");
4961 pw.println("Settings parse messages:");
4962 pw.println(mSettings.mReadMessages.toString());
4963 }
4964 }
4965
4966 static final class BasePermission {
4967 final static int TYPE_NORMAL = 0;
4968 final static int TYPE_BUILTIN = 1;
4969 final static int TYPE_DYNAMIC = 2;
4970
4971 final String name;
4972 final String sourcePackage;
4973 final int type;
4974 PackageParser.Permission perm;
4975 PermissionInfo pendingInfo;
4976 int uid;
4977 int[] gids;
4978
4979 BasePermission(String _name, String _sourcePackage, int _type) {
4980 name = _name;
4981 sourcePackage = _sourcePackage;
4982 type = _type;
4983 }
4984 }
4985
4986 static class PackageSignatures {
4987 private Signature[] mSignatures;
4988
4989 PackageSignatures(Signature[] sigs) {
4990 assignSignatures(sigs);
4991 }
4992
4993 PackageSignatures() {
4994 }
4995
4996 void writeXml(XmlSerializer serializer, String tagName,
4997 ArrayList<Signature> pastSignatures) throws IOException {
4998 if (mSignatures == null) {
4999 return;
5000 }
5001 serializer.startTag(null, tagName);
5002 serializer.attribute(null, "count",
5003 Integer.toString(mSignatures.length));
5004 for (int i=0; i<mSignatures.length; i++) {
5005 serializer.startTag(null, "cert");
5006 final Signature sig = mSignatures[i];
5007 final int sigHash = sig.hashCode();
5008 final int numPast = pastSignatures.size();
5009 int j;
5010 for (j=0; j<numPast; j++) {
5011 Signature pastSig = pastSignatures.get(j);
5012 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5013 serializer.attribute(null, "index", Integer.toString(j));
5014 break;
5015 }
5016 }
5017 if (j >= numPast) {
5018 pastSignatures.add(sig);
5019 serializer.attribute(null, "index", Integer.toString(numPast));
5020 serializer.attribute(null, "key", sig.toCharsString());
5021 }
5022 serializer.endTag(null, "cert");
5023 }
5024 serializer.endTag(null, tagName);
5025 }
5026
5027 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5028 throws IOException, XmlPullParserException {
5029 String countStr = parser.getAttributeValue(null, "count");
5030 if (countStr == null) {
5031 reportSettingsProblem(Log.WARN,
5032 "Error in package manager settings: <signatures> has"
5033 + " no count at " + parser.getPositionDescription());
5034 XmlUtils.skipCurrentTag(parser);
5035 }
5036 final int count = Integer.parseInt(countStr);
5037 mSignatures = new Signature[count];
5038 int pos = 0;
5039
5040 int outerDepth = parser.getDepth();
5041 int type;
5042 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5043 && (type != XmlPullParser.END_TAG
5044 || parser.getDepth() > outerDepth)) {
5045 if (type == XmlPullParser.END_TAG
5046 || type == XmlPullParser.TEXT) {
5047 continue;
5048 }
5049
5050 String tagName = parser.getName();
5051 if (tagName.equals("cert")) {
5052 if (pos < count) {
5053 String index = parser.getAttributeValue(null, "index");
5054 if (index != null) {
5055 try {
5056 int idx = Integer.parseInt(index);
5057 String key = parser.getAttributeValue(null, "key");
5058 if (key == null) {
5059 if (idx >= 0 && idx < pastSignatures.size()) {
5060 Signature sig = pastSignatures.get(idx);
5061 if (sig != null) {
5062 mSignatures[pos] = pastSignatures.get(idx);
5063 pos++;
5064 } else {
5065 reportSettingsProblem(Log.WARN,
5066 "Error in package manager settings: <cert> "
5067 + "index " + index + " is not defined at "
5068 + parser.getPositionDescription());
5069 }
5070 } else {
5071 reportSettingsProblem(Log.WARN,
5072 "Error in package manager settings: <cert> "
5073 + "index " + index + " is out of bounds at "
5074 + parser.getPositionDescription());
5075 }
5076 } else {
5077 while (pastSignatures.size() <= idx) {
5078 pastSignatures.add(null);
5079 }
5080 Signature sig = new Signature(key);
5081 pastSignatures.set(idx, sig);
5082 mSignatures[pos] = sig;
5083 pos++;
5084 }
5085 } catch (NumberFormatException e) {
5086 reportSettingsProblem(Log.WARN,
5087 "Error in package manager settings: <cert> "
5088 + "index " + index + " is not a number at "
5089 + parser.getPositionDescription());
5090 }
5091 } else {
5092 reportSettingsProblem(Log.WARN,
5093 "Error in package manager settings: <cert> has"
5094 + " no index at " + parser.getPositionDescription());
5095 }
5096 } else {
5097 reportSettingsProblem(Log.WARN,
5098 "Error in package manager settings: too "
5099 + "many <cert> tags, expected " + count
5100 + " at " + parser.getPositionDescription());
5101 }
5102 } else {
5103 reportSettingsProblem(Log.WARN,
5104 "Unknown element under <cert>: "
5105 + parser.getName());
5106 }
5107 XmlUtils.skipCurrentTag(parser);
5108 }
5109
5110 if (pos < count) {
5111 // Should never happen -- there is an error in the written
5112 // settings -- but if it does we don't want to generate
5113 // a bad array.
5114 Signature[] newSigs = new Signature[pos];
5115 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5116 mSignatures = newSigs;
5117 }
5118 }
5119
5120 /**
5121 * If any of the given 'sigs' is contained in the existing signatures,
5122 * then completely replace the current signatures with the ones in
5123 * 'sigs'. This is used for updating an existing package to a newly
5124 * installed version.
5125 */
5126 boolean updateSignatures(Signature[] sigs, boolean update) {
5127 if (mSignatures == null) {
5128 if (update) {
5129 assignSignatures(sigs);
5130 }
5131 return true;
5132 }
5133 if (sigs == null) {
5134 return false;
5135 }
5136
5137 for (int i=0; i<sigs.length; i++) {
5138 Signature sig = sigs[i];
5139 for (int j=0; j<mSignatures.length; j++) {
5140 if (mSignatures[j].equals(sig)) {
5141 if (update) {
5142 assignSignatures(sigs);
5143 }
5144 return true;
5145 }
5146 }
5147 }
5148 return false;
5149 }
5150
5151 /**
5152 * If any of the given 'sigs' is contained in the existing signatures,
5153 * then add in any new signatures found in 'sigs'. This is used for
5154 * including a new package into an existing shared user id.
5155 */
5156 boolean mergeSignatures(Signature[] sigs, boolean update) {
5157 if (mSignatures == null) {
5158 if (update) {
5159 assignSignatures(sigs);
5160 }
5161 return true;
5162 }
5163 if (sigs == null) {
5164 return false;
5165 }
5166
5167 Signature[] added = null;
5168 int addedCount = 0;
5169 boolean haveMatch = false;
5170 for (int i=0; i<sigs.length; i++) {
5171 Signature sig = sigs[i];
5172 boolean found = false;
5173 for (int j=0; j<mSignatures.length; j++) {
5174 if (mSignatures[j].equals(sig)) {
5175 found = true;
5176 haveMatch = true;
5177 break;
5178 }
5179 }
5180
5181 if (!found) {
5182 if (added == null) {
5183 added = new Signature[sigs.length];
5184 }
5185 added[i] = sig;
5186 addedCount++;
5187 }
5188 }
5189
5190 if (!haveMatch) {
5191 // Nothing matched -- reject the new signatures.
5192 return false;
5193 }
5194 if (added == null) {
5195 // Completely matched -- nothing else to do.
5196 return true;
5197 }
5198
5199 // Add additional signatures in.
5200 if (update) {
5201 Signature[] total = new Signature[addedCount+mSignatures.length];
5202 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5203 int j = mSignatures.length;
5204 for (int i=0; i<added.length; i++) {
5205 if (added[i] != null) {
5206 total[j] = added[i];
5207 j++;
5208 }
5209 }
5210 mSignatures = total;
5211 }
5212 return true;
5213 }
5214
5215 private void assignSignatures(Signature[] sigs) {
5216 if (sigs == null) {
5217 mSignatures = null;
5218 return;
5219 }
5220 mSignatures = new Signature[sigs.length];
5221 for (int i=0; i<sigs.length; i++) {
5222 mSignatures[i] = sigs[i];
5223 }
5224 }
5225
5226 @Override
5227 public String toString() {
5228 StringBuffer buf = new StringBuffer(128);
5229 buf.append("PackageSignatures{");
5230 buf.append(Integer.toHexString(System.identityHashCode(this)));
5231 buf.append(" [");
5232 if (mSignatures != null) {
5233 for (int i=0; i<mSignatures.length; i++) {
5234 if (i > 0) buf.append(", ");
5235 buf.append(Integer.toHexString(
5236 System.identityHashCode(mSignatures[i])));
5237 }
5238 }
5239 buf.append("]}");
5240 return buf.toString();
5241 }
5242 }
5243
5244 static class PreferredActivity extends IntentFilter {
5245 final int mMatch;
5246 final String[] mSetPackages;
5247 final String[] mSetClasses;
5248 final String[] mSetComponents;
5249 final ComponentName mActivity;
5250 final String mShortActivity;
5251 String mParseError;
5252
5253 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5254 ComponentName activity) {
5255 super(filter);
5256 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5257 mActivity = activity;
5258 mShortActivity = activity.flattenToShortString();
5259 mParseError = null;
5260 if (set != null) {
5261 final int N = set.length;
5262 String[] myPackages = new String[N];
5263 String[] myClasses = new String[N];
5264 String[] myComponents = new String[N];
5265 for (int i=0; i<N; i++) {
5266 ComponentName cn = set[i];
5267 if (cn == null) {
5268 mSetPackages = null;
5269 mSetClasses = null;
5270 mSetComponents = null;
5271 return;
5272 }
5273 myPackages[i] = cn.getPackageName().intern();
5274 myClasses[i] = cn.getClassName().intern();
5275 myComponents[i] = cn.flattenToShortString().intern();
5276 }
5277 mSetPackages = myPackages;
5278 mSetClasses = myClasses;
5279 mSetComponents = myComponents;
5280 } else {
5281 mSetPackages = null;
5282 mSetClasses = null;
5283 mSetComponents = null;
5284 }
5285 }
5286
5287 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5288 IOException {
5289 mShortActivity = parser.getAttributeValue(null, "name");
5290 mActivity = ComponentName.unflattenFromString(mShortActivity);
5291 if (mActivity == null) {
5292 mParseError = "Bad activity name " + mShortActivity;
5293 }
5294 String matchStr = parser.getAttributeValue(null, "match");
5295 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5296 String setCountStr = parser.getAttributeValue(null, "set");
5297 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5298
5299 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5300 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5301 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5302
5303 int setPos = 0;
5304
5305 int outerDepth = parser.getDepth();
5306 int type;
5307 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5308 && (type != XmlPullParser.END_TAG
5309 || parser.getDepth() > outerDepth)) {
5310 if (type == XmlPullParser.END_TAG
5311 || type == XmlPullParser.TEXT) {
5312 continue;
5313 }
5314
5315 String tagName = parser.getName();
5316 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5317 // + parser.getDepth() + " tag=" + tagName);
5318 if (tagName.equals("set")) {
5319 String name = parser.getAttributeValue(null, "name");
5320 if (name == null) {
5321 if (mParseError == null) {
5322 mParseError = "No name in set tag in preferred activity "
5323 + mShortActivity;
5324 }
5325 } else if (setPos >= setCount) {
5326 if (mParseError == null) {
5327 mParseError = "Too many set tags in preferred activity "
5328 + mShortActivity;
5329 }
5330 } else {
5331 ComponentName cn = ComponentName.unflattenFromString(name);
5332 if (cn == null) {
5333 if (mParseError == null) {
5334 mParseError = "Bad set name " + name + " in preferred activity "
5335 + mShortActivity;
5336 }
5337 } else {
5338 myPackages[setPos] = cn.getPackageName();
5339 myClasses[setPos] = cn.getClassName();
5340 myComponents[setPos] = name;
5341 setPos++;
5342 }
5343 }
5344 XmlUtils.skipCurrentTag(parser);
5345 } else if (tagName.equals("filter")) {
5346 //Log.i(TAG, "Starting to parse filter...");
5347 readFromXml(parser);
5348 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5349 // + parser.getDepth() + " tag=" + parser.getName());
5350 } else {
5351 reportSettingsProblem(Log.WARN,
5352 "Unknown element under <preferred-activities>: "
5353 + parser.getName());
5354 XmlUtils.skipCurrentTag(parser);
5355 }
5356 }
5357
5358 if (setPos != setCount) {
5359 if (mParseError == null) {
5360 mParseError = "Not enough set tags (expected " + setCount
5361 + " but found " + setPos + ") in " + mShortActivity;
5362 }
5363 }
5364
5365 mSetPackages = myPackages;
5366 mSetClasses = myClasses;
5367 mSetComponents = myComponents;
5368 }
5369
5370 public void writeToXml(XmlSerializer serializer) throws IOException {
5371 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5372 serializer.attribute(null, "name", mShortActivity);
5373 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5374 serializer.attribute(null, "set", Integer.toString(NS));
5375 for (int s=0; s<NS; s++) {
5376 serializer.startTag(null, "set");
5377 serializer.attribute(null, "name", mSetComponents[s]);
5378 serializer.endTag(null, "set");
5379 }
5380 serializer.startTag(null, "filter");
5381 super.writeToXml(serializer);
5382 serializer.endTag(null, "filter");
5383 }
5384
5385 boolean sameSet(List<ResolveInfo> query, int priority) {
5386 if (mSetPackages == null) return false;
5387 final int NQ = query.size();
5388 final int NS = mSetPackages.length;
5389 int numMatch = 0;
5390 for (int i=0; i<NQ; i++) {
5391 ResolveInfo ri = query.get(i);
5392 if (ri.priority != priority) continue;
5393 ActivityInfo ai = ri.activityInfo;
5394 boolean good = false;
5395 for (int j=0; j<NS; j++) {
5396 if (mSetPackages[j].equals(ai.packageName)
5397 && mSetClasses[j].equals(ai.name)) {
5398 numMatch++;
5399 good = true;
5400 break;
5401 }
5402 }
5403 if (!good) return false;
5404 }
5405 return numMatch == NS;
5406 }
5407 }
5408
5409 static class GrantedPermissions {
5410 final int pkgFlags;
5411
5412 HashSet<String> grantedPermissions = new HashSet<String>();
5413 int[] gids;
5414
5415 HashSet<String> loadedPermissions = new HashSet<String>();
5416
5417 GrantedPermissions(int pkgFlags) {
5418 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5419 }
5420 }
5421
5422 /**
5423 * Settings base class for pending and resolved classes.
5424 */
5425 static class PackageSettingBase extends GrantedPermissions {
5426 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005427 File codePath;
5428 String codePathString;
5429 File resourcePath;
5430 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 private long timeStamp;
5432 private String timeStampString = "0";
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005433 final int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005434
5435 PackageSignatures signatures = new PackageSignatures();
5436
5437 boolean permissionsFixed;
5438
5439 /* Explicitly disabled components */
5440 HashSet<String> disabledComponents = new HashSet<String>(0);
5441 /* Explicitly enabled components */
5442 HashSet<String> enabledComponents = new HashSet<String>(0);
5443 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5444 int installStatus = PKG_INSTALL_COMPLETE;
Jacek Surazskic64322c2009-04-28 15:26:38 +02005445
5446 /* package name of the app that installed this package */
5447 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448
5449 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005450 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 super(pkgFlags);
5452 this.name = name;
5453 this.codePath = codePath;
5454 this.codePathString = codePath.toString();
5455 this.resourcePath = resourcePath;
5456 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005457 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 }
5459
Jacek Surazskic64322c2009-04-28 15:26:38 +02005460 public void setInstallerPackageName(String packageName) {
5461 installerPackageName = packageName;
5462 }
5463
5464 String getInstallerPackageName() {
5465 return installerPackageName;
5466 }
5467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 public void setInstallStatus(int newStatus) {
5469 installStatus = newStatus;
5470 }
5471
5472 public int getInstallStatus() {
5473 return installStatus;
5474 }
5475
5476 public void setTimeStamp(long newStamp) {
5477 if (newStamp != timeStamp) {
5478 timeStamp = newStamp;
5479 timeStampString = Long.toString(newStamp);
5480 }
5481 }
5482
5483 public void setTimeStamp(long newStamp, String newStampStr) {
5484 timeStamp = newStamp;
5485 timeStampString = newStampStr;
5486 }
5487
5488 public long getTimeStamp() {
5489 return timeStamp;
5490 }
5491
5492 public String getTimeStampStr() {
5493 return timeStampString;
5494 }
5495
5496 public void copyFrom(PackageSettingBase base) {
5497 grantedPermissions = base.grantedPermissions;
5498 gids = base.gids;
5499 loadedPermissions = base.loadedPermissions;
5500
5501 timeStamp = base.timeStamp;
5502 timeStampString = base.timeStampString;
5503 signatures = base.signatures;
5504 permissionsFixed = base.permissionsFixed;
5505 disabledComponents = base.disabledComponents;
5506 enabledComponents = base.enabledComponents;
5507 enabled = base.enabled;
5508 installStatus = base.installStatus;
5509 }
5510
5511 void enableComponentLP(String componentClassName) {
5512 disabledComponents.remove(componentClassName);
5513 enabledComponents.add(componentClassName);
5514 }
5515
5516 void disableComponentLP(String componentClassName) {
5517 enabledComponents.remove(componentClassName);
5518 disabledComponents.add(componentClassName);
5519 }
5520
5521 void restoreComponentLP(String componentClassName) {
5522 enabledComponents.remove(componentClassName);
5523 disabledComponents.remove(componentClassName);
5524 }
5525
5526 int currentEnabledStateLP(String componentName) {
5527 if (enabledComponents.contains(componentName)) {
5528 return COMPONENT_ENABLED_STATE_ENABLED;
5529 } else if (disabledComponents.contains(componentName)) {
5530 return COMPONENT_ENABLED_STATE_DISABLED;
5531 } else {
5532 return COMPONENT_ENABLED_STATE_DEFAULT;
5533 }
5534 }
5535 }
5536
5537 /**
5538 * Settings data for a particular package we know about.
5539 */
5540 static final class PackageSetting extends PackageSettingBase {
5541 int userId;
5542 PackageParser.Package pkg;
5543 SharedUserSetting sharedUser;
5544
5545 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005546 int pVersionCode, int pkgFlags) {
5547 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 }
5549
5550 @Override
5551 public String toString() {
5552 return "PackageSetting{"
5553 + Integer.toHexString(System.identityHashCode(this))
5554 + " " + name + "/" + userId + "}";
5555 }
5556 }
5557
5558 /**
5559 * Settings data for a particular shared user ID we know about.
5560 */
5561 static final class SharedUserSetting extends GrantedPermissions {
5562 final String name;
5563 int userId;
5564 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
5565 final PackageSignatures signatures = new PackageSignatures();
5566
5567 SharedUserSetting(String _name, int _pkgFlags) {
5568 super(_pkgFlags);
5569 name = _name;
5570 }
5571
5572 @Override
5573 public String toString() {
5574 return "SharedUserSetting{"
5575 + Integer.toHexString(System.identityHashCode(this))
5576 + " " + name + "/" + userId + "}";
5577 }
5578 }
5579
5580 /**
5581 * Holds information about dynamic settings.
5582 */
5583 private static final class Settings {
5584 private final File mSettingsFilename;
5585 private final File mBackupSettingsFilename;
5586 private final HashMap<String, PackageSetting> mPackages =
5587 new HashMap<String, PackageSetting>();
5588 // The user's preferred packages/applications, in order of preference.
5589 // First is the most preferred.
5590 private final ArrayList<PackageSetting> mPreferredPackages =
5591 new ArrayList<PackageSetting>();
5592 // List of replaced system applications
5593 final HashMap<String, PackageSetting> mDisabledSysPackages =
5594 new HashMap<String, PackageSetting>();
5595
5596 // The user's preferred activities associated with particular intent
5597 // filters.
5598 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
5599 new IntentResolver<PreferredActivity, PreferredActivity>() {
5600 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005601 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005603 out.print(prefix); out.print(
5604 Integer.toHexString(System.identityHashCode(filter)));
5605 out.print(' ');
5606 out.print(filter.mActivity.flattenToShortString());
5607 out.print(" match=0x");
5608 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005610 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005612 out.print(prefix); out.print(" ");
5613 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 }
5615 }
5616 }
5617 };
5618 private final HashMap<String, SharedUserSetting> mSharedUsers =
5619 new HashMap<String, SharedUserSetting>();
5620 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
5621 private final SparseArray<Object> mOtherUserIds =
5622 new SparseArray<Object>();
5623
5624 // For reading/writing settings file.
5625 private final ArrayList<Signature> mPastSignatures =
5626 new ArrayList<Signature>();
5627
5628 // Mapping from permission names to info about them.
5629 final HashMap<String, BasePermission> mPermissions =
5630 new HashMap<String, BasePermission>();
5631
5632 // Mapping from permission tree names to info about them.
5633 final HashMap<String, BasePermission> mPermissionTrees =
5634 new HashMap<String, BasePermission>();
5635
5636 private final ArrayList<String> mPendingPreferredPackages
5637 = new ArrayList<String>();
5638
5639 private final StringBuilder mReadMessages = new StringBuilder();
5640
5641 private static final class PendingPackage extends PackageSettingBase {
5642 final int sharedId;
5643
5644 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005645 int sharedId, int pVersionCode, int pkgFlags) {
5646 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 this.sharedId = sharedId;
5648 }
5649 }
5650 private final ArrayList<PendingPackage> mPendingPackages
5651 = new ArrayList<PendingPackage>();
5652
5653 Settings() {
5654 File dataDir = Environment.getDataDirectory();
5655 File systemDir = new File(dataDir, "system");
5656 systemDir.mkdirs();
5657 FileUtils.setPermissions(systemDir.toString(),
5658 FileUtils.S_IRWXU|FileUtils.S_IRWXG
5659 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
5660 -1, -1);
5661 mSettingsFilename = new File(systemDir, "packages.xml");
5662 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
5663 }
5664
5665 PackageSetting getPackageLP(PackageParser.Package pkg,
5666 SharedUserSetting sharedUser, File codePath, File resourcePath,
5667 int pkgFlags, boolean create, boolean add) {
5668 final String name = pkg.packageName;
5669 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005670 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671
5672 if (p != null) {
5673 p.pkg = pkg;
5674 }
5675 return p;
5676 }
5677
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005678 PackageSetting peekPackageLP(String name) {
5679 return mPackages.get(name);
5680 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 PackageSetting p = mPackages.get(name);
5682 if (p != null && p.codePath.getPath().equals(codePath)) {
5683 return p;
5684 }
5685 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005686 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 }
5688
5689 void setInstallStatus(String pkgName, int status) {
5690 PackageSetting p = mPackages.get(pkgName);
5691 if(p != null) {
5692 if(p.getInstallStatus() != status) {
5693 p.setInstallStatus(status);
5694 }
5695 }
5696 }
5697
Jacek Surazskic64322c2009-04-28 15:26:38 +02005698 void setInstallerPackageName(String pkgName,
5699 String installerPkgName) {
5700 PackageSetting p = mPackages.get(pkgName);
5701 if(p != null) {
5702 p.setInstallerPackageName(installerPkgName);
5703 }
5704 }
5705
5706 String getInstallerPackageName(String pkgName) {
5707 PackageSetting p = mPackages.get(pkgName);
5708 return (p == null) ? null : p.getInstallerPackageName();
5709 }
5710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 int getInstallStatus(String pkgName) {
5712 PackageSetting p = mPackages.get(pkgName);
5713 if(p != null) {
5714 return p.getInstallStatus();
5715 }
5716 return -1;
5717 }
5718
5719 SharedUserSetting getSharedUserLP(String name,
5720 int pkgFlags, boolean create) {
5721 SharedUserSetting s = mSharedUsers.get(name);
5722 if (s == null) {
5723 if (!create) {
5724 return null;
5725 }
5726 s = new SharedUserSetting(name, pkgFlags);
5727 if (MULTIPLE_APPLICATION_UIDS) {
5728 s.userId = newUserIdLP(s);
5729 } else {
5730 s.userId = FIRST_APPLICATION_UID;
5731 }
5732 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
5733 // < 0 means we couldn't assign a userid; fall out and return
5734 // s, which is currently null
5735 if (s.userId >= 0) {
5736 mSharedUsers.put(name, s);
5737 }
5738 }
5739
5740 return s;
5741 }
5742
5743 int disableSystemPackageLP(String name) {
5744 PackageSetting p = mPackages.get(name);
5745 if(p == null) {
5746 Log.w(TAG, "Package:"+name+" is not an installed package");
5747 return -1;
5748 }
5749 PackageSetting dp = mDisabledSysPackages.get(name);
5750 // always make sure the system package code and resource paths dont change
5751 if(dp == null) {
5752 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
5753 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5754 }
5755 mDisabledSysPackages.put(name, p);
5756 }
5757 return removePackageLP(name);
5758 }
5759
5760 PackageSetting enableSystemPackageLP(String name) {
5761 PackageSetting p = mDisabledSysPackages.get(name);
5762 if(p == null) {
5763 Log.w(TAG, "Package:"+name+" is not disabled");
5764 return null;
5765 }
5766 // Reset flag in ApplicationInfo object
5767 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
5768 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5769 }
5770 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005771 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 mDisabledSysPackages.remove(name);
5773 return ret;
5774 }
5775
5776 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005777 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 PackageSetting p = mPackages.get(name);
5779 if (p != null) {
5780 if (p.userId == uid) {
5781 return p;
5782 }
5783 reportSettingsProblem(Log.ERROR,
5784 "Adding duplicate package, keeping first: " + name);
5785 return null;
5786 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005787 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 p.userId = uid;
5789 if (addUserIdLP(uid, p, name)) {
5790 mPackages.put(name, p);
5791 return p;
5792 }
5793 return null;
5794 }
5795
5796 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
5797 SharedUserSetting s = mSharedUsers.get(name);
5798 if (s != null) {
5799 if (s.userId == uid) {
5800 return s;
5801 }
5802 reportSettingsProblem(Log.ERROR,
5803 "Adding duplicate shared user, keeping first: " + name);
5804 return null;
5805 }
5806 s = new SharedUserSetting(name, pkgFlags);
5807 s.userId = uid;
5808 if (addUserIdLP(uid, s, name)) {
5809 mSharedUsers.put(name, s);
5810 return s;
5811 }
5812 return null;
5813 }
5814
5815 private PackageSetting getPackageLP(String name,
5816 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005817 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 PackageSetting p = mPackages.get(name);
5819 if (p != null) {
5820 if (!p.codePath.equals(codePath)) {
5821 // Check to see if its a disabled system app
5822 PackageSetting ps = mDisabledSysPackages.get(name);
5823 if((ps != null) && ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07005824 // This is an updated system app with versions in both system
5825 // and data partition. Just let the most recent version
5826 // take precedence.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 return p;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005828 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07005829 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07005830 reportSettingsProblem(Log.WARN,
5831 "Package " + name + " codePath changed from " + p.codePath
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005832 + " to " + codePath + "; Retaining data and using new code from " +
5833 codePath);
5834 p.codePath = codePath;
5835 p.resourcePath = resourcePath;
5836 p.codePathString = codePath.toString();
5837 p.resourcePathString = resourcePath.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 }
5839 } else if (p.sharedUser != sharedUser) {
5840 reportSettingsProblem(Log.WARN,
5841 "Package " + name + " shared user changed from "
5842 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
5843 + " to "
5844 + (sharedUser != null ? sharedUser.name : "<nothing>")
5845 + "; replacing with new");
5846 p = null;
5847 }
5848 }
5849 if (p == null) {
5850 // Create a new PackageSettings entry. this can end up here because
5851 // of code path mismatch or user id mismatch of an updated system partition
5852 if (!create) {
5853 return null;
5854 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005855 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07005857 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 if (sharedUser != null) {
5859 p.userId = sharedUser.userId;
5860 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005861 // Assign new user id
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 p.userId = newUserIdLP(p);
5863 } else {
5864 p.userId = FIRST_APPLICATION_UID;
5865 }
5866 if (p.userId < 0) {
5867 reportSettingsProblem(Log.WARN,
5868 "Package " + name + " could not be assigned a valid uid");
5869 return null;
5870 }
5871 if (add) {
5872 // Finish adding new package by adding it and updating shared
5873 // user preferences
5874 insertPackageSettingLP(p, name, sharedUser);
5875 }
5876 }
5877 return p;
5878 }
5879
5880 // Utility method that adds a PackageSetting to mPackages and
5881 // completes updating the shared user attributes
5882 private void insertPackageSettingLP(PackageSetting p, String name,
5883 SharedUserSetting sharedUser) {
5884 mPackages.put(name, p);
5885 if (sharedUser != null) {
5886 if (p.sharedUser != null && p.sharedUser != sharedUser) {
5887 reportSettingsProblem(Log.ERROR,
5888 "Package " + p.name + " was user "
5889 + p.sharedUser + " but is now " + sharedUser
5890 + "; I am not changing its files so it will probably fail!");
5891 p.sharedUser.packages.remove(p);
5892 } else if (p.userId != sharedUser.userId) {
5893 reportSettingsProblem(Log.ERROR,
5894 "Package " + p.name + " was user id " + p.userId
5895 + " but is now user " + sharedUser
5896 + " with id " + sharedUser.userId
5897 + "; I am not changing its files so it will probably fail!");
5898 }
5899
5900 sharedUser.packages.add(p);
5901 p.sharedUser = sharedUser;
5902 p.userId = sharedUser.userId;
5903 }
5904 }
5905
5906 private void updateSharedUserPerms (PackageSetting deletedPs) {
5907 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
5908 Log.i(TAG, "Trying to update info for null package. Just ignoring");
5909 return;
5910 }
5911 // No sharedUserId
5912 if (deletedPs.sharedUser == null) {
5913 return;
5914 }
5915 SharedUserSetting sus = deletedPs.sharedUser;
5916 // Update permissions
5917 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
5918 boolean used = false;
5919 if (!sus.grantedPermissions.contains (eachPerm)) {
5920 continue;
5921 }
5922 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapub97b8f82009-06-19 15:09:18 -07005923 if (pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005924 used = true;
5925 break;
5926 }
5927 }
5928 if (!used) {
5929 // can safely delete this permission from list
5930 sus.grantedPermissions.remove(eachPerm);
5931 sus.loadedPermissions.remove(eachPerm);
5932 }
5933 }
5934 // Update gids
5935 int newGids[] = null;
5936 for (PackageSetting pkg:sus.packages) {
5937 newGids = appendInts(newGids, pkg.gids);
5938 }
5939 sus.gids = newGids;
5940 }
5941
5942 private int removePackageLP(String name) {
5943 PackageSetting p = mPackages.get(name);
5944 if (p != null) {
5945 mPackages.remove(name);
5946 if (p.sharedUser != null) {
5947 p.sharedUser.packages.remove(p);
5948 if (p.sharedUser.packages.size() == 0) {
5949 mSharedUsers.remove(p.sharedUser.name);
5950 removeUserIdLP(p.sharedUser.userId);
5951 return p.sharedUser.userId;
5952 }
5953 } else {
5954 removeUserIdLP(p.userId);
5955 return p.userId;
5956 }
5957 }
5958 return -1;
5959 }
5960
5961 private boolean addUserIdLP(int uid, Object obj, Object name) {
5962 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
5963 return false;
5964 }
5965
5966 if (uid >= FIRST_APPLICATION_UID) {
5967 int N = mUserIds.size();
5968 final int index = uid - FIRST_APPLICATION_UID;
5969 while (index >= N) {
5970 mUserIds.add(null);
5971 N++;
5972 }
5973 if (mUserIds.get(index) != null) {
5974 reportSettingsProblem(Log.ERROR,
5975 "Adding duplicate shared id: " + uid
5976 + " name=" + name);
5977 return false;
5978 }
5979 mUserIds.set(index, obj);
5980 } else {
5981 if (mOtherUserIds.get(uid) != null) {
5982 reportSettingsProblem(Log.ERROR,
5983 "Adding duplicate shared id: " + uid
5984 + " name=" + name);
5985 return false;
5986 }
5987 mOtherUserIds.put(uid, obj);
5988 }
5989 return true;
5990 }
5991
5992 public Object getUserIdLP(int uid) {
5993 if (uid >= FIRST_APPLICATION_UID) {
5994 int N = mUserIds.size();
5995 final int index = uid - FIRST_APPLICATION_UID;
5996 return index < N ? mUserIds.get(index) : null;
5997 } else {
5998 return mOtherUserIds.get(uid);
5999 }
6000 }
6001
6002 private void removeUserIdLP(int uid) {
6003 if (uid >= FIRST_APPLICATION_UID) {
6004 int N = mUserIds.size();
6005 final int index = uid - FIRST_APPLICATION_UID;
6006 if (index < N) mUserIds.set(index, null);
6007 } else {
6008 mOtherUserIds.remove(uid);
6009 }
6010 }
6011
6012 void writeLP() {
6013 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6014
6015 // Keep the old settings around until we know the new ones have
6016 // been successfully written.
6017 if (mSettingsFilename.exists()) {
6018 if (mBackupSettingsFilename.exists()) {
6019 mBackupSettingsFilename.delete();
6020 }
6021 mSettingsFilename.renameTo(mBackupSettingsFilename);
6022 }
6023
6024 mPastSignatures.clear();
6025
6026 try {
6027 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6028
6029 //XmlSerializer serializer = XmlUtils.serializerInstance();
6030 XmlSerializer serializer = new FastXmlSerializer();
6031 serializer.setOutput(str, "utf-8");
6032 serializer.startDocument(null, true);
6033 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6034
6035 serializer.startTag(null, "packages");
6036
6037 serializer.startTag(null, "permission-trees");
6038 for (BasePermission bp : mPermissionTrees.values()) {
6039 writePermission(serializer, bp);
6040 }
6041 serializer.endTag(null, "permission-trees");
6042
6043 serializer.startTag(null, "permissions");
6044 for (BasePermission bp : mPermissions.values()) {
6045 writePermission(serializer, bp);
6046 }
6047 serializer.endTag(null, "permissions");
6048
6049 for (PackageSetting pkg : mPackages.values()) {
6050 writePackage(serializer, pkg);
6051 }
6052
6053 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6054 writeDisabledSysPackage(serializer, pkg);
6055 }
6056
6057 serializer.startTag(null, "preferred-packages");
6058 int N = mPreferredPackages.size();
6059 for (int i=0; i<N; i++) {
6060 PackageSetting pkg = mPreferredPackages.get(i);
6061 serializer.startTag(null, "item");
6062 serializer.attribute(null, "name", pkg.name);
6063 serializer.endTag(null, "item");
6064 }
6065 serializer.endTag(null, "preferred-packages");
6066
6067 serializer.startTag(null, "preferred-activities");
6068 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6069 serializer.startTag(null, "item");
6070 pa.writeToXml(serializer);
6071 serializer.endTag(null, "item");
6072 }
6073 serializer.endTag(null, "preferred-activities");
6074
6075 for (SharedUserSetting usr : mSharedUsers.values()) {
6076 serializer.startTag(null, "shared-user");
6077 serializer.attribute(null, "name", usr.name);
6078 serializer.attribute(null, "userId",
6079 Integer.toString(usr.userId));
6080 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6081 serializer.startTag(null, "perms");
6082 for (String name : usr.grantedPermissions) {
6083 serializer.startTag(null, "item");
6084 serializer.attribute(null, "name", name);
6085 serializer.endTag(null, "item");
6086 }
6087 serializer.endTag(null, "perms");
6088 serializer.endTag(null, "shared-user");
6089 }
6090
6091 serializer.endTag(null, "packages");
6092
6093 serializer.endDocument();
6094
6095 str.flush();
6096 str.close();
6097
6098 // New settings successfully written, old ones are no longer
6099 // needed.
6100 mBackupSettingsFilename.delete();
6101 FileUtils.setPermissions(mSettingsFilename.toString(),
6102 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6103 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6104 |FileUtils.S_IROTH,
6105 -1, -1);
6106
6107 } catch(XmlPullParserException e) {
6108 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
6109
6110 } catch(java.io.IOException e) {
6111 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
6112
6113 }
6114
6115 //Debug.stopMethodTracing();
6116 }
6117
6118 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
6119 throws java.io.IOException {
6120 serializer.startTag(null, "updated-package");
6121 serializer.attribute(null, "name", pkg.name);
6122 serializer.attribute(null, "codePath", pkg.codePathString);
6123 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006124 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6126 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6127 }
6128 if (pkg.sharedUser == null) {
6129 serializer.attribute(null, "userId",
6130 Integer.toString(pkg.userId));
6131 } else {
6132 serializer.attribute(null, "sharedUserId",
6133 Integer.toString(pkg.userId));
6134 }
6135 serializer.startTag(null, "perms");
6136 if (pkg.sharedUser == null) {
6137 // If this is a shared user, the permissions will
6138 // be written there. We still need to write an
6139 // empty permissions list so permissionsFixed will
6140 // be set.
6141 for (final String name : pkg.grantedPermissions) {
6142 BasePermission bp = mPermissions.get(name);
6143 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6144 // We only need to write signature or system permissions but this wont
6145 // match the semantics of grantedPermissions. So write all permissions.
6146 serializer.startTag(null, "item");
6147 serializer.attribute(null, "name", name);
6148 serializer.endTag(null, "item");
6149 }
6150 }
6151 }
6152 serializer.endTag(null, "perms");
6153 serializer.endTag(null, "updated-package");
6154 }
6155
6156 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
6157 throws java.io.IOException {
6158 serializer.startTag(null, "package");
6159 serializer.attribute(null, "name", pkg.name);
6160 serializer.attribute(null, "codePath", pkg.codePathString);
6161 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6162 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6163 }
6164 serializer.attribute(null, "system",
6165 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6166 ? "true" : "false");
6167 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006168 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 if (pkg.sharedUser == null) {
6170 serializer.attribute(null, "userId",
6171 Integer.toString(pkg.userId));
6172 } else {
6173 serializer.attribute(null, "sharedUserId",
6174 Integer.toString(pkg.userId));
6175 }
6176 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6177 serializer.attribute(null, "enabled",
6178 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6179 ? "true" : "false");
6180 }
6181 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6182 serializer.attribute(null, "installStatus", "false");
6183 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02006184 if (pkg.installerPackageName != null) {
6185 serializer.attribute(null, "installer", pkg.installerPackageName);
6186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6188 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6189 serializer.startTag(null, "perms");
6190 if (pkg.sharedUser == null) {
6191 // If this is a shared user, the permissions will
6192 // be written there. We still need to write an
6193 // empty permissions list so permissionsFixed will
6194 // be set.
6195 for (final String name : pkg.grantedPermissions) {
6196 serializer.startTag(null, "item");
6197 serializer.attribute(null, "name", name);
6198 serializer.endTag(null, "item");
6199 }
6200 }
6201 serializer.endTag(null, "perms");
6202 }
6203 if (pkg.disabledComponents.size() > 0) {
6204 serializer.startTag(null, "disabled-components");
6205 for (final String name : pkg.disabledComponents) {
6206 serializer.startTag(null, "item");
6207 serializer.attribute(null, "name", name);
6208 serializer.endTag(null, "item");
6209 }
6210 serializer.endTag(null, "disabled-components");
6211 }
6212 if (pkg.enabledComponents.size() > 0) {
6213 serializer.startTag(null, "enabled-components");
6214 for (final String name : pkg.enabledComponents) {
6215 serializer.startTag(null, "item");
6216 serializer.attribute(null, "name", name);
6217 serializer.endTag(null, "item");
6218 }
6219 serializer.endTag(null, "enabled-components");
6220 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02006221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 serializer.endTag(null, "package");
6223 }
6224
6225 void writePermission(XmlSerializer serializer, BasePermission bp)
6226 throws XmlPullParserException, java.io.IOException {
6227 if (bp.type != BasePermission.TYPE_BUILTIN
6228 && bp.sourcePackage != null) {
6229 serializer.startTag(null, "item");
6230 serializer.attribute(null, "name", bp.name);
6231 serializer.attribute(null, "package", bp.sourcePackage);
6232 if (DEBUG_SETTINGS) Log.v(TAG,
6233 "Writing perm: name=" + bp.name + " type=" + bp.type);
6234 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6235 PermissionInfo pi = bp.perm != null ? bp.perm.info
6236 : bp.pendingInfo;
6237 if (pi != null) {
6238 serializer.attribute(null, "type", "dynamic");
6239 if (pi.icon != 0) {
6240 serializer.attribute(null, "icon",
6241 Integer.toString(pi.icon));
6242 }
6243 if (pi.nonLocalizedLabel != null) {
6244 serializer.attribute(null, "label",
6245 pi.nonLocalizedLabel.toString());
6246 }
6247 if (pi.protectionLevel !=
6248 PermissionInfo.PROTECTION_NORMAL) {
6249 serializer.attribute(null, "protection",
6250 Integer.toString(pi.protectionLevel));
6251 }
6252 }
6253 }
6254 serializer.endTag(null, "item");
6255 }
6256 }
6257
6258 String getReadMessagesLP() {
6259 return mReadMessages.toString();
6260 }
6261
6262 ArrayList<String> getListOfIncompleteInstallPackages() {
6263 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6264 Iterator<String> its = kList.iterator();
6265 ArrayList<String> ret = new ArrayList<String>();
6266 while(its.hasNext()) {
6267 String key = its.next();
6268 PackageSetting ps = mPackages.get(key);
6269 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
6270 ret.add(key);
6271 }
6272 }
6273 return ret;
6274 }
6275
6276 boolean readLP() {
6277 FileInputStream str = null;
6278 if (mBackupSettingsFilename.exists()) {
6279 try {
6280 str = new FileInputStream(mBackupSettingsFilename);
6281 mReadMessages.append("Reading from backup settings file\n");
6282 Log.i(TAG, "Reading from backup settings file!");
6283 } catch (java.io.IOException e) {
6284 // We'll try for the normal settings file.
6285 }
6286 }
6287
6288 mPastSignatures.clear();
6289
6290 try {
6291 if (str == null) {
6292 if (!mSettingsFilename.exists()) {
6293 mReadMessages.append("No settings file found\n");
6294 Log.i(TAG, "No current settings file!");
6295 return false;
6296 }
6297 str = new FileInputStream(mSettingsFilename);
6298 }
6299 XmlPullParser parser = Xml.newPullParser();
6300 parser.setInput(str, null);
6301
6302 int type;
6303 while ((type=parser.next()) != XmlPullParser.START_TAG
6304 && type != XmlPullParser.END_DOCUMENT) {
6305 ;
6306 }
6307
6308 if (type != XmlPullParser.START_TAG) {
6309 mReadMessages.append("No start tag found in settings file\n");
6310 Log.e(TAG, "No start tag found in package manager settings");
6311 return false;
6312 }
6313
6314 int outerDepth = parser.getDepth();
6315 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6316 && (type != XmlPullParser.END_TAG
6317 || parser.getDepth() > outerDepth)) {
6318 if (type == XmlPullParser.END_TAG
6319 || type == XmlPullParser.TEXT) {
6320 continue;
6321 }
6322
6323 String tagName = parser.getName();
6324 if (tagName.equals("package")) {
6325 readPackageLP(parser);
6326 } else if (tagName.equals("permissions")) {
6327 readPermissionsLP(mPermissions, parser);
6328 } else if (tagName.equals("permission-trees")) {
6329 readPermissionsLP(mPermissionTrees, parser);
6330 } else if (tagName.equals("shared-user")) {
6331 readSharedUserLP(parser);
6332 } else if (tagName.equals("preferred-packages")) {
6333 readPreferredPackagesLP(parser);
6334 } else if (tagName.equals("preferred-activities")) {
6335 readPreferredActivitiesLP(parser);
6336 } else if(tagName.equals("updated-package")) {
6337 readDisabledSysPackageLP(parser);
6338 } else {
6339 Log.w(TAG, "Unknown element under <packages>: "
6340 + parser.getName());
6341 XmlUtils.skipCurrentTag(parser);
6342 }
6343 }
6344
6345 str.close();
6346
6347 } catch(XmlPullParserException e) {
6348 mReadMessages.append("Error reading: " + e.toString());
6349 Log.e(TAG, "Error reading package manager settings", e);
6350
6351 } catch(java.io.IOException e) {
6352 mReadMessages.append("Error reading: " + e.toString());
6353 Log.e(TAG, "Error reading package manager settings", e);
6354
6355 }
6356
6357 int N = mPendingPackages.size();
6358 for (int i=0; i<N; i++) {
6359 final PendingPackage pp = mPendingPackages.get(i);
6360 Object idObj = getUserIdLP(pp.sharedId);
6361 if (idObj != null && idObj instanceof SharedUserSetting) {
6362 PackageSetting p = getPackageLP(pp.name,
6363 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006364 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 if (p == null) {
6366 Log.w(TAG, "Unable to create application package for "
6367 + pp.name);
6368 continue;
6369 }
6370 p.copyFrom(pp);
6371 } else if (idObj != null) {
6372 String msg = "Bad package setting: package " + pp.name
6373 + " has shared uid " + pp.sharedId
6374 + " that is not a shared uid\n";
6375 mReadMessages.append(msg);
6376 Log.e(TAG, msg);
6377 } else {
6378 String msg = "Bad package setting: package " + pp.name
6379 + " has shared uid " + pp.sharedId
6380 + " that is not defined\n";
6381 mReadMessages.append(msg);
6382 Log.e(TAG, msg);
6383 }
6384 }
6385 mPendingPackages.clear();
6386
6387 N = mPendingPreferredPackages.size();
6388 mPreferredPackages.clear();
6389 for (int i=0; i<N; i++) {
6390 final String name = mPendingPreferredPackages.get(i);
6391 final PackageSetting p = mPackages.get(name);
6392 if (p != null) {
6393 mPreferredPackages.add(p);
6394 } else {
6395 Log.w(TAG, "Unknown preferred package: " + name);
6396 }
6397 }
6398 mPendingPreferredPackages.clear();
6399
6400 mReadMessages.append("Read completed successfully: "
6401 + mPackages.size() + " packages, "
6402 + mSharedUsers.size() + " shared uids\n");
6403
6404 return true;
6405 }
6406
6407 private int readInt(XmlPullParser parser, String ns, String name,
6408 int defValue) {
6409 String v = parser.getAttributeValue(ns, name);
6410 try {
6411 if (v == null) {
6412 return defValue;
6413 }
6414 return Integer.parseInt(v);
6415 } catch (NumberFormatException e) {
6416 reportSettingsProblem(Log.WARN,
6417 "Error in package manager settings: attribute " +
6418 name + " has bad integer value " + v + " at "
6419 + parser.getPositionDescription());
6420 }
6421 return defValue;
6422 }
6423
6424 private void readPermissionsLP(HashMap<String, BasePermission> out,
6425 XmlPullParser parser)
6426 throws IOException, XmlPullParserException {
6427 int outerDepth = parser.getDepth();
6428 int type;
6429 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6430 && (type != XmlPullParser.END_TAG
6431 || parser.getDepth() > outerDepth)) {
6432 if (type == XmlPullParser.END_TAG
6433 || type == XmlPullParser.TEXT) {
6434 continue;
6435 }
6436
6437 String tagName = parser.getName();
6438 if (tagName.equals("item")) {
6439 String name = parser.getAttributeValue(null, "name");
6440 String sourcePackage = parser.getAttributeValue(null, "package");
6441 String ptype = parser.getAttributeValue(null, "type");
6442 if (name != null && sourcePackage != null) {
6443 boolean dynamic = "dynamic".equals(ptype);
6444 BasePermission bp = new BasePermission(name, sourcePackage,
6445 dynamic
6446 ? BasePermission.TYPE_DYNAMIC
6447 : BasePermission.TYPE_NORMAL);
6448 if (dynamic) {
6449 PermissionInfo pi = new PermissionInfo();
6450 pi.packageName = sourcePackage.intern();
6451 pi.name = name.intern();
6452 pi.icon = readInt(parser, null, "icon", 0);
6453 pi.nonLocalizedLabel = parser.getAttributeValue(
6454 null, "label");
6455 pi.protectionLevel = readInt(parser, null, "protection",
6456 PermissionInfo.PROTECTION_NORMAL);
6457 bp.pendingInfo = pi;
6458 }
6459 out.put(bp.name, bp);
6460 } else {
6461 reportSettingsProblem(Log.WARN,
6462 "Error in package manager settings: permissions has"
6463 + " no name at " + parser.getPositionDescription());
6464 }
6465 } else {
6466 reportSettingsProblem(Log.WARN,
6467 "Unknown element reading permissions: "
6468 + parser.getName() + " at "
6469 + parser.getPositionDescription());
6470 }
6471 XmlUtils.skipCurrentTag(parser);
6472 }
6473 }
6474
6475 private void readDisabledSysPackageLP(XmlPullParser parser)
6476 throws XmlPullParserException, IOException {
6477 String name = parser.getAttributeValue(null, "name");
6478 String codePathStr = parser.getAttributeValue(null, "codePath");
6479 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6480 if(resourcePathStr == null) {
6481 resourcePathStr = codePathStr;
6482 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006483 String version = parser.getAttributeValue(null, "version");
6484 int versionCode = 0;
6485 if (version != null) {
6486 try {
6487 versionCode = Integer.parseInt(version);
6488 } catch (NumberFormatException e) {
6489 }
6490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491
6492 int pkgFlags = 0;
6493 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6494 PackageSetting ps = new PackageSetting(name,
6495 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006496 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 String timeStampStr = parser.getAttributeValue(null, "ts");
6498 if (timeStampStr != null) {
6499 try {
6500 long timeStamp = Long.parseLong(timeStampStr);
6501 ps.setTimeStamp(timeStamp, timeStampStr);
6502 } catch (NumberFormatException e) {
6503 }
6504 }
6505 String idStr = parser.getAttributeValue(null, "userId");
6506 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
6507 if(ps.userId <= 0) {
6508 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6509 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
6510 }
6511 int outerDepth = parser.getDepth();
6512 int type;
6513 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6514 && (type != XmlPullParser.END_TAG
6515 || parser.getDepth() > outerDepth)) {
6516 if (type == XmlPullParser.END_TAG
6517 || type == XmlPullParser.TEXT) {
6518 continue;
6519 }
6520
6521 String tagName = parser.getName();
6522 if (tagName.equals("perms")) {
6523 readGrantedPermissionsLP(parser,
6524 ps.grantedPermissions);
6525 } else {
6526 reportSettingsProblem(Log.WARN,
6527 "Unknown element under <updated-package>: "
6528 + parser.getName());
6529 XmlUtils.skipCurrentTag(parser);
6530 }
6531 }
6532 mDisabledSysPackages.put(name, ps);
6533 }
6534
6535 private void readPackageLP(XmlPullParser parser)
6536 throws XmlPullParserException, IOException {
6537 String name = null;
6538 String idStr = null;
6539 String sharedIdStr = null;
6540 String codePathStr = null;
6541 String resourcePathStr = null;
6542 String systemStr = null;
Jacek Surazskic64322c2009-04-28 15:26:38 +02006543 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 int pkgFlags = 0;
6545 String timeStampStr;
6546 long timeStamp = 0;
6547 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006548 String version = null;
6549 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 try {
6551 name = parser.getAttributeValue(null, "name");
6552 idStr = parser.getAttributeValue(null, "userId");
6553 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6554 codePathStr = parser.getAttributeValue(null, "codePath");
6555 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006556 version = parser.getAttributeValue(null, "version");
6557 if (version != null) {
6558 try {
6559 versionCode = Integer.parseInt(version);
6560 } catch (NumberFormatException e) {
6561 }
6562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazskic64322c2009-04-28 15:26:38 +02006564 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 if (systemStr != null) {
6566 if ("true".equals(systemStr)) {
6567 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6568 }
6569 } else {
6570 // Old settings that don't specify system... just treat
6571 // them as system, good enough.
6572 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6573 }
6574 timeStampStr = parser.getAttributeValue(null, "ts");
6575 if (timeStampStr != null) {
6576 try {
6577 timeStamp = Long.parseLong(timeStampStr);
6578 } catch (NumberFormatException e) {
6579 }
6580 }
6581 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
6582 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
6583 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
6584 if (resourcePathStr == null) {
6585 resourcePathStr = codePathStr;
6586 }
6587 if (name == null) {
6588 reportSettingsProblem(Log.WARN,
6589 "Error in package manager settings: <package> has no name at "
6590 + parser.getPositionDescription());
6591 } else if (codePathStr == null) {
6592 reportSettingsProblem(Log.WARN,
6593 "Error in package manager settings: <package> has no codePath at "
6594 + parser.getPositionDescription());
6595 } else if (userId > 0) {
6596 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006597 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
6599 + ": userId=" + userId + " pkg=" + packageSetting);
6600 if (packageSetting == null) {
6601 reportSettingsProblem(Log.ERROR,
6602 "Failure adding uid " + userId
6603 + " while parsing settings at "
6604 + parser.getPositionDescription());
6605 } else {
6606 packageSetting.setTimeStamp(timeStamp, timeStampStr);
6607 }
6608 } else if (sharedIdStr != null) {
6609 userId = sharedIdStr != null
6610 ? Integer.parseInt(sharedIdStr) : 0;
6611 if (userId > 0) {
6612 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006613 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 packageSetting.setTimeStamp(timeStamp, timeStampStr);
6615 mPendingPackages.add((PendingPackage) packageSetting);
6616 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
6617 + ": sharedUserId=" + userId + " pkg="
6618 + packageSetting);
6619 } else {
6620 reportSettingsProblem(Log.WARN,
6621 "Error in package manager settings: package "
6622 + name + " has bad sharedId " + sharedIdStr
6623 + " at " + parser.getPositionDescription());
6624 }
6625 } else {
6626 reportSettingsProblem(Log.WARN,
6627 "Error in package manager settings: package "
6628 + name + " has bad userId " + idStr + " at "
6629 + parser.getPositionDescription());
6630 }
6631 } catch (NumberFormatException e) {
6632 reportSettingsProblem(Log.WARN,
6633 "Error in package manager settings: package "
6634 + name + " has bad userId " + idStr + " at "
6635 + parser.getPositionDescription());
6636 }
6637 if (packageSetting != null) {
Jacek Surazskic64322c2009-04-28 15:26:38 +02006638 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 final String enabledStr = parser.getAttributeValue(null, "enabled");
6640 if (enabledStr != null) {
6641 if (enabledStr.equalsIgnoreCase("true")) {
6642 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
6643 } else if (enabledStr.equalsIgnoreCase("false")) {
6644 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
6645 } else if (enabledStr.equalsIgnoreCase("default")) {
6646 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6647 } else {
6648 reportSettingsProblem(Log.WARN,
6649 "Error in package manager settings: package "
6650 + name + " has bad enabled value: " + idStr
6651 + " at " + parser.getPositionDescription());
6652 }
6653 } else {
6654 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6655 }
6656 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
6657 if (installStatusStr != null) {
6658 if (installStatusStr.equalsIgnoreCase("false")) {
6659 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
6660 } else {
6661 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
6662 }
6663 }
6664
6665 int outerDepth = parser.getDepth();
6666 int type;
6667 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6668 && (type != XmlPullParser.END_TAG
6669 || parser.getDepth() > outerDepth)) {
6670 if (type == XmlPullParser.END_TAG
6671 || type == XmlPullParser.TEXT) {
6672 continue;
6673 }
6674
6675 String tagName = parser.getName();
6676 if (tagName.equals("disabled-components")) {
6677 readDisabledComponentsLP(packageSetting, parser);
6678 } else if (tagName.equals("enabled-components")) {
6679 readEnabledComponentsLP(packageSetting, parser);
6680 } else if (tagName.equals("sigs")) {
6681 packageSetting.signatures.readXml(parser, mPastSignatures);
6682 } else if (tagName.equals("perms")) {
6683 readGrantedPermissionsLP(parser,
6684 packageSetting.loadedPermissions);
6685 packageSetting.permissionsFixed = true;
6686 } else {
6687 reportSettingsProblem(Log.WARN,
6688 "Unknown element under <package>: "
6689 + parser.getName());
6690 XmlUtils.skipCurrentTag(parser);
6691 }
6692 }
6693 } else {
6694 XmlUtils.skipCurrentTag(parser);
6695 }
6696 }
6697
6698 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
6699 XmlPullParser parser)
6700 throws IOException, XmlPullParserException {
6701 int outerDepth = parser.getDepth();
6702 int type;
6703 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6704 && (type != XmlPullParser.END_TAG
6705 || parser.getDepth() > outerDepth)) {
6706 if (type == XmlPullParser.END_TAG
6707 || type == XmlPullParser.TEXT) {
6708 continue;
6709 }
6710
6711 String tagName = parser.getName();
6712 if (tagName.equals("item")) {
6713 String name = parser.getAttributeValue(null, "name");
6714 if (name != null) {
6715 packageSetting.disabledComponents.add(name.intern());
6716 } else {
6717 reportSettingsProblem(Log.WARN,
6718 "Error in package manager settings: <disabled-components> has"
6719 + " no name at " + parser.getPositionDescription());
6720 }
6721 } else {
6722 reportSettingsProblem(Log.WARN,
6723 "Unknown element under <disabled-components>: "
6724 + parser.getName());
6725 }
6726 XmlUtils.skipCurrentTag(parser);
6727 }
6728 }
6729
6730 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
6731 XmlPullParser parser)
6732 throws IOException, XmlPullParserException {
6733 int outerDepth = parser.getDepth();
6734 int type;
6735 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6736 && (type != XmlPullParser.END_TAG
6737 || parser.getDepth() > outerDepth)) {
6738 if (type == XmlPullParser.END_TAG
6739 || type == XmlPullParser.TEXT) {
6740 continue;
6741 }
6742
6743 String tagName = parser.getName();
6744 if (tagName.equals("item")) {
6745 String name = parser.getAttributeValue(null, "name");
6746 if (name != null) {
6747 packageSetting.enabledComponents.add(name.intern());
6748 } else {
6749 reportSettingsProblem(Log.WARN,
6750 "Error in package manager settings: <enabled-components> has"
6751 + " no name at " + parser.getPositionDescription());
6752 }
6753 } else {
6754 reportSettingsProblem(Log.WARN,
6755 "Unknown element under <enabled-components>: "
6756 + parser.getName());
6757 }
6758 XmlUtils.skipCurrentTag(parser);
6759 }
6760 }
6761
6762 private void readSharedUserLP(XmlPullParser parser)
6763 throws XmlPullParserException, IOException {
6764 String name = null;
6765 String idStr = null;
6766 int pkgFlags = 0;
6767 SharedUserSetting su = null;
6768 try {
6769 name = parser.getAttributeValue(null, "name");
6770 idStr = parser.getAttributeValue(null, "userId");
6771 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
6772 if ("true".equals(parser.getAttributeValue(null, "system"))) {
6773 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6774 }
6775 if (name == null) {
6776 reportSettingsProblem(Log.WARN,
6777 "Error in package manager settings: <shared-user> has no name at "
6778 + parser.getPositionDescription());
6779 } else if (userId == 0) {
6780 reportSettingsProblem(Log.WARN,
6781 "Error in package manager settings: shared-user "
6782 + name + " has bad userId " + idStr + " at "
6783 + parser.getPositionDescription());
6784 } else {
6785 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
6786 reportSettingsProblem(Log.ERROR,
6787 "Occurred while parsing settings at "
6788 + parser.getPositionDescription());
6789 }
6790 }
6791 } catch (NumberFormatException e) {
6792 reportSettingsProblem(Log.WARN,
6793 "Error in package manager settings: package "
6794 + name + " has bad userId " + idStr + " at "
6795 + parser.getPositionDescription());
6796 };
6797
6798 if (su != null) {
6799 int outerDepth = parser.getDepth();
6800 int type;
6801 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6802 && (type != XmlPullParser.END_TAG
6803 || parser.getDepth() > outerDepth)) {
6804 if (type == XmlPullParser.END_TAG
6805 || type == XmlPullParser.TEXT) {
6806 continue;
6807 }
6808
6809 String tagName = parser.getName();
6810 if (tagName.equals("sigs")) {
6811 su.signatures.readXml(parser, mPastSignatures);
6812 } else if (tagName.equals("perms")) {
6813 readGrantedPermissionsLP(parser, su.loadedPermissions);
6814 } else {
6815 reportSettingsProblem(Log.WARN,
6816 "Unknown element under <shared-user>: "
6817 + parser.getName());
6818 XmlUtils.skipCurrentTag(parser);
6819 }
6820 }
6821
6822 } else {
6823 XmlUtils.skipCurrentTag(parser);
6824 }
6825 }
6826
6827 private void readGrantedPermissionsLP(XmlPullParser parser,
6828 HashSet<String> outPerms) throws IOException, XmlPullParserException {
6829 int outerDepth = parser.getDepth();
6830 int type;
6831 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6832 && (type != XmlPullParser.END_TAG
6833 || parser.getDepth() > outerDepth)) {
6834 if (type == XmlPullParser.END_TAG
6835 || type == XmlPullParser.TEXT) {
6836 continue;
6837 }
6838
6839 String tagName = parser.getName();
6840 if (tagName.equals("item")) {
6841 String name = parser.getAttributeValue(null, "name");
6842 if (name != null) {
6843 outPerms.add(name.intern());
6844 } else {
6845 reportSettingsProblem(Log.WARN,
6846 "Error in package manager settings: <perms> has"
6847 + " no name at " + parser.getPositionDescription());
6848 }
6849 } else {
6850 reportSettingsProblem(Log.WARN,
6851 "Unknown element under <perms>: "
6852 + parser.getName());
6853 }
6854 XmlUtils.skipCurrentTag(parser);
6855 }
6856 }
6857
6858 private void readPreferredPackagesLP(XmlPullParser parser)
6859 throws XmlPullParserException, IOException {
6860 int outerDepth = parser.getDepth();
6861 int type;
6862 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6863 && (type != XmlPullParser.END_TAG
6864 || parser.getDepth() > outerDepth)) {
6865 if (type == XmlPullParser.END_TAG
6866 || type == XmlPullParser.TEXT) {
6867 continue;
6868 }
6869
6870 String tagName = parser.getName();
6871 if (tagName.equals("item")) {
6872 String name = parser.getAttributeValue(null, "name");
6873 if (name != null) {
6874 mPendingPreferredPackages.add(name);
6875 } else {
6876 reportSettingsProblem(Log.WARN,
6877 "Error in package manager settings: <preferred-package> has no name at "
6878 + parser.getPositionDescription());
6879 }
6880 } else {
6881 reportSettingsProblem(Log.WARN,
6882 "Unknown element under <preferred-packages>: "
6883 + parser.getName());
6884 }
6885 XmlUtils.skipCurrentTag(parser);
6886 }
6887 }
6888
6889 private void readPreferredActivitiesLP(XmlPullParser parser)
6890 throws XmlPullParserException, IOException {
6891 int outerDepth = parser.getDepth();
6892 int type;
6893 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6894 && (type != XmlPullParser.END_TAG
6895 || parser.getDepth() > outerDepth)) {
6896 if (type == XmlPullParser.END_TAG
6897 || type == XmlPullParser.TEXT) {
6898 continue;
6899 }
6900
6901 String tagName = parser.getName();
6902 if (tagName.equals("item")) {
6903 PreferredActivity pa = new PreferredActivity(parser);
6904 if (pa.mParseError == null) {
6905 mPreferredActivities.addFilter(pa);
6906 } else {
6907 reportSettingsProblem(Log.WARN,
6908 "Error in package manager settings: <preferred-activity> "
6909 + pa.mParseError + " at "
6910 + parser.getPositionDescription());
6911 }
6912 } else {
6913 reportSettingsProblem(Log.WARN,
6914 "Unknown element under <preferred-activities>: "
6915 + parser.getName());
6916 XmlUtils.skipCurrentTag(parser);
6917 }
6918 }
6919 }
6920
6921 // Returns -1 if we could not find an available UserId to assign
6922 private int newUserIdLP(Object obj) {
6923 // Let's be stupidly inefficient for now...
6924 final int N = mUserIds.size();
6925 for (int i=0; i<N; i++) {
6926 if (mUserIds.get(i) == null) {
6927 mUserIds.set(i, obj);
6928 return FIRST_APPLICATION_UID + i;
6929 }
6930 }
6931
6932 // None left?
6933 if (N >= MAX_APPLICATION_UIDS) {
6934 return -1;
6935 }
6936
6937 mUserIds.add(obj);
6938 return FIRST_APPLICATION_UID + N;
6939 }
6940
6941 public PackageSetting getDisabledSystemPkg(String name) {
6942 synchronized(mPackages) {
6943 PackageSetting ps = mDisabledSysPackages.get(name);
6944 return ps;
6945 }
6946 }
6947
6948 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
6949 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
6950 if (Config.LOGV) {
6951 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
6952 + " componentName = " + componentInfo.name);
6953 Log.v(TAG, "enabledComponents: "
6954 + Arrays.toString(packageSettings.enabledComponents.toArray()));
6955 Log.v(TAG, "disabledComponents: "
6956 + Arrays.toString(packageSettings.disabledComponents.toArray()));
6957 }
6958 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
6959 || ((componentInfo.enabled
6960 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
6961 || (componentInfo.applicationInfo.enabled
6962 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
6963 && !packageSettings.disabledComponents.contains(componentInfo.name))
6964 || packageSettings.enabledComponents.contains(componentInfo.name));
6965 }
6966 }
6967}