blob: d8dafb63b25767c357d96e9b52b6471adbc435fe [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);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07004908 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
4909 pw.print(" densities="); pw.println(ps.pkg.supportsDensityList);
4910 ArrayList<String> screens = new ArrayList<String>();
4911 if ((ps.pkg.applicationInfo.flags &
4912 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
4913 screens.add("medium");
4914 }
4915 if ((ps.pkg.applicationInfo.flags &
4916 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
4917 screens.add("large");
4918 }
4919 if ((ps.pkg.applicationInfo.flags &
4920 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
4921 screens.add("small,");
4922 }
4923 pw.print(" supportsScreens="); pw.println(screens);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004924 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004925 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
4926 pw.print(" signatures="); pw.println(ps.signatures);
4927 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
4928 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
4929 pw.print(" installStatus="); pw.print(ps.installStatus);
4930 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 if (ps.disabledComponents.size() > 0) {
4932 pw.println(" disabledComponents:");
4933 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004934 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004935 }
4936 }
4937 if (ps.enabledComponents.size() > 0) {
4938 pw.println(" enabledComponents:");
4939 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004940 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 }
4942 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004943 if (ps.grantedPermissions.size() > 0) {
4944 pw.println(" grantedPermissions:");
4945 for (String s : ps.grantedPermissions) {
4946 pw.print(" "); pw.println(s);
4947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004949 if (ps.loadedPermissions.size() > 0) {
4950 pw.println(" loadedPermissions:");
4951 for (String s : ps.loadedPermissions) {
4952 pw.print(" "); pw.println(s);
4953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 }
4955 }
4956 }
4957 pw.println(" ");
4958 pw.println("Shared Users:");
4959 {
4960 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004961 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
4962 pw.print(Integer.toHexString(System.identityHashCode(su)));
4963 pw.println("):");
4964 pw.print(" userId="); pw.print(su.userId);
4965 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004966 pw.println(" grantedPermissions:");
4967 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004968 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004969 }
4970 pw.println(" loadedPermissions:");
4971 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004972 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 }
4974 }
4975 }
4976 pw.println(" ");
4977 pw.println("Settings parse messages:");
4978 pw.println(mSettings.mReadMessages.toString());
4979 }
4980 }
4981
4982 static final class BasePermission {
4983 final static int TYPE_NORMAL = 0;
4984 final static int TYPE_BUILTIN = 1;
4985 final static int TYPE_DYNAMIC = 2;
4986
4987 final String name;
4988 final String sourcePackage;
4989 final int type;
4990 PackageParser.Permission perm;
4991 PermissionInfo pendingInfo;
4992 int uid;
4993 int[] gids;
4994
4995 BasePermission(String _name, String _sourcePackage, int _type) {
4996 name = _name;
4997 sourcePackage = _sourcePackage;
4998 type = _type;
4999 }
5000 }
5001
5002 static class PackageSignatures {
5003 private Signature[] mSignatures;
5004
5005 PackageSignatures(Signature[] sigs) {
5006 assignSignatures(sigs);
5007 }
5008
5009 PackageSignatures() {
5010 }
5011
5012 void writeXml(XmlSerializer serializer, String tagName,
5013 ArrayList<Signature> pastSignatures) throws IOException {
5014 if (mSignatures == null) {
5015 return;
5016 }
5017 serializer.startTag(null, tagName);
5018 serializer.attribute(null, "count",
5019 Integer.toString(mSignatures.length));
5020 for (int i=0; i<mSignatures.length; i++) {
5021 serializer.startTag(null, "cert");
5022 final Signature sig = mSignatures[i];
5023 final int sigHash = sig.hashCode();
5024 final int numPast = pastSignatures.size();
5025 int j;
5026 for (j=0; j<numPast; j++) {
5027 Signature pastSig = pastSignatures.get(j);
5028 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5029 serializer.attribute(null, "index", Integer.toString(j));
5030 break;
5031 }
5032 }
5033 if (j >= numPast) {
5034 pastSignatures.add(sig);
5035 serializer.attribute(null, "index", Integer.toString(numPast));
5036 serializer.attribute(null, "key", sig.toCharsString());
5037 }
5038 serializer.endTag(null, "cert");
5039 }
5040 serializer.endTag(null, tagName);
5041 }
5042
5043 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5044 throws IOException, XmlPullParserException {
5045 String countStr = parser.getAttributeValue(null, "count");
5046 if (countStr == null) {
5047 reportSettingsProblem(Log.WARN,
5048 "Error in package manager settings: <signatures> has"
5049 + " no count at " + parser.getPositionDescription());
5050 XmlUtils.skipCurrentTag(parser);
5051 }
5052 final int count = Integer.parseInt(countStr);
5053 mSignatures = new Signature[count];
5054 int pos = 0;
5055
5056 int outerDepth = parser.getDepth();
5057 int type;
5058 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5059 && (type != XmlPullParser.END_TAG
5060 || parser.getDepth() > outerDepth)) {
5061 if (type == XmlPullParser.END_TAG
5062 || type == XmlPullParser.TEXT) {
5063 continue;
5064 }
5065
5066 String tagName = parser.getName();
5067 if (tagName.equals("cert")) {
5068 if (pos < count) {
5069 String index = parser.getAttributeValue(null, "index");
5070 if (index != null) {
5071 try {
5072 int idx = Integer.parseInt(index);
5073 String key = parser.getAttributeValue(null, "key");
5074 if (key == null) {
5075 if (idx >= 0 && idx < pastSignatures.size()) {
5076 Signature sig = pastSignatures.get(idx);
5077 if (sig != null) {
5078 mSignatures[pos] = pastSignatures.get(idx);
5079 pos++;
5080 } else {
5081 reportSettingsProblem(Log.WARN,
5082 "Error in package manager settings: <cert> "
5083 + "index " + index + " is not defined at "
5084 + parser.getPositionDescription());
5085 }
5086 } else {
5087 reportSettingsProblem(Log.WARN,
5088 "Error in package manager settings: <cert> "
5089 + "index " + index + " is out of bounds at "
5090 + parser.getPositionDescription());
5091 }
5092 } else {
5093 while (pastSignatures.size() <= idx) {
5094 pastSignatures.add(null);
5095 }
5096 Signature sig = new Signature(key);
5097 pastSignatures.set(idx, sig);
5098 mSignatures[pos] = sig;
5099 pos++;
5100 }
5101 } catch (NumberFormatException e) {
5102 reportSettingsProblem(Log.WARN,
5103 "Error in package manager settings: <cert> "
5104 + "index " + index + " is not a number at "
5105 + parser.getPositionDescription());
5106 }
5107 } else {
5108 reportSettingsProblem(Log.WARN,
5109 "Error in package manager settings: <cert> has"
5110 + " no index at " + parser.getPositionDescription());
5111 }
5112 } else {
5113 reportSettingsProblem(Log.WARN,
5114 "Error in package manager settings: too "
5115 + "many <cert> tags, expected " + count
5116 + " at " + parser.getPositionDescription());
5117 }
5118 } else {
5119 reportSettingsProblem(Log.WARN,
5120 "Unknown element under <cert>: "
5121 + parser.getName());
5122 }
5123 XmlUtils.skipCurrentTag(parser);
5124 }
5125
5126 if (pos < count) {
5127 // Should never happen -- there is an error in the written
5128 // settings -- but if it does we don't want to generate
5129 // a bad array.
5130 Signature[] newSigs = new Signature[pos];
5131 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5132 mSignatures = newSigs;
5133 }
5134 }
5135
5136 /**
5137 * If any of the given 'sigs' is contained in the existing signatures,
5138 * then completely replace the current signatures with the ones in
5139 * 'sigs'. This is used for updating an existing package to a newly
5140 * installed version.
5141 */
5142 boolean updateSignatures(Signature[] sigs, boolean update) {
5143 if (mSignatures == null) {
5144 if (update) {
5145 assignSignatures(sigs);
5146 }
5147 return true;
5148 }
5149 if (sigs == null) {
5150 return false;
5151 }
5152
5153 for (int i=0; i<sigs.length; i++) {
5154 Signature sig = sigs[i];
5155 for (int j=0; j<mSignatures.length; j++) {
5156 if (mSignatures[j].equals(sig)) {
5157 if (update) {
5158 assignSignatures(sigs);
5159 }
5160 return true;
5161 }
5162 }
5163 }
5164 return false;
5165 }
5166
5167 /**
5168 * If any of the given 'sigs' is contained in the existing signatures,
5169 * then add in any new signatures found in 'sigs'. This is used for
5170 * including a new package into an existing shared user id.
5171 */
5172 boolean mergeSignatures(Signature[] sigs, boolean update) {
5173 if (mSignatures == null) {
5174 if (update) {
5175 assignSignatures(sigs);
5176 }
5177 return true;
5178 }
5179 if (sigs == null) {
5180 return false;
5181 }
5182
5183 Signature[] added = null;
5184 int addedCount = 0;
5185 boolean haveMatch = false;
5186 for (int i=0; i<sigs.length; i++) {
5187 Signature sig = sigs[i];
5188 boolean found = false;
5189 for (int j=0; j<mSignatures.length; j++) {
5190 if (mSignatures[j].equals(sig)) {
5191 found = true;
5192 haveMatch = true;
5193 break;
5194 }
5195 }
5196
5197 if (!found) {
5198 if (added == null) {
5199 added = new Signature[sigs.length];
5200 }
5201 added[i] = sig;
5202 addedCount++;
5203 }
5204 }
5205
5206 if (!haveMatch) {
5207 // Nothing matched -- reject the new signatures.
5208 return false;
5209 }
5210 if (added == null) {
5211 // Completely matched -- nothing else to do.
5212 return true;
5213 }
5214
5215 // Add additional signatures in.
5216 if (update) {
5217 Signature[] total = new Signature[addedCount+mSignatures.length];
5218 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5219 int j = mSignatures.length;
5220 for (int i=0; i<added.length; i++) {
5221 if (added[i] != null) {
5222 total[j] = added[i];
5223 j++;
5224 }
5225 }
5226 mSignatures = total;
5227 }
5228 return true;
5229 }
5230
5231 private void assignSignatures(Signature[] sigs) {
5232 if (sigs == null) {
5233 mSignatures = null;
5234 return;
5235 }
5236 mSignatures = new Signature[sigs.length];
5237 for (int i=0; i<sigs.length; i++) {
5238 mSignatures[i] = sigs[i];
5239 }
5240 }
5241
5242 @Override
5243 public String toString() {
5244 StringBuffer buf = new StringBuffer(128);
5245 buf.append("PackageSignatures{");
5246 buf.append(Integer.toHexString(System.identityHashCode(this)));
5247 buf.append(" [");
5248 if (mSignatures != null) {
5249 for (int i=0; i<mSignatures.length; i++) {
5250 if (i > 0) buf.append(", ");
5251 buf.append(Integer.toHexString(
5252 System.identityHashCode(mSignatures[i])));
5253 }
5254 }
5255 buf.append("]}");
5256 return buf.toString();
5257 }
5258 }
5259
5260 static class PreferredActivity extends IntentFilter {
5261 final int mMatch;
5262 final String[] mSetPackages;
5263 final String[] mSetClasses;
5264 final String[] mSetComponents;
5265 final ComponentName mActivity;
5266 final String mShortActivity;
5267 String mParseError;
5268
5269 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5270 ComponentName activity) {
5271 super(filter);
5272 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5273 mActivity = activity;
5274 mShortActivity = activity.flattenToShortString();
5275 mParseError = null;
5276 if (set != null) {
5277 final int N = set.length;
5278 String[] myPackages = new String[N];
5279 String[] myClasses = new String[N];
5280 String[] myComponents = new String[N];
5281 for (int i=0; i<N; i++) {
5282 ComponentName cn = set[i];
5283 if (cn == null) {
5284 mSetPackages = null;
5285 mSetClasses = null;
5286 mSetComponents = null;
5287 return;
5288 }
5289 myPackages[i] = cn.getPackageName().intern();
5290 myClasses[i] = cn.getClassName().intern();
5291 myComponents[i] = cn.flattenToShortString().intern();
5292 }
5293 mSetPackages = myPackages;
5294 mSetClasses = myClasses;
5295 mSetComponents = myComponents;
5296 } else {
5297 mSetPackages = null;
5298 mSetClasses = null;
5299 mSetComponents = null;
5300 }
5301 }
5302
5303 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5304 IOException {
5305 mShortActivity = parser.getAttributeValue(null, "name");
5306 mActivity = ComponentName.unflattenFromString(mShortActivity);
5307 if (mActivity == null) {
5308 mParseError = "Bad activity name " + mShortActivity;
5309 }
5310 String matchStr = parser.getAttributeValue(null, "match");
5311 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5312 String setCountStr = parser.getAttributeValue(null, "set");
5313 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5314
5315 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5316 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5317 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5318
5319 int setPos = 0;
5320
5321 int outerDepth = parser.getDepth();
5322 int type;
5323 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5324 && (type != XmlPullParser.END_TAG
5325 || parser.getDepth() > outerDepth)) {
5326 if (type == XmlPullParser.END_TAG
5327 || type == XmlPullParser.TEXT) {
5328 continue;
5329 }
5330
5331 String tagName = parser.getName();
5332 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5333 // + parser.getDepth() + " tag=" + tagName);
5334 if (tagName.equals("set")) {
5335 String name = parser.getAttributeValue(null, "name");
5336 if (name == null) {
5337 if (mParseError == null) {
5338 mParseError = "No name in set tag in preferred activity "
5339 + mShortActivity;
5340 }
5341 } else if (setPos >= setCount) {
5342 if (mParseError == null) {
5343 mParseError = "Too many set tags in preferred activity "
5344 + mShortActivity;
5345 }
5346 } else {
5347 ComponentName cn = ComponentName.unflattenFromString(name);
5348 if (cn == null) {
5349 if (mParseError == null) {
5350 mParseError = "Bad set name " + name + " in preferred activity "
5351 + mShortActivity;
5352 }
5353 } else {
5354 myPackages[setPos] = cn.getPackageName();
5355 myClasses[setPos] = cn.getClassName();
5356 myComponents[setPos] = name;
5357 setPos++;
5358 }
5359 }
5360 XmlUtils.skipCurrentTag(parser);
5361 } else if (tagName.equals("filter")) {
5362 //Log.i(TAG, "Starting to parse filter...");
5363 readFromXml(parser);
5364 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5365 // + parser.getDepth() + " tag=" + parser.getName());
5366 } else {
5367 reportSettingsProblem(Log.WARN,
5368 "Unknown element under <preferred-activities>: "
5369 + parser.getName());
5370 XmlUtils.skipCurrentTag(parser);
5371 }
5372 }
5373
5374 if (setPos != setCount) {
5375 if (mParseError == null) {
5376 mParseError = "Not enough set tags (expected " + setCount
5377 + " but found " + setPos + ") in " + mShortActivity;
5378 }
5379 }
5380
5381 mSetPackages = myPackages;
5382 mSetClasses = myClasses;
5383 mSetComponents = myComponents;
5384 }
5385
5386 public void writeToXml(XmlSerializer serializer) throws IOException {
5387 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5388 serializer.attribute(null, "name", mShortActivity);
5389 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5390 serializer.attribute(null, "set", Integer.toString(NS));
5391 for (int s=0; s<NS; s++) {
5392 serializer.startTag(null, "set");
5393 serializer.attribute(null, "name", mSetComponents[s]);
5394 serializer.endTag(null, "set");
5395 }
5396 serializer.startTag(null, "filter");
5397 super.writeToXml(serializer);
5398 serializer.endTag(null, "filter");
5399 }
5400
5401 boolean sameSet(List<ResolveInfo> query, int priority) {
5402 if (mSetPackages == null) return false;
5403 final int NQ = query.size();
5404 final int NS = mSetPackages.length;
5405 int numMatch = 0;
5406 for (int i=0; i<NQ; i++) {
5407 ResolveInfo ri = query.get(i);
5408 if (ri.priority != priority) continue;
5409 ActivityInfo ai = ri.activityInfo;
5410 boolean good = false;
5411 for (int j=0; j<NS; j++) {
5412 if (mSetPackages[j].equals(ai.packageName)
5413 && mSetClasses[j].equals(ai.name)) {
5414 numMatch++;
5415 good = true;
5416 break;
5417 }
5418 }
5419 if (!good) return false;
5420 }
5421 return numMatch == NS;
5422 }
5423 }
5424
5425 static class GrantedPermissions {
5426 final int pkgFlags;
5427
5428 HashSet<String> grantedPermissions = new HashSet<String>();
5429 int[] gids;
5430
5431 HashSet<String> loadedPermissions = new HashSet<String>();
5432
5433 GrantedPermissions(int pkgFlags) {
5434 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5435 }
5436 }
5437
5438 /**
5439 * Settings base class for pending and resolved classes.
5440 */
5441 static class PackageSettingBase extends GrantedPermissions {
5442 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005443 File codePath;
5444 String codePathString;
5445 File resourcePath;
5446 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 private long timeStamp;
5448 private String timeStampString = "0";
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005449 final int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450
5451 PackageSignatures signatures = new PackageSignatures();
5452
5453 boolean permissionsFixed;
5454
5455 /* Explicitly disabled components */
5456 HashSet<String> disabledComponents = new HashSet<String>(0);
5457 /* Explicitly enabled components */
5458 HashSet<String> enabledComponents = new HashSet<String>(0);
5459 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5460 int installStatus = PKG_INSTALL_COMPLETE;
Jacek Surazskic64322c2009-04-28 15:26:38 +02005461
5462 /* package name of the app that installed this package */
5463 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464
5465 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005466 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005467 super(pkgFlags);
5468 this.name = name;
5469 this.codePath = codePath;
5470 this.codePathString = codePath.toString();
5471 this.resourcePath = resourcePath;
5472 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005473 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 }
5475
Jacek Surazskic64322c2009-04-28 15:26:38 +02005476 public void setInstallerPackageName(String packageName) {
5477 installerPackageName = packageName;
5478 }
5479
5480 String getInstallerPackageName() {
5481 return installerPackageName;
5482 }
5483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 public void setInstallStatus(int newStatus) {
5485 installStatus = newStatus;
5486 }
5487
5488 public int getInstallStatus() {
5489 return installStatus;
5490 }
5491
5492 public void setTimeStamp(long newStamp) {
5493 if (newStamp != timeStamp) {
5494 timeStamp = newStamp;
5495 timeStampString = Long.toString(newStamp);
5496 }
5497 }
5498
5499 public void setTimeStamp(long newStamp, String newStampStr) {
5500 timeStamp = newStamp;
5501 timeStampString = newStampStr;
5502 }
5503
5504 public long getTimeStamp() {
5505 return timeStamp;
5506 }
5507
5508 public String getTimeStampStr() {
5509 return timeStampString;
5510 }
5511
5512 public void copyFrom(PackageSettingBase base) {
5513 grantedPermissions = base.grantedPermissions;
5514 gids = base.gids;
5515 loadedPermissions = base.loadedPermissions;
5516
5517 timeStamp = base.timeStamp;
5518 timeStampString = base.timeStampString;
5519 signatures = base.signatures;
5520 permissionsFixed = base.permissionsFixed;
5521 disabledComponents = base.disabledComponents;
5522 enabledComponents = base.enabledComponents;
5523 enabled = base.enabled;
5524 installStatus = base.installStatus;
5525 }
5526
5527 void enableComponentLP(String componentClassName) {
5528 disabledComponents.remove(componentClassName);
5529 enabledComponents.add(componentClassName);
5530 }
5531
5532 void disableComponentLP(String componentClassName) {
5533 enabledComponents.remove(componentClassName);
5534 disabledComponents.add(componentClassName);
5535 }
5536
5537 void restoreComponentLP(String componentClassName) {
5538 enabledComponents.remove(componentClassName);
5539 disabledComponents.remove(componentClassName);
5540 }
5541
5542 int currentEnabledStateLP(String componentName) {
5543 if (enabledComponents.contains(componentName)) {
5544 return COMPONENT_ENABLED_STATE_ENABLED;
5545 } else if (disabledComponents.contains(componentName)) {
5546 return COMPONENT_ENABLED_STATE_DISABLED;
5547 } else {
5548 return COMPONENT_ENABLED_STATE_DEFAULT;
5549 }
5550 }
5551 }
5552
5553 /**
5554 * Settings data for a particular package we know about.
5555 */
5556 static final class PackageSetting extends PackageSettingBase {
5557 int userId;
5558 PackageParser.Package pkg;
5559 SharedUserSetting sharedUser;
5560
5561 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005562 int pVersionCode, int pkgFlags) {
5563 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005564 }
5565
5566 @Override
5567 public String toString() {
5568 return "PackageSetting{"
5569 + Integer.toHexString(System.identityHashCode(this))
5570 + " " + name + "/" + userId + "}";
5571 }
5572 }
5573
5574 /**
5575 * Settings data for a particular shared user ID we know about.
5576 */
5577 static final class SharedUserSetting extends GrantedPermissions {
5578 final String name;
5579 int userId;
5580 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
5581 final PackageSignatures signatures = new PackageSignatures();
5582
5583 SharedUserSetting(String _name, int _pkgFlags) {
5584 super(_pkgFlags);
5585 name = _name;
5586 }
5587
5588 @Override
5589 public String toString() {
5590 return "SharedUserSetting{"
5591 + Integer.toHexString(System.identityHashCode(this))
5592 + " " + name + "/" + userId + "}";
5593 }
5594 }
5595
5596 /**
5597 * Holds information about dynamic settings.
5598 */
5599 private static final class Settings {
5600 private final File mSettingsFilename;
5601 private final File mBackupSettingsFilename;
5602 private final HashMap<String, PackageSetting> mPackages =
5603 new HashMap<String, PackageSetting>();
5604 // The user's preferred packages/applications, in order of preference.
5605 // First is the most preferred.
5606 private final ArrayList<PackageSetting> mPreferredPackages =
5607 new ArrayList<PackageSetting>();
5608 // List of replaced system applications
5609 final HashMap<String, PackageSetting> mDisabledSysPackages =
5610 new HashMap<String, PackageSetting>();
5611
5612 // The user's preferred activities associated with particular intent
5613 // filters.
5614 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
5615 new IntentResolver<PreferredActivity, PreferredActivity>() {
5616 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005617 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005619 out.print(prefix); out.print(
5620 Integer.toHexString(System.identityHashCode(filter)));
5621 out.print(' ');
5622 out.print(filter.mActivity.flattenToShortString());
5623 out.print(" match=0x");
5624 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005626 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005628 out.print(prefix); out.print(" ");
5629 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 }
5631 }
5632 }
5633 };
5634 private final HashMap<String, SharedUserSetting> mSharedUsers =
5635 new HashMap<String, SharedUserSetting>();
5636 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
5637 private final SparseArray<Object> mOtherUserIds =
5638 new SparseArray<Object>();
5639
5640 // For reading/writing settings file.
5641 private final ArrayList<Signature> mPastSignatures =
5642 new ArrayList<Signature>();
5643
5644 // Mapping from permission names to info about them.
5645 final HashMap<String, BasePermission> mPermissions =
5646 new HashMap<String, BasePermission>();
5647
5648 // Mapping from permission tree names to info about them.
5649 final HashMap<String, BasePermission> mPermissionTrees =
5650 new HashMap<String, BasePermission>();
5651
5652 private final ArrayList<String> mPendingPreferredPackages
5653 = new ArrayList<String>();
5654
5655 private final StringBuilder mReadMessages = new StringBuilder();
5656
5657 private static final class PendingPackage extends PackageSettingBase {
5658 final int sharedId;
5659
5660 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005661 int sharedId, int pVersionCode, int pkgFlags) {
5662 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663 this.sharedId = sharedId;
5664 }
5665 }
5666 private final ArrayList<PendingPackage> mPendingPackages
5667 = new ArrayList<PendingPackage>();
5668
5669 Settings() {
5670 File dataDir = Environment.getDataDirectory();
5671 File systemDir = new File(dataDir, "system");
5672 systemDir.mkdirs();
5673 FileUtils.setPermissions(systemDir.toString(),
5674 FileUtils.S_IRWXU|FileUtils.S_IRWXG
5675 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
5676 -1, -1);
5677 mSettingsFilename = new File(systemDir, "packages.xml");
5678 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
5679 }
5680
5681 PackageSetting getPackageLP(PackageParser.Package pkg,
5682 SharedUserSetting sharedUser, File codePath, File resourcePath,
5683 int pkgFlags, boolean create, boolean add) {
5684 final String name = pkg.packageName;
5685 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005686 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687
5688 if (p != null) {
5689 p.pkg = pkg;
5690 }
5691 return p;
5692 }
5693
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005694 PackageSetting peekPackageLP(String name) {
5695 return mPackages.get(name);
5696 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 PackageSetting p = mPackages.get(name);
5698 if (p != null && p.codePath.getPath().equals(codePath)) {
5699 return p;
5700 }
5701 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005702 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 }
5704
5705 void setInstallStatus(String pkgName, int status) {
5706 PackageSetting p = mPackages.get(pkgName);
5707 if(p != null) {
5708 if(p.getInstallStatus() != status) {
5709 p.setInstallStatus(status);
5710 }
5711 }
5712 }
5713
Jacek Surazskic64322c2009-04-28 15:26:38 +02005714 void setInstallerPackageName(String pkgName,
5715 String installerPkgName) {
5716 PackageSetting p = mPackages.get(pkgName);
5717 if(p != null) {
5718 p.setInstallerPackageName(installerPkgName);
5719 }
5720 }
5721
5722 String getInstallerPackageName(String pkgName) {
5723 PackageSetting p = mPackages.get(pkgName);
5724 return (p == null) ? null : p.getInstallerPackageName();
5725 }
5726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 int getInstallStatus(String pkgName) {
5728 PackageSetting p = mPackages.get(pkgName);
5729 if(p != null) {
5730 return p.getInstallStatus();
5731 }
5732 return -1;
5733 }
5734
5735 SharedUserSetting getSharedUserLP(String name,
5736 int pkgFlags, boolean create) {
5737 SharedUserSetting s = mSharedUsers.get(name);
5738 if (s == null) {
5739 if (!create) {
5740 return null;
5741 }
5742 s = new SharedUserSetting(name, pkgFlags);
5743 if (MULTIPLE_APPLICATION_UIDS) {
5744 s.userId = newUserIdLP(s);
5745 } else {
5746 s.userId = FIRST_APPLICATION_UID;
5747 }
5748 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
5749 // < 0 means we couldn't assign a userid; fall out and return
5750 // s, which is currently null
5751 if (s.userId >= 0) {
5752 mSharedUsers.put(name, s);
5753 }
5754 }
5755
5756 return s;
5757 }
5758
5759 int disableSystemPackageLP(String name) {
5760 PackageSetting p = mPackages.get(name);
5761 if(p == null) {
5762 Log.w(TAG, "Package:"+name+" is not an installed package");
5763 return -1;
5764 }
5765 PackageSetting dp = mDisabledSysPackages.get(name);
5766 // always make sure the system package code and resource paths dont change
5767 if(dp == null) {
5768 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
5769 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5770 }
5771 mDisabledSysPackages.put(name, p);
5772 }
5773 return removePackageLP(name);
5774 }
5775
5776 PackageSetting enableSystemPackageLP(String name) {
5777 PackageSetting p = mDisabledSysPackages.get(name);
5778 if(p == null) {
5779 Log.w(TAG, "Package:"+name+" is not disabled");
5780 return null;
5781 }
5782 // Reset flag in ApplicationInfo object
5783 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
5784 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5785 }
5786 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005787 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 mDisabledSysPackages.remove(name);
5789 return ret;
5790 }
5791
5792 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005793 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 PackageSetting p = mPackages.get(name);
5795 if (p != null) {
5796 if (p.userId == uid) {
5797 return p;
5798 }
5799 reportSettingsProblem(Log.ERROR,
5800 "Adding duplicate package, keeping first: " + name);
5801 return null;
5802 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005803 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 p.userId = uid;
5805 if (addUserIdLP(uid, p, name)) {
5806 mPackages.put(name, p);
5807 return p;
5808 }
5809 return null;
5810 }
5811
5812 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
5813 SharedUserSetting s = mSharedUsers.get(name);
5814 if (s != null) {
5815 if (s.userId == uid) {
5816 return s;
5817 }
5818 reportSettingsProblem(Log.ERROR,
5819 "Adding duplicate shared user, keeping first: " + name);
5820 return null;
5821 }
5822 s = new SharedUserSetting(name, pkgFlags);
5823 s.userId = uid;
5824 if (addUserIdLP(uid, s, name)) {
5825 mSharedUsers.put(name, s);
5826 return s;
5827 }
5828 return null;
5829 }
5830
5831 private PackageSetting getPackageLP(String name,
5832 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005833 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 PackageSetting p = mPackages.get(name);
5835 if (p != null) {
5836 if (!p.codePath.equals(codePath)) {
5837 // Check to see if its a disabled system app
5838 PackageSetting ps = mDisabledSysPackages.get(name);
5839 if((ps != null) && ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07005840 // This is an updated system app with versions in both system
5841 // and data partition. Just let the most recent version
5842 // take precedence.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 return p;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005844 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07005845 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07005846 reportSettingsProblem(Log.WARN,
5847 "Package " + name + " codePath changed from " + p.codePath
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005848 + " to " + codePath + "; Retaining data and using new code from " +
5849 codePath);
5850 p.codePath = codePath;
5851 p.resourcePath = resourcePath;
5852 p.codePathString = codePath.toString();
5853 p.resourcePathString = resourcePath.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854 }
5855 } else if (p.sharedUser != sharedUser) {
5856 reportSettingsProblem(Log.WARN,
5857 "Package " + name + " shared user changed from "
5858 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
5859 + " to "
5860 + (sharedUser != null ? sharedUser.name : "<nothing>")
5861 + "; replacing with new");
5862 p = null;
5863 }
5864 }
5865 if (p == null) {
5866 // Create a new PackageSettings entry. this can end up here because
5867 // of code path mismatch or user id mismatch of an updated system partition
5868 if (!create) {
5869 return null;
5870 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005871 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07005873 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 if (sharedUser != null) {
5875 p.userId = sharedUser.userId;
5876 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005877 // Assign new user id
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 p.userId = newUserIdLP(p);
5879 } else {
5880 p.userId = FIRST_APPLICATION_UID;
5881 }
5882 if (p.userId < 0) {
5883 reportSettingsProblem(Log.WARN,
5884 "Package " + name + " could not be assigned a valid uid");
5885 return null;
5886 }
5887 if (add) {
5888 // Finish adding new package by adding it and updating shared
5889 // user preferences
5890 insertPackageSettingLP(p, name, sharedUser);
5891 }
5892 }
5893 return p;
5894 }
5895
5896 // Utility method that adds a PackageSetting to mPackages and
5897 // completes updating the shared user attributes
5898 private void insertPackageSettingLP(PackageSetting p, String name,
5899 SharedUserSetting sharedUser) {
5900 mPackages.put(name, p);
5901 if (sharedUser != null) {
5902 if (p.sharedUser != null && p.sharedUser != sharedUser) {
5903 reportSettingsProblem(Log.ERROR,
5904 "Package " + p.name + " was user "
5905 + p.sharedUser + " but is now " + sharedUser
5906 + "; I am not changing its files so it will probably fail!");
5907 p.sharedUser.packages.remove(p);
5908 } else if (p.userId != sharedUser.userId) {
5909 reportSettingsProblem(Log.ERROR,
5910 "Package " + p.name + " was user id " + p.userId
5911 + " but is now user " + sharedUser
5912 + " with id " + sharedUser.userId
5913 + "; I am not changing its files so it will probably fail!");
5914 }
5915
5916 sharedUser.packages.add(p);
5917 p.sharedUser = sharedUser;
5918 p.userId = sharedUser.userId;
5919 }
5920 }
5921
5922 private void updateSharedUserPerms (PackageSetting deletedPs) {
5923 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
5924 Log.i(TAG, "Trying to update info for null package. Just ignoring");
5925 return;
5926 }
5927 // No sharedUserId
5928 if (deletedPs.sharedUser == null) {
5929 return;
5930 }
5931 SharedUserSetting sus = deletedPs.sharedUser;
5932 // Update permissions
5933 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
5934 boolean used = false;
5935 if (!sus.grantedPermissions.contains (eachPerm)) {
5936 continue;
5937 }
5938 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapub97b8f82009-06-19 15:09:18 -07005939 if (pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 used = true;
5941 break;
5942 }
5943 }
5944 if (!used) {
5945 // can safely delete this permission from list
5946 sus.grantedPermissions.remove(eachPerm);
5947 sus.loadedPermissions.remove(eachPerm);
5948 }
5949 }
5950 // Update gids
5951 int newGids[] = null;
5952 for (PackageSetting pkg:sus.packages) {
5953 newGids = appendInts(newGids, pkg.gids);
5954 }
5955 sus.gids = newGids;
5956 }
5957
5958 private int removePackageLP(String name) {
5959 PackageSetting p = mPackages.get(name);
5960 if (p != null) {
5961 mPackages.remove(name);
5962 if (p.sharedUser != null) {
5963 p.sharedUser.packages.remove(p);
5964 if (p.sharedUser.packages.size() == 0) {
5965 mSharedUsers.remove(p.sharedUser.name);
5966 removeUserIdLP(p.sharedUser.userId);
5967 return p.sharedUser.userId;
5968 }
5969 } else {
5970 removeUserIdLP(p.userId);
5971 return p.userId;
5972 }
5973 }
5974 return -1;
5975 }
5976
5977 private boolean addUserIdLP(int uid, Object obj, Object name) {
5978 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
5979 return false;
5980 }
5981
5982 if (uid >= FIRST_APPLICATION_UID) {
5983 int N = mUserIds.size();
5984 final int index = uid - FIRST_APPLICATION_UID;
5985 while (index >= N) {
5986 mUserIds.add(null);
5987 N++;
5988 }
5989 if (mUserIds.get(index) != null) {
5990 reportSettingsProblem(Log.ERROR,
5991 "Adding duplicate shared id: " + uid
5992 + " name=" + name);
5993 return false;
5994 }
5995 mUserIds.set(index, obj);
5996 } else {
5997 if (mOtherUserIds.get(uid) != null) {
5998 reportSettingsProblem(Log.ERROR,
5999 "Adding duplicate shared id: " + uid
6000 + " name=" + name);
6001 return false;
6002 }
6003 mOtherUserIds.put(uid, obj);
6004 }
6005 return true;
6006 }
6007
6008 public Object getUserIdLP(int uid) {
6009 if (uid >= FIRST_APPLICATION_UID) {
6010 int N = mUserIds.size();
6011 final int index = uid - FIRST_APPLICATION_UID;
6012 return index < N ? mUserIds.get(index) : null;
6013 } else {
6014 return mOtherUserIds.get(uid);
6015 }
6016 }
6017
6018 private void removeUserIdLP(int uid) {
6019 if (uid >= FIRST_APPLICATION_UID) {
6020 int N = mUserIds.size();
6021 final int index = uid - FIRST_APPLICATION_UID;
6022 if (index < N) mUserIds.set(index, null);
6023 } else {
6024 mOtherUserIds.remove(uid);
6025 }
6026 }
6027
6028 void writeLP() {
6029 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6030
6031 // Keep the old settings around until we know the new ones have
6032 // been successfully written.
6033 if (mSettingsFilename.exists()) {
6034 if (mBackupSettingsFilename.exists()) {
6035 mBackupSettingsFilename.delete();
6036 }
6037 mSettingsFilename.renameTo(mBackupSettingsFilename);
6038 }
6039
6040 mPastSignatures.clear();
6041
6042 try {
6043 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6044
6045 //XmlSerializer serializer = XmlUtils.serializerInstance();
6046 XmlSerializer serializer = new FastXmlSerializer();
6047 serializer.setOutput(str, "utf-8");
6048 serializer.startDocument(null, true);
6049 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6050
6051 serializer.startTag(null, "packages");
6052
6053 serializer.startTag(null, "permission-trees");
6054 for (BasePermission bp : mPermissionTrees.values()) {
6055 writePermission(serializer, bp);
6056 }
6057 serializer.endTag(null, "permission-trees");
6058
6059 serializer.startTag(null, "permissions");
6060 for (BasePermission bp : mPermissions.values()) {
6061 writePermission(serializer, bp);
6062 }
6063 serializer.endTag(null, "permissions");
6064
6065 for (PackageSetting pkg : mPackages.values()) {
6066 writePackage(serializer, pkg);
6067 }
6068
6069 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6070 writeDisabledSysPackage(serializer, pkg);
6071 }
6072
6073 serializer.startTag(null, "preferred-packages");
6074 int N = mPreferredPackages.size();
6075 for (int i=0; i<N; i++) {
6076 PackageSetting pkg = mPreferredPackages.get(i);
6077 serializer.startTag(null, "item");
6078 serializer.attribute(null, "name", pkg.name);
6079 serializer.endTag(null, "item");
6080 }
6081 serializer.endTag(null, "preferred-packages");
6082
6083 serializer.startTag(null, "preferred-activities");
6084 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6085 serializer.startTag(null, "item");
6086 pa.writeToXml(serializer);
6087 serializer.endTag(null, "item");
6088 }
6089 serializer.endTag(null, "preferred-activities");
6090
6091 for (SharedUserSetting usr : mSharedUsers.values()) {
6092 serializer.startTag(null, "shared-user");
6093 serializer.attribute(null, "name", usr.name);
6094 serializer.attribute(null, "userId",
6095 Integer.toString(usr.userId));
6096 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6097 serializer.startTag(null, "perms");
6098 for (String name : usr.grantedPermissions) {
6099 serializer.startTag(null, "item");
6100 serializer.attribute(null, "name", name);
6101 serializer.endTag(null, "item");
6102 }
6103 serializer.endTag(null, "perms");
6104 serializer.endTag(null, "shared-user");
6105 }
6106
6107 serializer.endTag(null, "packages");
6108
6109 serializer.endDocument();
6110
6111 str.flush();
6112 str.close();
6113
6114 // New settings successfully written, old ones are no longer
6115 // needed.
6116 mBackupSettingsFilename.delete();
6117 FileUtils.setPermissions(mSettingsFilename.toString(),
6118 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6119 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6120 |FileUtils.S_IROTH,
6121 -1, -1);
6122
6123 } catch(XmlPullParserException e) {
6124 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
6125
6126 } catch(java.io.IOException e) {
6127 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
6128
6129 }
6130
6131 //Debug.stopMethodTracing();
6132 }
6133
6134 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
6135 throws java.io.IOException {
6136 serializer.startTag(null, "updated-package");
6137 serializer.attribute(null, "name", pkg.name);
6138 serializer.attribute(null, "codePath", pkg.codePathString);
6139 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006140 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6142 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6143 }
6144 if (pkg.sharedUser == null) {
6145 serializer.attribute(null, "userId",
6146 Integer.toString(pkg.userId));
6147 } else {
6148 serializer.attribute(null, "sharedUserId",
6149 Integer.toString(pkg.userId));
6150 }
6151 serializer.startTag(null, "perms");
6152 if (pkg.sharedUser == null) {
6153 // If this is a shared user, the permissions will
6154 // be written there. We still need to write an
6155 // empty permissions list so permissionsFixed will
6156 // be set.
6157 for (final String name : pkg.grantedPermissions) {
6158 BasePermission bp = mPermissions.get(name);
6159 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6160 // We only need to write signature or system permissions but this wont
6161 // match the semantics of grantedPermissions. So write all permissions.
6162 serializer.startTag(null, "item");
6163 serializer.attribute(null, "name", name);
6164 serializer.endTag(null, "item");
6165 }
6166 }
6167 }
6168 serializer.endTag(null, "perms");
6169 serializer.endTag(null, "updated-package");
6170 }
6171
6172 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
6173 throws java.io.IOException {
6174 serializer.startTag(null, "package");
6175 serializer.attribute(null, "name", pkg.name);
6176 serializer.attribute(null, "codePath", pkg.codePathString);
6177 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6178 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6179 }
6180 serializer.attribute(null, "system",
6181 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6182 ? "true" : "false");
6183 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006184 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 if (pkg.sharedUser == null) {
6186 serializer.attribute(null, "userId",
6187 Integer.toString(pkg.userId));
6188 } else {
6189 serializer.attribute(null, "sharedUserId",
6190 Integer.toString(pkg.userId));
6191 }
6192 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6193 serializer.attribute(null, "enabled",
6194 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6195 ? "true" : "false");
6196 }
6197 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6198 serializer.attribute(null, "installStatus", "false");
6199 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02006200 if (pkg.installerPackageName != null) {
6201 serializer.attribute(null, "installer", pkg.installerPackageName);
6202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6204 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6205 serializer.startTag(null, "perms");
6206 if (pkg.sharedUser == null) {
6207 // If this is a shared user, the permissions will
6208 // be written there. We still need to write an
6209 // empty permissions list so permissionsFixed will
6210 // be set.
6211 for (final String name : pkg.grantedPermissions) {
6212 serializer.startTag(null, "item");
6213 serializer.attribute(null, "name", name);
6214 serializer.endTag(null, "item");
6215 }
6216 }
6217 serializer.endTag(null, "perms");
6218 }
6219 if (pkg.disabledComponents.size() > 0) {
6220 serializer.startTag(null, "disabled-components");
6221 for (final String name : pkg.disabledComponents) {
6222 serializer.startTag(null, "item");
6223 serializer.attribute(null, "name", name);
6224 serializer.endTag(null, "item");
6225 }
6226 serializer.endTag(null, "disabled-components");
6227 }
6228 if (pkg.enabledComponents.size() > 0) {
6229 serializer.startTag(null, "enabled-components");
6230 for (final String name : pkg.enabledComponents) {
6231 serializer.startTag(null, "item");
6232 serializer.attribute(null, "name", name);
6233 serializer.endTag(null, "item");
6234 }
6235 serializer.endTag(null, "enabled-components");
6236 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02006237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 serializer.endTag(null, "package");
6239 }
6240
6241 void writePermission(XmlSerializer serializer, BasePermission bp)
6242 throws XmlPullParserException, java.io.IOException {
6243 if (bp.type != BasePermission.TYPE_BUILTIN
6244 && bp.sourcePackage != null) {
6245 serializer.startTag(null, "item");
6246 serializer.attribute(null, "name", bp.name);
6247 serializer.attribute(null, "package", bp.sourcePackage);
6248 if (DEBUG_SETTINGS) Log.v(TAG,
6249 "Writing perm: name=" + bp.name + " type=" + bp.type);
6250 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6251 PermissionInfo pi = bp.perm != null ? bp.perm.info
6252 : bp.pendingInfo;
6253 if (pi != null) {
6254 serializer.attribute(null, "type", "dynamic");
6255 if (pi.icon != 0) {
6256 serializer.attribute(null, "icon",
6257 Integer.toString(pi.icon));
6258 }
6259 if (pi.nonLocalizedLabel != null) {
6260 serializer.attribute(null, "label",
6261 pi.nonLocalizedLabel.toString());
6262 }
6263 if (pi.protectionLevel !=
6264 PermissionInfo.PROTECTION_NORMAL) {
6265 serializer.attribute(null, "protection",
6266 Integer.toString(pi.protectionLevel));
6267 }
6268 }
6269 }
6270 serializer.endTag(null, "item");
6271 }
6272 }
6273
6274 String getReadMessagesLP() {
6275 return mReadMessages.toString();
6276 }
6277
6278 ArrayList<String> getListOfIncompleteInstallPackages() {
6279 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6280 Iterator<String> its = kList.iterator();
6281 ArrayList<String> ret = new ArrayList<String>();
6282 while(its.hasNext()) {
6283 String key = its.next();
6284 PackageSetting ps = mPackages.get(key);
6285 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
6286 ret.add(key);
6287 }
6288 }
6289 return ret;
6290 }
6291
6292 boolean readLP() {
6293 FileInputStream str = null;
6294 if (mBackupSettingsFilename.exists()) {
6295 try {
6296 str = new FileInputStream(mBackupSettingsFilename);
6297 mReadMessages.append("Reading from backup settings file\n");
6298 Log.i(TAG, "Reading from backup settings file!");
6299 } catch (java.io.IOException e) {
6300 // We'll try for the normal settings file.
6301 }
6302 }
6303
6304 mPastSignatures.clear();
6305
6306 try {
6307 if (str == null) {
6308 if (!mSettingsFilename.exists()) {
6309 mReadMessages.append("No settings file found\n");
6310 Log.i(TAG, "No current settings file!");
6311 return false;
6312 }
6313 str = new FileInputStream(mSettingsFilename);
6314 }
6315 XmlPullParser parser = Xml.newPullParser();
6316 parser.setInput(str, null);
6317
6318 int type;
6319 while ((type=parser.next()) != XmlPullParser.START_TAG
6320 && type != XmlPullParser.END_DOCUMENT) {
6321 ;
6322 }
6323
6324 if (type != XmlPullParser.START_TAG) {
6325 mReadMessages.append("No start tag found in settings file\n");
6326 Log.e(TAG, "No start tag found in package manager settings");
6327 return false;
6328 }
6329
6330 int outerDepth = parser.getDepth();
6331 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6332 && (type != XmlPullParser.END_TAG
6333 || parser.getDepth() > outerDepth)) {
6334 if (type == XmlPullParser.END_TAG
6335 || type == XmlPullParser.TEXT) {
6336 continue;
6337 }
6338
6339 String tagName = parser.getName();
6340 if (tagName.equals("package")) {
6341 readPackageLP(parser);
6342 } else if (tagName.equals("permissions")) {
6343 readPermissionsLP(mPermissions, parser);
6344 } else if (tagName.equals("permission-trees")) {
6345 readPermissionsLP(mPermissionTrees, parser);
6346 } else if (tagName.equals("shared-user")) {
6347 readSharedUserLP(parser);
6348 } else if (tagName.equals("preferred-packages")) {
6349 readPreferredPackagesLP(parser);
6350 } else if (tagName.equals("preferred-activities")) {
6351 readPreferredActivitiesLP(parser);
6352 } else if(tagName.equals("updated-package")) {
6353 readDisabledSysPackageLP(parser);
6354 } else {
6355 Log.w(TAG, "Unknown element under <packages>: "
6356 + parser.getName());
6357 XmlUtils.skipCurrentTag(parser);
6358 }
6359 }
6360
6361 str.close();
6362
6363 } catch(XmlPullParserException e) {
6364 mReadMessages.append("Error reading: " + e.toString());
6365 Log.e(TAG, "Error reading package manager settings", e);
6366
6367 } catch(java.io.IOException e) {
6368 mReadMessages.append("Error reading: " + e.toString());
6369 Log.e(TAG, "Error reading package manager settings", e);
6370
6371 }
6372
6373 int N = mPendingPackages.size();
6374 for (int i=0; i<N; i++) {
6375 final PendingPackage pp = mPendingPackages.get(i);
6376 Object idObj = getUserIdLP(pp.sharedId);
6377 if (idObj != null && idObj instanceof SharedUserSetting) {
6378 PackageSetting p = getPackageLP(pp.name,
6379 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006380 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 if (p == null) {
6382 Log.w(TAG, "Unable to create application package for "
6383 + pp.name);
6384 continue;
6385 }
6386 p.copyFrom(pp);
6387 } else if (idObj != null) {
6388 String msg = "Bad package setting: package " + pp.name
6389 + " has shared uid " + pp.sharedId
6390 + " that is not a shared uid\n";
6391 mReadMessages.append(msg);
6392 Log.e(TAG, msg);
6393 } else {
6394 String msg = "Bad package setting: package " + pp.name
6395 + " has shared uid " + pp.sharedId
6396 + " that is not defined\n";
6397 mReadMessages.append(msg);
6398 Log.e(TAG, msg);
6399 }
6400 }
6401 mPendingPackages.clear();
6402
6403 N = mPendingPreferredPackages.size();
6404 mPreferredPackages.clear();
6405 for (int i=0; i<N; i++) {
6406 final String name = mPendingPreferredPackages.get(i);
6407 final PackageSetting p = mPackages.get(name);
6408 if (p != null) {
6409 mPreferredPackages.add(p);
6410 } else {
6411 Log.w(TAG, "Unknown preferred package: " + name);
6412 }
6413 }
6414 mPendingPreferredPackages.clear();
6415
6416 mReadMessages.append("Read completed successfully: "
6417 + mPackages.size() + " packages, "
6418 + mSharedUsers.size() + " shared uids\n");
6419
6420 return true;
6421 }
6422
6423 private int readInt(XmlPullParser parser, String ns, String name,
6424 int defValue) {
6425 String v = parser.getAttributeValue(ns, name);
6426 try {
6427 if (v == null) {
6428 return defValue;
6429 }
6430 return Integer.parseInt(v);
6431 } catch (NumberFormatException e) {
6432 reportSettingsProblem(Log.WARN,
6433 "Error in package manager settings: attribute " +
6434 name + " has bad integer value " + v + " at "
6435 + parser.getPositionDescription());
6436 }
6437 return defValue;
6438 }
6439
6440 private void readPermissionsLP(HashMap<String, BasePermission> out,
6441 XmlPullParser parser)
6442 throws IOException, XmlPullParserException {
6443 int outerDepth = parser.getDepth();
6444 int type;
6445 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6446 && (type != XmlPullParser.END_TAG
6447 || parser.getDepth() > outerDepth)) {
6448 if (type == XmlPullParser.END_TAG
6449 || type == XmlPullParser.TEXT) {
6450 continue;
6451 }
6452
6453 String tagName = parser.getName();
6454 if (tagName.equals("item")) {
6455 String name = parser.getAttributeValue(null, "name");
6456 String sourcePackage = parser.getAttributeValue(null, "package");
6457 String ptype = parser.getAttributeValue(null, "type");
6458 if (name != null && sourcePackage != null) {
6459 boolean dynamic = "dynamic".equals(ptype);
6460 BasePermission bp = new BasePermission(name, sourcePackage,
6461 dynamic
6462 ? BasePermission.TYPE_DYNAMIC
6463 : BasePermission.TYPE_NORMAL);
6464 if (dynamic) {
6465 PermissionInfo pi = new PermissionInfo();
6466 pi.packageName = sourcePackage.intern();
6467 pi.name = name.intern();
6468 pi.icon = readInt(parser, null, "icon", 0);
6469 pi.nonLocalizedLabel = parser.getAttributeValue(
6470 null, "label");
6471 pi.protectionLevel = readInt(parser, null, "protection",
6472 PermissionInfo.PROTECTION_NORMAL);
6473 bp.pendingInfo = pi;
6474 }
6475 out.put(bp.name, bp);
6476 } else {
6477 reportSettingsProblem(Log.WARN,
6478 "Error in package manager settings: permissions has"
6479 + " no name at " + parser.getPositionDescription());
6480 }
6481 } else {
6482 reportSettingsProblem(Log.WARN,
6483 "Unknown element reading permissions: "
6484 + parser.getName() + " at "
6485 + parser.getPositionDescription());
6486 }
6487 XmlUtils.skipCurrentTag(parser);
6488 }
6489 }
6490
6491 private void readDisabledSysPackageLP(XmlPullParser parser)
6492 throws XmlPullParserException, IOException {
6493 String name = parser.getAttributeValue(null, "name");
6494 String codePathStr = parser.getAttributeValue(null, "codePath");
6495 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6496 if(resourcePathStr == null) {
6497 resourcePathStr = codePathStr;
6498 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006499 String version = parser.getAttributeValue(null, "version");
6500 int versionCode = 0;
6501 if (version != null) {
6502 try {
6503 versionCode = Integer.parseInt(version);
6504 } catch (NumberFormatException e) {
6505 }
6506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507
6508 int pkgFlags = 0;
6509 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6510 PackageSetting ps = new PackageSetting(name,
6511 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006512 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 String timeStampStr = parser.getAttributeValue(null, "ts");
6514 if (timeStampStr != null) {
6515 try {
6516 long timeStamp = Long.parseLong(timeStampStr);
6517 ps.setTimeStamp(timeStamp, timeStampStr);
6518 } catch (NumberFormatException e) {
6519 }
6520 }
6521 String idStr = parser.getAttributeValue(null, "userId");
6522 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
6523 if(ps.userId <= 0) {
6524 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6525 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
6526 }
6527 int outerDepth = parser.getDepth();
6528 int type;
6529 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6530 && (type != XmlPullParser.END_TAG
6531 || parser.getDepth() > outerDepth)) {
6532 if (type == XmlPullParser.END_TAG
6533 || type == XmlPullParser.TEXT) {
6534 continue;
6535 }
6536
6537 String tagName = parser.getName();
6538 if (tagName.equals("perms")) {
6539 readGrantedPermissionsLP(parser,
6540 ps.grantedPermissions);
6541 } else {
6542 reportSettingsProblem(Log.WARN,
6543 "Unknown element under <updated-package>: "
6544 + parser.getName());
6545 XmlUtils.skipCurrentTag(parser);
6546 }
6547 }
6548 mDisabledSysPackages.put(name, ps);
6549 }
6550
6551 private void readPackageLP(XmlPullParser parser)
6552 throws XmlPullParserException, IOException {
6553 String name = null;
6554 String idStr = null;
6555 String sharedIdStr = null;
6556 String codePathStr = null;
6557 String resourcePathStr = null;
6558 String systemStr = null;
Jacek Surazskic64322c2009-04-28 15:26:38 +02006559 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 int pkgFlags = 0;
6561 String timeStampStr;
6562 long timeStamp = 0;
6563 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006564 String version = null;
6565 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 try {
6567 name = parser.getAttributeValue(null, "name");
6568 idStr = parser.getAttributeValue(null, "userId");
6569 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6570 codePathStr = parser.getAttributeValue(null, "codePath");
6571 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006572 version = parser.getAttributeValue(null, "version");
6573 if (version != null) {
6574 try {
6575 versionCode = Integer.parseInt(version);
6576 } catch (NumberFormatException e) {
6577 }
6578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazskic64322c2009-04-28 15:26:38 +02006580 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 if (systemStr != null) {
6582 if ("true".equals(systemStr)) {
6583 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6584 }
6585 } else {
6586 // Old settings that don't specify system... just treat
6587 // them as system, good enough.
6588 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6589 }
6590 timeStampStr = parser.getAttributeValue(null, "ts");
6591 if (timeStampStr != null) {
6592 try {
6593 timeStamp = Long.parseLong(timeStampStr);
6594 } catch (NumberFormatException e) {
6595 }
6596 }
6597 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
6598 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
6599 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
6600 if (resourcePathStr == null) {
6601 resourcePathStr = codePathStr;
6602 }
6603 if (name == null) {
6604 reportSettingsProblem(Log.WARN,
6605 "Error in package manager settings: <package> has no name at "
6606 + parser.getPositionDescription());
6607 } else if (codePathStr == null) {
6608 reportSettingsProblem(Log.WARN,
6609 "Error in package manager settings: <package> has no codePath at "
6610 + parser.getPositionDescription());
6611 } else if (userId > 0) {
6612 packageSetting = addPackageLP(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 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
6615 + ": userId=" + userId + " pkg=" + packageSetting);
6616 if (packageSetting == null) {
6617 reportSettingsProblem(Log.ERROR,
6618 "Failure adding uid " + userId
6619 + " while parsing settings at "
6620 + parser.getPositionDescription());
6621 } else {
6622 packageSetting.setTimeStamp(timeStamp, timeStampStr);
6623 }
6624 } else if (sharedIdStr != null) {
6625 userId = sharedIdStr != null
6626 ? Integer.parseInt(sharedIdStr) : 0;
6627 if (userId > 0) {
6628 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006629 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 packageSetting.setTimeStamp(timeStamp, timeStampStr);
6631 mPendingPackages.add((PendingPackage) packageSetting);
6632 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
6633 + ": sharedUserId=" + userId + " pkg="
6634 + packageSetting);
6635 } else {
6636 reportSettingsProblem(Log.WARN,
6637 "Error in package manager settings: package "
6638 + name + " has bad sharedId " + sharedIdStr
6639 + " at " + parser.getPositionDescription());
6640 }
6641 } else {
6642 reportSettingsProblem(Log.WARN,
6643 "Error in package manager settings: package "
6644 + name + " has bad userId " + idStr + " at "
6645 + parser.getPositionDescription());
6646 }
6647 } catch (NumberFormatException e) {
6648 reportSettingsProblem(Log.WARN,
6649 "Error in package manager settings: package "
6650 + name + " has bad userId " + idStr + " at "
6651 + parser.getPositionDescription());
6652 }
6653 if (packageSetting != null) {
Jacek Surazskic64322c2009-04-28 15:26:38 +02006654 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 final String enabledStr = parser.getAttributeValue(null, "enabled");
6656 if (enabledStr != null) {
6657 if (enabledStr.equalsIgnoreCase("true")) {
6658 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
6659 } else if (enabledStr.equalsIgnoreCase("false")) {
6660 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
6661 } else if (enabledStr.equalsIgnoreCase("default")) {
6662 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6663 } else {
6664 reportSettingsProblem(Log.WARN,
6665 "Error in package manager settings: package "
6666 + name + " has bad enabled value: " + idStr
6667 + " at " + parser.getPositionDescription());
6668 }
6669 } else {
6670 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6671 }
6672 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
6673 if (installStatusStr != null) {
6674 if (installStatusStr.equalsIgnoreCase("false")) {
6675 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
6676 } else {
6677 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
6678 }
6679 }
6680
6681 int outerDepth = parser.getDepth();
6682 int type;
6683 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6684 && (type != XmlPullParser.END_TAG
6685 || parser.getDepth() > outerDepth)) {
6686 if (type == XmlPullParser.END_TAG
6687 || type == XmlPullParser.TEXT) {
6688 continue;
6689 }
6690
6691 String tagName = parser.getName();
6692 if (tagName.equals("disabled-components")) {
6693 readDisabledComponentsLP(packageSetting, parser);
6694 } else if (tagName.equals("enabled-components")) {
6695 readEnabledComponentsLP(packageSetting, parser);
6696 } else if (tagName.equals("sigs")) {
6697 packageSetting.signatures.readXml(parser, mPastSignatures);
6698 } else if (tagName.equals("perms")) {
6699 readGrantedPermissionsLP(parser,
6700 packageSetting.loadedPermissions);
6701 packageSetting.permissionsFixed = true;
6702 } else {
6703 reportSettingsProblem(Log.WARN,
6704 "Unknown element under <package>: "
6705 + parser.getName());
6706 XmlUtils.skipCurrentTag(parser);
6707 }
6708 }
6709 } else {
6710 XmlUtils.skipCurrentTag(parser);
6711 }
6712 }
6713
6714 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
6715 XmlPullParser parser)
6716 throws IOException, XmlPullParserException {
6717 int outerDepth = parser.getDepth();
6718 int type;
6719 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6720 && (type != XmlPullParser.END_TAG
6721 || parser.getDepth() > outerDepth)) {
6722 if (type == XmlPullParser.END_TAG
6723 || type == XmlPullParser.TEXT) {
6724 continue;
6725 }
6726
6727 String tagName = parser.getName();
6728 if (tagName.equals("item")) {
6729 String name = parser.getAttributeValue(null, "name");
6730 if (name != null) {
6731 packageSetting.disabledComponents.add(name.intern());
6732 } else {
6733 reportSettingsProblem(Log.WARN,
6734 "Error in package manager settings: <disabled-components> has"
6735 + " no name at " + parser.getPositionDescription());
6736 }
6737 } else {
6738 reportSettingsProblem(Log.WARN,
6739 "Unknown element under <disabled-components>: "
6740 + parser.getName());
6741 }
6742 XmlUtils.skipCurrentTag(parser);
6743 }
6744 }
6745
6746 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
6747 XmlPullParser parser)
6748 throws IOException, XmlPullParserException {
6749 int outerDepth = parser.getDepth();
6750 int type;
6751 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6752 && (type != XmlPullParser.END_TAG
6753 || parser.getDepth() > outerDepth)) {
6754 if (type == XmlPullParser.END_TAG
6755 || type == XmlPullParser.TEXT) {
6756 continue;
6757 }
6758
6759 String tagName = parser.getName();
6760 if (tagName.equals("item")) {
6761 String name = parser.getAttributeValue(null, "name");
6762 if (name != null) {
6763 packageSetting.enabledComponents.add(name.intern());
6764 } else {
6765 reportSettingsProblem(Log.WARN,
6766 "Error in package manager settings: <enabled-components> has"
6767 + " no name at " + parser.getPositionDescription());
6768 }
6769 } else {
6770 reportSettingsProblem(Log.WARN,
6771 "Unknown element under <enabled-components>: "
6772 + parser.getName());
6773 }
6774 XmlUtils.skipCurrentTag(parser);
6775 }
6776 }
6777
6778 private void readSharedUserLP(XmlPullParser parser)
6779 throws XmlPullParserException, IOException {
6780 String name = null;
6781 String idStr = null;
6782 int pkgFlags = 0;
6783 SharedUserSetting su = null;
6784 try {
6785 name = parser.getAttributeValue(null, "name");
6786 idStr = parser.getAttributeValue(null, "userId");
6787 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
6788 if ("true".equals(parser.getAttributeValue(null, "system"))) {
6789 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6790 }
6791 if (name == null) {
6792 reportSettingsProblem(Log.WARN,
6793 "Error in package manager settings: <shared-user> has no name at "
6794 + parser.getPositionDescription());
6795 } else if (userId == 0) {
6796 reportSettingsProblem(Log.WARN,
6797 "Error in package manager settings: shared-user "
6798 + name + " has bad userId " + idStr + " at "
6799 + parser.getPositionDescription());
6800 } else {
6801 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
6802 reportSettingsProblem(Log.ERROR,
6803 "Occurred while parsing settings at "
6804 + parser.getPositionDescription());
6805 }
6806 }
6807 } catch (NumberFormatException e) {
6808 reportSettingsProblem(Log.WARN,
6809 "Error in package manager settings: package "
6810 + name + " has bad userId " + idStr + " at "
6811 + parser.getPositionDescription());
6812 };
6813
6814 if (su != null) {
6815 int outerDepth = parser.getDepth();
6816 int type;
6817 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6818 && (type != XmlPullParser.END_TAG
6819 || parser.getDepth() > outerDepth)) {
6820 if (type == XmlPullParser.END_TAG
6821 || type == XmlPullParser.TEXT) {
6822 continue;
6823 }
6824
6825 String tagName = parser.getName();
6826 if (tagName.equals("sigs")) {
6827 su.signatures.readXml(parser, mPastSignatures);
6828 } else if (tagName.equals("perms")) {
6829 readGrantedPermissionsLP(parser, su.loadedPermissions);
6830 } else {
6831 reportSettingsProblem(Log.WARN,
6832 "Unknown element under <shared-user>: "
6833 + parser.getName());
6834 XmlUtils.skipCurrentTag(parser);
6835 }
6836 }
6837
6838 } else {
6839 XmlUtils.skipCurrentTag(parser);
6840 }
6841 }
6842
6843 private void readGrantedPermissionsLP(XmlPullParser parser,
6844 HashSet<String> outPerms) throws IOException, XmlPullParserException {
6845 int outerDepth = parser.getDepth();
6846 int type;
6847 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6848 && (type != XmlPullParser.END_TAG
6849 || parser.getDepth() > outerDepth)) {
6850 if (type == XmlPullParser.END_TAG
6851 || type == XmlPullParser.TEXT) {
6852 continue;
6853 }
6854
6855 String tagName = parser.getName();
6856 if (tagName.equals("item")) {
6857 String name = parser.getAttributeValue(null, "name");
6858 if (name != null) {
6859 outPerms.add(name.intern());
6860 } else {
6861 reportSettingsProblem(Log.WARN,
6862 "Error in package manager settings: <perms> has"
6863 + " no name at " + parser.getPositionDescription());
6864 }
6865 } else {
6866 reportSettingsProblem(Log.WARN,
6867 "Unknown element under <perms>: "
6868 + parser.getName());
6869 }
6870 XmlUtils.skipCurrentTag(parser);
6871 }
6872 }
6873
6874 private void readPreferredPackagesLP(XmlPullParser parser)
6875 throws XmlPullParserException, IOException {
6876 int outerDepth = parser.getDepth();
6877 int type;
6878 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6879 && (type != XmlPullParser.END_TAG
6880 || parser.getDepth() > outerDepth)) {
6881 if (type == XmlPullParser.END_TAG
6882 || type == XmlPullParser.TEXT) {
6883 continue;
6884 }
6885
6886 String tagName = parser.getName();
6887 if (tagName.equals("item")) {
6888 String name = parser.getAttributeValue(null, "name");
6889 if (name != null) {
6890 mPendingPreferredPackages.add(name);
6891 } else {
6892 reportSettingsProblem(Log.WARN,
6893 "Error in package manager settings: <preferred-package> has no name at "
6894 + parser.getPositionDescription());
6895 }
6896 } else {
6897 reportSettingsProblem(Log.WARN,
6898 "Unknown element under <preferred-packages>: "
6899 + parser.getName());
6900 }
6901 XmlUtils.skipCurrentTag(parser);
6902 }
6903 }
6904
6905 private void readPreferredActivitiesLP(XmlPullParser parser)
6906 throws XmlPullParserException, IOException {
6907 int outerDepth = parser.getDepth();
6908 int type;
6909 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6910 && (type != XmlPullParser.END_TAG
6911 || parser.getDepth() > outerDepth)) {
6912 if (type == XmlPullParser.END_TAG
6913 || type == XmlPullParser.TEXT) {
6914 continue;
6915 }
6916
6917 String tagName = parser.getName();
6918 if (tagName.equals("item")) {
6919 PreferredActivity pa = new PreferredActivity(parser);
6920 if (pa.mParseError == null) {
6921 mPreferredActivities.addFilter(pa);
6922 } else {
6923 reportSettingsProblem(Log.WARN,
6924 "Error in package manager settings: <preferred-activity> "
6925 + pa.mParseError + " at "
6926 + parser.getPositionDescription());
6927 }
6928 } else {
6929 reportSettingsProblem(Log.WARN,
6930 "Unknown element under <preferred-activities>: "
6931 + parser.getName());
6932 XmlUtils.skipCurrentTag(parser);
6933 }
6934 }
6935 }
6936
6937 // Returns -1 if we could not find an available UserId to assign
6938 private int newUserIdLP(Object obj) {
6939 // Let's be stupidly inefficient for now...
6940 final int N = mUserIds.size();
6941 for (int i=0; i<N; i++) {
6942 if (mUserIds.get(i) == null) {
6943 mUserIds.set(i, obj);
6944 return FIRST_APPLICATION_UID + i;
6945 }
6946 }
6947
6948 // None left?
6949 if (N >= MAX_APPLICATION_UIDS) {
6950 return -1;
6951 }
6952
6953 mUserIds.add(obj);
6954 return FIRST_APPLICATION_UID + N;
6955 }
6956
6957 public PackageSetting getDisabledSystemPkg(String name) {
6958 synchronized(mPackages) {
6959 PackageSetting ps = mDisabledSysPackages.get(name);
6960 return ps;
6961 }
6962 }
6963
6964 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
6965 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
6966 if (Config.LOGV) {
6967 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
6968 + " componentName = " + componentInfo.name);
6969 Log.v(TAG, "enabledComponents: "
6970 + Arrays.toString(packageSettings.enabledComponents.toArray()));
6971 Log.v(TAG, "disabledComponents: "
6972 + Arrays.toString(packageSettings.disabledComponents.toArray()));
6973 }
6974 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
6975 || ((componentInfo.enabled
6976 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
6977 || (componentInfo.applicationInfo.enabled
6978 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
6979 && !packageSettings.disabledComponents.contains(componentInfo.name))
6980 || packageSettings.enabledComponents.contains(componentInfo.name));
6981 }
6982 }
6983}