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