blob: 86504a095daf999724611f77ec6ba924dc744d7a [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;
Dianne Hackborn49237342009-08-27 20:08:01 -070038import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.pm.IPackageDataObserver;
40import android.content.pm.IPackageDeleteObserver;
41import android.content.pm.IPackageInstallObserver;
42import android.content.pm.IPackageManager;
43import android.content.pm.IPackageStatsObserver;
44import android.content.pm.InstrumentationInfo;
45import android.content.pm.PackageInfo;
46import android.content.pm.PackageManager;
47import android.content.pm.PackageStats;
48import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
49import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
50import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
51import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
52import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
53import android.content.pm.PackageParser;
54import android.content.pm.PermissionInfo;
55import android.content.pm.PermissionGroupInfo;
56import android.content.pm.ProviderInfo;
57import android.content.pm.ResolveInfo;
58import android.content.pm.ServiceInfo;
59import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.Uri;
61import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070062import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.Bundle;
64import android.os.HandlerThread;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070065import android.os.Looper;
66import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.os.Parcel;
68import android.os.RemoteException;
69import android.os.Environment;
70import android.os.FileObserver;
71import android.os.FileUtils;
72import android.os.Handler;
73import android.os.ParcelFileDescriptor;
74import android.os.Process;
75import android.os.ServiceManager;
76import android.os.SystemClock;
77import android.os.SystemProperties;
78import android.util.*;
79import android.view.Display;
80import android.view.WindowManager;
81
82import java.io.File;
83import java.io.FileDescriptor;
84import java.io.FileInputStream;
85import java.io.FileNotFoundException;
86import java.io.FileOutputStream;
87import java.io.FileReader;
88import java.io.FilenameFilter;
89import java.io.IOException;
90import java.io.InputStream;
91import java.io.PrintWriter;
92import java.util.ArrayList;
93import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -070094import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.util.Collections;
96import java.util.Comparator;
97import java.util.Enumeration;
98import java.util.HashMap;
99import java.util.HashSet;
100import java.util.Iterator;
101import java.util.List;
102import java.util.Map;
103import java.util.Set;
104import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800105import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.zip.ZipFile;
107import java.util.zip.ZipOutputStream;
108
109class PackageManagerService extends IPackageManager.Stub {
110 private static final String TAG = "PackageManager";
111 private static final boolean DEBUG_SETTINGS = false;
112 private static final boolean DEBUG_PREFERRED = false;
113
114 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
115 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400116 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private static final int FIRST_APPLICATION_UID =
118 Process.FIRST_APPLICATION_UID;
119 private static final int MAX_APPLICATION_UIDS = 1000;
120
121 private static final boolean SHOW_INFO = false;
122
123 private static final boolean GET_CERTIFICATES = true;
124
125 private static final int REMOVE_EVENTS =
126 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
127 private static final int ADD_EVENTS =
128 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
129
130 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
131
132 static final int SCAN_MONITOR = 1<<0;
133 static final int SCAN_NO_DEX = 1<<1;
134 static final int SCAN_FORCE_DEX = 1<<2;
135 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
136 static final int SCAN_FORWARD_LOCKED = 1<<4;
The Android Open Source Project10592532009-03-18 17:39:46 -0700137 static final int SCAN_NEW_INSTALL = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
139 static final int LOG_BOOT_PROGRESS_PMS_START = 3060;
140 static final int LOG_BOOT_PROGRESS_PMS_SYSTEM_SCAN_START = 3070;
141 static final int LOG_BOOT_PROGRESS_PMS_DATA_SCAN_START = 3080;
142 static final int LOG_BOOT_PROGRESS_PMS_SCAN_END = 3090;
143 static final int LOG_BOOT_PROGRESS_PMS_READY = 3100;
144
145 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
146 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700147 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
Dianne Hackborn851a5412009-05-08 12:06:44 -0700149 final int mSdkVersion = Build.VERSION.SDK_INT;
150 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
151 ? null : Build.VERSION.CODENAME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
153 final Context mContext;
154 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700155 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 final DisplayMetrics mMetrics;
157 final int mDefParseFlags;
158 final String[] mSeparateProcesses;
159
160 // This is where all application persistent data goes.
161 final File mAppDataDir;
162
163 // This is the object monitoring the framework dir.
164 final FileObserver mFrameworkInstallObserver;
165
166 // This is the object monitoring the system app dir.
167 final FileObserver mSystemInstallObserver;
168
169 // This is the object monitoring mAppInstallDir.
170 final FileObserver mAppInstallObserver;
171
172 // This is the object monitoring mDrmAppPrivateInstallDir.
173 final FileObserver mDrmAppInstallObserver;
174
175 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
176 // LOCK HELD. Can be called with mInstallLock held.
177 final Installer mInstaller;
178
179 final File mFrameworkDir;
180 final File mSystemAppDir;
181 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700182 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
184 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
185 // apps.
186 final File mDrmAppPrivateInstallDir;
187
188 // ----------------------------------------------------------------
189
190 // Lock for state used when installing and doing other long running
191 // operations. Methods that must be called with this lock held have
192 // the prefix "LI".
193 final Object mInstallLock = new Object();
194
195 // These are the directories in the 3rd party applications installed dir
196 // that we have currently loaded packages from. Keys are the application's
197 // installed zip file (absolute codePath), and values are Package.
198 final HashMap<String, PackageParser.Package> mAppDirs =
199 new HashMap<String, PackageParser.Package>();
200
201 // Information for the parser to write more useful error messages.
202 File mScanningPath;
203 int mLastScanError;
204
205 final int[] mOutPermissions = new int[3];
206
207 // ----------------------------------------------------------------
208
209 // Keys are String (package name), values are Package. This also serves
210 // as the lock for the global state. Methods that must be called with
211 // this lock held have the prefix "LP".
212 final HashMap<String, PackageParser.Package> mPackages =
213 new HashMap<String, PackageParser.Package>();
214
215 final Settings mSettings;
216 boolean mRestoredSettings;
217 boolean mReportedUidError;
218
219 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
220 int[] mGlobalGids;
221
222 // These are the built-in uid -> permission mappings that were read from the
223 // etc/permissions.xml file.
224 final SparseArray<HashSet<String>> mSystemPermissions =
225 new SparseArray<HashSet<String>>();
226
227 // These are the built-in shared libraries that were read from the
228 // etc/permissions.xml file.
229 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
230
Dianne Hackborn49237342009-08-27 20:08:01 -0700231 // Temporary for building the final shared libraries for an .apk.
232 String[] mTmpSharedLibraries = null;
233
234 // These are the features this devices supports that were read from the
235 // etc/permissions.xml file.
236 final HashMap<String, FeatureInfo> mAvailableFeatures =
237 new HashMap<String, FeatureInfo>();
238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 // All available activities, for your resolving pleasure.
240 final ActivityIntentResolver mActivities =
241 new ActivityIntentResolver();
242
243 // All available receivers, for your resolving pleasure.
244 final ActivityIntentResolver mReceivers =
245 new ActivityIntentResolver();
246
247 // All available services, for your resolving pleasure.
248 final ServiceIntentResolver mServices = new ServiceIntentResolver();
249
250 // Keys are String (provider class name), values are Provider.
251 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
252 new HashMap<ComponentName, PackageParser.Provider>();
253
254 // Mapping from provider base names (first directory in content URI codePath)
255 // to the provider information.
256 final HashMap<String, PackageParser.Provider> mProviders =
257 new HashMap<String, PackageParser.Provider>();
258
259 // Mapping from instrumentation class names to info about them.
260 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
261 new HashMap<ComponentName, PackageParser.Instrumentation>();
262
263 // Mapping from permission names to info about them.
264 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
265 new HashMap<String, PackageParser.PermissionGroup>();
266
Dianne Hackborn854060af2009-07-09 18:14:31 -0700267 // Broadcast actions that are only available to the system.
268 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 boolean mSystemReady;
271 boolean mSafeMode;
272 boolean mHasSystemUidErrors;
273
274 ApplicationInfo mAndroidApplication;
275 final ActivityInfo mResolveActivity = new ActivityInfo();
276 final ResolveInfo mResolveInfo = new ResolveInfo();
277 ComponentName mResolveComponentName;
278 PackageParser.Package mPlatformPackage;
279
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700280 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800281 final HashMap<String, ArrayList<String>> mPendingBroadcasts
282 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700283 static final int SEND_PENDING_BROADCAST = 1;
284 // Delay time in millisecs
285 static final int BROADCAST_DELAY = 10 * 1000;
286
287 class PackageHandler extends Handler {
288 PackageHandler(Looper looper) {
289 super(looper);
290 }
291 public void handleMessage(Message msg) {
292 switch (msg.what) {
293 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800294 String packages[];
295 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700296 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700297 int uids[];
298 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800299 if (mPendingBroadcasts == null) {
300 return;
301 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700302 size = mPendingBroadcasts.size();
303 if (size <= 0) {
304 // Nothing to be done. Just return
305 return;
306 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800307 packages = new String[size];
308 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700309 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800310 Iterator<HashMap.Entry<String, ArrayList<String>>>
311 it = mPendingBroadcasts.entrySet().iterator();
312 int i = 0;
313 while (it.hasNext() && i < size) {
314 HashMap.Entry<String, ArrayList<String>> ent = it.next();
315 packages[i] = ent.getKey();
316 components[i] = ent.getValue();
317 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700318 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800319 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700320 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800321 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700322 mPendingBroadcasts.clear();
323 }
324 // Send broadcasts
325 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800326 sendPackageChangedBroadcast(packages[i], true,
327 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700328 }
329 break;
330 }
331 }
332 }
333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 public static final IPackageManager main(Context context, boolean factoryTest) {
335 PackageManagerService m = new PackageManagerService(context, factoryTest);
336 ServiceManager.addService("package", m);
337 return m;
338 }
339
340 static String[] splitString(String str, char sep) {
341 int count = 1;
342 int i = 0;
343 while ((i=str.indexOf(sep, i)) >= 0) {
344 count++;
345 i++;
346 }
347
348 String[] res = new String[count];
349 i=0;
350 count = 0;
351 int lastI=0;
352 while ((i=str.indexOf(sep, i)) >= 0) {
353 res[count] = str.substring(lastI, i);
354 count++;
355 i++;
356 lastI = i;
357 }
358 res[count] = str.substring(lastI, str.length());
359 return res;
360 }
361
362 public PackageManagerService(Context context, boolean factoryTest) {
363 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_START,
364 SystemClock.uptimeMillis());
365
366 if (mSdkVersion <= 0) {
367 Log.w(TAG, "**** ro.build.version.sdk not set!");
368 }
369
370 mContext = context;
371 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700372 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 mMetrics = new DisplayMetrics();
374 mSettings = new Settings();
375 mSettings.addSharedUserLP("android.uid.system",
376 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
377 mSettings.addSharedUserLP("android.uid.phone",
378 MULTIPLE_APPLICATION_UIDS
379 ? RADIO_UID : FIRST_APPLICATION_UID,
380 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400381 mSettings.addSharedUserLP("android.uid.log",
382 MULTIPLE_APPLICATION_UIDS
383 ? LOG_UID : FIRST_APPLICATION_UID,
384 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385
386 String separateProcesses = SystemProperties.get("debug.separate_processes");
387 if (separateProcesses != null && separateProcesses.length() > 0) {
388 if ("*".equals(separateProcesses)) {
389 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
390 mSeparateProcesses = null;
391 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
392 } else {
393 mDefParseFlags = 0;
394 mSeparateProcesses = separateProcesses.split(",");
395 Log.w(TAG, "Running with debug.separate_processes: "
396 + separateProcesses);
397 }
398 } else {
399 mDefParseFlags = 0;
400 mSeparateProcesses = null;
401 }
402
403 Installer installer = new Installer();
404 // Little hacky thing to check if installd is here, to determine
405 // whether we are running on the simulator and thus need to take
406 // care of building the /data file structure ourself.
407 // (apparently the sim now has a working installer)
408 if (installer.ping() && Process.supportsProcesses()) {
409 mInstaller = installer;
410 } else {
411 mInstaller = null;
412 }
413
414 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
415 Display d = wm.getDefaultDisplay();
416 d.getMetrics(mMetrics);
417
418 synchronized (mInstallLock) {
419 synchronized (mPackages) {
420 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 mHandler = new PackageHandler(mHandlerThread.getLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422
423 File dataDir = Environment.getDataDirectory();
424 mAppDataDir = new File(dataDir, "data");
425 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
426
427 if (mInstaller == null) {
428 // Make sure these dirs exist, when we are running in
429 // the simulator.
430 // Make a wide-open directory for random misc stuff.
431 File miscDir = new File(dataDir, "misc");
432 miscDir.mkdirs();
433 mAppDataDir.mkdirs();
434 mDrmAppPrivateInstallDir.mkdirs();
435 }
436
437 readPermissions();
438
439 mRestoredSettings = mSettings.readLP();
440 long startTime = SystemClock.uptimeMillis();
441
442 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
443 startTime);
444
445 int scanMode = SCAN_MONITOR;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700446 if (mNoDexOpt) {
447 Log.w(TAG, "Running ENG build: no pre-dexopt!");
448 scanMode |= SCAN_NO_DEX;
449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450
451 final HashSet<String> libFiles = new HashSet<String>();
452
453 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700454 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455
456 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700457 boolean didDexOpt = false;
458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 /**
460 * Out of paranoia, ensure that everything in the boot class
461 * path has been dexed.
462 */
463 String bootClassPath = System.getProperty("java.boot.class.path");
464 if (bootClassPath != null) {
465 String[] paths = splitString(bootClassPath, ':');
466 for (int i=0; i<paths.length; i++) {
467 try {
468 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
469 libFiles.add(paths[i]);
470 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700471 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 }
473 } catch (FileNotFoundException e) {
474 Log.w(TAG, "Boot class path not found: " + paths[i]);
475 } catch (IOException e) {
476 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
477 }
478 }
479 } else {
480 Log.w(TAG, "No BOOTCLASSPATH found!");
481 }
482
483 /**
484 * Also ensure all external libraries have had dexopt run on them.
485 */
486 if (mSharedLibraries.size() > 0) {
487 Iterator<String> libs = mSharedLibraries.values().iterator();
488 while (libs.hasNext()) {
489 String lib = libs.next();
490 try {
491 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
492 libFiles.add(lib);
493 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700494 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 }
496 } catch (FileNotFoundException e) {
497 Log.w(TAG, "Library not found: " + lib);
498 } catch (IOException e) {
499 Log.w(TAG, "Exception reading library: " + lib, e);
500 }
501 }
502 }
503
504 // Gross hack for now: we know this file doesn't contain any
505 // code, so don't dexopt it to avoid the resulting log spew.
506 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
507
508 /**
509 * And there are a number of commands implemented in Java, which
510 * we currently need to do the dexopt on so that they can be
511 * run from a non-root shell.
512 */
513 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700514 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 for (int i=0; i<frameworkFiles.length; i++) {
516 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
517 String path = libPath.getPath();
518 // Skip the file if we alrady did it.
519 if (libFiles.contains(path)) {
520 continue;
521 }
522 // Skip the file if it is not a type we want to dexopt.
523 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
524 continue;
525 }
526 try {
527 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
528 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700529 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 }
531 } catch (FileNotFoundException e) {
532 Log.w(TAG, "Jar not found: " + path);
533 } catch (IOException e) {
534 Log.w(TAG, "Exception reading jar: " + path, e);
535 }
536 }
537 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700538
539 if (didDexOpt) {
540 // If we had to do a dexopt of one of the previous
541 // things, then something on the system has changed.
542 // Consider this significant, and wipe away all other
543 // existing dexopt files to ensure we don't leave any
544 // dangling around.
545 String[] files = mDalvikCacheDir.list();
546 if (files != null) {
547 for (int i=0; i<files.length; i++) {
548 String fn = files[i];
549 if (fn.startsWith("data@app@")
550 || fn.startsWith("data@app-private@")) {
551 Log.i(TAG, "Pruning dalvik file: " + fn);
552 (new File(mDalvikCacheDir, fn)).delete();
553 }
554 }
555 }
556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 }
558
559 mFrameworkInstallObserver = new AppDirObserver(
560 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
561 mFrameworkInstallObserver.startWatching();
562 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
563 scanMode | SCAN_NO_DEX);
564 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
565 mSystemInstallObserver = new AppDirObserver(
566 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
567 mSystemInstallObserver.startWatching();
568 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
569 mAppInstallDir = new File(dataDir, "app");
570 if (mInstaller == null) {
571 // Make sure these dirs exist, when we are running in
572 // the simulator.
573 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
574 }
575 //look for any incomplete package installations
Dianne Hackborne6620b22010-01-22 14:46:21 -0800576 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 //clean up list
578 for(int i = 0; i < deletePkgsList.size(); i++) {
579 //clean up here
580 cleanupInstallFailedPackage(deletePkgsList.get(i));
581 }
582 //delete tmp files
583 deleteTempPackageFiles();
584
585 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_DATA_SCAN_START,
586 SystemClock.uptimeMillis());
587 mAppInstallObserver = new AppDirObserver(
588 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
589 mAppInstallObserver.startWatching();
590 scanDirLI(mAppInstallDir, 0, scanMode);
591
592 mDrmAppInstallObserver = new AppDirObserver(
593 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
594 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -0700595 scanDirLI(mDrmAppPrivateInstallDir, 0, scanMode | SCAN_FORWARD_LOCKED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596
597 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_SCAN_END,
598 SystemClock.uptimeMillis());
599 Log.i(TAG, "Time to scan packages: "
600 + ((SystemClock.uptimeMillis()-startTime)/1000f)
601 + " seconds");
602
603 updatePermissionsLP();
604
605 mSettings.writeLP();
606
607 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_READY,
608 SystemClock.uptimeMillis());
609
610 // Now after opening every single application zip, make sure they
611 // are all flushed. Not really needed, but keeps things nice and
612 // tidy.
613 Runtime.getRuntime().gc();
614 } // synchronized (mPackages)
615 } // synchronized (mInstallLock)
616 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 @Override
619 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
620 throws RemoteException {
621 try {
622 return super.onTransact(code, data, reply, flags);
623 } catch (RuntimeException e) {
624 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
625 Log.e(TAG, "Package Manager Crash", e);
626 }
627 throw e;
628 }
629 }
630
Dianne Hackborne6620b22010-01-22 14:46:21 -0800631 void cleanupInstallFailedPackage(PackageSetting ps) {
632 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 if (mInstaller != null) {
Dianne Hackborne6620b22010-01-22 14:46:21 -0800634 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 if (retCode < 0) {
636 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800637 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 }
639 } else {
640 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800641 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 File dataDir = new File(pkg.applicationInfo.dataDir);
643 dataDir.delete();
644 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800645 if (ps.codePath != null) {
646 if (!ps.codePath.delete()) {
647 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
648 }
649 }
650 if (ps.resourcePath != null) {
651 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
652 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
653 }
654 }
655 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 }
657
658 void readPermissions() {
659 // Read permissions from .../etc/permission directory.
660 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
661 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
662 Log.w(TAG, "No directory " + libraryDir + ", skipping");
663 return;
664 }
665 if (!libraryDir.canRead()) {
666 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
667 return;
668 }
669
670 // Iterate over the files in the directory and scan .xml files
671 for (File f : libraryDir.listFiles()) {
672 // We'll read platform.xml last
673 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
674 continue;
675 }
676
677 if (!f.getPath().endsWith(".xml")) {
678 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
679 continue;
680 }
681 if (!f.canRead()) {
682 Log.w(TAG, "Permissions library file " + f + " cannot be read");
683 continue;
684 }
685
686 readPermissionsFromXml(f);
687 }
688
689 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
690 final File permFile = new File(Environment.getRootDirectory(),
691 "etc/permissions/platform.xml");
692 readPermissionsFromXml(permFile);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700693
694 StringBuilder sb = new StringBuilder(128);
695 sb.append("Libs:");
696 Iterator<String> it = mSharedLibraries.keySet().iterator();
697 while (it.hasNext()) {
698 sb.append(' ');
699 String name = it.next();
700 sb.append(name);
701 sb.append(':');
702 sb.append(mSharedLibraries.get(name));
703 }
704 Log.i(TAG, sb.toString());
705
706 sb.setLength(0);
707 sb.append("Features:");
708 it = mAvailableFeatures.keySet().iterator();
709 while (it.hasNext()) {
710 sb.append(' ');
711 sb.append(it.next());
712 }
713 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 }
715
716 private void readPermissionsFromXml(File permFile) {
717 FileReader permReader = null;
718 try {
719 permReader = new FileReader(permFile);
720 } catch (FileNotFoundException e) {
721 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
722 return;
723 }
724
725 try {
726 XmlPullParser parser = Xml.newPullParser();
727 parser.setInput(permReader);
728
729 XmlUtils.beginDocument(parser, "permissions");
730
731 while (true) {
732 XmlUtils.nextElement(parser);
733 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
734 break;
735 }
736
737 String name = parser.getName();
738 if ("group".equals(name)) {
739 String gidStr = parser.getAttributeValue(null, "gid");
740 if (gidStr != null) {
741 int gid = Integer.parseInt(gidStr);
742 mGlobalGids = appendInt(mGlobalGids, gid);
743 } else {
744 Log.w(TAG, "<group> without gid at "
745 + parser.getPositionDescription());
746 }
747
748 XmlUtils.skipCurrentTag(parser);
749 continue;
750 } else if ("permission".equals(name)) {
751 String perm = parser.getAttributeValue(null, "name");
752 if (perm == null) {
753 Log.w(TAG, "<permission> without name at "
754 + parser.getPositionDescription());
755 XmlUtils.skipCurrentTag(parser);
756 continue;
757 }
758 perm = perm.intern();
759 readPermission(parser, perm);
760
761 } else if ("assign-permission".equals(name)) {
762 String perm = parser.getAttributeValue(null, "name");
763 if (perm == null) {
764 Log.w(TAG, "<assign-permission> without name at "
765 + parser.getPositionDescription());
766 XmlUtils.skipCurrentTag(parser);
767 continue;
768 }
769 String uidStr = parser.getAttributeValue(null, "uid");
770 if (uidStr == null) {
771 Log.w(TAG, "<assign-permission> without uid at "
772 + parser.getPositionDescription());
773 XmlUtils.skipCurrentTag(parser);
774 continue;
775 }
776 int uid = Process.getUidForName(uidStr);
777 if (uid < 0) {
778 Log.w(TAG, "<assign-permission> with unknown uid \""
779 + uidStr + "\" at "
780 + parser.getPositionDescription());
781 XmlUtils.skipCurrentTag(parser);
782 continue;
783 }
784 perm = perm.intern();
785 HashSet<String> perms = mSystemPermissions.get(uid);
786 if (perms == null) {
787 perms = new HashSet<String>();
788 mSystemPermissions.put(uid, perms);
789 }
790 perms.add(perm);
791 XmlUtils.skipCurrentTag(parser);
792
793 } else if ("library".equals(name)) {
794 String lname = parser.getAttributeValue(null, "name");
795 String lfile = parser.getAttributeValue(null, "file");
796 if (lname == null) {
797 Log.w(TAG, "<library> without name at "
798 + parser.getPositionDescription());
799 } else if (lfile == null) {
800 Log.w(TAG, "<library> without file at "
801 + parser.getPositionDescription());
802 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700803 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700804 mSharedLibraries.put(lname, lfile);
805 }
806 XmlUtils.skipCurrentTag(parser);
807 continue;
808
809 } else if ("feature".equals(name)) {
810 String fname = parser.getAttributeValue(null, "name");
811 if (fname == null) {
812 Log.w(TAG, "<feature> without name at "
813 + parser.getPositionDescription());
814 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700815 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700816 FeatureInfo fi = new FeatureInfo();
817 fi.name = fname;
818 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 }
820 XmlUtils.skipCurrentTag(parser);
821 continue;
822
823 } else {
824 XmlUtils.skipCurrentTag(parser);
825 continue;
826 }
827
828 }
829 } catch (XmlPullParserException e) {
830 Log.w(TAG, "Got execption parsing permissions.", e);
831 } catch (IOException e) {
832 Log.w(TAG, "Got execption parsing permissions.", e);
833 }
834 }
835
836 void readPermission(XmlPullParser parser, String name)
837 throws IOException, XmlPullParserException {
838
839 name = name.intern();
840
841 BasePermission bp = mSettings.mPermissions.get(name);
842 if (bp == null) {
843 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
844 mSettings.mPermissions.put(name, bp);
845 }
846 int outerDepth = parser.getDepth();
847 int type;
848 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
849 && (type != XmlPullParser.END_TAG
850 || parser.getDepth() > outerDepth)) {
851 if (type == XmlPullParser.END_TAG
852 || type == XmlPullParser.TEXT) {
853 continue;
854 }
855
856 String tagName = parser.getName();
857 if ("group".equals(tagName)) {
858 String gidStr = parser.getAttributeValue(null, "gid");
859 if (gidStr != null) {
860 int gid = Process.getGidForName(gidStr);
861 bp.gids = appendInt(bp.gids, gid);
862 } else {
863 Log.w(TAG, "<group> without gid at "
864 + parser.getPositionDescription());
865 }
866 }
867 XmlUtils.skipCurrentTag(parser);
868 }
869 }
870
871 static int[] appendInt(int[] cur, int val) {
872 if (cur == null) {
873 return new int[] { val };
874 }
875 final int N = cur.length;
876 for (int i=0; i<N; i++) {
877 if (cur[i] == val) {
878 return cur;
879 }
880 }
881 int[] ret = new int[N+1];
882 System.arraycopy(cur, 0, ret, 0, N);
883 ret[N] = val;
884 return ret;
885 }
886
887 static int[] appendInts(int[] cur, int[] add) {
888 if (add == null) return cur;
889 if (cur == null) return add;
890 final int N = add.length;
891 for (int i=0; i<N; i++) {
892 cur = appendInt(cur, add[i]);
893 }
894 return cur;
895 }
896
897 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -0700898 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
899 // The package has been uninstalled but has retained data and resources.
900 return PackageParser.generatePackageInfo(p, null, flags);
901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 final PackageSetting ps = (PackageSetting)p.mExtras;
903 if (ps == null) {
904 return null;
905 }
906 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
907 return PackageParser.generatePackageInfo(p, gp.gids, flags);
908 }
909
910 public PackageInfo getPackageInfo(String packageName, int flags) {
911 synchronized (mPackages) {
912 PackageParser.Package p = mPackages.get(packageName);
913 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700914 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 + ": " + p);
916 if (p != null) {
917 return generatePackageInfo(p, flags);
918 }
919 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
920 return generatePackageInfoFromSettingsLP(packageName, flags);
921 }
922 }
923 return null;
924 }
925
926 public int getPackageUid(String packageName) {
927 synchronized (mPackages) {
928 PackageParser.Package p = mPackages.get(packageName);
929 if(p != null) {
930 return p.applicationInfo.uid;
931 }
932 PackageSetting ps = mSettings.mPackages.get(packageName);
933 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
934 return -1;
935 }
936 p = ps.pkg;
937 return p != null ? p.applicationInfo.uid : -1;
938 }
939 }
940
941 public int[] getPackageGids(String packageName) {
942 synchronized (mPackages) {
943 PackageParser.Package p = mPackages.get(packageName);
944 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700945 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 + ": " + p);
947 if (p != null) {
948 final PackageSetting ps = (PackageSetting)p.mExtras;
949 final SharedUserSetting suid = ps.sharedUser;
950 return suid != null ? suid.gids : ps.gids;
951 }
952 }
953 // stupid thing to indicate an error.
954 return new int[0];
955 }
956
957 public PermissionInfo getPermissionInfo(String name, int flags) {
958 synchronized (mPackages) {
959 final BasePermission p = mSettings.mPermissions.get(name);
960 if (p != null && p.perm != null) {
961 return PackageParser.generatePermissionInfo(p.perm, flags);
962 }
963 return null;
964 }
965 }
966
967 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
968 synchronized (mPackages) {
969 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
970 for (BasePermission p : mSettings.mPermissions.values()) {
971 if (group == null) {
972 if (p.perm.info.group == null) {
973 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
974 }
975 } else {
976 if (group.equals(p.perm.info.group)) {
977 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
978 }
979 }
980 }
981
982 if (out.size() > 0) {
983 return out;
984 }
985 return mPermissionGroups.containsKey(group) ? out : null;
986 }
987 }
988
989 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
990 synchronized (mPackages) {
991 return PackageParser.generatePermissionGroupInfo(
992 mPermissionGroups.get(name), flags);
993 }
994 }
995
996 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
997 synchronized (mPackages) {
998 final int N = mPermissionGroups.size();
999 ArrayList<PermissionGroupInfo> out
1000 = new ArrayList<PermissionGroupInfo>(N);
1001 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1002 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1003 }
1004 return out;
1005 }
1006 }
1007
1008 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1009 PackageSetting ps = mSettings.mPackages.get(packageName);
1010 if(ps != null) {
1011 if(ps.pkg == null) {
1012 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1013 if(pInfo != null) {
1014 return pInfo.applicationInfo;
1015 }
1016 return null;
1017 }
1018 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1019 }
1020 return null;
1021 }
1022
1023 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1024 PackageSetting ps = mSettings.mPackages.get(packageName);
1025 if(ps != null) {
1026 if(ps.pkg == null) {
1027 ps.pkg = new PackageParser.Package(packageName);
1028 ps.pkg.applicationInfo.packageName = packageName;
1029 }
1030 return generatePackageInfo(ps.pkg, flags);
1031 }
1032 return null;
1033 }
1034
1035 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1036 synchronized (mPackages) {
1037 PackageParser.Package p = mPackages.get(packageName);
1038 if (Config.LOGV) Log.v(
1039 TAG, "getApplicationInfo " + packageName
1040 + ": " + p);
1041 if (p != null) {
1042 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001043 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
1045 if ("android".equals(packageName)||"system".equals(packageName)) {
1046 return mAndroidApplication;
1047 }
1048 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1049 return generateApplicationInfoFromSettingsLP(packageName, flags);
1050 }
1051 }
1052 return null;
1053 }
1054
1055
1056 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1057 mContext.enforceCallingOrSelfPermission(
1058 android.Manifest.permission.CLEAR_APP_CACHE, null);
1059 // Queue up an async operation since clearing cache may take a little while.
1060 mHandler.post(new Runnable() {
1061 public void run() {
1062 mHandler.removeCallbacks(this);
1063 int retCode = -1;
1064 if (mInstaller != null) {
1065 retCode = mInstaller.freeCache(freeStorageSize);
1066 if (retCode < 0) {
1067 Log.w(TAG, "Couldn't clear application caches");
1068 }
1069 } //end if mInstaller
1070 if (observer != null) {
1071 try {
1072 observer.onRemoveCompleted(null, (retCode >= 0));
1073 } catch (RemoteException e) {
1074 Log.w(TAG, "RemoveException when invoking call back");
1075 }
1076 }
1077 }
1078 });
1079 }
1080
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001081 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001082 mContext.enforceCallingOrSelfPermission(
1083 android.Manifest.permission.CLEAR_APP_CACHE, null);
1084 // Queue up an async operation since clearing cache may take a little while.
1085 mHandler.post(new Runnable() {
1086 public void run() {
1087 mHandler.removeCallbacks(this);
1088 int retCode = -1;
1089 if (mInstaller != null) {
1090 retCode = mInstaller.freeCache(freeStorageSize);
1091 if (retCode < 0) {
1092 Log.w(TAG, "Couldn't clear application caches");
1093 }
1094 }
1095 if(pi != null) {
1096 try {
1097 // Callback via pending intent
1098 int code = (retCode >= 0) ? 1 : 0;
1099 pi.sendIntent(null, code, null,
1100 null, null);
1101 } catch (SendIntentException e1) {
1102 Log.i(TAG, "Failed to send pending intent");
1103 }
1104 }
1105 }
1106 });
1107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108
1109 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1110 synchronized (mPackages) {
1111 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001112
1113 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001115 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
1117 if (mResolveComponentName.equals(component)) {
1118 return mResolveActivity;
1119 }
1120 }
1121 return null;
1122 }
1123
1124 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1125 synchronized (mPackages) {
1126 PackageParser.Activity a = mReceivers.mActivities.get(component);
1127 if (Config.LOGV) Log.v(
1128 TAG, "getReceiverInfo " + component + ": " + a);
1129 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1130 return PackageParser.generateActivityInfo(a, flags);
1131 }
1132 }
1133 return null;
1134 }
1135
1136 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1137 synchronized (mPackages) {
1138 PackageParser.Service s = mServices.mServices.get(component);
1139 if (Config.LOGV) Log.v(
1140 TAG, "getServiceInfo " + component + ": " + s);
1141 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1142 return PackageParser.generateServiceInfo(s, flags);
1143 }
1144 }
1145 return null;
1146 }
1147
1148 public String[] getSystemSharedLibraryNames() {
1149 Set<String> libSet;
1150 synchronized (mPackages) {
1151 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001152 int size = libSet.size();
1153 if (size > 0) {
1154 String[] libs = new String[size];
1155 libSet.toArray(libs);
1156 return libs;
1157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001159 return null;
1160 }
1161
1162 public FeatureInfo[] getSystemAvailableFeatures() {
1163 Collection<FeatureInfo> featSet;
1164 synchronized (mPackages) {
1165 featSet = mAvailableFeatures.values();
1166 int size = featSet.size();
1167 if (size > 0) {
1168 FeatureInfo[] features = new FeatureInfo[size+1];
1169 featSet.toArray(features);
1170 FeatureInfo fi = new FeatureInfo();
1171 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1172 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1173 features[size] = fi;
1174 return features;
1175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
1177 return null;
1178 }
1179
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001180 public boolean hasSystemFeature(String name) {
1181 synchronized (mPackages) {
1182 return mAvailableFeatures.containsKey(name);
1183 }
1184 }
1185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 public int checkPermission(String permName, String pkgName) {
1187 synchronized (mPackages) {
1188 PackageParser.Package p = mPackages.get(pkgName);
1189 if (p != null && p.mExtras != null) {
1190 PackageSetting ps = (PackageSetting)p.mExtras;
1191 if (ps.sharedUser != null) {
1192 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1193 return PackageManager.PERMISSION_GRANTED;
1194 }
1195 } else if (ps.grantedPermissions.contains(permName)) {
1196 return PackageManager.PERMISSION_GRANTED;
1197 }
1198 }
1199 }
1200 return PackageManager.PERMISSION_DENIED;
1201 }
1202
1203 public int checkUidPermission(String permName, int uid) {
1204 synchronized (mPackages) {
1205 Object obj = mSettings.getUserIdLP(uid);
1206 if (obj != null) {
1207 if (obj instanceof SharedUserSetting) {
1208 SharedUserSetting sus = (SharedUserSetting)obj;
1209 if (sus.grantedPermissions.contains(permName)) {
1210 return PackageManager.PERMISSION_GRANTED;
1211 }
1212 } else if (obj instanceof PackageSetting) {
1213 PackageSetting ps = (PackageSetting)obj;
1214 if (ps.grantedPermissions.contains(permName)) {
1215 return PackageManager.PERMISSION_GRANTED;
1216 }
1217 }
1218 } else {
1219 HashSet<String> perms = mSystemPermissions.get(uid);
1220 if (perms != null && perms.contains(permName)) {
1221 return PackageManager.PERMISSION_GRANTED;
1222 }
1223 }
1224 }
1225 return PackageManager.PERMISSION_DENIED;
1226 }
1227
1228 private BasePermission findPermissionTreeLP(String permName) {
1229 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1230 if (permName.startsWith(bp.name) &&
1231 permName.length() > bp.name.length() &&
1232 permName.charAt(bp.name.length()) == '.') {
1233 return bp;
1234 }
1235 }
1236 return null;
1237 }
1238
1239 private BasePermission checkPermissionTreeLP(String permName) {
1240 if (permName != null) {
1241 BasePermission bp = findPermissionTreeLP(permName);
1242 if (bp != null) {
1243 if (bp.uid == Binder.getCallingUid()) {
1244 return bp;
1245 }
1246 throw new SecurityException("Calling uid "
1247 + Binder.getCallingUid()
1248 + " is not allowed to add to permission tree "
1249 + bp.name + " owned by uid " + bp.uid);
1250 }
1251 }
1252 throw new SecurityException("No permission tree found for " + permName);
1253 }
1254
1255 public boolean addPermission(PermissionInfo info) {
1256 synchronized (mPackages) {
1257 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1258 throw new SecurityException("Label must be specified in permission");
1259 }
1260 BasePermission tree = checkPermissionTreeLP(info.name);
1261 BasePermission bp = mSettings.mPermissions.get(info.name);
1262 boolean added = bp == null;
1263 if (added) {
1264 bp = new BasePermission(info.name, tree.sourcePackage,
1265 BasePermission.TYPE_DYNAMIC);
1266 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1267 throw new SecurityException(
1268 "Not allowed to modify non-dynamic permission "
1269 + info.name);
1270 }
1271 bp.perm = new PackageParser.Permission(tree.perm.owner,
1272 new PermissionInfo(info));
1273 bp.perm.info.packageName = tree.perm.info.packageName;
1274 bp.uid = tree.uid;
1275 if (added) {
1276 mSettings.mPermissions.put(info.name, bp);
1277 }
1278 mSettings.writeLP();
1279 return added;
1280 }
1281 }
1282
1283 public void removePermission(String name) {
1284 synchronized (mPackages) {
1285 checkPermissionTreeLP(name);
1286 BasePermission bp = mSettings.mPermissions.get(name);
1287 if (bp != null) {
1288 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1289 throw new SecurityException(
1290 "Not allowed to modify non-dynamic permission "
1291 + name);
1292 }
1293 mSettings.mPermissions.remove(name);
1294 mSettings.writeLP();
1295 }
1296 }
1297 }
1298
Dianne Hackborn854060af2009-07-09 18:14:31 -07001299 public boolean isProtectedBroadcast(String actionName) {
1300 synchronized (mPackages) {
1301 return mProtectedBroadcasts.contains(actionName);
1302 }
1303 }
1304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 public int checkSignatures(String pkg1, String pkg2) {
1306 synchronized (mPackages) {
1307 PackageParser.Package p1 = mPackages.get(pkg1);
1308 PackageParser.Package p2 = mPackages.get(pkg2);
1309 if (p1 == null || p1.mExtras == null
1310 || p2 == null || p2.mExtras == null) {
1311 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1312 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001313 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
1315 }
1316
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001317 public int checkUidSignatures(int uid1, int uid2) {
1318 synchronized (mPackages) {
1319 Signature[] s1;
1320 Signature[] s2;
1321 Object obj = mSettings.getUserIdLP(uid1);
1322 if (obj != null) {
1323 if (obj instanceof SharedUserSetting) {
1324 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1325 } else if (obj instanceof PackageSetting) {
1326 s1 = ((PackageSetting)obj).signatures.mSignatures;
1327 } else {
1328 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1329 }
1330 } else {
1331 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1332 }
1333 obj = mSettings.getUserIdLP(uid2);
1334 if (obj != null) {
1335 if (obj instanceof SharedUserSetting) {
1336 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1337 } else if (obj instanceof PackageSetting) {
1338 s2 = ((PackageSetting)obj).signatures.mSignatures;
1339 } else {
1340 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1341 }
1342 } else {
1343 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1344 }
1345 return checkSignaturesLP(s1, s2);
1346 }
1347 }
1348
1349 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1350 if (s1 == null) {
1351 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1353 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1354 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001355 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1357 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001358 final int N1 = s1.length;
1359 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 for (int i=0; i<N1; i++) {
1361 boolean match = false;
1362 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001363 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 match = true;
1365 break;
1366 }
1367 }
1368 if (!match) {
1369 return PackageManager.SIGNATURE_NO_MATCH;
1370 }
1371 }
1372 return PackageManager.SIGNATURE_MATCH;
1373 }
1374
1375 public String[] getPackagesForUid(int uid) {
1376 synchronized (mPackages) {
1377 Object obj = mSettings.getUserIdLP(uid);
1378 if (obj instanceof SharedUserSetting) {
1379 SharedUserSetting sus = (SharedUserSetting)obj;
1380 final int N = sus.packages.size();
1381 String[] res = new String[N];
1382 Iterator<PackageSetting> it = sus.packages.iterator();
1383 int i=0;
1384 while (it.hasNext()) {
1385 res[i++] = it.next().name;
1386 }
1387 return res;
1388 } else if (obj instanceof PackageSetting) {
1389 PackageSetting ps = (PackageSetting)obj;
1390 return new String[] { ps.name };
1391 }
1392 }
1393 return null;
1394 }
1395
1396 public String getNameForUid(int uid) {
1397 synchronized (mPackages) {
1398 Object obj = mSettings.getUserIdLP(uid);
1399 if (obj instanceof SharedUserSetting) {
1400 SharedUserSetting sus = (SharedUserSetting)obj;
1401 return sus.name + ":" + sus.userId;
1402 } else if (obj instanceof PackageSetting) {
1403 PackageSetting ps = (PackageSetting)obj;
1404 return ps.name;
1405 }
1406 }
1407 return null;
1408 }
1409
1410 public int getUidForSharedUser(String sharedUserName) {
1411 if(sharedUserName == null) {
1412 return -1;
1413 }
1414 synchronized (mPackages) {
1415 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1416 if(suid == null) {
1417 return -1;
1418 }
1419 return suid.userId;
1420 }
1421 }
1422
1423 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1424 int flags) {
1425 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001426 return chooseBestActivity(intent, resolvedType, flags, query);
1427 }
1428
Mihai Predaeae850c2009-05-13 10:13:48 +02001429 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1430 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 if (query != null) {
1432 final int N = query.size();
1433 if (N == 1) {
1434 return query.get(0);
1435 } else if (N > 1) {
1436 // If there is more than one activity with the same priority,
1437 // then let the user decide between them.
1438 ResolveInfo r0 = query.get(0);
1439 ResolveInfo r1 = query.get(1);
1440 if (false) {
1441 System.out.println(r0.activityInfo.name +
1442 "=" + r0.priority + " vs " +
1443 r1.activityInfo.name +
1444 "=" + r1.priority);
1445 }
1446 // If the first activity has a higher priority, or a different
1447 // default, then it is always desireable to pick it.
1448 if (r0.priority != r1.priority
1449 || r0.preferredOrder != r1.preferredOrder
1450 || r0.isDefault != r1.isDefault) {
1451 return query.get(0);
1452 }
1453 // If we have saved a preference for a preferred activity for
1454 // this Intent, use that.
1455 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1456 flags, query, r0.priority);
1457 if (ri != null) {
1458 return ri;
1459 }
1460 return mResolveInfo;
1461 }
1462 }
1463 return null;
1464 }
1465
1466 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1467 int flags, List<ResolveInfo> query, int priority) {
1468 synchronized (mPackages) {
1469 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1470 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001471 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1473 if (prefs != null && prefs.size() > 0) {
1474 // First figure out how good the original match set is.
1475 // We will only allow preferred activities that came
1476 // from the same match quality.
1477 int match = 0;
1478 final int N = query.size();
1479 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1480 for (int j=0; j<N; j++) {
1481 ResolveInfo ri = query.get(j);
1482 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1483 + ": 0x" + Integer.toHexString(match));
1484 if (ri.match > match) match = ri.match;
1485 }
1486 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1487 + Integer.toHexString(match));
1488 match &= IntentFilter.MATCH_CATEGORY_MASK;
1489 final int M = prefs.size();
1490 for (int i=0; i<M; i++) {
1491 PreferredActivity pa = prefs.get(i);
1492 if (pa.mMatch != match) {
1493 continue;
1494 }
1495 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1496 if (DEBUG_PREFERRED) {
1497 Log.v(TAG, "Got preferred activity:");
1498 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1499 }
1500 if (ai != null) {
1501 for (int j=0; j<N; j++) {
1502 ResolveInfo ri = query.get(j);
1503 if (!ri.activityInfo.applicationInfo.packageName
1504 .equals(ai.applicationInfo.packageName)) {
1505 continue;
1506 }
1507 if (!ri.activityInfo.name.equals(ai.name)) {
1508 continue;
1509 }
1510
1511 // Okay we found a previously set preferred app.
1512 // If the result set is different from when this
1513 // was created, we need to clear it and re-ask the
1514 // user their preference.
1515 if (!pa.sameSet(query, priority)) {
1516 Log.i(TAG, "Result set changed, dropping preferred activity for "
1517 + intent + " type " + resolvedType);
1518 mSettings.mPreferredActivities.removeFilter(pa);
1519 return null;
1520 }
1521
1522 // Yay!
1523 return ri;
1524 }
1525 }
1526 }
1527 }
1528 }
1529 return null;
1530 }
1531
1532 public List<ResolveInfo> queryIntentActivities(Intent intent,
1533 String resolvedType, int flags) {
1534 ComponentName comp = intent.getComponent();
1535 if (comp != null) {
1536 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1537 ActivityInfo ai = getActivityInfo(comp, flags);
1538 if (ai != null) {
1539 ResolveInfo ri = new ResolveInfo();
1540 ri.activityInfo = ai;
1541 list.add(ri);
1542 }
1543 return list;
1544 }
1545
1546 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001547 String pkgName = intent.getPackage();
1548 if (pkgName == null) {
1549 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1550 resolvedType, flags);
1551 }
1552 PackageParser.Package pkg = mPackages.get(pkgName);
1553 if (pkg != null) {
1554 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1555 resolvedType, flags, pkg.activities);
1556 }
1557 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559 }
1560
1561 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1562 Intent[] specifics, String[] specificTypes, Intent intent,
1563 String resolvedType, int flags) {
1564 final String resultsAction = intent.getAction();
1565
1566 List<ResolveInfo> results = queryIntentActivities(
1567 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1568 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1569
1570 int specificsPos = 0;
1571 int N;
1572
1573 // todo: note that the algorithm used here is O(N^2). This
1574 // isn't a problem in our current environment, but if we start running
1575 // into situations where we have more than 5 or 10 matches then this
1576 // should probably be changed to something smarter...
1577
1578 // First we go through and resolve each of the specific items
1579 // that were supplied, taking care of removing any corresponding
1580 // duplicate items in the generic resolve list.
1581 if (specifics != null) {
1582 for (int i=0; i<specifics.length; i++) {
1583 final Intent sintent = specifics[i];
1584 if (sintent == null) {
1585 continue;
1586 }
1587
1588 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1589 String action = sintent.getAction();
1590 if (resultsAction != null && resultsAction.equals(action)) {
1591 // If this action was explicitly requested, then don't
1592 // remove things that have it.
1593 action = null;
1594 }
1595 ComponentName comp = sintent.getComponent();
1596 ResolveInfo ri = null;
1597 ActivityInfo ai = null;
1598 if (comp == null) {
1599 ri = resolveIntent(
1600 sintent,
1601 specificTypes != null ? specificTypes[i] : null,
1602 flags);
1603 if (ri == null) {
1604 continue;
1605 }
1606 if (ri == mResolveInfo) {
1607 // ACK! Must do something better with this.
1608 }
1609 ai = ri.activityInfo;
1610 comp = new ComponentName(ai.applicationInfo.packageName,
1611 ai.name);
1612 } else {
1613 ai = getActivityInfo(comp, flags);
1614 if (ai == null) {
1615 continue;
1616 }
1617 }
1618
1619 // Look for any generic query activities that are duplicates
1620 // of this specific one, and remove them from the results.
1621 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1622 N = results.size();
1623 int j;
1624 for (j=specificsPos; j<N; j++) {
1625 ResolveInfo sri = results.get(j);
1626 if ((sri.activityInfo.name.equals(comp.getClassName())
1627 && sri.activityInfo.applicationInfo.packageName.equals(
1628 comp.getPackageName()))
1629 || (action != null && sri.filter.matchAction(action))) {
1630 results.remove(j);
1631 if (Config.LOGV) Log.v(
1632 TAG, "Removing duplicate item from " + j
1633 + " due to specific " + specificsPos);
1634 if (ri == null) {
1635 ri = sri;
1636 }
1637 j--;
1638 N--;
1639 }
1640 }
1641
1642 // Add this specific item to its proper place.
1643 if (ri == null) {
1644 ri = new ResolveInfo();
1645 ri.activityInfo = ai;
1646 }
1647 results.add(specificsPos, ri);
1648 ri.specificIndex = i;
1649 specificsPos++;
1650 }
1651 }
1652
1653 // Now we go through the remaining generic results and remove any
1654 // duplicate actions that are found here.
1655 N = results.size();
1656 for (int i=specificsPos; i<N-1; i++) {
1657 final ResolveInfo rii = results.get(i);
1658 if (rii.filter == null) {
1659 continue;
1660 }
1661
1662 // Iterate over all of the actions of this result's intent
1663 // filter... typically this should be just one.
1664 final Iterator<String> it = rii.filter.actionsIterator();
1665 if (it == null) {
1666 continue;
1667 }
1668 while (it.hasNext()) {
1669 final String action = it.next();
1670 if (resultsAction != null && resultsAction.equals(action)) {
1671 // If this action was explicitly requested, then don't
1672 // remove things that have it.
1673 continue;
1674 }
1675 for (int j=i+1; j<N; j++) {
1676 final ResolveInfo rij = results.get(j);
1677 if (rij.filter != null && rij.filter.hasAction(action)) {
1678 results.remove(j);
1679 if (Config.LOGV) Log.v(
1680 TAG, "Removing duplicate item from " + j
1681 + " due to action " + action + " at " + i);
1682 j--;
1683 N--;
1684 }
1685 }
1686 }
1687
1688 // If the caller didn't request filter information, drop it now
1689 // so we don't have to marshall/unmarshall it.
1690 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1691 rii.filter = null;
1692 }
1693 }
1694
1695 // Filter out the caller activity if so requested.
1696 if (caller != null) {
1697 N = results.size();
1698 for (int i=0; i<N; i++) {
1699 ActivityInfo ainfo = results.get(i).activityInfo;
1700 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1701 && caller.getClassName().equals(ainfo.name)) {
1702 results.remove(i);
1703 break;
1704 }
1705 }
1706 }
1707
1708 // If the caller didn't request filter information,
1709 // drop them now so we don't have to
1710 // marshall/unmarshall it.
1711 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1712 N = results.size();
1713 for (int i=0; i<N; i++) {
1714 results.get(i).filter = null;
1715 }
1716 }
1717
1718 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1719 return results;
1720 }
1721
1722 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1723 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001724 ComponentName comp = intent.getComponent();
1725 if (comp != null) {
1726 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1727 ActivityInfo ai = getReceiverInfo(comp, flags);
1728 if (ai != null) {
1729 ResolveInfo ri = new ResolveInfo();
1730 ri.activityInfo = ai;
1731 list.add(ri);
1732 }
1733 return list;
1734 }
1735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001737 String pkgName = intent.getPackage();
1738 if (pkgName == null) {
1739 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1740 resolvedType, flags);
1741 }
1742 PackageParser.Package pkg = mPackages.get(pkgName);
1743 if (pkg != null) {
1744 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1745 resolvedType, flags, pkg.receivers);
1746 }
1747 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 }
1749 }
1750
1751 public ResolveInfo resolveService(Intent intent, String resolvedType,
1752 int flags) {
1753 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1754 flags);
1755 if (query != null) {
1756 if (query.size() >= 1) {
1757 // If there is more than one service with the same priority,
1758 // just arbitrarily pick the first one.
1759 return query.get(0);
1760 }
1761 }
1762 return null;
1763 }
1764
1765 public List<ResolveInfo> queryIntentServices(Intent intent,
1766 String resolvedType, int flags) {
1767 ComponentName comp = intent.getComponent();
1768 if (comp != null) {
1769 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1770 ServiceInfo si = getServiceInfo(comp, flags);
1771 if (si != null) {
1772 ResolveInfo ri = new ResolveInfo();
1773 ri.serviceInfo = si;
1774 list.add(ri);
1775 }
1776 return list;
1777 }
1778
1779 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001780 String pkgName = intent.getPackage();
1781 if (pkgName == null) {
1782 return (List<ResolveInfo>)mServices.queryIntent(intent,
1783 resolvedType, flags);
1784 }
1785 PackageParser.Package pkg = mPackages.get(pkgName);
1786 if (pkg != null) {
1787 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1788 resolvedType, flags, pkg.services);
1789 }
1790 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 }
1792 }
1793
1794 public List<PackageInfo> getInstalledPackages(int flags) {
1795 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1796
1797 synchronized (mPackages) {
1798 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1799 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1800 while (i.hasNext()) {
1801 final PackageSetting ps = i.next();
1802 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1803 if(psPkg != null) {
1804 finalList.add(psPkg);
1805 }
1806 }
1807 }
1808 else {
1809 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1810 while (i.hasNext()) {
1811 final PackageParser.Package p = i.next();
1812 if (p.applicationInfo != null) {
1813 PackageInfo pi = generatePackageInfo(p, flags);
1814 if(pi != null) {
1815 finalList.add(pi);
1816 }
1817 }
1818 }
1819 }
1820 }
1821 return finalList;
1822 }
1823
1824 public List<ApplicationInfo> getInstalledApplications(int flags) {
1825 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1826 synchronized(mPackages) {
1827 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1828 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1829 while (i.hasNext()) {
1830 final PackageSetting ps = i.next();
1831 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1832 if(ai != null) {
1833 finalList.add(ai);
1834 }
1835 }
1836 }
1837 else {
1838 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1839 while (i.hasNext()) {
1840 final PackageParser.Package p = i.next();
1841 if (p.applicationInfo != null) {
1842 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1843 if(ai != null) {
1844 finalList.add(ai);
1845 }
1846 }
1847 }
1848 }
1849 }
1850 return finalList;
1851 }
1852
1853 public List<ApplicationInfo> getPersistentApplications(int flags) {
1854 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1855
1856 synchronized (mPackages) {
1857 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1858 while (i.hasNext()) {
1859 PackageParser.Package p = i.next();
1860 if (p.applicationInfo != null
1861 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
1862 && (!mSafeMode || (p.applicationInfo.flags
1863 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1864 finalList.add(p.applicationInfo);
1865 }
1866 }
1867 }
1868
1869 return finalList;
1870 }
1871
1872 public ProviderInfo resolveContentProvider(String name, int flags) {
1873 synchronized (mPackages) {
1874 final PackageParser.Provider provider = mProviders.get(name);
1875 return provider != null
1876 && mSettings.isEnabledLP(provider.info, flags)
1877 && (!mSafeMode || (provider.info.applicationInfo.flags
1878 &ApplicationInfo.FLAG_SYSTEM) != 0)
1879 ? PackageParser.generateProviderInfo(provider, flags)
1880 : null;
1881 }
1882 }
1883
Fred Quintana718d8a22009-04-29 17:53:20 -07001884 /**
1885 * @deprecated
1886 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 public void querySyncProviders(List outNames, List outInfo) {
1888 synchronized (mPackages) {
1889 Iterator<Map.Entry<String, PackageParser.Provider>> i
1890 = mProviders.entrySet().iterator();
1891
1892 while (i.hasNext()) {
1893 Map.Entry<String, PackageParser.Provider> entry = i.next();
1894 PackageParser.Provider p = entry.getValue();
1895
1896 if (p.syncable
1897 && (!mSafeMode || (p.info.applicationInfo.flags
1898 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1899 outNames.add(entry.getKey());
1900 outInfo.add(PackageParser.generateProviderInfo(p, 0));
1901 }
1902 }
1903 }
1904 }
1905
1906 public List<ProviderInfo> queryContentProviders(String processName,
1907 int uid, int flags) {
1908 ArrayList<ProviderInfo> finalList = null;
1909
1910 synchronized (mPackages) {
1911 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
1912 while (i.hasNext()) {
1913 PackageParser.Provider p = i.next();
1914 if (p.info.authority != null
1915 && (processName == null ||
1916 (p.info.processName.equals(processName)
1917 && p.info.applicationInfo.uid == uid))
1918 && mSettings.isEnabledLP(p.info, flags)
1919 && (!mSafeMode || (p.info.applicationInfo.flags
1920 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1921 if (finalList == null) {
1922 finalList = new ArrayList<ProviderInfo>(3);
1923 }
1924 finalList.add(PackageParser.generateProviderInfo(p,
1925 flags));
1926 }
1927 }
1928 }
1929
1930 if (finalList != null) {
1931 Collections.sort(finalList, mProviderInitOrderSorter);
1932 }
1933
1934 return finalList;
1935 }
1936
1937 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
1938 int flags) {
1939 synchronized (mPackages) {
1940 final PackageParser.Instrumentation i = mInstrumentation.get(name);
1941 return PackageParser.generateInstrumentationInfo(i, flags);
1942 }
1943 }
1944
1945 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
1946 int flags) {
1947 ArrayList<InstrumentationInfo> finalList =
1948 new ArrayList<InstrumentationInfo>();
1949
1950 synchronized (mPackages) {
1951 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
1952 while (i.hasNext()) {
1953 PackageParser.Instrumentation p = i.next();
1954 if (targetPackage == null
1955 || targetPackage.equals(p.info.targetPackage)) {
1956 finalList.add(PackageParser.generateInstrumentationInfo(p,
1957 flags));
1958 }
1959 }
1960 }
1961
1962 return finalList;
1963 }
1964
1965 private void scanDirLI(File dir, int flags, int scanMode) {
1966 Log.d(TAG, "Scanning app dir " + dir);
1967
1968 String[] files = dir.list();
1969
1970 int i;
1971 for (i=0; i<files.length; i++) {
1972 File file = new File(dir, files[i]);
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07001973 File resFile = file;
1974 // Pick up the resource path from settings for fwd locked apps
1975 if ((scanMode & SCAN_FORWARD_LOCKED) != 0) {
1976 resFile = null;
1977 }
1978 PackageParser.Package pkg = scanPackageLI(file, file, resFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
1980 }
1981 }
1982
1983 private static void reportSettingsProblem(int priority, String msg) {
1984 try {
1985 File dataDir = Environment.getDataDirectory();
1986 File systemDir = new File(dataDir, "system");
1987 File fname = new File(systemDir, "uiderrors.txt");
1988 FileOutputStream out = new FileOutputStream(fname, true);
1989 PrintWriter pw = new PrintWriter(out);
1990 pw.println(msg);
1991 pw.close();
1992 FileUtils.setPermissions(
1993 fname.toString(),
1994 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
1995 -1, -1);
1996 } catch (java.io.IOException e) {
1997 }
1998 Log.println(priority, TAG, msg);
1999 }
2000
2001 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2002 PackageParser.Package pkg, File srcFile, int parseFlags) {
2003 if (GET_CERTIFICATES) {
2004 if (ps == null || !ps.codePath.equals(srcFile)
2005 || ps.getTimeStamp() != srcFile.lastModified()) {
2006 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2007 if (!pp.collectCertificates(pkg, parseFlags)) {
2008 mLastScanError = pp.getParseError();
2009 return false;
2010 }
2011 }
2012 }
2013 return true;
2014 }
2015
2016 /*
2017 * Scan a package and return the newly parsed package.
2018 * Returns null in case of errors and the error code is stored in mLastScanError
2019 */
2020 private PackageParser.Package scanPackageLI(File scanFile,
2021 File destCodeFile, File destResourceFile, int parseFlags,
2022 int scanMode) {
2023 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2024 parseFlags |= mDefParseFlags;
2025 PackageParser pp = new PackageParser(scanFile.getPath());
2026 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 final PackageParser.Package pkg = pp.parsePackage(scanFile,
2028 destCodeFile.getAbsolutePath(), mMetrics, parseFlags);
2029 if (pkg == null) {
2030 mLastScanError = pp.getParseError();
2031 return null;
2032 }
2033 PackageSetting ps;
2034 PackageSetting updatedPkg;
2035 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002036 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2038 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002039 // Verify certificates first
2040 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2041 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2042 return null;
2043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 if (updatedPkg != null) {
2045 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2046 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2047 }
2048 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2049 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002050 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2051 if (pkg.mVersionCode < ps.versionCode) {
2052 // The system package has been updated and the code path does not match
2053 // Ignore entry. Just return
2054 Log.w(TAG, "Package:" + pkg.packageName +
2055 " has been updated. Ignoring the one from path:"+scanFile);
2056 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2057 return null;
2058 } else {
2059 // Delete the older apk pointed to by ps
2060 // At this point, its safely assumed that package installation for
2061 // apps in system partition will go through. If not there won't be a working
2062 // version of the app
2063 synchronized (mPackages) {
2064 // Just remove the loaded entries from package lists.
2065 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002066 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002067 deletePackageResourcesLI(ps.name, ps.codePathString, ps.resourcePathString);
2068 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
2071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 // The apk is forward locked (not public) if its code and resources
2073 // are kept in different files.
2074 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
2075 scanMode |= SCAN_FORWARD_LOCKED;
2076 }
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002077 File resFile = destResourceFile;
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07002078 if (ps != null && ((scanMode & SCAN_FORWARD_LOCKED) != 0)) {
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002079 resFile = getFwdLockedResource(ps.name);
2080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002082 return scanPackageLI(scanFile, destCodeFile, resFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
2084 }
2085
2086 private static String fixProcessName(String defProcessName,
2087 String processName, int uid) {
2088 if (processName == null) {
2089 return defProcessName;
2090 }
2091 return processName;
2092 }
2093
2094 private boolean verifySignaturesLP(PackageSetting pkgSetting,
2095 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2096 if (pkg.mSignatures != null) {
2097 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2098 updateSignature)) {
2099 Log.e(TAG, "Package " + pkg.packageName
2100 + " signatures do not match the previously installed version; ignoring!");
2101 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2102 return false;
2103 }
2104
2105 if (pkgSetting.sharedUser != null) {
2106 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2107 pkg.mSignatures, updateSignature)) {
2108 Log.e(TAG, "Package " + pkg.packageName
2109 + " has no signatures that match those in shared user "
2110 + pkgSetting.sharedUser.name + "; ignoring!");
2111 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2112 return false;
2113 }
2114 }
2115 } else {
2116 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2117 }
2118 return true;
2119 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002120
2121 public boolean performDexOpt(String packageName) {
2122 if (!mNoDexOpt) {
2123 return false;
2124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002126 PackageParser.Package p;
2127 synchronized (mPackages) {
2128 p = mPackages.get(packageName);
2129 if (p == null || p.mDidDexOpt) {
2130 return false;
2131 }
2132 }
2133 synchronized (mInstallLock) {
2134 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2135 }
2136 }
2137
2138 static final int DEX_OPT_SKIPPED = 0;
2139 static final int DEX_OPT_PERFORMED = 1;
2140 static final int DEX_OPT_FAILED = -1;
2141
2142 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2143 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002144 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002145 String path = pkg.mScanPath;
2146 int ret = 0;
2147 try {
2148 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
2149 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
2150 !pkg.mForwardLocked);
2151 pkg.mDidDexOpt = true;
2152 performed = true;
2153 }
2154 } catch (FileNotFoundException e) {
2155 Log.w(TAG, "Apk not found for dexopt: " + path);
2156 ret = -1;
2157 } catch (IOException e) {
2158 Log.w(TAG, "Exception reading apk: " + path, e);
2159 ret = -1;
2160 }
2161 if (ret < 0) {
2162 //error from installer
2163 return DEX_OPT_FAILED;
2164 }
2165 }
2166
2167 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2168 }
2169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 private PackageParser.Package scanPackageLI(
2171 File scanFile, File destCodeFile, File destResourceFile,
2172 PackageParser.Package pkg, int parseFlags, int scanMode) {
2173
2174 mScanningPath = scanFile;
2175 if (pkg == null) {
2176 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2177 return null;
2178 }
2179
2180 final String pkgName = pkg.applicationInfo.packageName;
2181 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2182 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2183 }
2184
2185 if (pkgName.equals("android")) {
2186 synchronized (mPackages) {
2187 if (mAndroidApplication != null) {
2188 Log.w(TAG, "*************************************************");
2189 Log.w(TAG, "Core android package being redefined. Skipping.");
2190 Log.w(TAG, " file=" + mScanningPath);
2191 Log.w(TAG, "*************************************************");
2192 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2193 return null;
2194 }
2195
2196 // Set up information for our fall-back user intent resolution
2197 // activity.
2198 mPlatformPackage = pkg;
2199 pkg.mVersionCode = mSdkVersion;
2200 mAndroidApplication = pkg.applicationInfo;
2201 mResolveActivity.applicationInfo = mAndroidApplication;
2202 mResolveActivity.name = ResolverActivity.class.getName();
2203 mResolveActivity.packageName = mAndroidApplication.packageName;
2204 mResolveActivity.processName = mAndroidApplication.processName;
2205 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2206 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2207 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2208 mResolveActivity.exported = true;
2209 mResolveActivity.enabled = true;
2210 mResolveInfo.activityInfo = mResolveActivity;
2211 mResolveInfo.priority = 0;
2212 mResolveInfo.preferredOrder = 0;
2213 mResolveInfo.match = 0;
2214 mResolveComponentName = new ComponentName(
2215 mAndroidApplication.packageName, mResolveActivity.name);
2216 }
2217 }
2218
2219 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2220 TAG, "Scanning package " + pkgName);
2221 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2222 Log.w(TAG, "*************************************************");
2223 Log.w(TAG, "Application package " + pkgName
2224 + " already installed. Skipping duplicate.");
2225 Log.w(TAG, "*************************************************");
2226 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2227 return null;
2228 }
2229
2230 SharedUserSetting suid = null;
2231 PackageSetting pkgSetting = null;
2232
2233 boolean removeExisting = false;
2234
2235 synchronized (mPackages) {
2236 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002237 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2238 if (mTmpSharedLibraries == null ||
2239 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2240 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2241 }
2242 int num = 0;
2243 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2244 for (int i=0; i<N; i++) {
2245 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 if (file == null) {
2247 Log.e(TAG, "Package " + pkg.packageName
2248 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002249 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2251 return null;
2252 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002253 mTmpSharedLibraries[num] = file;
2254 num++;
2255 }
2256 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2257 for (int i=0; i<N; i++) {
2258 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2259 if (file == null) {
2260 Log.w(TAG, "Package " + pkg.packageName
2261 + " desires unavailable shared library "
2262 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2263 } else {
2264 mTmpSharedLibraries[num] = file;
2265 num++;
2266 }
2267 }
2268 if (num > 0) {
2269 pkg.usesLibraryFiles = new String[num];
2270 System.arraycopy(mTmpSharedLibraries, 0,
2271 pkg.usesLibraryFiles, 0, num);
2272 }
2273
2274 if (pkg.reqFeatures != null) {
2275 N = pkg.reqFeatures.size();
2276 for (int i=0; i<N; i++) {
2277 FeatureInfo fi = pkg.reqFeatures.get(i);
2278 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2279 // Don't care.
2280 continue;
2281 }
2282
2283 if (fi.name != null) {
2284 if (mAvailableFeatures.get(fi.name) == null) {
2285 Log.e(TAG, "Package " + pkg.packageName
2286 + " requires unavailable feature "
2287 + fi.name + "; failing!");
2288 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2289 return null;
2290 }
2291 }
2292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 }
2294 }
2295
2296 if (pkg.mSharedUserId != null) {
2297 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2298 pkg.applicationInfo.flags, true);
2299 if (suid == null) {
2300 Log.w(TAG, "Creating application package " + pkgName
2301 + " for shared user failed");
2302 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2303 return null;
2304 }
2305 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2306 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2307 + suid.userId + "): packages=" + suid.packages);
2308 }
2309 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002310
2311 // Just create the setting, don't add it yet. For already existing packages
2312 // the PkgSetting exists already and doesn't have to be created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
2314 destResourceFile, pkg.applicationInfo.flags, true, false);
2315 if (pkgSetting == null) {
2316 Log.w(TAG, "Creating application package " + pkgName + " failed");
2317 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2318 return null;
2319 }
2320 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
2321 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2322 }
2323
2324 pkg.applicationInfo.uid = pkgSetting.userId;
2325 pkg.mExtras = pkgSetting;
2326
2327 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
2328 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2329 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2330 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2331 return null;
2332 }
2333 // The signature has changed, but this package is in the system
2334 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002335 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 // However... if this package is part of a shared user, but it
2337 // doesn't match the signature of the shared user, let's fail.
2338 // What this means is that you can't change the signatures
2339 // associated with an overall shared user, which doesn't seem all
2340 // that unreasonable.
2341 if (pkgSetting.sharedUser != null) {
2342 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2343 pkg.mSignatures, false)) {
2344 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2345 return null;
2346 }
2347 }
2348 removeExisting = true;
2349 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002350
2351 // Verify that this new package doesn't have any content providers
2352 // that conflict with existing packages. Only do this if the
2353 // package isn't already installed, since we don't want to break
2354 // things that are installed.
2355 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2356 int N = pkg.providers.size();
2357 int i;
2358 for (i=0; i<N; i++) {
2359 PackageParser.Provider p = pkg.providers.get(i);
2360 String names[] = p.info.authority.split(";");
2361 for (int j = 0; j < names.length; j++) {
2362 if (mProviders.containsKey(names[j])) {
2363 PackageParser.Provider other = mProviders.get(names[j]);
2364 Log.w(TAG, "Can't install because provider name " + names[j] +
2365 " (in package " + pkg.applicationInfo.packageName +
2366 ") is already used by "
2367 + ((other != null && other.component != null)
2368 ? other.component.getPackageName() : "?"));
2369 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2370 return null;
2371 }
2372 }
2373 }
2374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 }
2376
2377 if (removeExisting) {
2378 if (mInstaller != null) {
2379 int ret = mInstaller.remove(pkgName);
2380 if (ret != 0) {
2381 String msg = "System package " + pkg.packageName
2382 + " could not have data directory erased after signature change.";
2383 reportSettingsProblem(Log.WARN, msg);
2384 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2385 return null;
2386 }
2387 }
2388 Log.w(TAG, "System package " + pkg.packageName
2389 + " signature changed: existing data removed.");
2390 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2391 }
2392
2393 long scanFileTime = scanFile.lastModified();
2394 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2395 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2396 pkg.applicationInfo.processName = fixProcessName(
2397 pkg.applicationInfo.packageName,
2398 pkg.applicationInfo.processName,
2399 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002400 pkg.applicationInfo.publicSourceDir = destResourceFile.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401
2402 File dataPath;
2403 if (mPlatformPackage == pkg) {
2404 // The system package is special.
2405 dataPath = new File (Environment.getDataDirectory(), "system");
2406 pkg.applicationInfo.dataDir = dataPath.getPath();
2407 } else {
2408 // This is a normal package, need to make its data directory.
2409 dataPath = new File(mAppDataDir, pkgName);
2410 if (dataPath.exists()) {
2411 mOutPermissions[1] = 0;
2412 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2413 if (mOutPermissions[1] == pkg.applicationInfo.uid
2414 || !Process.supportsProcesses()) {
2415 pkg.applicationInfo.dataDir = dataPath.getPath();
2416 } else {
2417 boolean recovered = false;
2418 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2419 // If this is a system app, we can at least delete its
2420 // current data so the application will still work.
2421 if (mInstaller != null) {
2422 int ret = mInstaller.remove(pkgName);
2423 if(ret >= 0) {
2424 // Old data gone!
2425 String msg = "System package " + pkg.packageName
2426 + " has changed from uid: "
2427 + mOutPermissions[1] + " to "
2428 + pkg.applicationInfo.uid + "; old data erased";
2429 reportSettingsProblem(Log.WARN, msg);
2430 recovered = true;
2431
2432 // And now re-install the app.
2433 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2434 pkg.applicationInfo.uid);
2435 if (ret == -1) {
2436 // Ack should not happen!
2437 msg = "System package " + pkg.packageName
2438 + " could not have data directory re-created after delete.";
2439 reportSettingsProblem(Log.WARN, msg);
2440 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2441 return null;
2442 }
2443 }
2444 }
2445 if (!recovered) {
2446 mHasSystemUidErrors = true;
2447 }
2448 }
2449 if (!recovered) {
2450 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2451 + pkg.applicationInfo.uid + "/fs_"
2452 + mOutPermissions[1];
2453 String msg = "Package " + pkg.packageName
2454 + " has mismatched uid: "
2455 + mOutPermissions[1] + " on disk, "
2456 + pkg.applicationInfo.uid + " in settings";
2457 synchronized (mPackages) {
2458 if (!mReportedUidError) {
2459 mReportedUidError = true;
2460 msg = msg + "; read messages:\n"
2461 + mSettings.getReadMessagesLP();
2462 }
2463 reportSettingsProblem(Log.ERROR, msg);
2464 }
2465 }
2466 }
2467 pkg.applicationInfo.dataDir = dataPath.getPath();
2468 } else {
2469 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2470 Log.v(TAG, "Want this data dir: " + dataPath);
2471 //invoke installer to do the actual installation
2472 if (mInstaller != null) {
2473 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2474 pkg.applicationInfo.uid);
2475 if(ret < 0) {
2476 // Error from installer
2477 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2478 return null;
2479 }
2480 } else {
2481 dataPath.mkdirs();
2482 if (dataPath.exists()) {
2483 FileUtils.setPermissions(
2484 dataPath.toString(),
2485 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2486 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2487 }
2488 }
2489 if (dataPath.exists()) {
2490 pkg.applicationInfo.dataDir = dataPath.getPath();
2491 } else {
2492 Log.w(TAG, "Unable to create data directory: " + dataPath);
2493 pkg.applicationInfo.dataDir = null;
2494 }
2495 }
2496 }
2497
2498 // Perform shared library installation and dex validation and
2499 // optimization, if this is not a system app.
2500 if (mInstaller != null) {
2501 String path = scanFile.getPath();
2502 if (scanFileNewer) {
2503 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002504 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2505 if (err != PackageManager.INSTALL_SUCCEEDED) {
2506 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 return null;
2508 }
2509 }
2510
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002511 pkg.mForwardLocked = (scanMode&SCAN_FORWARD_LOCKED) != 0;
2512 pkg.mScanPath = path;
2513
2514 if ((scanMode&SCAN_NO_DEX) == 0) {
2515 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2517 return null;
2518 }
2519 }
2520 }
2521
2522 if (mFactoryTest && pkg.requestedPermissions.contains(
2523 android.Manifest.permission.FACTORY_TEST)) {
2524 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2525 }
2526
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002527 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 if ((scanMode&SCAN_MONITOR) != 0) {
2529 pkg.mPath = destCodeFile.getAbsolutePath();
2530 mAppDirs.put(pkg.mPath, pkg);
2531 }
2532
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002533 // Request the ActivityManager to kill the process(only for existing packages)
2534 // so that we do not end up in a confused state while the user is still using the older
2535 // version of the application while the new one gets installed.
2536 IActivityManager am = ActivityManagerNative.getDefault();
2537 if ((am != null) && ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0)) {
2538 try {
2539 am.killApplicationWithUid(pkg.applicationInfo.packageName,
2540 pkg.applicationInfo.uid);
2541 } catch (RemoteException e) {
2542 }
2543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 // Add the new setting to mSettings
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002546 mSettings.insertPackageSettingLP(pkgSetting, pkg, destCodeFile, destResourceFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002548 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 int N = pkg.providers.size();
2550 StringBuilder r = null;
2551 int i;
2552 for (i=0; i<N; i++) {
2553 PackageParser.Provider p = pkg.providers.get(i);
2554 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2555 p.info.processName, pkg.applicationInfo.uid);
2556 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2557 p.info.name), p);
2558 p.syncable = p.info.isSyncable;
2559 String names[] = p.info.authority.split(";");
2560 p.info.authority = null;
2561 for (int j = 0; j < names.length; j++) {
2562 if (j == 1 && p.syncable) {
2563 // We only want the first authority for a provider to possibly be
2564 // syncable, so if we already added this provider using a different
2565 // authority clear the syncable flag. We copy the provider before
2566 // changing it because the mProviders object contains a reference
2567 // to a provider that we don't want to change.
2568 // Only do this for the second authority since the resulting provider
2569 // object can be the same for all future authorities for this provider.
2570 p = new PackageParser.Provider(p);
2571 p.syncable = false;
2572 }
2573 if (!mProviders.containsKey(names[j])) {
2574 mProviders.put(names[j], p);
2575 if (p.info.authority == null) {
2576 p.info.authority = names[j];
2577 } else {
2578 p.info.authority = p.info.authority + ";" + names[j];
2579 }
2580 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2581 Log.d(TAG, "Registered content provider: " + names[j] +
2582 ", className = " + p.info.name +
2583 ", isSyncable = " + p.info.isSyncable);
2584 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002585 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 Log.w(TAG, "Skipping provider name " + names[j] +
2587 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002588 "): name already used by "
2589 + ((other != null && other.component != null)
2590 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
2592 }
2593 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2594 if (r == null) {
2595 r = new StringBuilder(256);
2596 } else {
2597 r.append(' ');
2598 }
2599 r.append(p.info.name);
2600 }
2601 }
2602 if (r != null) {
2603 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2604 }
2605
2606 N = pkg.services.size();
2607 r = null;
2608 for (i=0; i<N; i++) {
2609 PackageParser.Service s = pkg.services.get(i);
2610 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2611 s.info.processName, pkg.applicationInfo.uid);
2612 mServices.addService(s);
2613 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2614 if (r == null) {
2615 r = new StringBuilder(256);
2616 } else {
2617 r.append(' ');
2618 }
2619 r.append(s.info.name);
2620 }
2621 }
2622 if (r != null) {
2623 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2624 }
2625
2626 N = pkg.receivers.size();
2627 r = null;
2628 for (i=0; i<N; i++) {
2629 PackageParser.Activity a = pkg.receivers.get(i);
2630 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2631 a.info.processName, pkg.applicationInfo.uid);
2632 mReceivers.addActivity(a, "receiver");
2633 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2634 if (r == null) {
2635 r = new StringBuilder(256);
2636 } else {
2637 r.append(' ');
2638 }
2639 r.append(a.info.name);
2640 }
2641 }
2642 if (r != null) {
2643 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2644 }
2645
2646 N = pkg.activities.size();
2647 r = null;
2648 for (i=0; i<N; i++) {
2649 PackageParser.Activity a = pkg.activities.get(i);
2650 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2651 a.info.processName, pkg.applicationInfo.uid);
2652 mActivities.addActivity(a, "activity");
2653 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2654 if (r == null) {
2655 r = new StringBuilder(256);
2656 } else {
2657 r.append(' ');
2658 }
2659 r.append(a.info.name);
2660 }
2661 }
2662 if (r != null) {
2663 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2664 }
2665
2666 N = pkg.permissionGroups.size();
2667 r = null;
2668 for (i=0; i<N; i++) {
2669 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2670 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2671 if (cur == null) {
2672 mPermissionGroups.put(pg.info.name, pg);
2673 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2674 if (r == null) {
2675 r = new StringBuilder(256);
2676 } else {
2677 r.append(' ');
2678 }
2679 r.append(pg.info.name);
2680 }
2681 } else {
2682 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2683 + pg.info.packageName + " ignored: original from "
2684 + cur.info.packageName);
2685 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2686 if (r == null) {
2687 r = new StringBuilder(256);
2688 } else {
2689 r.append(' ');
2690 }
2691 r.append("DUP:");
2692 r.append(pg.info.name);
2693 }
2694 }
2695 }
2696 if (r != null) {
2697 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2698 }
2699
2700 N = pkg.permissions.size();
2701 r = null;
2702 for (i=0; i<N; i++) {
2703 PackageParser.Permission p = pkg.permissions.get(i);
2704 HashMap<String, BasePermission> permissionMap =
2705 p.tree ? mSettings.mPermissionTrees
2706 : mSettings.mPermissions;
2707 p.group = mPermissionGroups.get(p.info.group);
2708 if (p.info.group == null || p.group != null) {
2709 BasePermission bp = permissionMap.get(p.info.name);
2710 if (bp == null) {
2711 bp = new BasePermission(p.info.name, p.info.packageName,
2712 BasePermission.TYPE_NORMAL);
2713 permissionMap.put(p.info.name, bp);
2714 }
2715 if (bp.perm == null) {
2716 if (bp.sourcePackage == null
2717 || bp.sourcePackage.equals(p.info.packageName)) {
2718 BasePermission tree = findPermissionTreeLP(p.info.name);
2719 if (tree == null
2720 || tree.sourcePackage.equals(p.info.packageName)) {
2721 bp.perm = p;
2722 bp.uid = pkg.applicationInfo.uid;
2723 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2724 if (r == null) {
2725 r = new StringBuilder(256);
2726 } else {
2727 r.append(' ');
2728 }
2729 r.append(p.info.name);
2730 }
2731 } else {
2732 Log.w(TAG, "Permission " + p.info.name + " from package "
2733 + p.info.packageName + " ignored: base tree "
2734 + tree.name + " is from package "
2735 + tree.sourcePackage);
2736 }
2737 } else {
2738 Log.w(TAG, "Permission " + p.info.name + " from package "
2739 + p.info.packageName + " ignored: original from "
2740 + bp.sourcePackage);
2741 }
2742 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2743 if (r == null) {
2744 r = new StringBuilder(256);
2745 } else {
2746 r.append(' ');
2747 }
2748 r.append("DUP:");
2749 r.append(p.info.name);
2750 }
2751 } else {
2752 Log.w(TAG, "Permission " + p.info.name + " from package "
2753 + p.info.packageName + " ignored: no group "
2754 + p.group);
2755 }
2756 }
2757 if (r != null) {
2758 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2759 }
2760
2761 N = pkg.instrumentation.size();
2762 r = null;
2763 for (i=0; i<N; i++) {
2764 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2765 a.info.packageName = pkg.applicationInfo.packageName;
2766 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2767 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2768 a.info.dataDir = pkg.applicationInfo.dataDir;
2769 mInstrumentation.put(a.component, a);
2770 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2771 if (r == null) {
2772 r = new StringBuilder(256);
2773 } else {
2774 r.append(' ');
2775 }
2776 r.append(a.info.name);
2777 }
2778 }
2779 if (r != null) {
2780 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2781 }
2782
Dianne Hackborn854060af2009-07-09 18:14:31 -07002783 if (pkg.protectedBroadcasts != null) {
2784 N = pkg.protectedBroadcasts.size();
2785 for (i=0; i<N; i++) {
2786 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
2787 }
2788 }
2789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 pkgSetting.setTimeStamp(scanFileTime);
2791 }
2792
2793 return pkg;
2794 }
2795
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002796 // The following constants are returned by cachePackageSharedLibsForAbiLI
2797 // to indicate if native shared libraries were found in the package.
2798 // Values are:
2799 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
2800 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
2801 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
2802 // in package (and not installed)
2803 //
2804 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
2805 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
2806 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002808 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
2809 // and automatically copy them to /data/data/<appname>/lib if present.
2810 //
2811 // NOTE: this method may throw an IOException if the library cannot
2812 // be copied to its final destination, e.g. if there isn't enough
2813 // room left on the data partition, or a ZipException if the package
2814 // file is malformed.
2815 //
2816 private int cachePackageSharedLibsForAbiLI( PackageParser.Package pkg,
2817 File dataPath, File scanFile, String cpuAbi)
2818 throws IOException, ZipException {
2819 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
2820 final String apkLib = "lib/";
2821 final int apkLibLen = apkLib.length();
2822 final int cpuAbiLen = cpuAbi.length();
2823 final String libPrefix = "lib";
2824 final int libPrefixLen = libPrefix.length();
2825 final String libSuffix = ".so";
2826 final int libSuffixLen = libSuffix.length();
2827 boolean hasNativeLibraries = false;
2828 boolean installedNativeLibraries = false;
2829
2830 // the minimum length of a valid native shared library of the form
2831 // lib/<something>/lib<name>.so.
2832 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
2833
2834 ZipFile zipFile = new ZipFile(scanFile);
2835 Enumeration<ZipEntry> entries =
2836 (Enumeration<ZipEntry>) zipFile.entries();
2837
2838 while (entries.hasMoreElements()) {
2839 ZipEntry entry = entries.nextElement();
2840 // skip directories
2841 if (entry.isDirectory()) {
2842 continue;
2843 }
2844 String entryName = entry.getName();
2845
2846 // check that the entry looks like lib/<something>/lib<name>.so
2847 // here, but don't check the ABI just yet.
2848 //
2849 // - must be sufficiently long
2850 // - must end with libSuffix, i.e. ".so"
2851 // - must start with apkLib, i.e. "lib/"
2852 if (entryName.length() < minEntryLen ||
2853 !entryName.endsWith(libSuffix) ||
2854 !entryName.startsWith(apkLib) ) {
2855 continue;
2856 }
2857
2858 // file name must start with libPrefix, i.e. "lib"
2859 int lastSlash = entryName.lastIndexOf('/');
2860
2861 if (lastSlash < 0 ||
2862 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
2863 continue;
2864 }
2865
2866 hasNativeLibraries = true;
2867
2868 // check the cpuAbi now, between lib/ and /lib<name>.so
2869 //
2870 if (lastSlash != apkLibLen + cpuAbiLen ||
2871 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
2872 continue;
2873
2874 // extract the library file name, ensure it doesn't contain
2875 // weird characters. we're guaranteed here that it doesn't contain
2876 // a directory separator though.
2877 String libFileName = entryName.substring(lastSlash+1);
2878 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
2879 continue;
2880 }
2881
2882 installedNativeLibraries = true;
2883
2884 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
2885 File.separator + libFileName;
2886 File sharedLibraryFile = new File(sharedLibraryFilePath);
2887 if (! sharedLibraryFile.exists() ||
2888 sharedLibraryFile.length() != entry.getSize() ||
2889 sharedLibraryFile.lastModified() != entry.getTime()) {
2890 if (Config.LOGD) {
2891 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002893 if (mInstaller == null) {
2894 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07002895 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002896 cacheSharedLibLI(pkg, zipFile, entry, sharedLibraryDir,
2897 sharedLibraryFile);
2898 }
2899 }
2900 if (!hasNativeLibraries)
2901 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
2902
2903 if (!installedNativeLibraries)
2904 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
2905
2906 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
2907 }
2908
2909 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
2910 // and copy them to /data/data/<appname>/lib.
2911 //
2912 // This function will first try the main CPU ABI defined by Build.CPU_ABI
2913 // (which corresponds to ro.product.cpu.abi), and also try an alternate
2914 // one if ro.product.cpu.abi2 is defined.
2915 //
2916 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
2917 File dataPath, File scanFile) {
2918 final String cpuAbi = Build.CPU_ABI;
2919 try {
2920 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
2921
2922 // some architectures are capable of supporting several CPU ABIs
2923 // for example, 'armeabi-v7a' also supports 'armeabi' native code
2924 // this is indicated by the definition of the ro.product.cpu.abi2
2925 // system property.
2926 //
2927 // only scan the package twice in case of ABI mismatch
2928 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
2929 String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
2930 if (cpuAbi2 != null) {
2931 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002933
2934 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
2935 Log.w(TAG,"Native ABI mismatch from package file");
2936 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 }
2938 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002939 } catch (ZipException e) {
2940 Log.w(TAG, "Failed to extract data from package file", e);
2941 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002943 Log.w(TAG, "Failed to cache package shared libs", e);
2944 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002946 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 }
2948
2949 private void cacheSharedLibLI(PackageParser.Package pkg,
2950 ZipFile zipFile, ZipEntry entry,
2951 File sharedLibraryDir,
2952 File sharedLibraryFile) throws IOException {
2953 InputStream inputStream = zipFile.getInputStream(entry);
2954 try {
2955 File tempFile = File.createTempFile("tmp", "tmp", sharedLibraryDir);
2956 String tempFilePath = tempFile.getPath();
2957 // XXX package manager can't change owner, so the lib files for
2958 // now need to be left as world readable and owned by the system.
2959 if (! FileUtils.copyToFile(inputStream, tempFile) ||
2960 ! tempFile.setLastModified(entry.getTime()) ||
2961 FileUtils.setPermissions(tempFilePath,
2962 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
2963 |FileUtils.S_IROTH, -1, -1) != 0 ||
2964 ! tempFile.renameTo(sharedLibraryFile)) {
2965 // Failed to properly write file.
2966 tempFile.delete();
2967 throw new IOException("Couldn't create cached shared lib "
2968 + sharedLibraryFile + " in " + sharedLibraryDir);
2969 }
2970 } finally {
2971 inputStream.close();
2972 }
2973 }
2974
2975 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
2976 if (chatty && Config.LOGD) Log.d(
2977 TAG, "Removing package " + pkg.applicationInfo.packageName );
2978
2979 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 clearPackagePreferredActivitiesLP(pkg.packageName);
2981
2982 mPackages.remove(pkg.applicationInfo.packageName);
2983 if (pkg.mPath != null) {
2984 mAppDirs.remove(pkg.mPath);
2985 }
2986
2987 PackageSetting ps = (PackageSetting)pkg.mExtras;
2988 if (ps != null && ps.sharedUser != null) {
2989 // XXX don't do this until the data is removed.
2990 if (false) {
2991 ps.sharedUser.packages.remove(ps);
2992 if (ps.sharedUser.packages.size() == 0) {
2993 // Remove.
2994 }
2995 }
2996 }
2997
2998 int N = pkg.providers.size();
2999 StringBuilder r = null;
3000 int i;
3001 for (i=0; i<N; i++) {
3002 PackageParser.Provider p = pkg.providers.get(i);
3003 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3004 p.info.name));
3005 if (p.info.authority == null) {
3006
3007 /* The is another ContentProvider with this authority when
3008 * this app was installed so this authority is null,
3009 * Ignore it as we don't have to unregister the provider.
3010 */
3011 continue;
3012 }
3013 String names[] = p.info.authority.split(";");
3014 for (int j = 0; j < names.length; j++) {
3015 if (mProviders.get(names[j]) == p) {
3016 mProviders.remove(names[j]);
3017 if (chatty && Config.LOGD) Log.d(
3018 TAG, "Unregistered content provider: " + names[j] +
3019 ", className = " + p.info.name +
3020 ", isSyncable = " + p.info.isSyncable);
3021 }
3022 }
3023 if (chatty) {
3024 if (r == null) {
3025 r = new StringBuilder(256);
3026 } else {
3027 r.append(' ');
3028 }
3029 r.append(p.info.name);
3030 }
3031 }
3032 if (r != null) {
3033 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3034 }
3035
3036 N = pkg.services.size();
3037 r = null;
3038 for (i=0; i<N; i++) {
3039 PackageParser.Service s = pkg.services.get(i);
3040 mServices.removeService(s);
3041 if (chatty) {
3042 if (r == null) {
3043 r = new StringBuilder(256);
3044 } else {
3045 r.append(' ');
3046 }
3047 r.append(s.info.name);
3048 }
3049 }
3050 if (r != null) {
3051 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3052 }
3053
3054 N = pkg.receivers.size();
3055 r = null;
3056 for (i=0; i<N; i++) {
3057 PackageParser.Activity a = pkg.receivers.get(i);
3058 mReceivers.removeActivity(a, "receiver");
3059 if (chatty) {
3060 if (r == null) {
3061 r = new StringBuilder(256);
3062 } else {
3063 r.append(' ');
3064 }
3065 r.append(a.info.name);
3066 }
3067 }
3068 if (r != null) {
3069 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3070 }
3071
3072 N = pkg.activities.size();
3073 r = null;
3074 for (i=0; i<N; i++) {
3075 PackageParser.Activity a = pkg.activities.get(i);
3076 mActivities.removeActivity(a, "activity");
3077 if (chatty) {
3078 if (r == null) {
3079 r = new StringBuilder(256);
3080 } else {
3081 r.append(' ');
3082 }
3083 r.append(a.info.name);
3084 }
3085 }
3086 if (r != null) {
3087 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3088 }
3089
3090 N = pkg.permissions.size();
3091 r = null;
3092 for (i=0; i<N; i++) {
3093 PackageParser.Permission p = pkg.permissions.get(i);
3094 boolean tree = false;
3095 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3096 if (bp == null) {
3097 tree = true;
3098 bp = mSettings.mPermissionTrees.get(p.info.name);
3099 }
3100 if (bp != null && bp.perm == p) {
3101 if (bp.type != BasePermission.TYPE_BUILTIN) {
3102 if (tree) {
3103 mSettings.mPermissionTrees.remove(p.info.name);
3104 } else {
3105 mSettings.mPermissions.remove(p.info.name);
3106 }
3107 } else {
3108 bp.perm = null;
3109 }
3110 if (chatty) {
3111 if (r == null) {
3112 r = new StringBuilder(256);
3113 } else {
3114 r.append(' ');
3115 }
3116 r.append(p.info.name);
3117 }
3118 }
3119 }
3120 if (r != null) {
3121 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3122 }
3123
3124 N = pkg.instrumentation.size();
3125 r = null;
3126 for (i=0; i<N; i++) {
3127 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3128 mInstrumentation.remove(a.component);
3129 if (chatty) {
3130 if (r == null) {
3131 r = new StringBuilder(256);
3132 } else {
3133 r.append(' ');
3134 }
3135 r.append(a.info.name);
3136 }
3137 }
3138 if (r != null) {
3139 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3140 }
3141 }
3142 }
3143
3144 private static final boolean isPackageFilename(String name) {
3145 return name != null && name.endsWith(".apk");
3146 }
3147
3148 private void updatePermissionsLP() {
3149 // Make sure there are no dangling permission trees.
3150 Iterator<BasePermission> it = mSettings.mPermissionTrees
3151 .values().iterator();
3152 while (it.hasNext()) {
3153 BasePermission bp = it.next();
3154 if (bp.perm == null) {
3155 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3156 + " from package " + bp.sourcePackage);
3157 it.remove();
3158 }
3159 }
3160
3161 // Make sure all dynamic permissions have been assigned to a package,
3162 // and make sure there are no dangling permissions.
3163 it = mSettings.mPermissions.values().iterator();
3164 while (it.hasNext()) {
3165 BasePermission bp = it.next();
3166 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3167 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3168 + bp.name + " pkg=" + bp.sourcePackage
3169 + " info=" + bp.pendingInfo);
3170 if (bp.perm == null && bp.pendingInfo != null) {
3171 BasePermission tree = findPermissionTreeLP(bp.name);
3172 if (tree != null) {
3173 bp.perm = new PackageParser.Permission(tree.perm.owner,
3174 new PermissionInfo(bp.pendingInfo));
3175 bp.perm.info.packageName = tree.perm.info.packageName;
3176 bp.perm.info.name = bp.name;
3177 bp.uid = tree.uid;
3178 }
3179 }
3180 }
3181 if (bp.perm == null) {
3182 Log.w(TAG, "Removing dangling permission: " + bp.name
3183 + " from package " + bp.sourcePackage);
3184 it.remove();
3185 }
3186 }
3187
3188 // Now update the permissions for all packages, in particular
3189 // replace the granted permissions of the system packages.
3190 for (PackageParser.Package pkg : mPackages.values()) {
3191 grantPermissionsLP(pkg, false);
3192 }
3193 }
3194
3195 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3196 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3197 if (ps == null) {
3198 return;
3199 }
3200 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3201 boolean addedPermission = false;
3202
3203 if (replace) {
3204 ps.permissionsFixed = false;
3205 if (gp == ps) {
3206 gp.grantedPermissions.clear();
3207 gp.gids = mGlobalGids;
3208 }
3209 }
3210
3211 if (gp.gids == null) {
3212 gp.gids = mGlobalGids;
3213 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07003214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 final int N = pkg.requestedPermissions.size();
3216 for (int i=0; i<N; i++) {
3217 String name = pkg.requestedPermissions.get(i);
3218 BasePermission bp = mSettings.mPermissions.get(name);
3219 PackageParser.Permission p = bp != null ? bp.perm : null;
3220 if (false) {
3221 if (gp != ps) {
3222 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3223 + ": " + p);
3224 }
3225 }
3226 if (p != null) {
3227 final String perm = p.info.name;
3228 boolean allowed;
3229 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3230 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3231 allowed = true;
3232 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3233 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003234 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003236 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 == PackageManager.SIGNATURE_MATCH);
3238 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3239 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3240 // For updated system applications, the signatureOrSystem permission
3241 // is granted only if it had been defined by the original application.
3242 if ((pkg.applicationInfo.flags
3243 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3244 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3245 if(sysPs.grantedPermissions.contains(perm)) {
3246 allowed = true;
3247 } else {
3248 allowed = false;
3249 }
3250 } else {
3251 allowed = true;
3252 }
3253 }
3254 }
3255 } else {
3256 allowed = false;
3257 }
3258 if (false) {
3259 if (gp != ps) {
3260 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3261 }
3262 }
3263 if (allowed) {
3264 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3265 && ps.permissionsFixed) {
3266 // If this is an existing, non-system package, then
3267 // we can't add any new permissions to it.
3268 if (!gp.loadedPermissions.contains(perm)) {
3269 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003270 // Except... if this is a permission that was added
3271 // to the platform (note: need to only do this when
3272 // updating the platform).
3273 final int NP = PackageParser.NEW_PERMISSIONS.length;
3274 for (int ip=0; ip<NP; ip++) {
3275 final PackageParser.NewPermissionInfo npi
3276 = PackageParser.NEW_PERMISSIONS[ip];
3277 if (npi.name.equals(perm)
3278 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3279 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003280 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003281 + pkg.packageName);
3282 break;
3283 }
3284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 }
3286 }
3287 if (allowed) {
3288 if (!gp.grantedPermissions.contains(perm)) {
3289 addedPermission = true;
3290 gp.grantedPermissions.add(perm);
3291 gp.gids = appendInts(gp.gids, bp.gids);
3292 }
3293 } else {
3294 Log.w(TAG, "Not granting permission " + perm
3295 + " to package " + pkg.packageName
3296 + " because it was previously installed without");
3297 }
3298 } else {
3299 Log.w(TAG, "Not granting permission " + perm
3300 + " to package " + pkg.packageName
3301 + " (protectionLevel=" + p.info.protectionLevel
3302 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3303 + ")");
3304 }
3305 } else {
3306 Log.w(TAG, "Unknown permission " + name
3307 + " in package " + pkg.packageName);
3308 }
3309 }
3310
3311 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003312 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3313 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 // This is the first that we have heard about this package, so the
3315 // permissions we have now selected are fixed until explicitly
3316 // changed.
3317 ps.permissionsFixed = true;
3318 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3319 }
3320 }
3321
3322 private final class ActivityIntentResolver
3323 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003324 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003326 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 }
3328
Mihai Preda074edef2009-05-18 17:13:31 +02003329 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003331 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3333 }
3334
Mihai Predaeae850c2009-05-13 10:13:48 +02003335 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3336 ArrayList<PackageParser.Activity> packageActivities) {
3337 if (packageActivities == null) {
3338 return null;
3339 }
3340 mFlags = flags;
3341 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3342 int N = packageActivities.size();
3343 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3344 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003345
3346 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003347 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003348 intentFilters = packageActivities.get(i).intents;
3349 if (intentFilters != null && intentFilters.size() > 0) {
3350 listCut.add(intentFilters);
3351 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003352 }
3353 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3354 }
3355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 public final void addActivity(PackageParser.Activity a, String type) {
3357 mActivities.put(a.component, a);
3358 if (SHOW_INFO || Config.LOGV) Log.v(
3359 TAG, " " + type + " " +
3360 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3361 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3362 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003363 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3365 if (SHOW_INFO || Config.LOGV) {
3366 Log.v(TAG, " IntentFilter:");
3367 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3368 }
3369 if (!intent.debugCheck()) {
3370 Log.w(TAG, "==> For Activity " + a.info.name);
3371 }
3372 addFilter(intent);
3373 }
3374 }
3375
3376 public final void removeActivity(PackageParser.Activity a, String type) {
3377 mActivities.remove(a.component);
3378 if (SHOW_INFO || Config.LOGV) Log.v(
3379 TAG, " " + type + " " +
3380 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3381 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3382 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003383 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3385 if (SHOW_INFO || Config.LOGV) {
3386 Log.v(TAG, " IntentFilter:");
3387 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3388 }
3389 removeFilter(intent);
3390 }
3391 }
3392
3393 @Override
3394 protected boolean allowFilterResult(
3395 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3396 ActivityInfo filterAi = filter.activity.info;
3397 for (int i=dest.size()-1; i>=0; i--) {
3398 ActivityInfo destAi = dest.get(i).activityInfo;
3399 if (destAi.name == filterAi.name
3400 && destAi.packageName == filterAi.packageName) {
3401 return false;
3402 }
3403 }
3404 return true;
3405 }
3406
3407 @Override
3408 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3409 int match) {
3410 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3411 return null;
3412 }
3413 final PackageParser.Activity activity = info.activity;
3414 if (mSafeMode && (activity.info.applicationInfo.flags
3415 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3416 return null;
3417 }
3418 final ResolveInfo res = new ResolveInfo();
3419 res.activityInfo = PackageParser.generateActivityInfo(activity,
3420 mFlags);
3421 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3422 res.filter = info;
3423 }
3424 res.priority = info.getPriority();
3425 res.preferredOrder = activity.owner.mPreferredOrder;
3426 //System.out.println("Result: " + res.activityInfo.className +
3427 // " = " + res.priority);
3428 res.match = match;
3429 res.isDefault = info.hasDefault;
3430 res.labelRes = info.labelRes;
3431 res.nonLocalizedLabel = info.nonLocalizedLabel;
3432 res.icon = info.icon;
3433 return res;
3434 }
3435
3436 @Override
3437 protected void sortResults(List<ResolveInfo> results) {
3438 Collections.sort(results, mResolvePrioritySorter);
3439 }
3440
3441 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003442 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003444 out.print(prefix); out.print(
3445 Integer.toHexString(System.identityHashCode(filter.activity)));
3446 out.print(' ');
3447 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
3449
3450// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3451// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3452// final List<ResolveInfo> retList = Lists.newArrayList();
3453// while (i.hasNext()) {
3454// final ResolveInfo resolveInfo = i.next();
3455// if (isEnabledLP(resolveInfo.activityInfo)) {
3456// retList.add(resolveInfo);
3457// }
3458// }
3459// return retList;
3460// }
3461
3462 // Keys are String (activity class name), values are Activity.
3463 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3464 = new HashMap<ComponentName, PackageParser.Activity>();
3465 private int mFlags;
3466 }
3467
3468 private final class ServiceIntentResolver
3469 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003470 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003472 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 }
3474
Mihai Preda074edef2009-05-18 17:13:31 +02003475 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003477 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3479 }
3480
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003481 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3482 ArrayList<PackageParser.Service> packageServices) {
3483 if (packageServices == null) {
3484 return null;
3485 }
3486 mFlags = flags;
3487 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3488 int N = packageServices.size();
3489 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3490 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3491
3492 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3493 for (int i = 0; i < N; ++i) {
3494 intentFilters = packageServices.get(i).intents;
3495 if (intentFilters != null && intentFilters.size() > 0) {
3496 listCut.add(intentFilters);
3497 }
3498 }
3499 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3500 }
3501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 public final void addService(PackageParser.Service s) {
3503 mServices.put(s.component, s);
3504 if (SHOW_INFO || Config.LOGV) Log.v(
3505 TAG, " " + (s.info.nonLocalizedLabel != null
3506 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3507 if (SHOW_INFO || Config.LOGV) Log.v(
3508 TAG, " Class=" + s.info.name);
3509 int NI = s.intents.size();
3510 int j;
3511 for (j=0; j<NI; j++) {
3512 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3513 if (SHOW_INFO || Config.LOGV) {
3514 Log.v(TAG, " IntentFilter:");
3515 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3516 }
3517 if (!intent.debugCheck()) {
3518 Log.w(TAG, "==> For Service " + s.info.name);
3519 }
3520 addFilter(intent);
3521 }
3522 }
3523
3524 public final void removeService(PackageParser.Service s) {
3525 mServices.remove(s.component);
3526 if (SHOW_INFO || Config.LOGV) Log.v(
3527 TAG, " " + (s.info.nonLocalizedLabel != null
3528 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3529 if (SHOW_INFO || Config.LOGV) Log.v(
3530 TAG, " Class=" + s.info.name);
3531 int NI = s.intents.size();
3532 int j;
3533 for (j=0; j<NI; j++) {
3534 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3535 if (SHOW_INFO || Config.LOGV) {
3536 Log.v(TAG, " IntentFilter:");
3537 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3538 }
3539 removeFilter(intent);
3540 }
3541 }
3542
3543 @Override
3544 protected boolean allowFilterResult(
3545 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3546 ServiceInfo filterSi = filter.service.info;
3547 for (int i=dest.size()-1; i>=0; i--) {
3548 ServiceInfo destAi = dest.get(i).serviceInfo;
3549 if (destAi.name == filterSi.name
3550 && destAi.packageName == filterSi.packageName) {
3551 return false;
3552 }
3553 }
3554 return true;
3555 }
3556
3557 @Override
3558 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3559 int match) {
3560 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3561 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3562 return null;
3563 }
3564 final PackageParser.Service service = info.service;
3565 if (mSafeMode && (service.info.applicationInfo.flags
3566 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3567 return null;
3568 }
3569 final ResolveInfo res = new ResolveInfo();
3570 res.serviceInfo = PackageParser.generateServiceInfo(service,
3571 mFlags);
3572 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3573 res.filter = filter;
3574 }
3575 res.priority = info.getPriority();
3576 res.preferredOrder = service.owner.mPreferredOrder;
3577 //System.out.println("Result: " + res.activityInfo.className +
3578 // " = " + res.priority);
3579 res.match = match;
3580 res.isDefault = info.hasDefault;
3581 res.labelRes = info.labelRes;
3582 res.nonLocalizedLabel = info.nonLocalizedLabel;
3583 res.icon = info.icon;
3584 return res;
3585 }
3586
3587 @Override
3588 protected void sortResults(List<ResolveInfo> results) {
3589 Collections.sort(results, mResolvePrioritySorter);
3590 }
3591
3592 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003593 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003595 out.print(prefix); out.print(
3596 Integer.toHexString(System.identityHashCode(filter.service)));
3597 out.print(' ');
3598 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 }
3600
3601// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3602// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3603// final List<ResolveInfo> retList = Lists.newArrayList();
3604// while (i.hasNext()) {
3605// final ResolveInfo resolveInfo = (ResolveInfo) i;
3606// if (isEnabledLP(resolveInfo.serviceInfo)) {
3607// retList.add(resolveInfo);
3608// }
3609// }
3610// return retList;
3611// }
3612
3613 // Keys are String (activity class name), values are Activity.
3614 private final HashMap<ComponentName, PackageParser.Service> mServices
3615 = new HashMap<ComponentName, PackageParser.Service>();
3616 private int mFlags;
3617 };
3618
3619 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3620 new Comparator<ResolveInfo>() {
3621 public int compare(ResolveInfo r1, ResolveInfo r2) {
3622 int v1 = r1.priority;
3623 int v2 = r2.priority;
3624 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3625 if (v1 != v2) {
3626 return (v1 > v2) ? -1 : 1;
3627 }
3628 v1 = r1.preferredOrder;
3629 v2 = r2.preferredOrder;
3630 if (v1 != v2) {
3631 return (v1 > v2) ? -1 : 1;
3632 }
3633 if (r1.isDefault != r2.isDefault) {
3634 return r1.isDefault ? -1 : 1;
3635 }
3636 v1 = r1.match;
3637 v2 = r2.match;
3638 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3639 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3640 }
3641 };
3642
3643 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3644 new Comparator<ProviderInfo>() {
3645 public int compare(ProviderInfo p1, ProviderInfo p2) {
3646 final int v1 = p1.initOrder;
3647 final int v2 = p2.initOrder;
3648 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3649 }
3650 };
3651
3652 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3653 IActivityManager am = ActivityManagerNative.getDefault();
3654 if (am != null) {
3655 try {
3656 final Intent intent = new Intent(action,
3657 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3658 if (extras != null) {
3659 intent.putExtras(extras);
3660 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003661 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 am.broadcastIntent(
3663 null, intent,
3664 null, null, 0, null, null, null, false, false);
3665 } catch (RemoteException ex) {
3666 }
3667 }
3668 }
3669
3670 private final class AppDirObserver extends FileObserver {
3671 public AppDirObserver(String path, int mask, boolean isrom) {
3672 super(path, mask);
3673 mRootDir = path;
3674 mIsRom = isrom;
3675 }
3676
3677 public void onEvent(int event, String path) {
3678 String removedPackage = null;
3679 int removedUid = -1;
3680 String addedPackage = null;
3681 int addedUid = -1;
3682
3683 synchronized (mInstallLock) {
3684 String fullPathStr = null;
3685 File fullPath = null;
3686 if (path != null) {
3687 fullPath = new File(mRootDir, path);
3688 fullPathStr = fullPath.getPath();
3689 }
3690
3691 if (Config.LOGV) Log.v(
3692 TAG, "File " + fullPathStr + " changed: "
3693 + Integer.toHexString(event));
3694
3695 if (!isPackageFilename(path)) {
3696 if (Config.LOGV) Log.v(
3697 TAG, "Ignoring change of non-package file: " + fullPathStr);
3698 return;
3699 }
3700
3701 if ((event&REMOVE_EVENTS) != 0) {
3702 synchronized (mInstallLock) {
3703 PackageParser.Package p = mAppDirs.get(fullPathStr);
3704 if (p != null) {
3705 removePackageLI(p, true);
3706 removedPackage = p.applicationInfo.packageName;
3707 removedUid = p.applicationInfo.uid;
3708 }
3709 }
3710 }
3711
3712 if ((event&ADD_EVENTS) != 0) {
3713 PackageParser.Package p = mAppDirs.get(fullPathStr);
3714 if (p == null) {
3715 p = scanPackageLI(fullPath, fullPath, fullPath,
3716 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3717 PackageParser.PARSE_CHATTY |
3718 PackageParser.PARSE_MUST_BE_APK,
3719 SCAN_MONITOR);
3720 if (p != null) {
3721 synchronized (mPackages) {
3722 grantPermissionsLP(p, false);
3723 }
3724 addedPackage = p.applicationInfo.packageName;
3725 addedUid = p.applicationInfo.uid;
3726 }
3727 }
3728 }
3729
3730 synchronized (mPackages) {
3731 mSettings.writeLP();
3732 }
3733 }
3734
3735 if (removedPackage != null) {
3736 Bundle extras = new Bundle(1);
3737 extras.putInt(Intent.EXTRA_UID, removedUid);
3738 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3739 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3740 }
3741 if (addedPackage != null) {
3742 Bundle extras = new Bundle(1);
3743 extras.putInt(Intent.EXTRA_UID, addedUid);
3744 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3745 }
3746 }
3747
3748 private final String mRootDir;
3749 private final boolean mIsRom;
3750 }
Jacek Surazski65e13172009-04-28 15:26:38 +02003751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 /* Called when a downloaded package installation has been confirmed by the user */
3753 public void installPackage(
3754 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003755 installPackage(packageURI, observer, flags, null);
3756 }
3757
3758 /* Called when a downloaded package installation has been confirmed by the user */
3759 public void installPackage(
3760 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3761 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 mContext.enforceCallingOrSelfPermission(
3763 android.Manifest.permission.INSTALL_PACKAGES, null);
Jacek Surazski65e13172009-04-28 15:26:38 +02003764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 // Queue up an async operation since the package installation may take a little while.
3766 mHandler.post(new Runnable() {
3767 public void run() {
3768 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003769 // Result object to be returned
3770 PackageInstalledInfo res = new PackageInstalledInfo();
3771 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3772 res.uid = -1;
3773 res.pkg = null;
3774 res.removedInfo = new PackageRemovedInfo();
3775 // Make a temporary copy of file from given packageURI
3776 File tmpPackageFile = copyTempInstallFile(packageURI, res);
3777 if (tmpPackageFile != null) {
3778 synchronized (mInstallLock) {
3779 installPackageLI(packageURI, flags, true, installerPackageName, tmpPackageFile, res);
3780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 }
3782 if (observer != null) {
3783 try {
3784 observer.packageInstalled(res.name, res.returnCode);
3785 } catch (RemoteException e) {
3786 Log.i(TAG, "Observer no longer exists.");
3787 }
3788 }
3789 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3790 // call appears in the synchronized block above.
3791 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3792 res.removedInfo.sendBroadcast(false, true);
3793 Bundle extras = new Bundle(1);
3794 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003795 final boolean update = res.removedInfo.removedPackage != null;
3796 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3798 }
3799 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3800 res.pkg.applicationInfo.packageName,
3801 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003802 if (update) {
3803 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3804 res.pkg.applicationInfo.packageName,
3805 extras);
3806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 }
3808 Runtime.getRuntime().gc();
3809 }
3810 });
3811 }
3812
3813 class PackageInstalledInfo {
3814 String name;
3815 int uid;
3816 PackageParser.Package pkg;
3817 int returnCode;
3818 PackageRemovedInfo removedInfo;
3819 }
3820
3821 /*
3822 * Install a non-existing package.
3823 */
3824 private void installNewPackageLI(String pkgName,
3825 File tmpPackageFile,
3826 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003827 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003828 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 // Remember this for later, in case we need to rollback this install
3830 boolean dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3831 res.name = pkgName;
3832 synchronized(mPackages) {
3833 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(destFilePath)) {
3834 // Don't allow installation over an existing package with the same name.
3835 Log.w(TAG, "Attempt to re-install " + pkgName
3836 + " without first uninstalling.");
3837 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3838 return;
3839 }
3840 }
3841 if (destPackageFile.exists()) {
3842 // It's safe to do this because we know (from the above check) that the file
3843 // isn't currently used for an installed package.
3844 destPackageFile.delete();
3845 }
3846 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3847 PackageParser.Package newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3848 destResourceFile, pkg, 0,
3849 SCAN_MONITOR | SCAN_FORCE_DEX
3850 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003851 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3852 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 if (newPackage == null) {
3854 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3855 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3856 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3857 }
3858 } else {
3859 updateSettingsLI(pkgName, tmpPackageFile,
3860 destFilePath, destPackageFile,
3861 destResourceFile, pkg,
3862 newPackage,
3863 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02003864 forwardLocked,
3865 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 res);
3867 // delete the partially installed application. the data directory will have to be
3868 // restored if it was already existing
3869 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3870 // remove package from internal structures. Note that we want deletePackageX to
3871 // delete the package data and cache directories that it created in
3872 // scanPackageLocked, unless those directories existed before we even tried to
3873 // install.
3874 deletePackageLI(
3875 pkgName, true,
3876 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3877 res.removedInfo);
3878 }
3879 }
3880 }
3881
3882 private void replacePackageLI(String pkgName,
3883 File tmpPackageFile,
3884 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003885 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003886 String installerPackageName, PackageInstalledInfo res) {
3887
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003888 PackageParser.Package oldPackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 // First find the old package info and check signatures
3890 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003891 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003892 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
3893 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3895 return;
3896 }
3897 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003898 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 if(sysPkg) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003900 replaceSystemPackageLI(oldPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003902 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003903 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 } else {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003905 replaceNonSystemPackageLI(oldPackage, tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003906 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003907 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
3910
3911 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
3912 File tmpPackageFile,
3913 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003914 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003915 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 PackageParser.Package newPackage = null;
3917 String pkgName = deletedPackage.packageName;
3918 boolean deletedPkg = true;
3919 boolean updatedSettings = false;
Jacek Surazski65e13172009-04-28 15:26:38 +02003920
3921 String oldInstallerPackageName = null;
3922 synchronized (mPackages) {
3923 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3924 }
3925
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003926 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 // First delete the existing package while retaining the data directory
3928 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3929 res.removedInfo)) {
3930 // If the existing package was'nt successfully deleted
3931 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3932 deletedPkg = false;
3933 } else {
3934 // Successfully deleted the old package. Now proceed with re-installation
3935 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3936 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3937 destResourceFile, pkg, parseFlags,
3938 SCAN_MONITOR | SCAN_FORCE_DEX
3939 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003940 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3941 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 if (newPackage == null) {
3943 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3944 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3945 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3946 }
3947 } else {
3948 updateSettingsLI(pkgName, tmpPackageFile,
3949 destFilePath, destPackageFile,
3950 destResourceFile, pkg,
3951 newPackage,
3952 true,
3953 forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003954 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 res);
3956 updatedSettings = true;
3957 }
3958 }
3959
3960 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3961 // If we deleted an exisiting package, the old source and resource files that we
3962 // were keeping around in case we needed them (see below) can now be deleted
3963 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
3964 final ApplicationInfo installedPackageAppInfo =
3965 newPackage.applicationInfo;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003966 deletePackageResourcesLI(pkgName,
3967 !deletedPackageAppInfo.sourceDir
3968 .equals(installedPackageAppInfo.sourceDir)
3969 ? deletedPackageAppInfo.sourceDir : null,
3970 !deletedPackageAppInfo.publicSourceDir
3971 .equals(installedPackageAppInfo.publicSourceDir)
3972 ? deletedPackageAppInfo.publicSourceDir : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 //update signature on the new package setting
3974 //this should always succeed, since we checked the
3975 //signature earlier.
3976 synchronized(mPackages) {
3977 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
3978 parseFlags, true);
3979 }
3980 } else {
3981 // remove package from internal structures. Note that we want deletePackageX to
3982 // delete the package data and cache directories that it created in
3983 // scanPackageLocked, unless those directories existed before we even tried to
3984 // install.
3985 if(updatedSettings) {
3986 deletePackageLI(
3987 pkgName, true,
3988 PackageManager.DONT_DELETE_DATA,
3989 res.removedInfo);
3990 }
3991 // Since we failed to install the new package we need to restore the old
3992 // package that we deleted.
3993 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003994 File restoreFile = new File(deletedPackage.mPath);
3995 if (restoreFile == null) {
3996 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
3997 return;
3998 }
3999 File restoreTmpFile = createTempPackageFile();
4000 if (restoreTmpFile == null) {
4001 Log.e(TAG, "Failed creating temp file when restoring pkg : " + pkgName);
4002 return;
4003 }
4004 if (!FileUtils.copyFile(restoreFile, restoreTmpFile)) {
4005 Log.e(TAG, "Failed copying temp file when restoring pkg : " + pkgName);
4006 return;
4007 }
4008 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4009 restoreRes.removedInfo = new PackageRemovedInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 installPackageLI(
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004011 Uri.fromFile(restoreFile),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004013 ? PackageManager.INSTALL_FORWARD_LOCK
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004014 : 0, false, oldInstallerPackageName, restoreTmpFile, restoreRes);
4015 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4016 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 }
4019 }
4020 }
4021
4022 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
4023 File tmpPackageFile,
4024 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07004025 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02004026 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 PackageParser.Package newPackage = null;
4028 boolean updatedSettings = false;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004029 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 PackageParser.PARSE_IS_SYSTEM;
4031 String packageName = deletedPackage.packageName;
4032 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4033 if (packageName == null) {
4034 Log.w(TAG, "Attempt to delete null packageName.");
4035 return;
4036 }
4037 PackageParser.Package oldPkg;
4038 PackageSetting oldPkgSetting;
4039 synchronized (mPackages) {
4040 oldPkg = mPackages.get(packageName);
4041 oldPkgSetting = mSettings.mPackages.get(packageName);
4042 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4043 (oldPkgSetting == null)) {
4044 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4045 return;
4046 }
4047 }
4048 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4049 res.removedInfo.removedPackage = packageName;
4050 // Remove existing system package
4051 removePackageLI(oldPkg, true);
4052 synchronized (mPackages) {
4053 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4054 }
4055
4056 // Successfully disabled the old package. Now proceed with re-installation
4057 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4058 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4059 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
4060 destResourceFile, pkg, parseFlags,
4061 SCAN_MONITOR | SCAN_FORCE_DEX
4062 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07004063 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
4064 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 if (newPackage == null) {
4066 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
4067 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4068 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4069 }
4070 } else {
4071 updateSettingsLI(packageName, tmpPackageFile,
4072 destFilePath, destPackageFile,
4073 destResourceFile, pkg,
4074 newPackage,
4075 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02004076 forwardLocked,
4077 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 res);
4079 updatedSettings = true;
4080 }
4081
4082 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4083 //update signature on the new package setting
4084 //this should always succeed, since we checked the
4085 //signature earlier.
4086 synchronized(mPackages) {
4087 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4088 parseFlags, true);
4089 }
4090 } else {
4091 // Re installation failed. Restore old information
4092 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004093 if (newPackage != null) {
4094 removePackageLI(newPackage, true);
4095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 // Add back the old system package
4097 scanPackageLI(oldPkgSetting.codePath, oldPkgSetting.codePath,
4098 oldPkgSetting.resourcePath,
4099 oldPkg, parseFlags,
4100 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004101 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 // Restore the old system information in Settings
4103 synchronized(mPackages) {
4104 if(updatedSettings) {
4105 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004106 mSettings.setInstallerPackageName(packageName,
4107 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 }
4109 mSettings.writeLP();
4110 }
4111 }
4112 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 private void updateSettingsLI(String pkgName, File tmpPackageFile,
4115 String destFilePath, File destPackageFile,
4116 File destResourceFile,
4117 PackageParser.Package pkg,
4118 PackageParser.Package newPackage,
4119 boolean replacingExistingPackage,
4120 boolean forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02004121 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 synchronized (mPackages) {
4123 //write settings. the installStatus will be incomplete at this stage.
4124 //note that the new package setting would have already been
4125 //added to mPackages. It hasn't been persisted yet.
4126 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4127 mSettings.writeLP();
4128 }
4129
4130 int retCode = 0;
4131 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4132 retCode = mInstaller.movedex(tmpPackageFile.toString(),
4133 destPackageFile.toString());
4134 if (retCode != 0) {
4135 Log.e(TAG, "Couldn't rename dex file: " + destPackageFile);
4136 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4137 return;
4138 }
4139 }
4140 // XXX There are probably some big issues here: upon doing
4141 // the rename, we have reached the point of no return (the
4142 // original .apk is gone!), so we can't fail. Yet... we can.
4143 if (!tmpPackageFile.renameTo(destPackageFile)) {
4144 Log.e(TAG, "Couldn't move package file to: " + destPackageFile);
4145 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4146 } else {
4147 res.returnCode = setPermissionsLI(pkgName, newPackage, destFilePath,
4148 destResourceFile,
4149 forwardLocked);
4150 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4151 return;
4152 } else {
4153 Log.d(TAG, "New package installed in " + destPackageFile);
4154 }
4155 }
4156 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4157 if (mInstaller != null) {
4158 mInstaller.rmdex(tmpPackageFile.getPath());
4159 }
4160 }
4161
4162 synchronized (mPackages) {
4163 grantPermissionsLP(newPackage, true);
4164 res.name = pkgName;
4165 res.uid = newPackage.applicationInfo.uid;
4166 res.pkg = newPackage;
4167 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004168 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4170 //to update install status
4171 mSettings.writeLP();
4172 }
4173 }
4174
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07004175 private File getFwdLockedResource(String pkgName) {
4176 final String publicZipFileName = pkgName + ".zip";
4177 return new File(mAppInstallDir, publicZipFileName);
4178 }
4179
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004180 private File copyTempInstallFile(Uri pPackageURI,
4181 PackageInstalledInfo res) {
4182 File tmpPackageFile = createTempPackageFile();
4183 int retCode = PackageManager.INSTALL_SUCCEEDED;
4184 if (tmpPackageFile == null) {
4185 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4186 return null;
4187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004189 if (pPackageURI.getScheme().equals("file")) {
4190 final File srcPackageFile = new File(pPackageURI.getPath());
4191 // We copy the source package file to a temp file and then rename it to the
4192 // destination file in order to eliminate a window where the package directory
4193 // scanner notices the new package file but it's not completely copied yet.
4194 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
4195 Log.e(TAG, "Couldn't copy package file to temp file.");
4196 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004198 } else if (pPackageURI.getScheme().equals("content")) {
4199 ParcelFileDescriptor fd = null;
4200 try {
4201 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
4202 } catch (FileNotFoundException e) {
4203 Log.e(TAG, "Couldn't open file descriptor from download service. Failed with exception " + e);
4204 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4205 }
4206 if (fd == null) {
4207 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
4208 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4209 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 if (Config.LOGV) {
4211 Log.v(TAG, "Opened file descriptor from download service.");
4212 }
4213 ParcelFileDescriptor.AutoCloseInputStream
4214 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
4215 // We copy the source package file to a temp file and then rename it to the
4216 // destination file in order to eliminate a window where the package directory
4217 // scanner notices the new package file but it's not completely copied yet.
4218 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
4219 Log.e(TAG, "Couldn't copy package stream to temp file.");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004220 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004223 } else {
4224 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
4225 retCode = PackageManager.INSTALL_FAILED_INVALID_URI;
4226 }
4227
4228 res.returnCode = retCode;
4229 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
4230 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4231 tmpPackageFile.delete();
4232 }
4233 return null;
4234 }
4235 return tmpPackageFile;
4236 }
4237
4238 private void installPackageLI(Uri pPackageURI,
4239 int pFlags, boolean newInstall, String installerPackageName,
4240 File tmpPackageFile, PackageInstalledInfo res) {
4241 String pkgName = null;
4242 boolean forwardLocked = false;
4243 boolean replacingExistingPackage = false;
4244 // Result object to be returned
4245 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4246
4247 main_flow: try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 pkgName = PackageParser.parsePackageName(
4249 tmpPackageFile.getAbsolutePath(), 0);
4250 if (pkgName == null) {
4251 Log.e(TAG, "Couldn't find a package name in : " + tmpPackageFile);
4252 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4253 break main_flow;
4254 }
4255 res.name = pkgName;
4256 //initialize some variables before installing pkg
4257 final String pkgFileName = pkgName + ".apk";
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004258 final File destDir = ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 ? mDrmAppPrivateInstallDir
4260 : mAppInstallDir;
4261 final File destPackageFile = new File(destDir, pkgFileName);
4262 final String destFilePath = destPackageFile.getAbsolutePath();
4263 File destResourceFile;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004264 if ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0) {
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07004265 destResourceFile = getFwdLockedResource(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 forwardLocked = true;
4267 } else {
4268 destResourceFile = destPackageFile;
4269 }
4270 // Retrieve PackageSettings and parse package
4271 int parseFlags = PackageParser.PARSE_CHATTY;
4272 parseFlags |= mDefParseFlags;
4273 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4274 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004275 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
4276 destPackageFile.getAbsolutePath(), mMetrics, parseFlags);
4277 if (pkg == null) {
4278 res.returnCode = pp.getParseError();
4279 break main_flow;
4280 }
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004281 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4282 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4283 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4284 break main_flow;
4285 }
4286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4288 res.returnCode = pp.getParseError();
4289 break main_flow;
4290 }
4291
4292 synchronized (mPackages) {
4293 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004294 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 && mPackages.containsKey(pkgName)) {
4296 replacingExistingPackage = true;
4297 }
4298 }
4299
4300 if(replacingExistingPackage) {
4301 replacePackageLI(pkgName,
4302 tmpPackageFile,
4303 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02004304 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 res);
4306 } else {
4307 installNewPackageLI(pkgName,
4308 tmpPackageFile,
4309 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02004310 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 res);
4312 }
4313 } finally {
4314 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4315 tmpPackageFile.delete();
4316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317 }
4318 }
4319
4320 private int setPermissionsLI(String pkgName,
4321 PackageParser.Package newPackage,
4322 String destFilePath,
4323 File destResourceFile,
4324 boolean forwardLocked) {
4325 int retCode;
4326 if (forwardLocked) {
4327 try {
4328 extractPublicFiles(newPackage, destResourceFile);
4329 } catch (IOException e) {
4330 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
4331 " forward-locked app.");
4332 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4333 } finally {
4334 //TODO clean up the extracted public files
4335 }
4336 if (mInstaller != null) {
4337 retCode = mInstaller.setForwardLockPerm(pkgName,
4338 newPackage.applicationInfo.uid);
4339 } else {
4340 final int filePermissions =
4341 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
4342 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1,
4343 newPackage.applicationInfo.uid);
4344 }
4345 } else {
4346 final int filePermissions =
4347 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4348 |FileUtils.S_IROTH;
4349 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1, -1);
4350 }
4351 if (retCode != 0) {
4352 Log.e(TAG, "Couldn't set new package file permissions for " + destFilePath
4353 + ". The return code was: " + retCode);
4354 }
4355 return PackageManager.INSTALL_SUCCEEDED;
4356 }
4357
4358 private boolean isForwardLocked(PackageParser.Package deletedPackage) {
4359 final ApplicationInfo applicationInfo = deletedPackage.applicationInfo;
4360 return applicationInfo.sourceDir.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath());
4361 }
4362
4363 private void extractPublicFiles(PackageParser.Package newPackage,
4364 File publicZipFile) throws IOException {
4365 final ZipOutputStream publicZipOutStream =
4366 new ZipOutputStream(new FileOutputStream(publicZipFile));
4367 final ZipFile privateZip = new ZipFile(newPackage.mPath);
4368
4369 // Copy manifest, resources.arsc and res directory to public zip
4370
4371 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
4372 while (privateZipEntries.hasMoreElements()) {
4373 final ZipEntry zipEntry = privateZipEntries.nextElement();
4374 final String zipEntryName = zipEntry.getName();
4375 if ("AndroidManifest.xml".equals(zipEntryName)
4376 || "resources.arsc".equals(zipEntryName)
4377 || zipEntryName.startsWith("res/")) {
4378 try {
4379 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
4380 } catch (IOException e) {
4381 try {
4382 publicZipOutStream.close();
4383 throw e;
4384 } finally {
4385 publicZipFile.delete();
4386 }
4387 }
4388 }
4389 }
4390
4391 publicZipOutStream.close();
4392 FileUtils.setPermissions(
4393 publicZipFile.getAbsolutePath(),
4394 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4395 -1, -1);
4396 }
4397
4398 private static void copyZipEntry(ZipEntry zipEntry,
4399 ZipFile inZipFile,
4400 ZipOutputStream outZipStream) throws IOException {
4401 byte[] buffer = new byte[4096];
4402 int num;
4403
4404 ZipEntry newEntry;
4405 if (zipEntry.getMethod() == ZipEntry.STORED) {
4406 // Preserve the STORED method of the input entry.
4407 newEntry = new ZipEntry(zipEntry);
4408 } else {
4409 // Create a new entry so that the compressed len is recomputed.
4410 newEntry = new ZipEntry(zipEntry.getName());
4411 }
4412 outZipStream.putNextEntry(newEntry);
4413
4414 InputStream data = inZipFile.getInputStream(zipEntry);
4415 while ((num = data.read(buffer)) > 0) {
4416 outZipStream.write(buffer, 0, num);
4417 }
4418 outZipStream.flush();
4419 }
4420
4421 private void deleteTempPackageFiles() {
4422 FilenameFilter filter = new FilenameFilter() {
4423 public boolean accept(File dir, String name) {
4424 return name.startsWith("vmdl") && name.endsWith(".tmp");
4425 }
4426 };
4427 String tmpFilesList[] = mAppInstallDir.list(filter);
4428 if(tmpFilesList == null) {
4429 return;
4430 }
4431 for(int i = 0; i < tmpFilesList.length; i++) {
4432 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4433 tmpFile.delete();
4434 }
4435 }
4436
4437 private File createTempPackageFile() {
4438 File tmpPackageFile;
4439 try {
4440 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
4441 } catch (IOException e) {
4442 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4443 return null;
4444 }
4445 try {
4446 FileUtils.setPermissions(
4447 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4448 -1, -1);
4449 } catch (IOException e) {
4450 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4451 return null;
4452 }
4453 return tmpPackageFile;
4454 }
4455
4456 public void deletePackage(final String packageName,
4457 final IPackageDeleteObserver observer,
4458 final int flags) {
4459 mContext.enforceCallingOrSelfPermission(
4460 android.Manifest.permission.DELETE_PACKAGES, null);
4461 // Queue up an async operation since the package deletion may take a little while.
4462 mHandler.post(new Runnable() {
4463 public void run() {
4464 mHandler.removeCallbacks(this);
4465 final boolean succeded = deletePackageX(packageName, true, true, flags);
4466 if (observer != null) {
4467 try {
4468 observer.packageDeleted(succeded);
4469 } catch (RemoteException e) {
4470 Log.i(TAG, "Observer no longer exists.");
4471 } //end catch
4472 } //end if
4473 } //end run
4474 });
4475 }
4476
4477 /**
4478 * This method is an internal method that could be get invoked either
4479 * to delete an installed package or to clean up a failed installation.
4480 * After deleting an installed package, a broadcast is sent to notify any
4481 * listeners that the package has been installed. For cleaning up a failed
4482 * installation, the broadcast is not necessary since the package's
4483 * installation wouldn't have sent the initial broadcast either
4484 * The key steps in deleting a package are
4485 * deleting the package information in internal structures like mPackages,
4486 * deleting the packages base directories through installd
4487 * updating mSettings to reflect current status
4488 * persisting settings for later use
4489 * sending a broadcast if necessary
4490 */
4491
4492 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4493 boolean deleteCodeAndResources, int flags) {
4494 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004495 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496
4497 synchronized (mInstallLock) {
4498 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4499 }
4500
4501 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004502 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4503 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4504
4505 // If the removed package was a system update, the old system packaged
4506 // was re-enabled; we need to broadcast this information
4507 if (systemUpdate) {
4508 Bundle extras = new Bundle(1);
4509 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4510 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4511
4512 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4513 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515 }
4516 return res;
4517 }
4518
4519 static class PackageRemovedInfo {
4520 String removedPackage;
4521 int uid = -1;
4522 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004523 boolean isRemovedPackageSystemUpdate = false;
4524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 void sendBroadcast(boolean fullRemove, boolean replacing) {
4526 Bundle extras = new Bundle(1);
4527 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4528 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4529 if (replacing) {
4530 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4531 }
4532 if (removedPackage != null) {
4533 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4534 }
4535 if (removedUid >= 0) {
4536 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4537 }
4538 }
4539 }
4540
4541 /*
4542 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4543 * flag is not set, the data directory is removed as well.
4544 * make sure this flag is set for partially installed apps. If not its meaningless to
4545 * delete a partially installed application.
4546 */
4547 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
4548 int flags) {
4549 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004550 if (outInfo != null) {
4551 outInfo.removedPackage = packageName;
4552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 removePackageLI(p, true);
4554 // Retrieve object to delete permissions for shared user later on
4555 PackageSetting deletedPs;
4556 synchronized (mPackages) {
4557 deletedPs = mSettings.mPackages.get(packageName);
4558 }
4559 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
4560 if (mInstaller != null) {
4561 int retCode = mInstaller.remove(packageName);
4562 if (retCode < 0) {
4563 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4564 + packageName + ", retcode=" + retCode);
4565 // we don't consider this to be a failure of the core package deletion
4566 }
4567 } else {
4568 //for emulator
4569 PackageParser.Package pkg = mPackages.get(packageName);
4570 File dataDir = new File(pkg.applicationInfo.dataDir);
4571 dataDir.delete();
4572 }
4573 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004574 if (outInfo != null) {
4575 outInfo.removedUid = mSettings.removePackageLP(packageName);
4576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 }
4578 }
4579 synchronized (mPackages) {
4580 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4581 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004582 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 }
4584 // Save settings now
4585 mSettings.writeLP ();
4586 }
4587 }
4588
4589 /*
4590 * Tries to delete system package.
4591 */
4592 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004593 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 ApplicationInfo applicationInfo = p.applicationInfo;
4595 //applicable for non-partially installed applications only
4596 if (applicationInfo == null) {
4597 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4598 return false;
4599 }
4600 PackageSetting ps = null;
4601 // Confirm if the system package has been updated
4602 // An updated system app can be deleted. This will also have to restore
4603 // the system pkg from system partition
4604 synchronized (mPackages) {
4605 ps = mSettings.getDisabledSystemPkg(p.packageName);
4606 }
4607 if (ps == null) {
4608 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4609 return false;
4610 } else {
4611 Log.i(TAG, "Deleting system pkg from data partition");
4612 }
4613 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004614 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004615 boolean deleteCodeAndResources = false;
4616 if (ps.versionCode < p.mVersionCode) {
4617 // Delete code and resources for downgrades
4618 deleteCodeAndResources = true;
4619 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4620 flags &= ~PackageManager.DONT_DELETE_DATA;
4621 }
4622 } else {
4623 // Preserve data by setting flag
4624 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4625 flags |= PackageManager.DONT_DELETE_DATA;
4626 }
4627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4629 if (!ret) {
4630 return false;
4631 }
4632 synchronized (mPackages) {
4633 // Reinstate the old system package
4634 mSettings.enableSystemPackageLP(p.packageName);
4635 }
4636 // Install the system package
4637 PackageParser.Package newPkg = scanPackageLI(ps.codePath, ps.codePath, ps.resourcePath,
4638 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
4639 SCAN_MONITOR);
4640
4641 if (newPkg == null) {
4642 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4643 return false;
4644 }
4645 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07004646 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647 mSettings.writeLP();
4648 }
4649 return true;
4650 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004651
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004652 private void deletePackageResourcesLI(String packageName,
4653 String sourceDir, String publicSourceDir) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004654 if (sourceDir != null) {
4655 File sourceFile = new File(sourceDir);
4656 if (!sourceFile.exists()) {
4657 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4658 }
4659 // Delete application's code and resources
4660 sourceFile.delete();
4661 if (mInstaller != null) {
4662 int retCode = mInstaller.rmdex(sourceFile.toString());
4663 if (retCode < 0) {
4664 Log.w(TAG, "Couldn't remove dex file for package: "
4665 + packageName + " at location "
4666 + sourceFile.toString() + ", retcode=" + retCode);
4667 // we don't consider this to be a failure of the core package deletion
4668 }
4669 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004670 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004671 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4672 final File publicSourceFile = new File(publicSourceDir);
4673 if (!publicSourceFile.exists()) {
4674 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4675 }
4676 if (publicSourceFile.exists()) {
4677 publicSourceFile.delete();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004678 }
4679 }
4680 }
4681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4683 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4684 ApplicationInfo applicationInfo = p.applicationInfo;
4685 if (applicationInfo == null) {
4686 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4687 return false;
4688 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004689 if (outInfo != null) {
4690 outInfo.uid = applicationInfo.uid;
4691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692
4693 // Delete package data from internal structures and also remove data if flag is set
4694 removePackageDataLI(p, outInfo, flags);
4695
4696 // Delete application code and resources
4697 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004698 deletePackageResourcesLI(applicationInfo.packageName,
4699 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 }
4701 return true;
4702 }
4703
4704 /*
4705 * This method handles package deletion in general
4706 */
4707 private boolean deletePackageLI(String packageName,
4708 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4709 if (packageName == null) {
4710 Log.w(TAG, "Attempt to delete null packageName.");
4711 return false;
4712 }
4713 PackageParser.Package p;
4714 boolean dataOnly = false;
4715 synchronized (mPackages) {
4716 p = mPackages.get(packageName);
4717 if (p == null) {
4718 //this retrieves partially installed apps
4719 dataOnly = true;
4720 PackageSetting ps = mSettings.mPackages.get(packageName);
4721 if (ps == null) {
4722 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4723 return false;
4724 }
4725 p = ps.pkg;
4726 }
4727 }
4728 if (p == null) {
4729 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4730 return false;
4731 }
4732
4733 if (dataOnly) {
4734 // Delete application data first
4735 removePackageDataLI(p, outInfo, flags);
4736 return true;
4737 }
4738 // At this point the package should have ApplicationInfo associated with it
4739 if (p.applicationInfo == null) {
4740 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4741 return false;
4742 }
4743 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4744 Log.i(TAG, "Removing system package:"+p.packageName);
4745 // When an updated system application is deleted we delete the existing resources as well and
4746 // fall back to existing code in system partition
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004747 return deleteSystemPackageLI(p, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 }
4749 Log.i(TAG, "Removing non-system package:"+p.packageName);
4750 return deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
4751 }
4752
4753 public void clearApplicationUserData(final String packageName,
4754 final IPackageDataObserver observer) {
4755 mContext.enforceCallingOrSelfPermission(
4756 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4757 // Queue up an async operation since the package deletion may take a little while.
4758 mHandler.post(new Runnable() {
4759 public void run() {
4760 mHandler.removeCallbacks(this);
4761 final boolean succeeded;
4762 synchronized (mInstallLock) {
4763 succeeded = clearApplicationUserDataLI(packageName);
4764 }
4765 if (succeeded) {
4766 // invoke DeviceStorageMonitor's update method to clear any notifications
4767 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4768 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4769 if (dsm != null) {
4770 dsm.updateMemory();
4771 }
4772 }
4773 if(observer != null) {
4774 try {
4775 observer.onRemoveCompleted(packageName, succeeded);
4776 } catch (RemoteException e) {
4777 Log.i(TAG, "Observer no longer exists.");
4778 }
4779 } //end if observer
4780 } //end run
4781 });
4782 }
4783
4784 private boolean clearApplicationUserDataLI(String packageName) {
4785 if (packageName == null) {
4786 Log.w(TAG, "Attempt to delete null packageName.");
4787 return false;
4788 }
4789 PackageParser.Package p;
4790 boolean dataOnly = false;
4791 synchronized (mPackages) {
4792 p = mPackages.get(packageName);
4793 if(p == null) {
4794 dataOnly = true;
4795 PackageSetting ps = mSettings.mPackages.get(packageName);
4796 if((ps == null) || (ps.pkg == null)) {
4797 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4798 return false;
4799 }
4800 p = ps.pkg;
4801 }
4802 }
4803 if(!dataOnly) {
4804 //need to check this only for fully installed applications
4805 if (p == null) {
4806 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4807 return false;
4808 }
4809 final ApplicationInfo applicationInfo = p.applicationInfo;
4810 if (applicationInfo == null) {
4811 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4812 return false;
4813 }
4814 }
4815 if (mInstaller != null) {
4816 int retCode = mInstaller.clearUserData(packageName);
4817 if (retCode < 0) {
4818 Log.w(TAG, "Couldn't remove cache files for package: "
4819 + packageName);
4820 return false;
4821 }
4822 }
4823 return true;
4824 }
4825
4826 public void deleteApplicationCacheFiles(final String packageName,
4827 final IPackageDataObserver observer) {
4828 mContext.enforceCallingOrSelfPermission(
4829 android.Manifest.permission.DELETE_CACHE_FILES, null);
4830 // Queue up an async operation since the package deletion may take a little while.
4831 mHandler.post(new Runnable() {
4832 public void run() {
4833 mHandler.removeCallbacks(this);
4834 final boolean succeded;
4835 synchronized (mInstallLock) {
4836 succeded = deleteApplicationCacheFilesLI(packageName);
4837 }
4838 if(observer != null) {
4839 try {
4840 observer.onRemoveCompleted(packageName, succeded);
4841 } catch (RemoteException e) {
4842 Log.i(TAG, "Observer no longer exists.");
4843 }
4844 } //end if observer
4845 } //end run
4846 });
4847 }
4848
4849 private boolean deleteApplicationCacheFilesLI(String packageName) {
4850 if (packageName == null) {
4851 Log.w(TAG, "Attempt to delete null packageName.");
4852 return false;
4853 }
4854 PackageParser.Package p;
4855 synchronized (mPackages) {
4856 p = mPackages.get(packageName);
4857 }
4858 if (p == null) {
4859 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4860 return false;
4861 }
4862 final ApplicationInfo applicationInfo = p.applicationInfo;
4863 if (applicationInfo == null) {
4864 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4865 return false;
4866 }
4867 if (mInstaller != null) {
4868 int retCode = mInstaller.deleteCacheFiles(packageName);
4869 if (retCode < 0) {
4870 Log.w(TAG, "Couldn't remove cache files for package: "
4871 + packageName);
4872 return false;
4873 }
4874 }
4875 return true;
4876 }
4877
4878 public void getPackageSizeInfo(final String packageName,
4879 final IPackageStatsObserver observer) {
4880 mContext.enforceCallingOrSelfPermission(
4881 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4882 // Queue up an async operation since the package deletion may take a little while.
4883 mHandler.post(new Runnable() {
4884 public void run() {
4885 mHandler.removeCallbacks(this);
4886 PackageStats lStats = new PackageStats(packageName);
4887 final boolean succeded;
4888 synchronized (mInstallLock) {
4889 succeded = getPackageSizeInfoLI(packageName, lStats);
4890 }
4891 if(observer != null) {
4892 try {
4893 observer.onGetStatsCompleted(lStats, succeded);
4894 } catch (RemoteException e) {
4895 Log.i(TAG, "Observer no longer exists.");
4896 }
4897 } //end if observer
4898 } //end run
4899 });
4900 }
4901
4902 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4903 if (packageName == null) {
4904 Log.w(TAG, "Attempt to get size of null packageName.");
4905 return false;
4906 }
4907 PackageParser.Package p;
4908 boolean dataOnly = false;
4909 synchronized (mPackages) {
4910 p = mPackages.get(packageName);
4911 if(p == null) {
4912 dataOnly = true;
4913 PackageSetting ps = mSettings.mPackages.get(packageName);
4914 if((ps == null) || (ps.pkg == null)) {
4915 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4916 return false;
4917 }
4918 p = ps.pkg;
4919 }
4920 }
4921 String publicSrcDir = null;
4922 if(!dataOnly) {
4923 final ApplicationInfo applicationInfo = p.applicationInfo;
4924 if (applicationInfo == null) {
4925 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4926 return false;
4927 }
4928 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4929 }
4930 if (mInstaller != null) {
4931 int res = mInstaller.getSizeInfo(packageName, p.mPath,
4932 publicSrcDir, pStats);
4933 if (res < 0) {
4934 return false;
4935 } else {
4936 return true;
4937 }
4938 }
4939 return true;
4940 }
4941
4942
4943 public void addPackageToPreferred(String packageName) {
4944 mContext.enforceCallingOrSelfPermission(
4945 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004946 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004947 }
4948
4949 public void removePackageFromPreferred(String packageName) {
4950 mContext.enforceCallingOrSelfPermission(
4951 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004952 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 }
4954
4955 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004956 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 }
4958
4959 public void addPreferredActivity(IntentFilter filter, int match,
4960 ComponentName[] set, ComponentName activity) {
4961 mContext.enforceCallingOrSelfPermission(
4962 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4963
4964 synchronized (mPackages) {
4965 Log.i(TAG, "Adding preferred activity " + activity + ":");
4966 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4967 mSettings.mPreferredActivities.addFilter(
4968 new PreferredActivity(filter, match, set, activity));
4969 mSettings.writeLP();
4970 }
4971 }
4972
Satish Sampath8dbe6122009-06-02 23:35:54 +01004973 public void replacePreferredActivity(IntentFilter filter, int match,
4974 ComponentName[] set, ComponentName activity) {
4975 mContext.enforceCallingOrSelfPermission(
4976 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4977 if (filter.countActions() != 1) {
4978 throw new IllegalArgumentException(
4979 "replacePreferredActivity expects filter to have only 1 action.");
4980 }
4981 if (filter.countCategories() != 1) {
4982 throw new IllegalArgumentException(
4983 "replacePreferredActivity expects filter to have only 1 category.");
4984 }
4985 if (filter.countDataAuthorities() != 0
4986 || filter.countDataPaths() != 0
4987 || filter.countDataSchemes() != 0
4988 || filter.countDataTypes() != 0) {
4989 throw new IllegalArgumentException(
4990 "replacePreferredActivity expects filter to have no data authorities, " +
4991 "paths, schemes or types.");
4992 }
4993 synchronized (mPackages) {
4994 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4995 String action = filter.getAction(0);
4996 String category = filter.getCategory(0);
4997 while (it.hasNext()) {
4998 PreferredActivity pa = it.next();
4999 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5000 it.remove();
5001 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5002 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5003 }
5004 }
5005 addPreferredActivity(filter, match, set, activity);
5006 }
5007 }
5008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005009 public void clearPackagePreferredActivities(String packageName) {
5010 mContext.enforceCallingOrSelfPermission(
5011 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5012
5013 synchronized (mPackages) {
5014 if (clearPackagePreferredActivitiesLP(packageName)) {
5015 mSettings.writeLP();
5016 }
5017 }
5018 }
5019
5020 boolean clearPackagePreferredActivitiesLP(String packageName) {
5021 boolean changed = false;
5022 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5023 while (it.hasNext()) {
5024 PreferredActivity pa = it.next();
5025 if (pa.mActivity.getPackageName().equals(packageName)) {
5026 it.remove();
5027 changed = true;
5028 }
5029 }
5030 return changed;
5031 }
5032
5033 public int getPreferredActivities(List<IntentFilter> outFilters,
5034 List<ComponentName> outActivities, String packageName) {
5035
5036 int num = 0;
5037 synchronized (mPackages) {
5038 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5039 while (it.hasNext()) {
5040 PreferredActivity pa = it.next();
5041 if (packageName == null
5042 || pa.mActivity.getPackageName().equals(packageName)) {
5043 if (outFilters != null) {
5044 outFilters.add(new IntentFilter(pa));
5045 }
5046 if (outActivities != null) {
5047 outActivities.add(pa.mActivity);
5048 }
5049 }
5050 }
5051 }
5052
5053 return num;
5054 }
5055
5056 public void setApplicationEnabledSetting(String appPackageName,
5057 int newState, int flags) {
5058 setEnabledSetting(appPackageName, null, newState, flags);
5059 }
5060
5061 public void setComponentEnabledSetting(ComponentName componentName,
5062 int newState, int flags) {
5063 setEnabledSetting(componentName.getPackageName(),
5064 componentName.getClassName(), newState, flags);
5065 }
5066
5067 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005068 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5070 || newState == COMPONENT_ENABLED_STATE_ENABLED
5071 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5072 throw new IllegalArgumentException("Invalid new component state: "
5073 + newState);
5074 }
5075 PackageSetting pkgSetting;
5076 final int uid = Binder.getCallingUid();
5077 final int permission = mContext.checkCallingPermission(
5078 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5079 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005080 boolean sendNow = false;
5081 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005082 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005083 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005084 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005085 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005086 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005087 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005088 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005090 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091 }
5092 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005093 "Unknown component: " + packageName
5094 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005095 }
5096 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5097 throw new SecurityException(
5098 "Permission Denial: attempt to change component state from pid="
5099 + Binder.getCallingPid()
5100 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5101 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005102 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005103 // We're dealing with an application/package level state change
5104 pkgSetting.enabled = newState;
5105 } else {
5106 // We're dealing with a component level state change
5107 switch (newState) {
5108 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005109 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005110 break;
5111 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005112 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005113 break;
5114 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005115 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 break;
5117 default:
5118 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005119 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005120 }
5121 }
5122 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005123 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005124 components = mPendingBroadcasts.get(packageName);
5125 boolean newPackage = components == null;
5126 if (newPackage) {
5127 components = new ArrayList<String>();
5128 }
5129 if (!components.contains(componentName)) {
5130 components.add(componentName);
5131 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005132 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5133 sendNow = true;
5134 // Purge entry from pending broadcast list if another one exists already
5135 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005136 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005137 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005138 if (newPackage) {
5139 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005140 }
5141 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5142 // Schedule a message
5143 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5144 }
5145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 long callingId = Binder.clearCallingIdentity();
5149 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005150 if (sendNow) {
5151 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005152 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005154 } finally {
5155 Binder.restoreCallingIdentity(callingId);
5156 }
5157 }
5158
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005159 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005160 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5161 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5162 + " components=" + componentNames);
5163 Bundle extras = new Bundle(4);
5164 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5165 String nameList[] = new String[componentNames.size()];
5166 componentNames.toArray(nameList);
5167 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005168 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5169 extras.putInt(Intent.EXTRA_UID, packageUid);
5170 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
5171 }
5172
Jacek Surazski65e13172009-04-28 15:26:38 +02005173 public String getInstallerPackageName(String packageName) {
5174 synchronized (mPackages) {
5175 PackageSetting pkg = mSettings.mPackages.get(packageName);
5176 if (pkg == null) {
5177 throw new IllegalArgumentException("Unknown package: " + packageName);
5178 }
5179 return pkg.installerPackageName;
5180 }
5181 }
5182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005183 public int getApplicationEnabledSetting(String appPackageName) {
5184 synchronized (mPackages) {
5185 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5186 if (pkg == null) {
5187 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5188 }
5189 return pkg.enabled;
5190 }
5191 }
5192
5193 public int getComponentEnabledSetting(ComponentName componentName) {
5194 synchronized (mPackages) {
5195 final String packageNameStr = componentName.getPackageName();
5196 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5197 if (pkg == null) {
5198 throw new IllegalArgumentException("Unknown component: " + componentName);
5199 }
5200 final String classNameStr = componentName.getClassName();
5201 return pkg.currentEnabledStateLP(classNameStr);
5202 }
5203 }
5204
5205 public void enterSafeMode() {
5206 if (!mSystemReady) {
5207 mSafeMode = true;
5208 }
5209 }
5210
5211 public void systemReady() {
5212 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005213
5214 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005215 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005216 mContext.getContentResolver(),
5217 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005218 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005219 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005220 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 }
5223
5224 public boolean isSafeMode() {
5225 return mSafeMode;
5226 }
5227
5228 public boolean hasSystemUidErrors() {
5229 return mHasSystemUidErrors;
5230 }
5231
5232 static String arrayToString(int[] array) {
5233 StringBuffer buf = new StringBuffer(128);
5234 buf.append('[');
5235 if (array != null) {
5236 for (int i=0; i<array.length; i++) {
5237 if (i > 0) buf.append(", ");
5238 buf.append(array[i]);
5239 }
5240 }
5241 buf.append(']');
5242 return buf.toString();
5243 }
5244
5245 @Override
5246 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5247 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5248 != PackageManager.PERMISSION_GRANTED) {
5249 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5250 + Binder.getCallingPid()
5251 + ", uid=" + Binder.getCallingUid()
5252 + " without permission "
5253 + android.Manifest.permission.DUMP);
5254 return;
5255 }
5256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 synchronized (mPackages) {
5258 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005259 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 pw.println(" ");
5261 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005262 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 pw.println(" ");
5264 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005265 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005266 pw.println(" ");
5267 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005268 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 pw.println("Permissions:");
5271 {
5272 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005273 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5274 pw.print(Integer.toHexString(System.identityHashCode(p)));
5275 pw.println("):");
5276 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5277 pw.print(" uid="); pw.print(p.uid);
5278 pw.print(" gids="); pw.print(arrayToString(p.gids));
5279 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005280 }
5281 }
5282 pw.println(" ");
5283 pw.println("Packages:");
5284 {
5285 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005286 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5287 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5288 pw.println("):");
5289 pw.print(" userId="); pw.print(ps.userId);
5290 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5291 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5292 pw.print(" pkg="); pw.println(ps.pkg);
5293 pw.print(" codePath="); pw.println(ps.codePathString);
5294 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005295 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005296 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005297 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005298 pw.print(" supportsScreens=[");
5299 boolean first = true;
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005300 if ((ps.pkg.applicationInfo.flags &
5301 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005302 if (!first) pw.print(", ");
5303 first = false;
5304 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005305 }
5306 if ((ps.pkg.applicationInfo.flags &
5307 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005308 if (!first) pw.print(", ");
5309 first = false;
5310 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005311 }
5312 if ((ps.pkg.applicationInfo.flags &
5313 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005314 if (!first) pw.print(", ");
5315 first = false;
5316 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005317 }
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005318 if ((ps.pkg.applicationInfo.flags &
5319 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005320 if (!first) pw.print(", ");
5321 first = false;
5322 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005323 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005324 if ((ps.pkg.applicationInfo.flags &
5325 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
5326 if (!first) pw.print(", ");
5327 first = false;
5328 pw.print("anyDensity");
5329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005330 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005331 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005332 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
5333 pw.print(" signatures="); pw.println(ps.signatures);
5334 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
5335 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
5336 pw.print(" installStatus="); pw.print(ps.installStatus);
5337 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005338 if (ps.disabledComponents.size() > 0) {
5339 pw.println(" disabledComponents:");
5340 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005341 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342 }
5343 }
5344 if (ps.enabledComponents.size() > 0) {
5345 pw.println(" enabledComponents:");
5346 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005347 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005348 }
5349 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005350 if (ps.grantedPermissions.size() > 0) {
5351 pw.println(" grantedPermissions:");
5352 for (String s : ps.grantedPermissions) {
5353 pw.print(" "); pw.println(s);
5354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005355 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005356 if (ps.loadedPermissions.size() > 0) {
5357 pw.println(" loadedPermissions:");
5358 for (String s : ps.loadedPermissions) {
5359 pw.print(" "); pw.println(s);
5360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 }
5362 }
5363 }
5364 pw.println(" ");
5365 pw.println("Shared Users:");
5366 {
5367 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005368 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5369 pw.print(Integer.toHexString(System.identityHashCode(su)));
5370 pw.println("):");
5371 pw.print(" userId="); pw.print(su.userId);
5372 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005373 pw.println(" grantedPermissions:");
5374 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005375 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005376 }
5377 pw.println(" loadedPermissions:");
5378 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005379 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 }
5381 }
5382 }
5383 pw.println(" ");
5384 pw.println("Settings parse messages:");
5385 pw.println(mSettings.mReadMessages.toString());
5386 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05005387
5388 synchronized (mProviders) {
5389 pw.println(" ");
5390 pw.println("Registered ContentProviders:");
5391 for (PackageParser.Provider p : mProviders.values()) {
5392 pw.println(" ["); pw.println(p.info.authority); pw.println("]: ");
5393 pw.println(p.toString());
5394 }
5395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005396 }
5397
5398 static final class BasePermission {
5399 final static int TYPE_NORMAL = 0;
5400 final static int TYPE_BUILTIN = 1;
5401 final static int TYPE_DYNAMIC = 2;
5402
5403 final String name;
5404 final String sourcePackage;
5405 final int type;
5406 PackageParser.Permission perm;
5407 PermissionInfo pendingInfo;
5408 int uid;
5409 int[] gids;
5410
5411 BasePermission(String _name, String _sourcePackage, int _type) {
5412 name = _name;
5413 sourcePackage = _sourcePackage;
5414 type = _type;
5415 }
5416 }
5417
5418 static class PackageSignatures {
5419 private Signature[] mSignatures;
5420
5421 PackageSignatures(Signature[] sigs) {
5422 assignSignatures(sigs);
5423 }
5424
5425 PackageSignatures() {
5426 }
5427
5428 void writeXml(XmlSerializer serializer, String tagName,
5429 ArrayList<Signature> pastSignatures) throws IOException {
5430 if (mSignatures == null) {
5431 return;
5432 }
5433 serializer.startTag(null, tagName);
5434 serializer.attribute(null, "count",
5435 Integer.toString(mSignatures.length));
5436 for (int i=0; i<mSignatures.length; i++) {
5437 serializer.startTag(null, "cert");
5438 final Signature sig = mSignatures[i];
5439 final int sigHash = sig.hashCode();
5440 final int numPast = pastSignatures.size();
5441 int j;
5442 for (j=0; j<numPast; j++) {
5443 Signature pastSig = pastSignatures.get(j);
5444 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5445 serializer.attribute(null, "index", Integer.toString(j));
5446 break;
5447 }
5448 }
5449 if (j >= numPast) {
5450 pastSignatures.add(sig);
5451 serializer.attribute(null, "index", Integer.toString(numPast));
5452 serializer.attribute(null, "key", sig.toCharsString());
5453 }
5454 serializer.endTag(null, "cert");
5455 }
5456 serializer.endTag(null, tagName);
5457 }
5458
5459 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5460 throws IOException, XmlPullParserException {
5461 String countStr = parser.getAttributeValue(null, "count");
5462 if (countStr == null) {
5463 reportSettingsProblem(Log.WARN,
5464 "Error in package manager settings: <signatures> has"
5465 + " no count at " + parser.getPositionDescription());
5466 XmlUtils.skipCurrentTag(parser);
5467 }
5468 final int count = Integer.parseInt(countStr);
5469 mSignatures = new Signature[count];
5470 int pos = 0;
5471
5472 int outerDepth = parser.getDepth();
5473 int type;
5474 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5475 && (type != XmlPullParser.END_TAG
5476 || parser.getDepth() > outerDepth)) {
5477 if (type == XmlPullParser.END_TAG
5478 || type == XmlPullParser.TEXT) {
5479 continue;
5480 }
5481
5482 String tagName = parser.getName();
5483 if (tagName.equals("cert")) {
5484 if (pos < count) {
5485 String index = parser.getAttributeValue(null, "index");
5486 if (index != null) {
5487 try {
5488 int idx = Integer.parseInt(index);
5489 String key = parser.getAttributeValue(null, "key");
5490 if (key == null) {
5491 if (idx >= 0 && idx < pastSignatures.size()) {
5492 Signature sig = pastSignatures.get(idx);
5493 if (sig != null) {
5494 mSignatures[pos] = pastSignatures.get(idx);
5495 pos++;
5496 } else {
5497 reportSettingsProblem(Log.WARN,
5498 "Error in package manager settings: <cert> "
5499 + "index " + index + " is not defined at "
5500 + parser.getPositionDescription());
5501 }
5502 } else {
5503 reportSettingsProblem(Log.WARN,
5504 "Error in package manager settings: <cert> "
5505 + "index " + index + " is out of bounds at "
5506 + parser.getPositionDescription());
5507 }
5508 } else {
5509 while (pastSignatures.size() <= idx) {
5510 pastSignatures.add(null);
5511 }
5512 Signature sig = new Signature(key);
5513 pastSignatures.set(idx, sig);
5514 mSignatures[pos] = sig;
5515 pos++;
5516 }
5517 } catch (NumberFormatException e) {
5518 reportSettingsProblem(Log.WARN,
5519 "Error in package manager settings: <cert> "
5520 + "index " + index + " is not a number at "
5521 + parser.getPositionDescription());
5522 }
5523 } else {
5524 reportSettingsProblem(Log.WARN,
5525 "Error in package manager settings: <cert> has"
5526 + " no index at " + parser.getPositionDescription());
5527 }
5528 } else {
5529 reportSettingsProblem(Log.WARN,
5530 "Error in package manager settings: too "
5531 + "many <cert> tags, expected " + count
5532 + " at " + parser.getPositionDescription());
5533 }
5534 } else {
5535 reportSettingsProblem(Log.WARN,
5536 "Unknown element under <cert>: "
5537 + parser.getName());
5538 }
5539 XmlUtils.skipCurrentTag(parser);
5540 }
5541
5542 if (pos < count) {
5543 // Should never happen -- there is an error in the written
5544 // settings -- but if it does we don't want to generate
5545 // a bad array.
5546 Signature[] newSigs = new Signature[pos];
5547 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5548 mSignatures = newSigs;
5549 }
5550 }
5551
5552 /**
5553 * If any of the given 'sigs' is contained in the existing signatures,
5554 * then completely replace the current signatures with the ones in
5555 * 'sigs'. This is used for updating an existing package to a newly
5556 * installed version.
5557 */
5558 boolean updateSignatures(Signature[] sigs, boolean update) {
5559 if (mSignatures == null) {
5560 if (update) {
5561 assignSignatures(sigs);
5562 }
5563 return true;
5564 }
5565 if (sigs == null) {
5566 return false;
5567 }
5568
5569 for (int i=0; i<sigs.length; i++) {
5570 Signature sig = sigs[i];
5571 for (int j=0; j<mSignatures.length; j++) {
5572 if (mSignatures[j].equals(sig)) {
5573 if (update) {
5574 assignSignatures(sigs);
5575 }
5576 return true;
5577 }
5578 }
5579 }
5580 return false;
5581 }
5582
5583 /**
5584 * If any of the given 'sigs' is contained in the existing signatures,
5585 * then add in any new signatures found in 'sigs'. This is used for
5586 * including a new package into an existing shared user id.
5587 */
5588 boolean mergeSignatures(Signature[] sigs, boolean update) {
5589 if (mSignatures == null) {
5590 if (update) {
5591 assignSignatures(sigs);
5592 }
5593 return true;
5594 }
5595 if (sigs == null) {
5596 return false;
5597 }
5598
5599 Signature[] added = null;
5600 int addedCount = 0;
5601 boolean haveMatch = false;
5602 for (int i=0; i<sigs.length; i++) {
5603 Signature sig = sigs[i];
5604 boolean found = false;
5605 for (int j=0; j<mSignatures.length; j++) {
5606 if (mSignatures[j].equals(sig)) {
5607 found = true;
5608 haveMatch = true;
5609 break;
5610 }
5611 }
5612
5613 if (!found) {
5614 if (added == null) {
5615 added = new Signature[sigs.length];
5616 }
5617 added[i] = sig;
5618 addedCount++;
5619 }
5620 }
5621
5622 if (!haveMatch) {
5623 // Nothing matched -- reject the new signatures.
5624 return false;
5625 }
5626 if (added == null) {
5627 // Completely matched -- nothing else to do.
5628 return true;
5629 }
5630
5631 // Add additional signatures in.
5632 if (update) {
5633 Signature[] total = new Signature[addedCount+mSignatures.length];
5634 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5635 int j = mSignatures.length;
5636 for (int i=0; i<added.length; i++) {
5637 if (added[i] != null) {
5638 total[j] = added[i];
5639 j++;
5640 }
5641 }
5642 mSignatures = total;
5643 }
5644 return true;
5645 }
5646
5647 private void assignSignatures(Signature[] sigs) {
5648 if (sigs == null) {
5649 mSignatures = null;
5650 return;
5651 }
5652 mSignatures = new Signature[sigs.length];
5653 for (int i=0; i<sigs.length; i++) {
5654 mSignatures[i] = sigs[i];
5655 }
5656 }
5657
5658 @Override
5659 public String toString() {
5660 StringBuffer buf = new StringBuffer(128);
5661 buf.append("PackageSignatures{");
5662 buf.append(Integer.toHexString(System.identityHashCode(this)));
5663 buf.append(" [");
5664 if (mSignatures != null) {
5665 for (int i=0; i<mSignatures.length; i++) {
5666 if (i > 0) buf.append(", ");
5667 buf.append(Integer.toHexString(
5668 System.identityHashCode(mSignatures[i])));
5669 }
5670 }
5671 buf.append("]}");
5672 return buf.toString();
5673 }
5674 }
5675
5676 static class PreferredActivity extends IntentFilter {
5677 final int mMatch;
5678 final String[] mSetPackages;
5679 final String[] mSetClasses;
5680 final String[] mSetComponents;
5681 final ComponentName mActivity;
5682 final String mShortActivity;
5683 String mParseError;
5684
5685 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5686 ComponentName activity) {
5687 super(filter);
5688 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5689 mActivity = activity;
5690 mShortActivity = activity.flattenToShortString();
5691 mParseError = null;
5692 if (set != null) {
5693 final int N = set.length;
5694 String[] myPackages = new String[N];
5695 String[] myClasses = new String[N];
5696 String[] myComponents = new String[N];
5697 for (int i=0; i<N; i++) {
5698 ComponentName cn = set[i];
5699 if (cn == null) {
5700 mSetPackages = null;
5701 mSetClasses = null;
5702 mSetComponents = null;
5703 return;
5704 }
5705 myPackages[i] = cn.getPackageName().intern();
5706 myClasses[i] = cn.getClassName().intern();
5707 myComponents[i] = cn.flattenToShortString().intern();
5708 }
5709 mSetPackages = myPackages;
5710 mSetClasses = myClasses;
5711 mSetComponents = myComponents;
5712 } else {
5713 mSetPackages = null;
5714 mSetClasses = null;
5715 mSetComponents = null;
5716 }
5717 }
5718
5719 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5720 IOException {
5721 mShortActivity = parser.getAttributeValue(null, "name");
5722 mActivity = ComponentName.unflattenFromString(mShortActivity);
5723 if (mActivity == null) {
5724 mParseError = "Bad activity name " + mShortActivity;
5725 }
5726 String matchStr = parser.getAttributeValue(null, "match");
5727 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5728 String setCountStr = parser.getAttributeValue(null, "set");
5729 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5730
5731 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5732 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5733 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5734
5735 int setPos = 0;
5736
5737 int outerDepth = parser.getDepth();
5738 int type;
5739 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5740 && (type != XmlPullParser.END_TAG
5741 || parser.getDepth() > outerDepth)) {
5742 if (type == XmlPullParser.END_TAG
5743 || type == XmlPullParser.TEXT) {
5744 continue;
5745 }
5746
5747 String tagName = parser.getName();
5748 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5749 // + parser.getDepth() + " tag=" + tagName);
5750 if (tagName.equals("set")) {
5751 String name = parser.getAttributeValue(null, "name");
5752 if (name == null) {
5753 if (mParseError == null) {
5754 mParseError = "No name in set tag in preferred activity "
5755 + mShortActivity;
5756 }
5757 } else if (setPos >= setCount) {
5758 if (mParseError == null) {
5759 mParseError = "Too many set tags in preferred activity "
5760 + mShortActivity;
5761 }
5762 } else {
5763 ComponentName cn = ComponentName.unflattenFromString(name);
5764 if (cn == null) {
5765 if (mParseError == null) {
5766 mParseError = "Bad set name " + name + " in preferred activity "
5767 + mShortActivity;
5768 }
5769 } else {
5770 myPackages[setPos] = cn.getPackageName();
5771 myClasses[setPos] = cn.getClassName();
5772 myComponents[setPos] = name;
5773 setPos++;
5774 }
5775 }
5776 XmlUtils.skipCurrentTag(parser);
5777 } else if (tagName.equals("filter")) {
5778 //Log.i(TAG, "Starting to parse filter...");
5779 readFromXml(parser);
5780 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5781 // + parser.getDepth() + " tag=" + parser.getName());
5782 } else {
5783 reportSettingsProblem(Log.WARN,
5784 "Unknown element under <preferred-activities>: "
5785 + parser.getName());
5786 XmlUtils.skipCurrentTag(parser);
5787 }
5788 }
5789
5790 if (setPos != setCount) {
5791 if (mParseError == null) {
5792 mParseError = "Not enough set tags (expected " + setCount
5793 + " but found " + setPos + ") in " + mShortActivity;
5794 }
5795 }
5796
5797 mSetPackages = myPackages;
5798 mSetClasses = myClasses;
5799 mSetComponents = myComponents;
5800 }
5801
5802 public void writeToXml(XmlSerializer serializer) throws IOException {
5803 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5804 serializer.attribute(null, "name", mShortActivity);
5805 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5806 serializer.attribute(null, "set", Integer.toString(NS));
5807 for (int s=0; s<NS; s++) {
5808 serializer.startTag(null, "set");
5809 serializer.attribute(null, "name", mSetComponents[s]);
5810 serializer.endTag(null, "set");
5811 }
5812 serializer.startTag(null, "filter");
5813 super.writeToXml(serializer);
5814 serializer.endTag(null, "filter");
5815 }
5816
5817 boolean sameSet(List<ResolveInfo> query, int priority) {
5818 if (mSetPackages == null) return false;
5819 final int NQ = query.size();
5820 final int NS = mSetPackages.length;
5821 int numMatch = 0;
5822 for (int i=0; i<NQ; i++) {
5823 ResolveInfo ri = query.get(i);
5824 if (ri.priority != priority) continue;
5825 ActivityInfo ai = ri.activityInfo;
5826 boolean good = false;
5827 for (int j=0; j<NS; j++) {
5828 if (mSetPackages[j].equals(ai.packageName)
5829 && mSetClasses[j].equals(ai.name)) {
5830 numMatch++;
5831 good = true;
5832 break;
5833 }
5834 }
5835 if (!good) return false;
5836 }
5837 return numMatch == NS;
5838 }
5839 }
5840
5841 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07005842 int pkgFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843
5844 HashSet<String> grantedPermissions = new HashSet<String>();
5845 int[] gids;
5846
5847 HashSet<String> loadedPermissions = new HashSet<String>();
5848
5849 GrantedPermissions(int pkgFlags) {
5850 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5851 }
5852 }
5853
5854 /**
5855 * Settings base class for pending and resolved classes.
5856 */
5857 static class PackageSettingBase extends GrantedPermissions {
5858 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005859 File codePath;
5860 String codePathString;
5861 File resourcePath;
5862 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 private long timeStamp;
5864 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005865 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866
5867 PackageSignatures signatures = new PackageSignatures();
5868
5869 boolean permissionsFixed;
5870
5871 /* Explicitly disabled components */
5872 HashSet<String> disabledComponents = new HashSet<String>(0);
5873 /* Explicitly enabled components */
5874 HashSet<String> enabledComponents = new HashSet<String>(0);
5875 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5876 int installStatus = PKG_INSTALL_COMPLETE;
Jacek Surazski65e13172009-04-28 15:26:38 +02005877
5878 /* package name of the app that installed this package */
5879 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880
5881 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005882 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 super(pkgFlags);
5884 this.name = name;
5885 this.codePath = codePath;
5886 this.codePathString = codePath.toString();
5887 this.resourcePath = resourcePath;
5888 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005889 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 }
5891
Jacek Surazski65e13172009-04-28 15:26:38 +02005892 public void setInstallerPackageName(String packageName) {
5893 installerPackageName = packageName;
5894 }
5895
5896 String getInstallerPackageName() {
5897 return installerPackageName;
5898 }
5899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 public void setInstallStatus(int newStatus) {
5901 installStatus = newStatus;
5902 }
5903
5904 public int getInstallStatus() {
5905 return installStatus;
5906 }
5907
5908 public void setTimeStamp(long newStamp) {
5909 if (newStamp != timeStamp) {
5910 timeStamp = newStamp;
5911 timeStampString = Long.toString(newStamp);
5912 }
5913 }
5914
5915 public void setTimeStamp(long newStamp, String newStampStr) {
5916 timeStamp = newStamp;
5917 timeStampString = newStampStr;
5918 }
5919
5920 public long getTimeStamp() {
5921 return timeStamp;
5922 }
5923
5924 public String getTimeStampStr() {
5925 return timeStampString;
5926 }
5927
5928 public void copyFrom(PackageSettingBase base) {
5929 grantedPermissions = base.grantedPermissions;
5930 gids = base.gids;
5931 loadedPermissions = base.loadedPermissions;
5932
5933 timeStamp = base.timeStamp;
5934 timeStampString = base.timeStampString;
5935 signatures = base.signatures;
5936 permissionsFixed = base.permissionsFixed;
5937 disabledComponents = base.disabledComponents;
5938 enabledComponents = base.enabledComponents;
5939 enabled = base.enabled;
5940 installStatus = base.installStatus;
5941 }
5942
5943 void enableComponentLP(String componentClassName) {
5944 disabledComponents.remove(componentClassName);
5945 enabledComponents.add(componentClassName);
5946 }
5947
5948 void disableComponentLP(String componentClassName) {
5949 enabledComponents.remove(componentClassName);
5950 disabledComponents.add(componentClassName);
5951 }
5952
5953 void restoreComponentLP(String componentClassName) {
5954 enabledComponents.remove(componentClassName);
5955 disabledComponents.remove(componentClassName);
5956 }
5957
5958 int currentEnabledStateLP(String componentName) {
5959 if (enabledComponents.contains(componentName)) {
5960 return COMPONENT_ENABLED_STATE_ENABLED;
5961 } else if (disabledComponents.contains(componentName)) {
5962 return COMPONENT_ENABLED_STATE_DISABLED;
5963 } else {
5964 return COMPONENT_ENABLED_STATE_DEFAULT;
5965 }
5966 }
5967 }
5968
5969 /**
5970 * Settings data for a particular package we know about.
5971 */
5972 static final class PackageSetting extends PackageSettingBase {
5973 int userId;
5974 PackageParser.Package pkg;
5975 SharedUserSetting sharedUser;
5976
5977 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005978 int pVersionCode, int pkgFlags) {
5979 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 }
5981
5982 @Override
5983 public String toString() {
5984 return "PackageSetting{"
5985 + Integer.toHexString(System.identityHashCode(this))
5986 + " " + name + "/" + userId + "}";
5987 }
5988 }
5989
5990 /**
5991 * Settings data for a particular shared user ID we know about.
5992 */
5993 static final class SharedUserSetting extends GrantedPermissions {
5994 final String name;
5995 int userId;
5996 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
5997 final PackageSignatures signatures = new PackageSignatures();
5998
5999 SharedUserSetting(String _name, int _pkgFlags) {
6000 super(_pkgFlags);
6001 name = _name;
6002 }
6003
6004 @Override
6005 public String toString() {
6006 return "SharedUserSetting{"
6007 + Integer.toHexString(System.identityHashCode(this))
6008 + " " + name + "/" + userId + "}";
6009 }
6010 }
6011
6012 /**
6013 * Holds information about dynamic settings.
6014 */
6015 private static final class Settings {
6016 private final File mSettingsFilename;
6017 private final File mBackupSettingsFilename;
6018 private final HashMap<String, PackageSetting> mPackages =
6019 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020 // List of replaced system applications
6021 final HashMap<String, PackageSetting> mDisabledSysPackages =
6022 new HashMap<String, PackageSetting>();
6023
6024 // The user's preferred activities associated with particular intent
6025 // filters.
6026 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6027 new IntentResolver<PreferredActivity, PreferredActivity>() {
6028 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006029 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006031 out.print(prefix); out.print(
6032 Integer.toHexString(System.identityHashCode(filter)));
6033 out.print(' ');
6034 out.print(filter.mActivity.flattenToShortString());
6035 out.print(" match=0x");
6036 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006038 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006040 out.print(prefix); out.print(" ");
6041 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 }
6043 }
6044 }
6045 };
6046 private final HashMap<String, SharedUserSetting> mSharedUsers =
6047 new HashMap<String, SharedUserSetting>();
6048 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6049 private final SparseArray<Object> mOtherUserIds =
6050 new SparseArray<Object>();
6051
6052 // For reading/writing settings file.
6053 private final ArrayList<Signature> mPastSignatures =
6054 new ArrayList<Signature>();
6055
6056 // Mapping from permission names to info about them.
6057 final HashMap<String, BasePermission> mPermissions =
6058 new HashMap<String, BasePermission>();
6059
6060 // Mapping from permission tree names to info about them.
6061 final HashMap<String, BasePermission> mPermissionTrees =
6062 new HashMap<String, BasePermission>();
6063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 private final StringBuilder mReadMessages = new StringBuilder();
6065
6066 private static final class PendingPackage extends PackageSettingBase {
6067 final int sharedId;
6068
6069 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006070 int sharedId, int pVersionCode, int pkgFlags) {
6071 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072 this.sharedId = sharedId;
6073 }
6074 }
6075 private final ArrayList<PendingPackage> mPendingPackages
6076 = new ArrayList<PendingPackage>();
6077
6078 Settings() {
6079 File dataDir = Environment.getDataDirectory();
6080 File systemDir = new File(dataDir, "system");
6081 systemDir.mkdirs();
6082 FileUtils.setPermissions(systemDir.toString(),
6083 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6084 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6085 -1, -1);
6086 mSettingsFilename = new File(systemDir, "packages.xml");
6087 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6088 }
6089
6090 PackageSetting getPackageLP(PackageParser.Package pkg,
6091 SharedUserSetting sharedUser, File codePath, File resourcePath,
6092 int pkgFlags, boolean create, boolean add) {
6093 final String name = pkg.packageName;
6094 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006095 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006096 return p;
6097 }
6098
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006099 PackageSetting peekPackageLP(String name) {
6100 return mPackages.get(name);
6101 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 PackageSetting p = mPackages.get(name);
6103 if (p != null && p.codePath.getPath().equals(codePath)) {
6104 return p;
6105 }
6106 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006107 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 }
6109
6110 void setInstallStatus(String pkgName, int status) {
6111 PackageSetting p = mPackages.get(pkgName);
6112 if(p != null) {
6113 if(p.getInstallStatus() != status) {
6114 p.setInstallStatus(status);
6115 }
6116 }
6117 }
6118
Jacek Surazski65e13172009-04-28 15:26:38 +02006119 void setInstallerPackageName(String pkgName,
6120 String installerPkgName) {
6121 PackageSetting p = mPackages.get(pkgName);
6122 if(p != null) {
6123 p.setInstallerPackageName(installerPkgName);
6124 }
6125 }
6126
6127 String getInstallerPackageName(String pkgName) {
6128 PackageSetting p = mPackages.get(pkgName);
6129 return (p == null) ? null : p.getInstallerPackageName();
6130 }
6131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 int getInstallStatus(String pkgName) {
6133 PackageSetting p = mPackages.get(pkgName);
6134 if(p != null) {
6135 return p.getInstallStatus();
6136 }
6137 return -1;
6138 }
6139
6140 SharedUserSetting getSharedUserLP(String name,
6141 int pkgFlags, boolean create) {
6142 SharedUserSetting s = mSharedUsers.get(name);
6143 if (s == null) {
6144 if (!create) {
6145 return null;
6146 }
6147 s = new SharedUserSetting(name, pkgFlags);
6148 if (MULTIPLE_APPLICATION_UIDS) {
6149 s.userId = newUserIdLP(s);
6150 } else {
6151 s.userId = FIRST_APPLICATION_UID;
6152 }
6153 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6154 // < 0 means we couldn't assign a userid; fall out and return
6155 // s, which is currently null
6156 if (s.userId >= 0) {
6157 mSharedUsers.put(name, s);
6158 }
6159 }
6160
6161 return s;
6162 }
6163
6164 int disableSystemPackageLP(String name) {
6165 PackageSetting p = mPackages.get(name);
6166 if(p == null) {
6167 Log.w(TAG, "Package:"+name+" is not an installed package");
6168 return -1;
6169 }
6170 PackageSetting dp = mDisabledSysPackages.get(name);
6171 // always make sure the system package code and resource paths dont change
6172 if(dp == null) {
6173 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6174 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6175 }
6176 mDisabledSysPackages.put(name, p);
6177 }
6178 return removePackageLP(name);
6179 }
6180
6181 PackageSetting enableSystemPackageLP(String name) {
6182 PackageSetting p = mDisabledSysPackages.get(name);
6183 if(p == null) {
6184 Log.w(TAG, "Package:"+name+" is not disabled");
6185 return null;
6186 }
6187 // Reset flag in ApplicationInfo object
6188 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6189 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6190 }
6191 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006192 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 mDisabledSysPackages.remove(name);
6194 return ret;
6195 }
6196
6197 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006198 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 PackageSetting p = mPackages.get(name);
6200 if (p != null) {
6201 if (p.userId == uid) {
6202 return p;
6203 }
6204 reportSettingsProblem(Log.ERROR,
6205 "Adding duplicate package, keeping first: " + name);
6206 return null;
6207 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006208 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 p.userId = uid;
6210 if (addUserIdLP(uid, p, name)) {
6211 mPackages.put(name, p);
6212 return p;
6213 }
6214 return null;
6215 }
6216
6217 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6218 SharedUserSetting s = mSharedUsers.get(name);
6219 if (s != null) {
6220 if (s.userId == uid) {
6221 return s;
6222 }
6223 reportSettingsProblem(Log.ERROR,
6224 "Adding duplicate shared user, keeping first: " + name);
6225 return null;
6226 }
6227 s = new SharedUserSetting(name, pkgFlags);
6228 s.userId = uid;
6229 if (addUserIdLP(uid, s, name)) {
6230 mSharedUsers.put(name, s);
6231 return s;
6232 }
6233 return null;
6234 }
6235
6236 private PackageSetting getPackageLP(String name,
6237 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006238 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 PackageSetting p = mPackages.get(name);
6240 if (p != null) {
6241 if (!p.codePath.equals(codePath)) {
6242 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006243 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006244 // This is an updated system app with versions in both system
6245 // and data partition. Just let the most recent version
6246 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006247 Log.w(TAG, "Trying to update system app code path from " +
6248 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006249 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006250 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07006251 reportSettingsProblem(Log.WARN,
6252 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006253 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006255 }
6256 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 reportSettingsProblem(Log.WARN,
6258 "Package " + name + " shared user changed from "
6259 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
6260 + " to "
6261 + (sharedUser != null ? sharedUser.name : "<nothing>")
6262 + "; replacing with new");
6263 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006264 } else {
6265 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6266 // If what we are scanning is a system package, then
6267 // make it so, regardless of whether it was previously
6268 // installed only in the data partition.
6269 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 }
6272 }
6273 if (p == null) {
6274 // Create a new PackageSettings entry. this can end up here because
6275 // of code path mismatch or user id mismatch of an updated system partition
6276 if (!create) {
6277 return null;
6278 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006279 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07006281 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 if (sharedUser != null) {
6283 p.userId = sharedUser.userId;
6284 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006285 // Clone the setting here for disabled system packages
6286 PackageSetting dis = mDisabledSysPackages.get(name);
6287 if (dis != null) {
6288 // For disabled packages a new setting is created
6289 // from the existing user id. This still has to be
6290 // added to list of user id's
6291 // Copy signatures from previous setting
6292 if (dis.signatures.mSignatures != null) {
6293 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
6294 }
6295 p.userId = dis.userId;
6296 // Clone permissions
6297 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
6298 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
6299 // Clone component info
6300 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
6301 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
6302 // Add new setting to list of user ids
6303 addUserIdLP(p.userId, p, name);
6304 } else {
6305 // Assign new user id
6306 p.userId = newUserIdLP(p);
6307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 } else {
6309 p.userId = FIRST_APPLICATION_UID;
6310 }
6311 if (p.userId < 0) {
6312 reportSettingsProblem(Log.WARN,
6313 "Package " + name + " could not be assigned a valid uid");
6314 return null;
6315 }
6316 if (add) {
6317 // Finish adding new package by adding it and updating shared
6318 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006319 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 }
6321 }
6322 return p;
6323 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006324
6325 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg,
6326 File codePath, File resourcePath) {
6327 p.pkg = pkg;
6328 // Update code path if needed
6329 if (!codePath.toString().equalsIgnoreCase(p.codePathString)) {
6330 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006331 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006332 p.codePath = codePath;
6333 p.codePathString = codePath.toString();
6334 }
6335 //Update resource path if needed
6336 if (!resourcePath.toString().equalsIgnoreCase(p.resourcePathString)) {
6337 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006338 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006339 p.resourcePath = resourcePath;
6340 p.resourcePathString = resourcePath.toString();
6341 }
6342 // Update version code if needed
6343 if (pkg.mVersionCode != p.versionCode) {
6344 p.versionCode = pkg.mVersionCode;
6345 }
6346 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
6347 }
6348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 // Utility method that adds a PackageSetting to mPackages and
6350 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006351 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 SharedUserSetting sharedUser) {
6353 mPackages.put(name, p);
6354 if (sharedUser != null) {
6355 if (p.sharedUser != null && p.sharedUser != sharedUser) {
6356 reportSettingsProblem(Log.ERROR,
6357 "Package " + p.name + " was user "
6358 + p.sharedUser + " but is now " + sharedUser
6359 + "; I am not changing its files so it will probably fail!");
6360 p.sharedUser.packages.remove(p);
6361 } else if (p.userId != sharedUser.userId) {
6362 reportSettingsProblem(Log.ERROR,
6363 "Package " + p.name + " was user id " + p.userId
6364 + " but is now user " + sharedUser
6365 + " with id " + sharedUser.userId
6366 + "; I am not changing its files so it will probably fail!");
6367 }
6368
6369 sharedUser.packages.add(p);
6370 p.sharedUser = sharedUser;
6371 p.userId = sharedUser.userId;
6372 }
6373 }
6374
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006375 /*
6376 * Update the shared user setting when a package using
6377 * specifying the shared user id is removed. The gids
6378 * associated with each permission of the deleted package
6379 * are removed from the shared user's gid list only if its
6380 * not in use by other permissions of packages in the
6381 * shared user setting.
6382 */
6383 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6385 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6386 return;
6387 }
6388 // No sharedUserId
6389 if (deletedPs.sharedUser == null) {
6390 return;
6391 }
6392 SharedUserSetting sus = deletedPs.sharedUser;
6393 // Update permissions
6394 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6395 boolean used = false;
6396 if (!sus.grantedPermissions.contains (eachPerm)) {
6397 continue;
6398 }
6399 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006400 if (pkg.pkg != null &&
6401 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
6402 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 used = true;
6404 break;
6405 }
6406 }
6407 if (!used) {
6408 // can safely delete this permission from list
6409 sus.grantedPermissions.remove(eachPerm);
6410 sus.loadedPermissions.remove(eachPerm);
6411 }
6412 }
6413 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006414 int newGids[] = globalGids;
6415 for (String eachPerm : sus.grantedPermissions) {
6416 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006417 if (bp != null) {
6418 newGids = appendInts(newGids, bp.gids);
6419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 }
6421 sus.gids = newGids;
6422 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 private int removePackageLP(String name) {
6425 PackageSetting p = mPackages.get(name);
6426 if (p != null) {
6427 mPackages.remove(name);
6428 if (p.sharedUser != null) {
6429 p.sharedUser.packages.remove(p);
6430 if (p.sharedUser.packages.size() == 0) {
6431 mSharedUsers.remove(p.sharedUser.name);
6432 removeUserIdLP(p.sharedUser.userId);
6433 return p.sharedUser.userId;
6434 }
6435 } else {
6436 removeUserIdLP(p.userId);
6437 return p.userId;
6438 }
6439 }
6440 return -1;
6441 }
6442
6443 private boolean addUserIdLP(int uid, Object obj, Object name) {
6444 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6445 return false;
6446 }
6447
6448 if (uid >= FIRST_APPLICATION_UID) {
6449 int N = mUserIds.size();
6450 final int index = uid - FIRST_APPLICATION_UID;
6451 while (index >= N) {
6452 mUserIds.add(null);
6453 N++;
6454 }
6455 if (mUserIds.get(index) != null) {
6456 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006457 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 + " name=" + name);
6459 return false;
6460 }
6461 mUserIds.set(index, obj);
6462 } else {
6463 if (mOtherUserIds.get(uid) != null) {
6464 reportSettingsProblem(Log.ERROR,
6465 "Adding duplicate shared id: " + uid
6466 + " name=" + name);
6467 return false;
6468 }
6469 mOtherUserIds.put(uid, obj);
6470 }
6471 return true;
6472 }
6473
6474 public Object getUserIdLP(int uid) {
6475 if (uid >= FIRST_APPLICATION_UID) {
6476 int N = mUserIds.size();
6477 final int index = uid - FIRST_APPLICATION_UID;
6478 return index < N ? mUserIds.get(index) : null;
6479 } else {
6480 return mOtherUserIds.get(uid);
6481 }
6482 }
6483
6484 private void removeUserIdLP(int uid) {
6485 if (uid >= FIRST_APPLICATION_UID) {
6486 int N = mUserIds.size();
6487 final int index = uid - FIRST_APPLICATION_UID;
6488 if (index < N) mUserIds.set(index, null);
6489 } else {
6490 mOtherUserIds.remove(uid);
6491 }
6492 }
6493
6494 void writeLP() {
6495 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6496
6497 // Keep the old settings around until we know the new ones have
6498 // been successfully written.
6499 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006500 // Presence of backup settings file indicates that we failed
6501 // to persist settings earlier. So preserve the older
6502 // backup for future reference since the current settings
6503 // might have been corrupted.
6504 if (!mBackupSettingsFilename.exists()) {
6505 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
6506 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
6507 return;
6508 }
6509 } else {
6510 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07006511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 }
6513
6514 mPastSignatures.clear();
6515
6516 try {
6517 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6518
6519 //XmlSerializer serializer = XmlUtils.serializerInstance();
6520 XmlSerializer serializer = new FastXmlSerializer();
6521 serializer.setOutput(str, "utf-8");
6522 serializer.startDocument(null, true);
6523 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6524
6525 serializer.startTag(null, "packages");
6526
6527 serializer.startTag(null, "permission-trees");
6528 for (BasePermission bp : mPermissionTrees.values()) {
6529 writePermission(serializer, bp);
6530 }
6531 serializer.endTag(null, "permission-trees");
6532
6533 serializer.startTag(null, "permissions");
6534 for (BasePermission bp : mPermissions.values()) {
6535 writePermission(serializer, bp);
6536 }
6537 serializer.endTag(null, "permissions");
6538
6539 for (PackageSetting pkg : mPackages.values()) {
6540 writePackage(serializer, pkg);
6541 }
6542
6543 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6544 writeDisabledSysPackage(serializer, pkg);
6545 }
6546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006547 serializer.startTag(null, "preferred-activities");
6548 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6549 serializer.startTag(null, "item");
6550 pa.writeToXml(serializer);
6551 serializer.endTag(null, "item");
6552 }
6553 serializer.endTag(null, "preferred-activities");
6554
6555 for (SharedUserSetting usr : mSharedUsers.values()) {
6556 serializer.startTag(null, "shared-user");
6557 serializer.attribute(null, "name", usr.name);
6558 serializer.attribute(null, "userId",
6559 Integer.toString(usr.userId));
6560 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6561 serializer.startTag(null, "perms");
6562 for (String name : usr.grantedPermissions) {
6563 serializer.startTag(null, "item");
6564 serializer.attribute(null, "name", name);
6565 serializer.endTag(null, "item");
6566 }
6567 serializer.endTag(null, "perms");
6568 serializer.endTag(null, "shared-user");
6569 }
6570
6571 serializer.endTag(null, "packages");
6572
6573 serializer.endDocument();
6574
6575 str.flush();
6576 str.close();
6577
6578 // New settings successfully written, old ones are no longer
6579 // needed.
6580 mBackupSettingsFilename.delete();
6581 FileUtils.setPermissions(mSettingsFilename.toString(),
6582 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6583 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6584 |FileUtils.S_IROTH,
6585 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006586 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587
6588 } catch(XmlPullParserException e) {
6589 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 } catch(java.io.IOException e) {
6591 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006593 // Clean up partially written file
6594 if (mSettingsFilename.exists()) {
6595 if (!mSettingsFilename.delete()) {
6596 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
6597 }
6598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 //Debug.stopMethodTracing();
6600 }
6601
6602 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
6603 throws java.io.IOException {
6604 serializer.startTag(null, "updated-package");
6605 serializer.attribute(null, "name", pkg.name);
6606 serializer.attribute(null, "codePath", pkg.codePathString);
6607 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006608 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6610 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6611 }
6612 if (pkg.sharedUser == null) {
6613 serializer.attribute(null, "userId",
6614 Integer.toString(pkg.userId));
6615 } else {
6616 serializer.attribute(null, "sharedUserId",
6617 Integer.toString(pkg.userId));
6618 }
6619 serializer.startTag(null, "perms");
6620 if (pkg.sharedUser == null) {
6621 // If this is a shared user, the permissions will
6622 // be written there. We still need to write an
6623 // empty permissions list so permissionsFixed will
6624 // be set.
6625 for (final String name : pkg.grantedPermissions) {
6626 BasePermission bp = mPermissions.get(name);
6627 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6628 // We only need to write signature or system permissions but this wont
6629 // match the semantics of grantedPermissions. So write all permissions.
6630 serializer.startTag(null, "item");
6631 serializer.attribute(null, "name", name);
6632 serializer.endTag(null, "item");
6633 }
6634 }
6635 }
6636 serializer.endTag(null, "perms");
6637 serializer.endTag(null, "updated-package");
6638 }
6639
6640 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
6641 throws java.io.IOException {
6642 serializer.startTag(null, "package");
6643 serializer.attribute(null, "name", pkg.name);
6644 serializer.attribute(null, "codePath", pkg.codePathString);
6645 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6646 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6647 }
6648 serializer.attribute(null, "system",
6649 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6650 ? "true" : "false");
6651 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006652 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 if (pkg.sharedUser == null) {
6654 serializer.attribute(null, "userId",
6655 Integer.toString(pkg.userId));
6656 } else {
6657 serializer.attribute(null, "sharedUserId",
6658 Integer.toString(pkg.userId));
6659 }
6660 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6661 serializer.attribute(null, "enabled",
6662 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6663 ? "true" : "false");
6664 }
6665 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6666 serializer.attribute(null, "installStatus", "false");
6667 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006668 if (pkg.installerPackageName != null) {
6669 serializer.attribute(null, "installer", pkg.installerPackageName);
6670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6672 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6673 serializer.startTag(null, "perms");
6674 if (pkg.sharedUser == null) {
6675 // If this is a shared user, the permissions will
6676 // be written there. We still need to write an
6677 // empty permissions list so permissionsFixed will
6678 // be set.
6679 for (final String name : pkg.grantedPermissions) {
6680 serializer.startTag(null, "item");
6681 serializer.attribute(null, "name", name);
6682 serializer.endTag(null, "item");
6683 }
6684 }
6685 serializer.endTag(null, "perms");
6686 }
6687 if (pkg.disabledComponents.size() > 0) {
6688 serializer.startTag(null, "disabled-components");
6689 for (final String name : pkg.disabledComponents) {
6690 serializer.startTag(null, "item");
6691 serializer.attribute(null, "name", name);
6692 serializer.endTag(null, "item");
6693 }
6694 serializer.endTag(null, "disabled-components");
6695 }
6696 if (pkg.enabledComponents.size() > 0) {
6697 serializer.startTag(null, "enabled-components");
6698 for (final String name : pkg.enabledComponents) {
6699 serializer.startTag(null, "item");
6700 serializer.attribute(null, "name", name);
6701 serializer.endTag(null, "item");
6702 }
6703 serializer.endTag(null, "enabled-components");
6704 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 serializer.endTag(null, "package");
6707 }
6708
6709 void writePermission(XmlSerializer serializer, BasePermission bp)
6710 throws XmlPullParserException, java.io.IOException {
6711 if (bp.type != BasePermission.TYPE_BUILTIN
6712 && bp.sourcePackage != null) {
6713 serializer.startTag(null, "item");
6714 serializer.attribute(null, "name", bp.name);
6715 serializer.attribute(null, "package", bp.sourcePackage);
6716 if (DEBUG_SETTINGS) Log.v(TAG,
6717 "Writing perm: name=" + bp.name + " type=" + bp.type);
6718 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6719 PermissionInfo pi = bp.perm != null ? bp.perm.info
6720 : bp.pendingInfo;
6721 if (pi != null) {
6722 serializer.attribute(null, "type", "dynamic");
6723 if (pi.icon != 0) {
6724 serializer.attribute(null, "icon",
6725 Integer.toString(pi.icon));
6726 }
6727 if (pi.nonLocalizedLabel != null) {
6728 serializer.attribute(null, "label",
6729 pi.nonLocalizedLabel.toString());
6730 }
6731 if (pi.protectionLevel !=
6732 PermissionInfo.PROTECTION_NORMAL) {
6733 serializer.attribute(null, "protection",
6734 Integer.toString(pi.protectionLevel));
6735 }
6736 }
6737 }
6738 serializer.endTag(null, "item");
6739 }
6740 }
6741
6742 String getReadMessagesLP() {
6743 return mReadMessages.toString();
6744 }
6745
Dianne Hackborne6620b22010-01-22 14:46:21 -08006746 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6748 Iterator<String> its = kList.iterator();
Dianne Hackborne6620b22010-01-22 14:46:21 -08006749 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 while(its.hasNext()) {
6751 String key = its.next();
6752 PackageSetting ps = mPackages.get(key);
6753 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Dianne Hackborne6620b22010-01-22 14:46:21 -08006754 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 }
6756 }
6757 return ret;
6758 }
6759
6760 boolean readLP() {
6761 FileInputStream str = null;
6762 if (mBackupSettingsFilename.exists()) {
6763 try {
6764 str = new FileInputStream(mBackupSettingsFilename);
6765 mReadMessages.append("Reading from backup settings file\n");
6766 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006767 if (mSettingsFilename.exists()) {
6768 // If both the backup and settings file exist, we
6769 // ignore the settings since it might have been
6770 // corrupted.
6771 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
6772 mSettingsFilename.delete();
6773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 } catch (java.io.IOException e) {
6775 // We'll try for the normal settings file.
6776 }
6777 }
6778
6779 mPastSignatures.clear();
6780
6781 try {
6782 if (str == null) {
6783 if (!mSettingsFilename.exists()) {
6784 mReadMessages.append("No settings file found\n");
6785 Log.i(TAG, "No current settings file!");
6786 return false;
6787 }
6788 str = new FileInputStream(mSettingsFilename);
6789 }
6790 XmlPullParser parser = Xml.newPullParser();
6791 parser.setInput(str, null);
6792
6793 int type;
6794 while ((type=parser.next()) != XmlPullParser.START_TAG
6795 && type != XmlPullParser.END_DOCUMENT) {
6796 ;
6797 }
6798
6799 if (type != XmlPullParser.START_TAG) {
6800 mReadMessages.append("No start tag found in settings file\n");
6801 Log.e(TAG, "No start tag found in package manager settings");
6802 return false;
6803 }
6804
6805 int outerDepth = parser.getDepth();
6806 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6807 && (type != XmlPullParser.END_TAG
6808 || parser.getDepth() > outerDepth)) {
6809 if (type == XmlPullParser.END_TAG
6810 || type == XmlPullParser.TEXT) {
6811 continue;
6812 }
6813
6814 String tagName = parser.getName();
6815 if (tagName.equals("package")) {
6816 readPackageLP(parser);
6817 } else if (tagName.equals("permissions")) {
6818 readPermissionsLP(mPermissions, parser);
6819 } else if (tagName.equals("permission-trees")) {
6820 readPermissionsLP(mPermissionTrees, parser);
6821 } else if (tagName.equals("shared-user")) {
6822 readSharedUserLP(parser);
6823 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006824 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006825 } else if (tagName.equals("preferred-activities")) {
6826 readPreferredActivitiesLP(parser);
6827 } else if(tagName.equals("updated-package")) {
6828 readDisabledSysPackageLP(parser);
6829 } else {
6830 Log.w(TAG, "Unknown element under <packages>: "
6831 + parser.getName());
6832 XmlUtils.skipCurrentTag(parser);
6833 }
6834 }
6835
6836 str.close();
6837
6838 } catch(XmlPullParserException e) {
6839 mReadMessages.append("Error reading: " + e.toString());
6840 Log.e(TAG, "Error reading package manager settings", e);
6841
6842 } catch(java.io.IOException e) {
6843 mReadMessages.append("Error reading: " + e.toString());
6844 Log.e(TAG, "Error reading package manager settings", e);
6845
6846 }
6847
6848 int N = mPendingPackages.size();
6849 for (int i=0; i<N; i++) {
6850 final PendingPackage pp = mPendingPackages.get(i);
6851 Object idObj = getUserIdLP(pp.sharedId);
6852 if (idObj != null && idObj instanceof SharedUserSetting) {
6853 PackageSetting p = getPackageLP(pp.name,
6854 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006855 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006856 if (p == null) {
6857 Log.w(TAG, "Unable to create application package for "
6858 + pp.name);
6859 continue;
6860 }
6861 p.copyFrom(pp);
6862 } else if (idObj != null) {
6863 String msg = "Bad package setting: package " + pp.name
6864 + " has shared uid " + pp.sharedId
6865 + " that is not a shared uid\n";
6866 mReadMessages.append(msg);
6867 Log.e(TAG, msg);
6868 } else {
6869 String msg = "Bad package setting: package " + pp.name
6870 + " has shared uid " + pp.sharedId
6871 + " that is not defined\n";
6872 mReadMessages.append(msg);
6873 Log.e(TAG, msg);
6874 }
6875 }
6876 mPendingPackages.clear();
6877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006878 mReadMessages.append("Read completed successfully: "
6879 + mPackages.size() + " packages, "
6880 + mSharedUsers.size() + " shared uids\n");
6881
6882 return true;
6883 }
6884
6885 private int readInt(XmlPullParser parser, String ns, String name,
6886 int defValue) {
6887 String v = parser.getAttributeValue(ns, name);
6888 try {
6889 if (v == null) {
6890 return defValue;
6891 }
6892 return Integer.parseInt(v);
6893 } catch (NumberFormatException e) {
6894 reportSettingsProblem(Log.WARN,
6895 "Error in package manager settings: attribute " +
6896 name + " has bad integer value " + v + " at "
6897 + parser.getPositionDescription());
6898 }
6899 return defValue;
6900 }
6901
6902 private void readPermissionsLP(HashMap<String, BasePermission> out,
6903 XmlPullParser parser)
6904 throws IOException, XmlPullParserException {
6905 int outerDepth = parser.getDepth();
6906 int type;
6907 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6908 && (type != XmlPullParser.END_TAG
6909 || parser.getDepth() > outerDepth)) {
6910 if (type == XmlPullParser.END_TAG
6911 || type == XmlPullParser.TEXT) {
6912 continue;
6913 }
6914
6915 String tagName = parser.getName();
6916 if (tagName.equals("item")) {
6917 String name = parser.getAttributeValue(null, "name");
6918 String sourcePackage = parser.getAttributeValue(null, "package");
6919 String ptype = parser.getAttributeValue(null, "type");
6920 if (name != null && sourcePackage != null) {
6921 boolean dynamic = "dynamic".equals(ptype);
6922 BasePermission bp = new BasePermission(name, sourcePackage,
6923 dynamic
6924 ? BasePermission.TYPE_DYNAMIC
6925 : BasePermission.TYPE_NORMAL);
6926 if (dynamic) {
6927 PermissionInfo pi = new PermissionInfo();
6928 pi.packageName = sourcePackage.intern();
6929 pi.name = name.intern();
6930 pi.icon = readInt(parser, null, "icon", 0);
6931 pi.nonLocalizedLabel = parser.getAttributeValue(
6932 null, "label");
6933 pi.protectionLevel = readInt(parser, null, "protection",
6934 PermissionInfo.PROTECTION_NORMAL);
6935 bp.pendingInfo = pi;
6936 }
6937 out.put(bp.name, bp);
6938 } else {
6939 reportSettingsProblem(Log.WARN,
6940 "Error in package manager settings: permissions has"
6941 + " no name at " + parser.getPositionDescription());
6942 }
6943 } else {
6944 reportSettingsProblem(Log.WARN,
6945 "Unknown element reading permissions: "
6946 + parser.getName() + " at "
6947 + parser.getPositionDescription());
6948 }
6949 XmlUtils.skipCurrentTag(parser);
6950 }
6951 }
6952
6953 private void readDisabledSysPackageLP(XmlPullParser parser)
6954 throws XmlPullParserException, IOException {
6955 String name = parser.getAttributeValue(null, "name");
6956 String codePathStr = parser.getAttributeValue(null, "codePath");
6957 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6958 if(resourcePathStr == null) {
6959 resourcePathStr = codePathStr;
6960 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006961 String version = parser.getAttributeValue(null, "version");
6962 int versionCode = 0;
6963 if (version != null) {
6964 try {
6965 versionCode = Integer.parseInt(version);
6966 } catch (NumberFormatException e) {
6967 }
6968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969
6970 int pkgFlags = 0;
6971 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6972 PackageSetting ps = new PackageSetting(name,
6973 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006974 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006975 String timeStampStr = parser.getAttributeValue(null, "ts");
6976 if (timeStampStr != null) {
6977 try {
6978 long timeStamp = Long.parseLong(timeStampStr);
6979 ps.setTimeStamp(timeStamp, timeStampStr);
6980 } catch (NumberFormatException e) {
6981 }
6982 }
6983 String idStr = parser.getAttributeValue(null, "userId");
6984 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
6985 if(ps.userId <= 0) {
6986 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6987 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
6988 }
6989 int outerDepth = parser.getDepth();
6990 int type;
6991 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6992 && (type != XmlPullParser.END_TAG
6993 || parser.getDepth() > outerDepth)) {
6994 if (type == XmlPullParser.END_TAG
6995 || type == XmlPullParser.TEXT) {
6996 continue;
6997 }
6998
6999 String tagName = parser.getName();
7000 if (tagName.equals("perms")) {
7001 readGrantedPermissionsLP(parser,
7002 ps.grantedPermissions);
7003 } else {
7004 reportSettingsProblem(Log.WARN,
7005 "Unknown element under <updated-package>: "
7006 + parser.getName());
7007 XmlUtils.skipCurrentTag(parser);
7008 }
7009 }
7010 mDisabledSysPackages.put(name, ps);
7011 }
7012
7013 private void readPackageLP(XmlPullParser parser)
7014 throws XmlPullParserException, IOException {
7015 String name = null;
7016 String idStr = null;
7017 String sharedIdStr = null;
7018 String codePathStr = null;
7019 String resourcePathStr = null;
7020 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007021 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 int pkgFlags = 0;
7023 String timeStampStr;
7024 long timeStamp = 0;
7025 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007026 String version = null;
7027 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 try {
7029 name = parser.getAttributeValue(null, "name");
7030 idStr = parser.getAttributeValue(null, "userId");
7031 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7032 codePathStr = parser.getAttributeValue(null, "codePath");
7033 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007034 version = parser.getAttributeValue(null, "version");
7035 if (version != null) {
7036 try {
7037 versionCode = Integer.parseInt(version);
7038 } catch (NumberFormatException e) {
7039 }
7040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazski65e13172009-04-28 15:26:38 +02007042 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 if (systemStr != null) {
7044 if ("true".equals(systemStr)) {
7045 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7046 }
7047 } else {
7048 // Old settings that don't specify system... just treat
7049 // them as system, good enough.
7050 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7051 }
7052 timeStampStr = parser.getAttributeValue(null, "ts");
7053 if (timeStampStr != null) {
7054 try {
7055 timeStamp = Long.parseLong(timeStampStr);
7056 } catch (NumberFormatException e) {
7057 }
7058 }
7059 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7060 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7061 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7062 if (resourcePathStr == null) {
7063 resourcePathStr = codePathStr;
7064 }
7065 if (name == null) {
7066 reportSettingsProblem(Log.WARN,
7067 "Error in package manager settings: <package> has no name at "
7068 + parser.getPositionDescription());
7069 } else if (codePathStr == null) {
7070 reportSettingsProblem(Log.WARN,
7071 "Error in package manager settings: <package> has no codePath at "
7072 + parser.getPositionDescription());
7073 } else if (userId > 0) {
7074 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007075 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7077 + ": userId=" + userId + " pkg=" + packageSetting);
7078 if (packageSetting == null) {
7079 reportSettingsProblem(Log.ERROR,
7080 "Failure adding uid " + userId
7081 + " while parsing settings at "
7082 + parser.getPositionDescription());
7083 } else {
7084 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7085 }
7086 } else if (sharedIdStr != null) {
7087 userId = sharedIdStr != null
7088 ? Integer.parseInt(sharedIdStr) : 0;
7089 if (userId > 0) {
7090 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007091 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7093 mPendingPackages.add((PendingPackage) packageSetting);
7094 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7095 + ": sharedUserId=" + userId + " pkg="
7096 + packageSetting);
7097 } else {
7098 reportSettingsProblem(Log.WARN,
7099 "Error in package manager settings: package "
7100 + name + " has bad sharedId " + sharedIdStr
7101 + " at " + parser.getPositionDescription());
7102 }
7103 } else {
7104 reportSettingsProblem(Log.WARN,
7105 "Error in package manager settings: package "
7106 + name + " has bad userId " + idStr + " at "
7107 + parser.getPositionDescription());
7108 }
7109 } catch (NumberFormatException e) {
7110 reportSettingsProblem(Log.WARN,
7111 "Error in package manager settings: package "
7112 + name + " has bad userId " + idStr + " at "
7113 + parser.getPositionDescription());
7114 }
7115 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02007116 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 final String enabledStr = parser.getAttributeValue(null, "enabled");
7118 if (enabledStr != null) {
7119 if (enabledStr.equalsIgnoreCase("true")) {
7120 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7121 } else if (enabledStr.equalsIgnoreCase("false")) {
7122 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7123 } else if (enabledStr.equalsIgnoreCase("default")) {
7124 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7125 } else {
7126 reportSettingsProblem(Log.WARN,
7127 "Error in package manager settings: package "
7128 + name + " has bad enabled value: " + idStr
7129 + " at " + parser.getPositionDescription());
7130 }
7131 } else {
7132 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7133 }
7134 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7135 if (installStatusStr != null) {
7136 if (installStatusStr.equalsIgnoreCase("false")) {
7137 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7138 } else {
7139 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7140 }
7141 }
7142
7143 int outerDepth = parser.getDepth();
7144 int type;
7145 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7146 && (type != XmlPullParser.END_TAG
7147 || parser.getDepth() > outerDepth)) {
7148 if (type == XmlPullParser.END_TAG
7149 || type == XmlPullParser.TEXT) {
7150 continue;
7151 }
7152
7153 String tagName = parser.getName();
7154 if (tagName.equals("disabled-components")) {
7155 readDisabledComponentsLP(packageSetting, parser);
7156 } else if (tagName.equals("enabled-components")) {
7157 readEnabledComponentsLP(packageSetting, parser);
7158 } else if (tagName.equals("sigs")) {
7159 packageSetting.signatures.readXml(parser, mPastSignatures);
7160 } else if (tagName.equals("perms")) {
7161 readGrantedPermissionsLP(parser,
7162 packageSetting.loadedPermissions);
7163 packageSetting.permissionsFixed = true;
7164 } else {
7165 reportSettingsProblem(Log.WARN,
7166 "Unknown element under <package>: "
7167 + parser.getName());
7168 XmlUtils.skipCurrentTag(parser);
7169 }
7170 }
7171 } else {
7172 XmlUtils.skipCurrentTag(parser);
7173 }
7174 }
7175
7176 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7177 XmlPullParser parser)
7178 throws IOException, XmlPullParserException {
7179 int outerDepth = parser.getDepth();
7180 int type;
7181 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7182 && (type != XmlPullParser.END_TAG
7183 || parser.getDepth() > outerDepth)) {
7184 if (type == XmlPullParser.END_TAG
7185 || type == XmlPullParser.TEXT) {
7186 continue;
7187 }
7188
7189 String tagName = parser.getName();
7190 if (tagName.equals("item")) {
7191 String name = parser.getAttributeValue(null, "name");
7192 if (name != null) {
7193 packageSetting.disabledComponents.add(name.intern());
7194 } else {
7195 reportSettingsProblem(Log.WARN,
7196 "Error in package manager settings: <disabled-components> has"
7197 + " no name at " + parser.getPositionDescription());
7198 }
7199 } else {
7200 reportSettingsProblem(Log.WARN,
7201 "Unknown element under <disabled-components>: "
7202 + parser.getName());
7203 }
7204 XmlUtils.skipCurrentTag(parser);
7205 }
7206 }
7207
7208 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
7209 XmlPullParser parser)
7210 throws IOException, XmlPullParserException {
7211 int outerDepth = parser.getDepth();
7212 int type;
7213 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7214 && (type != XmlPullParser.END_TAG
7215 || parser.getDepth() > outerDepth)) {
7216 if (type == XmlPullParser.END_TAG
7217 || type == XmlPullParser.TEXT) {
7218 continue;
7219 }
7220
7221 String tagName = parser.getName();
7222 if (tagName.equals("item")) {
7223 String name = parser.getAttributeValue(null, "name");
7224 if (name != null) {
7225 packageSetting.enabledComponents.add(name.intern());
7226 } else {
7227 reportSettingsProblem(Log.WARN,
7228 "Error in package manager settings: <enabled-components> has"
7229 + " no name at " + parser.getPositionDescription());
7230 }
7231 } else {
7232 reportSettingsProblem(Log.WARN,
7233 "Unknown element under <enabled-components>: "
7234 + parser.getName());
7235 }
7236 XmlUtils.skipCurrentTag(parser);
7237 }
7238 }
7239
7240 private void readSharedUserLP(XmlPullParser parser)
7241 throws XmlPullParserException, IOException {
7242 String name = null;
7243 String idStr = null;
7244 int pkgFlags = 0;
7245 SharedUserSetting su = null;
7246 try {
7247 name = parser.getAttributeValue(null, "name");
7248 idStr = parser.getAttributeValue(null, "userId");
7249 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7250 if ("true".equals(parser.getAttributeValue(null, "system"))) {
7251 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7252 }
7253 if (name == null) {
7254 reportSettingsProblem(Log.WARN,
7255 "Error in package manager settings: <shared-user> has no name at "
7256 + parser.getPositionDescription());
7257 } else if (userId == 0) {
7258 reportSettingsProblem(Log.WARN,
7259 "Error in package manager settings: shared-user "
7260 + name + " has bad userId " + idStr + " at "
7261 + parser.getPositionDescription());
7262 } else {
7263 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
7264 reportSettingsProblem(Log.ERROR,
7265 "Occurred while parsing settings at "
7266 + parser.getPositionDescription());
7267 }
7268 }
7269 } catch (NumberFormatException e) {
7270 reportSettingsProblem(Log.WARN,
7271 "Error in package manager settings: package "
7272 + name + " has bad userId " + idStr + " at "
7273 + parser.getPositionDescription());
7274 };
7275
7276 if (su != null) {
7277 int outerDepth = parser.getDepth();
7278 int type;
7279 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7280 && (type != XmlPullParser.END_TAG
7281 || parser.getDepth() > outerDepth)) {
7282 if (type == XmlPullParser.END_TAG
7283 || type == XmlPullParser.TEXT) {
7284 continue;
7285 }
7286
7287 String tagName = parser.getName();
7288 if (tagName.equals("sigs")) {
7289 su.signatures.readXml(parser, mPastSignatures);
7290 } else if (tagName.equals("perms")) {
7291 readGrantedPermissionsLP(parser, su.loadedPermissions);
7292 } else {
7293 reportSettingsProblem(Log.WARN,
7294 "Unknown element under <shared-user>: "
7295 + parser.getName());
7296 XmlUtils.skipCurrentTag(parser);
7297 }
7298 }
7299
7300 } else {
7301 XmlUtils.skipCurrentTag(parser);
7302 }
7303 }
7304
7305 private void readGrantedPermissionsLP(XmlPullParser parser,
7306 HashSet<String> outPerms) throws IOException, XmlPullParserException {
7307 int outerDepth = parser.getDepth();
7308 int type;
7309 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7310 && (type != XmlPullParser.END_TAG
7311 || parser.getDepth() > outerDepth)) {
7312 if (type == XmlPullParser.END_TAG
7313 || type == XmlPullParser.TEXT) {
7314 continue;
7315 }
7316
7317 String tagName = parser.getName();
7318 if (tagName.equals("item")) {
7319 String name = parser.getAttributeValue(null, "name");
7320 if (name != null) {
7321 outPerms.add(name.intern());
7322 } else {
7323 reportSettingsProblem(Log.WARN,
7324 "Error in package manager settings: <perms> has"
7325 + " no name at " + parser.getPositionDescription());
7326 }
7327 } else {
7328 reportSettingsProblem(Log.WARN,
7329 "Unknown element under <perms>: "
7330 + parser.getName());
7331 }
7332 XmlUtils.skipCurrentTag(parser);
7333 }
7334 }
7335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 private void readPreferredActivitiesLP(XmlPullParser parser)
7337 throws XmlPullParserException, IOException {
7338 int outerDepth = parser.getDepth();
7339 int type;
7340 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7341 && (type != XmlPullParser.END_TAG
7342 || parser.getDepth() > outerDepth)) {
7343 if (type == XmlPullParser.END_TAG
7344 || type == XmlPullParser.TEXT) {
7345 continue;
7346 }
7347
7348 String tagName = parser.getName();
7349 if (tagName.equals("item")) {
7350 PreferredActivity pa = new PreferredActivity(parser);
7351 if (pa.mParseError == null) {
7352 mPreferredActivities.addFilter(pa);
7353 } else {
7354 reportSettingsProblem(Log.WARN,
7355 "Error in package manager settings: <preferred-activity> "
7356 + pa.mParseError + " at "
7357 + parser.getPositionDescription());
7358 }
7359 } else {
7360 reportSettingsProblem(Log.WARN,
7361 "Unknown element under <preferred-activities>: "
7362 + parser.getName());
7363 XmlUtils.skipCurrentTag(parser);
7364 }
7365 }
7366 }
7367
7368 // Returns -1 if we could not find an available UserId to assign
7369 private int newUserIdLP(Object obj) {
7370 // Let's be stupidly inefficient for now...
7371 final int N = mUserIds.size();
7372 for (int i=0; i<N; i++) {
7373 if (mUserIds.get(i) == null) {
7374 mUserIds.set(i, obj);
7375 return FIRST_APPLICATION_UID + i;
7376 }
7377 }
7378
7379 // None left?
7380 if (N >= MAX_APPLICATION_UIDS) {
7381 return -1;
7382 }
7383
7384 mUserIds.add(obj);
7385 return FIRST_APPLICATION_UID + N;
7386 }
7387
7388 public PackageSetting getDisabledSystemPkg(String name) {
7389 synchronized(mPackages) {
7390 PackageSetting ps = mDisabledSysPackages.get(name);
7391 return ps;
7392 }
7393 }
7394
7395 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7396 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7397 if (Config.LOGV) {
7398 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7399 + " componentName = " + componentInfo.name);
7400 Log.v(TAG, "enabledComponents: "
7401 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7402 Log.v(TAG, "disabledComponents: "
7403 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7404 }
7405 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7406 || ((componentInfo.enabled
7407 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7408 || (componentInfo.applicationInfo.enabled
7409 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7410 && !packageSettings.disabledComponents.contains(componentInfo.name))
7411 || packageSettings.enabledComponents.contains(componentInfo.name));
7412 }
7413 }
7414}