blob: 6df9f2ba47d9601be34c058bf8e54cf52a86b59d [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);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08001980 // Don't mess around with apps in system partition.
1981 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0) {
1982 // Delete the apk
1983 Log.w(TAG, "Cleaning up failed install of " + file);
1984 file.delete();
1985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
1987 }
1988
1989 private static void reportSettingsProblem(int priority, String msg) {
1990 try {
1991 File dataDir = Environment.getDataDirectory();
1992 File systemDir = new File(dataDir, "system");
1993 File fname = new File(systemDir, "uiderrors.txt");
1994 FileOutputStream out = new FileOutputStream(fname, true);
1995 PrintWriter pw = new PrintWriter(out);
1996 pw.println(msg);
1997 pw.close();
1998 FileUtils.setPermissions(
1999 fname.toString(),
2000 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2001 -1, -1);
2002 } catch (java.io.IOException e) {
2003 }
2004 Log.println(priority, TAG, msg);
2005 }
2006
2007 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2008 PackageParser.Package pkg, File srcFile, int parseFlags) {
2009 if (GET_CERTIFICATES) {
2010 if (ps == null || !ps.codePath.equals(srcFile)
2011 || ps.getTimeStamp() != srcFile.lastModified()) {
2012 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2013 if (!pp.collectCertificates(pkg, parseFlags)) {
2014 mLastScanError = pp.getParseError();
2015 return false;
2016 }
2017 }
2018 }
2019 return true;
2020 }
2021
2022 /*
2023 * Scan a package and return the newly parsed package.
2024 * Returns null in case of errors and the error code is stored in mLastScanError
2025 */
2026 private PackageParser.Package scanPackageLI(File scanFile,
2027 File destCodeFile, File destResourceFile, int parseFlags,
2028 int scanMode) {
2029 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2030 parseFlags |= mDefParseFlags;
2031 PackageParser pp = new PackageParser(scanFile.getPath());
2032 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 final PackageParser.Package pkg = pp.parsePackage(scanFile,
2034 destCodeFile.getAbsolutePath(), mMetrics, parseFlags);
2035 if (pkg == null) {
2036 mLastScanError = pp.getParseError();
2037 return null;
2038 }
2039 PackageSetting ps;
2040 PackageSetting updatedPkg;
2041 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002042 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2044 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002045 // Verify certificates first
2046 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2047 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2048 return null;
2049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 if (updatedPkg != null) {
2051 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2052 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2053 }
2054 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2055 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002056 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2057 if (pkg.mVersionCode < ps.versionCode) {
2058 // The system package has been updated and the code path does not match
2059 // Ignore entry. Just return
2060 Log.w(TAG, "Package:" + pkg.packageName +
2061 " has been updated. Ignoring the one from path:"+scanFile);
2062 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2063 return null;
2064 } else {
2065 // Delete the older apk pointed to by ps
2066 // At this point, its safely assumed that package installation for
2067 // apps in system partition will go through. If not there won't be a working
2068 // version of the app
2069 synchronized (mPackages) {
2070 // Just remove the loaded entries from package lists.
2071 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002072 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002073 deletePackageResourcesLI(ps.name, ps.codePathString, ps.resourcePathString);
2074 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 }
2077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 // The apk is forward locked (not public) if its code and resources
2079 // are kept in different files.
2080 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
2081 scanMode |= SCAN_FORWARD_LOCKED;
2082 }
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002083 File resFile = destResourceFile;
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07002084 if (ps != null && ((scanMode & SCAN_FORWARD_LOCKED) != 0)) {
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002085 resFile = getFwdLockedResource(ps.name);
2086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002088 return scanPackageLI(scanFile, destCodeFile, resFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
2090 }
2091
2092 private static String fixProcessName(String defProcessName,
2093 String processName, int uid) {
2094 if (processName == null) {
2095 return defProcessName;
2096 }
2097 return processName;
2098 }
2099
2100 private boolean verifySignaturesLP(PackageSetting pkgSetting,
2101 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2102 if (pkg.mSignatures != null) {
2103 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2104 updateSignature)) {
2105 Log.e(TAG, "Package " + pkg.packageName
2106 + " signatures do not match the previously installed version; ignoring!");
2107 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2108 return false;
2109 }
2110
2111 if (pkgSetting.sharedUser != null) {
2112 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2113 pkg.mSignatures, updateSignature)) {
2114 Log.e(TAG, "Package " + pkg.packageName
2115 + " has no signatures that match those in shared user "
2116 + pkgSetting.sharedUser.name + "; ignoring!");
2117 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2118 return false;
2119 }
2120 }
2121 } else {
2122 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2123 }
2124 return true;
2125 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002126
2127 public boolean performDexOpt(String packageName) {
2128 if (!mNoDexOpt) {
2129 return false;
2130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002132 PackageParser.Package p;
2133 synchronized (mPackages) {
2134 p = mPackages.get(packageName);
2135 if (p == null || p.mDidDexOpt) {
2136 return false;
2137 }
2138 }
2139 synchronized (mInstallLock) {
2140 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2141 }
2142 }
2143
2144 static final int DEX_OPT_SKIPPED = 0;
2145 static final int DEX_OPT_PERFORMED = 1;
2146 static final int DEX_OPT_FAILED = -1;
2147
2148 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2149 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002150 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002151 String path = pkg.mScanPath;
2152 int ret = 0;
2153 try {
2154 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
2155 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
2156 !pkg.mForwardLocked);
2157 pkg.mDidDexOpt = true;
2158 performed = true;
2159 }
2160 } catch (FileNotFoundException e) {
2161 Log.w(TAG, "Apk not found for dexopt: " + path);
2162 ret = -1;
2163 } catch (IOException e) {
2164 Log.w(TAG, "Exception reading apk: " + path, e);
2165 ret = -1;
2166 }
2167 if (ret < 0) {
2168 //error from installer
2169 return DEX_OPT_FAILED;
2170 }
2171 }
2172
2173 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2174 }
2175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 private PackageParser.Package scanPackageLI(
2177 File scanFile, File destCodeFile, File destResourceFile,
2178 PackageParser.Package pkg, int parseFlags, int scanMode) {
2179
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002180 if (scanFile == null || destCodeFile == null ||
2181 destResourceFile == null) {
2182 // Bail out. The resource and code paths haven't been set.
2183 Log.w(TAG, " Code and resource paths haven't been set correctly");
2184 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2185 return null;
2186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 mScanningPath = scanFile;
2188 if (pkg == null) {
2189 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2190 return null;
2191 }
2192
2193 final String pkgName = pkg.applicationInfo.packageName;
2194 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2195 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2196 }
2197
2198 if (pkgName.equals("android")) {
2199 synchronized (mPackages) {
2200 if (mAndroidApplication != null) {
2201 Log.w(TAG, "*************************************************");
2202 Log.w(TAG, "Core android package being redefined. Skipping.");
2203 Log.w(TAG, " file=" + mScanningPath);
2204 Log.w(TAG, "*************************************************");
2205 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2206 return null;
2207 }
2208
2209 // Set up information for our fall-back user intent resolution
2210 // activity.
2211 mPlatformPackage = pkg;
2212 pkg.mVersionCode = mSdkVersion;
2213 mAndroidApplication = pkg.applicationInfo;
2214 mResolveActivity.applicationInfo = mAndroidApplication;
2215 mResolveActivity.name = ResolverActivity.class.getName();
2216 mResolveActivity.packageName = mAndroidApplication.packageName;
2217 mResolveActivity.processName = mAndroidApplication.processName;
2218 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2219 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2220 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2221 mResolveActivity.exported = true;
2222 mResolveActivity.enabled = true;
2223 mResolveInfo.activityInfo = mResolveActivity;
2224 mResolveInfo.priority = 0;
2225 mResolveInfo.preferredOrder = 0;
2226 mResolveInfo.match = 0;
2227 mResolveComponentName = new ComponentName(
2228 mAndroidApplication.packageName, mResolveActivity.name);
2229 }
2230 }
2231
2232 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2233 TAG, "Scanning package " + pkgName);
2234 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2235 Log.w(TAG, "*************************************************");
2236 Log.w(TAG, "Application package " + pkgName
2237 + " already installed. Skipping duplicate.");
2238 Log.w(TAG, "*************************************************");
2239 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2240 return null;
2241 }
2242
2243 SharedUserSetting suid = null;
2244 PackageSetting pkgSetting = null;
2245
2246 boolean removeExisting = false;
2247
2248 synchronized (mPackages) {
2249 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002250 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2251 if (mTmpSharedLibraries == null ||
2252 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2253 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2254 }
2255 int num = 0;
2256 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2257 for (int i=0; i<N; i++) {
2258 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 if (file == null) {
2260 Log.e(TAG, "Package " + pkg.packageName
2261 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002262 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2264 return null;
2265 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002266 mTmpSharedLibraries[num] = file;
2267 num++;
2268 }
2269 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2270 for (int i=0; i<N; i++) {
2271 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2272 if (file == null) {
2273 Log.w(TAG, "Package " + pkg.packageName
2274 + " desires unavailable shared library "
2275 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2276 } else {
2277 mTmpSharedLibraries[num] = file;
2278 num++;
2279 }
2280 }
2281 if (num > 0) {
2282 pkg.usesLibraryFiles = new String[num];
2283 System.arraycopy(mTmpSharedLibraries, 0,
2284 pkg.usesLibraryFiles, 0, num);
2285 }
2286
2287 if (pkg.reqFeatures != null) {
2288 N = pkg.reqFeatures.size();
2289 for (int i=0; i<N; i++) {
2290 FeatureInfo fi = pkg.reqFeatures.get(i);
2291 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2292 // Don't care.
2293 continue;
2294 }
2295
2296 if (fi.name != null) {
2297 if (mAvailableFeatures.get(fi.name) == null) {
2298 Log.e(TAG, "Package " + pkg.packageName
2299 + " requires unavailable feature "
2300 + fi.name + "; failing!");
2301 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2302 return null;
2303 }
2304 }
2305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 }
2307 }
2308
2309 if (pkg.mSharedUserId != null) {
2310 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2311 pkg.applicationInfo.flags, true);
2312 if (suid == null) {
2313 Log.w(TAG, "Creating application package " + pkgName
2314 + " for shared user failed");
2315 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2316 return null;
2317 }
2318 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2319 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2320 + suid.userId + "): packages=" + suid.packages);
2321 }
2322 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002323
2324 // Just create the setting, don't add it yet. For already existing packages
2325 // the PkgSetting exists already and doesn't have to be created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
2327 destResourceFile, pkg.applicationInfo.flags, true, false);
2328 if (pkgSetting == null) {
2329 Log.w(TAG, "Creating application package " + pkgName + " failed");
2330 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2331 return null;
2332 }
2333 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
2334 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2335 }
2336
2337 pkg.applicationInfo.uid = pkgSetting.userId;
2338 pkg.mExtras = pkgSetting;
2339
2340 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
2341 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2342 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2343 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2344 return null;
2345 }
2346 // The signature has changed, but this package is in the system
2347 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002348 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 // However... if this package is part of a shared user, but it
2350 // doesn't match the signature of the shared user, let's fail.
2351 // What this means is that you can't change the signatures
2352 // associated with an overall shared user, which doesn't seem all
2353 // that unreasonable.
2354 if (pkgSetting.sharedUser != null) {
2355 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2356 pkg.mSignatures, false)) {
2357 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2358 return null;
2359 }
2360 }
2361 removeExisting = true;
2362 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002363
2364 // Verify that this new package doesn't have any content providers
2365 // that conflict with existing packages. Only do this if the
2366 // package isn't already installed, since we don't want to break
2367 // things that are installed.
2368 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2369 int N = pkg.providers.size();
2370 int i;
2371 for (i=0; i<N; i++) {
2372 PackageParser.Provider p = pkg.providers.get(i);
2373 String names[] = p.info.authority.split(";");
2374 for (int j = 0; j < names.length; j++) {
2375 if (mProviders.containsKey(names[j])) {
2376 PackageParser.Provider other = mProviders.get(names[j]);
2377 Log.w(TAG, "Can't install because provider name " + names[j] +
2378 " (in package " + pkg.applicationInfo.packageName +
2379 ") is already used by "
2380 + ((other != null && other.component != null)
2381 ? other.component.getPackageName() : "?"));
2382 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2383 return null;
2384 }
2385 }
2386 }
2387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 }
2389
2390 if (removeExisting) {
2391 if (mInstaller != null) {
2392 int ret = mInstaller.remove(pkgName);
2393 if (ret != 0) {
2394 String msg = "System package " + pkg.packageName
2395 + " could not have data directory erased after signature change.";
2396 reportSettingsProblem(Log.WARN, msg);
2397 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2398 return null;
2399 }
2400 }
2401 Log.w(TAG, "System package " + pkg.packageName
2402 + " signature changed: existing data removed.");
2403 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2404 }
2405
2406 long scanFileTime = scanFile.lastModified();
2407 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2408 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2409 pkg.applicationInfo.processName = fixProcessName(
2410 pkg.applicationInfo.packageName,
2411 pkg.applicationInfo.processName,
2412 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002413 pkg.applicationInfo.publicSourceDir = destResourceFile.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414
2415 File dataPath;
2416 if (mPlatformPackage == pkg) {
2417 // The system package is special.
2418 dataPath = new File (Environment.getDataDirectory(), "system");
2419 pkg.applicationInfo.dataDir = dataPath.getPath();
2420 } else {
2421 // This is a normal package, need to make its data directory.
2422 dataPath = new File(mAppDataDir, pkgName);
2423 if (dataPath.exists()) {
2424 mOutPermissions[1] = 0;
2425 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2426 if (mOutPermissions[1] == pkg.applicationInfo.uid
2427 || !Process.supportsProcesses()) {
2428 pkg.applicationInfo.dataDir = dataPath.getPath();
2429 } else {
2430 boolean recovered = false;
2431 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2432 // If this is a system app, we can at least delete its
2433 // current data so the application will still work.
2434 if (mInstaller != null) {
2435 int ret = mInstaller.remove(pkgName);
2436 if(ret >= 0) {
2437 // Old data gone!
2438 String msg = "System package " + pkg.packageName
2439 + " has changed from uid: "
2440 + mOutPermissions[1] + " to "
2441 + pkg.applicationInfo.uid + "; old data erased";
2442 reportSettingsProblem(Log.WARN, msg);
2443 recovered = true;
2444
2445 // And now re-install the app.
2446 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2447 pkg.applicationInfo.uid);
2448 if (ret == -1) {
2449 // Ack should not happen!
2450 msg = "System package " + pkg.packageName
2451 + " could not have data directory re-created after delete.";
2452 reportSettingsProblem(Log.WARN, msg);
2453 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2454 return null;
2455 }
2456 }
2457 }
2458 if (!recovered) {
2459 mHasSystemUidErrors = true;
2460 }
2461 }
2462 if (!recovered) {
2463 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2464 + pkg.applicationInfo.uid + "/fs_"
2465 + mOutPermissions[1];
2466 String msg = "Package " + pkg.packageName
2467 + " has mismatched uid: "
2468 + mOutPermissions[1] + " on disk, "
2469 + pkg.applicationInfo.uid + " in settings";
2470 synchronized (mPackages) {
2471 if (!mReportedUidError) {
2472 mReportedUidError = true;
2473 msg = msg + "; read messages:\n"
2474 + mSettings.getReadMessagesLP();
2475 }
2476 reportSettingsProblem(Log.ERROR, msg);
2477 }
2478 }
2479 }
2480 pkg.applicationInfo.dataDir = dataPath.getPath();
2481 } else {
2482 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2483 Log.v(TAG, "Want this data dir: " + dataPath);
2484 //invoke installer to do the actual installation
2485 if (mInstaller != null) {
2486 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2487 pkg.applicationInfo.uid);
2488 if(ret < 0) {
2489 // Error from installer
2490 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2491 return null;
2492 }
2493 } else {
2494 dataPath.mkdirs();
2495 if (dataPath.exists()) {
2496 FileUtils.setPermissions(
2497 dataPath.toString(),
2498 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2499 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2500 }
2501 }
2502 if (dataPath.exists()) {
2503 pkg.applicationInfo.dataDir = dataPath.getPath();
2504 } else {
2505 Log.w(TAG, "Unable to create data directory: " + dataPath);
2506 pkg.applicationInfo.dataDir = null;
2507 }
2508 }
2509 }
2510
2511 // Perform shared library installation and dex validation and
2512 // optimization, if this is not a system app.
2513 if (mInstaller != null) {
2514 String path = scanFile.getPath();
2515 if (scanFileNewer) {
2516 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002517 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2518 if (err != PackageManager.INSTALL_SUCCEEDED) {
2519 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 return null;
2521 }
2522 }
2523
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002524 pkg.mForwardLocked = (scanMode&SCAN_FORWARD_LOCKED) != 0;
2525 pkg.mScanPath = path;
2526
2527 if ((scanMode&SCAN_NO_DEX) == 0) {
2528 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2530 return null;
2531 }
2532 }
2533 }
2534
2535 if (mFactoryTest && pkg.requestedPermissions.contains(
2536 android.Manifest.permission.FACTORY_TEST)) {
2537 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2538 }
2539
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002540 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 if ((scanMode&SCAN_MONITOR) != 0) {
2542 pkg.mPath = destCodeFile.getAbsolutePath();
2543 mAppDirs.put(pkg.mPath, pkg);
2544 }
2545
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002546 // Request the ActivityManager to kill the process(only for existing packages)
2547 // so that we do not end up in a confused state while the user is still using the older
2548 // version of the application while the new one gets installed.
2549 IActivityManager am = ActivityManagerNative.getDefault();
2550 if ((am != null) && ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0)) {
2551 try {
2552 am.killApplicationWithUid(pkg.applicationInfo.packageName,
2553 pkg.applicationInfo.uid);
2554 } catch (RemoteException e) {
2555 }
2556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 // Add the new setting to mSettings
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002559 mSettings.insertPackageSettingLP(pkgSetting, pkg, destCodeFile, destResourceFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002561 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 int N = pkg.providers.size();
2563 StringBuilder r = null;
2564 int i;
2565 for (i=0; i<N; i++) {
2566 PackageParser.Provider p = pkg.providers.get(i);
2567 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2568 p.info.processName, pkg.applicationInfo.uid);
2569 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2570 p.info.name), p);
2571 p.syncable = p.info.isSyncable;
2572 String names[] = p.info.authority.split(";");
2573 p.info.authority = null;
2574 for (int j = 0; j < names.length; j++) {
2575 if (j == 1 && p.syncable) {
2576 // We only want the first authority for a provider to possibly be
2577 // syncable, so if we already added this provider using a different
2578 // authority clear the syncable flag. We copy the provider before
2579 // changing it because the mProviders object contains a reference
2580 // to a provider that we don't want to change.
2581 // Only do this for the second authority since the resulting provider
2582 // object can be the same for all future authorities for this provider.
2583 p = new PackageParser.Provider(p);
2584 p.syncable = false;
2585 }
2586 if (!mProviders.containsKey(names[j])) {
2587 mProviders.put(names[j], p);
2588 if (p.info.authority == null) {
2589 p.info.authority = names[j];
2590 } else {
2591 p.info.authority = p.info.authority + ";" + names[j];
2592 }
2593 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2594 Log.d(TAG, "Registered content provider: " + names[j] +
2595 ", className = " + p.info.name +
2596 ", isSyncable = " + p.info.isSyncable);
2597 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002598 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 Log.w(TAG, "Skipping provider name " + names[j] +
2600 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002601 "): name already used by "
2602 + ((other != null && other.component != null)
2603 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 }
2605 }
2606 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2607 if (r == null) {
2608 r = new StringBuilder(256);
2609 } else {
2610 r.append(' ');
2611 }
2612 r.append(p.info.name);
2613 }
2614 }
2615 if (r != null) {
2616 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2617 }
2618
2619 N = pkg.services.size();
2620 r = null;
2621 for (i=0; i<N; i++) {
2622 PackageParser.Service s = pkg.services.get(i);
2623 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2624 s.info.processName, pkg.applicationInfo.uid);
2625 mServices.addService(s);
2626 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2627 if (r == null) {
2628 r = new StringBuilder(256);
2629 } else {
2630 r.append(' ');
2631 }
2632 r.append(s.info.name);
2633 }
2634 }
2635 if (r != null) {
2636 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2637 }
2638
2639 N = pkg.receivers.size();
2640 r = null;
2641 for (i=0; i<N; i++) {
2642 PackageParser.Activity a = pkg.receivers.get(i);
2643 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2644 a.info.processName, pkg.applicationInfo.uid);
2645 mReceivers.addActivity(a, "receiver");
2646 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2647 if (r == null) {
2648 r = new StringBuilder(256);
2649 } else {
2650 r.append(' ');
2651 }
2652 r.append(a.info.name);
2653 }
2654 }
2655 if (r != null) {
2656 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2657 }
2658
2659 N = pkg.activities.size();
2660 r = null;
2661 for (i=0; i<N; i++) {
2662 PackageParser.Activity a = pkg.activities.get(i);
2663 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2664 a.info.processName, pkg.applicationInfo.uid);
2665 mActivities.addActivity(a, "activity");
2666 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2667 if (r == null) {
2668 r = new StringBuilder(256);
2669 } else {
2670 r.append(' ');
2671 }
2672 r.append(a.info.name);
2673 }
2674 }
2675 if (r != null) {
2676 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2677 }
2678
2679 N = pkg.permissionGroups.size();
2680 r = null;
2681 for (i=0; i<N; i++) {
2682 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2683 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2684 if (cur == null) {
2685 mPermissionGroups.put(pg.info.name, pg);
2686 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2687 if (r == null) {
2688 r = new StringBuilder(256);
2689 } else {
2690 r.append(' ');
2691 }
2692 r.append(pg.info.name);
2693 }
2694 } else {
2695 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2696 + pg.info.packageName + " ignored: original from "
2697 + cur.info.packageName);
2698 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2699 if (r == null) {
2700 r = new StringBuilder(256);
2701 } else {
2702 r.append(' ');
2703 }
2704 r.append("DUP:");
2705 r.append(pg.info.name);
2706 }
2707 }
2708 }
2709 if (r != null) {
2710 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2711 }
2712
2713 N = pkg.permissions.size();
2714 r = null;
2715 for (i=0; i<N; i++) {
2716 PackageParser.Permission p = pkg.permissions.get(i);
2717 HashMap<String, BasePermission> permissionMap =
2718 p.tree ? mSettings.mPermissionTrees
2719 : mSettings.mPermissions;
2720 p.group = mPermissionGroups.get(p.info.group);
2721 if (p.info.group == null || p.group != null) {
2722 BasePermission bp = permissionMap.get(p.info.name);
2723 if (bp == null) {
2724 bp = new BasePermission(p.info.name, p.info.packageName,
2725 BasePermission.TYPE_NORMAL);
2726 permissionMap.put(p.info.name, bp);
2727 }
2728 if (bp.perm == null) {
2729 if (bp.sourcePackage == null
2730 || bp.sourcePackage.equals(p.info.packageName)) {
2731 BasePermission tree = findPermissionTreeLP(p.info.name);
2732 if (tree == null
2733 || tree.sourcePackage.equals(p.info.packageName)) {
2734 bp.perm = p;
2735 bp.uid = pkg.applicationInfo.uid;
2736 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2737 if (r == null) {
2738 r = new StringBuilder(256);
2739 } else {
2740 r.append(' ');
2741 }
2742 r.append(p.info.name);
2743 }
2744 } else {
2745 Log.w(TAG, "Permission " + p.info.name + " from package "
2746 + p.info.packageName + " ignored: base tree "
2747 + tree.name + " is from package "
2748 + tree.sourcePackage);
2749 }
2750 } else {
2751 Log.w(TAG, "Permission " + p.info.name + " from package "
2752 + p.info.packageName + " ignored: original from "
2753 + bp.sourcePackage);
2754 }
2755 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2756 if (r == null) {
2757 r = new StringBuilder(256);
2758 } else {
2759 r.append(' ');
2760 }
2761 r.append("DUP:");
2762 r.append(p.info.name);
2763 }
2764 } else {
2765 Log.w(TAG, "Permission " + p.info.name + " from package "
2766 + p.info.packageName + " ignored: no group "
2767 + p.group);
2768 }
2769 }
2770 if (r != null) {
2771 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2772 }
2773
2774 N = pkg.instrumentation.size();
2775 r = null;
2776 for (i=0; i<N; i++) {
2777 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2778 a.info.packageName = pkg.applicationInfo.packageName;
2779 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2780 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2781 a.info.dataDir = pkg.applicationInfo.dataDir;
2782 mInstrumentation.put(a.component, a);
2783 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2784 if (r == null) {
2785 r = new StringBuilder(256);
2786 } else {
2787 r.append(' ');
2788 }
2789 r.append(a.info.name);
2790 }
2791 }
2792 if (r != null) {
2793 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2794 }
2795
Dianne Hackborn854060af2009-07-09 18:14:31 -07002796 if (pkg.protectedBroadcasts != null) {
2797 N = pkg.protectedBroadcasts.size();
2798 for (i=0; i<N; i++) {
2799 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
2800 }
2801 }
2802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 pkgSetting.setTimeStamp(scanFileTime);
2804 }
2805
2806 return pkg;
2807 }
2808
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002809 // The following constants are returned by cachePackageSharedLibsForAbiLI
2810 // to indicate if native shared libraries were found in the package.
2811 // Values are:
2812 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
2813 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
2814 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
2815 // in package (and not installed)
2816 //
2817 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
2818 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
2819 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002821 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
2822 // and automatically copy them to /data/data/<appname>/lib if present.
2823 //
2824 // NOTE: this method may throw an IOException if the library cannot
2825 // be copied to its final destination, e.g. if there isn't enough
2826 // room left on the data partition, or a ZipException if the package
2827 // file is malformed.
2828 //
2829 private int cachePackageSharedLibsForAbiLI( PackageParser.Package pkg,
2830 File dataPath, File scanFile, String cpuAbi)
2831 throws IOException, ZipException {
2832 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
2833 final String apkLib = "lib/";
2834 final int apkLibLen = apkLib.length();
2835 final int cpuAbiLen = cpuAbi.length();
2836 final String libPrefix = "lib";
2837 final int libPrefixLen = libPrefix.length();
2838 final String libSuffix = ".so";
2839 final int libSuffixLen = libSuffix.length();
2840 boolean hasNativeLibraries = false;
2841 boolean installedNativeLibraries = false;
2842
2843 // the minimum length of a valid native shared library of the form
2844 // lib/<something>/lib<name>.so.
2845 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
2846
2847 ZipFile zipFile = new ZipFile(scanFile);
2848 Enumeration<ZipEntry> entries =
2849 (Enumeration<ZipEntry>) zipFile.entries();
2850
2851 while (entries.hasMoreElements()) {
2852 ZipEntry entry = entries.nextElement();
2853 // skip directories
2854 if (entry.isDirectory()) {
2855 continue;
2856 }
2857 String entryName = entry.getName();
2858
2859 // check that the entry looks like lib/<something>/lib<name>.so
2860 // here, but don't check the ABI just yet.
2861 //
2862 // - must be sufficiently long
2863 // - must end with libSuffix, i.e. ".so"
2864 // - must start with apkLib, i.e. "lib/"
2865 if (entryName.length() < minEntryLen ||
2866 !entryName.endsWith(libSuffix) ||
2867 !entryName.startsWith(apkLib) ) {
2868 continue;
2869 }
2870
2871 // file name must start with libPrefix, i.e. "lib"
2872 int lastSlash = entryName.lastIndexOf('/');
2873
2874 if (lastSlash < 0 ||
2875 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
2876 continue;
2877 }
2878
2879 hasNativeLibraries = true;
2880
2881 // check the cpuAbi now, between lib/ and /lib<name>.so
2882 //
2883 if (lastSlash != apkLibLen + cpuAbiLen ||
2884 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
2885 continue;
2886
2887 // extract the library file name, ensure it doesn't contain
2888 // weird characters. we're guaranteed here that it doesn't contain
2889 // a directory separator though.
2890 String libFileName = entryName.substring(lastSlash+1);
2891 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
2892 continue;
2893 }
2894
2895 installedNativeLibraries = true;
2896
2897 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
2898 File.separator + libFileName;
2899 File sharedLibraryFile = new File(sharedLibraryFilePath);
2900 if (! sharedLibraryFile.exists() ||
2901 sharedLibraryFile.length() != entry.getSize() ||
2902 sharedLibraryFile.lastModified() != entry.getTime()) {
2903 if (Config.LOGD) {
2904 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002906 if (mInstaller == null) {
2907 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07002908 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002909 cacheSharedLibLI(pkg, zipFile, entry, sharedLibraryDir,
2910 sharedLibraryFile);
2911 }
2912 }
2913 if (!hasNativeLibraries)
2914 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
2915
2916 if (!installedNativeLibraries)
2917 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
2918
2919 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
2920 }
2921
2922 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
2923 // and copy them to /data/data/<appname>/lib.
2924 //
2925 // This function will first try the main CPU ABI defined by Build.CPU_ABI
2926 // (which corresponds to ro.product.cpu.abi), and also try an alternate
2927 // one if ro.product.cpu.abi2 is defined.
2928 //
2929 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
2930 File dataPath, File scanFile) {
2931 final String cpuAbi = Build.CPU_ABI;
2932 try {
2933 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
2934
2935 // some architectures are capable of supporting several CPU ABIs
2936 // for example, 'armeabi-v7a' also supports 'armeabi' native code
2937 // this is indicated by the definition of the ro.product.cpu.abi2
2938 // system property.
2939 //
2940 // only scan the package twice in case of ABI mismatch
2941 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
2942 String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
2943 if (cpuAbi2 != null) {
2944 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002946
2947 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
2948 Log.w(TAG,"Native ABI mismatch from package file");
2949 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
2951 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002952 } catch (ZipException e) {
2953 Log.w(TAG, "Failed to extract data from package file", e);
2954 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002956 Log.w(TAG, "Failed to cache package shared libs", e);
2957 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002959 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 }
2961
2962 private void cacheSharedLibLI(PackageParser.Package pkg,
2963 ZipFile zipFile, ZipEntry entry,
2964 File sharedLibraryDir,
2965 File sharedLibraryFile) throws IOException {
2966 InputStream inputStream = zipFile.getInputStream(entry);
2967 try {
2968 File tempFile = File.createTempFile("tmp", "tmp", sharedLibraryDir);
2969 String tempFilePath = tempFile.getPath();
2970 // XXX package manager can't change owner, so the lib files for
2971 // now need to be left as world readable and owned by the system.
2972 if (! FileUtils.copyToFile(inputStream, tempFile) ||
2973 ! tempFile.setLastModified(entry.getTime()) ||
2974 FileUtils.setPermissions(tempFilePath,
2975 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
2976 |FileUtils.S_IROTH, -1, -1) != 0 ||
2977 ! tempFile.renameTo(sharedLibraryFile)) {
2978 // Failed to properly write file.
2979 tempFile.delete();
2980 throw new IOException("Couldn't create cached shared lib "
2981 + sharedLibraryFile + " in " + sharedLibraryDir);
2982 }
2983 } finally {
2984 inputStream.close();
2985 }
2986 }
2987
2988 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
2989 if (chatty && Config.LOGD) Log.d(
2990 TAG, "Removing package " + pkg.applicationInfo.packageName );
2991
2992 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 clearPackagePreferredActivitiesLP(pkg.packageName);
2994
2995 mPackages.remove(pkg.applicationInfo.packageName);
2996 if (pkg.mPath != null) {
2997 mAppDirs.remove(pkg.mPath);
2998 }
2999
3000 PackageSetting ps = (PackageSetting)pkg.mExtras;
3001 if (ps != null && ps.sharedUser != null) {
3002 // XXX don't do this until the data is removed.
3003 if (false) {
3004 ps.sharedUser.packages.remove(ps);
3005 if (ps.sharedUser.packages.size() == 0) {
3006 // Remove.
3007 }
3008 }
3009 }
3010
3011 int N = pkg.providers.size();
3012 StringBuilder r = null;
3013 int i;
3014 for (i=0; i<N; i++) {
3015 PackageParser.Provider p = pkg.providers.get(i);
3016 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3017 p.info.name));
3018 if (p.info.authority == null) {
3019
3020 /* The is another ContentProvider with this authority when
3021 * this app was installed so this authority is null,
3022 * Ignore it as we don't have to unregister the provider.
3023 */
3024 continue;
3025 }
3026 String names[] = p.info.authority.split(";");
3027 for (int j = 0; j < names.length; j++) {
3028 if (mProviders.get(names[j]) == p) {
3029 mProviders.remove(names[j]);
3030 if (chatty && Config.LOGD) Log.d(
3031 TAG, "Unregistered content provider: " + names[j] +
3032 ", className = " + p.info.name +
3033 ", isSyncable = " + p.info.isSyncable);
3034 }
3035 }
3036 if (chatty) {
3037 if (r == null) {
3038 r = new StringBuilder(256);
3039 } else {
3040 r.append(' ');
3041 }
3042 r.append(p.info.name);
3043 }
3044 }
3045 if (r != null) {
3046 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3047 }
3048
3049 N = pkg.services.size();
3050 r = null;
3051 for (i=0; i<N; i++) {
3052 PackageParser.Service s = pkg.services.get(i);
3053 mServices.removeService(s);
3054 if (chatty) {
3055 if (r == null) {
3056 r = new StringBuilder(256);
3057 } else {
3058 r.append(' ');
3059 }
3060 r.append(s.info.name);
3061 }
3062 }
3063 if (r != null) {
3064 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3065 }
3066
3067 N = pkg.receivers.size();
3068 r = null;
3069 for (i=0; i<N; i++) {
3070 PackageParser.Activity a = pkg.receivers.get(i);
3071 mReceivers.removeActivity(a, "receiver");
3072 if (chatty) {
3073 if (r == null) {
3074 r = new StringBuilder(256);
3075 } else {
3076 r.append(' ');
3077 }
3078 r.append(a.info.name);
3079 }
3080 }
3081 if (r != null) {
3082 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3083 }
3084
3085 N = pkg.activities.size();
3086 r = null;
3087 for (i=0; i<N; i++) {
3088 PackageParser.Activity a = pkg.activities.get(i);
3089 mActivities.removeActivity(a, "activity");
3090 if (chatty) {
3091 if (r == null) {
3092 r = new StringBuilder(256);
3093 } else {
3094 r.append(' ');
3095 }
3096 r.append(a.info.name);
3097 }
3098 }
3099 if (r != null) {
3100 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3101 }
3102
3103 N = pkg.permissions.size();
3104 r = null;
3105 for (i=0; i<N; i++) {
3106 PackageParser.Permission p = pkg.permissions.get(i);
3107 boolean tree = false;
3108 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3109 if (bp == null) {
3110 tree = true;
3111 bp = mSettings.mPermissionTrees.get(p.info.name);
3112 }
3113 if (bp != null && bp.perm == p) {
3114 if (bp.type != BasePermission.TYPE_BUILTIN) {
3115 if (tree) {
3116 mSettings.mPermissionTrees.remove(p.info.name);
3117 } else {
3118 mSettings.mPermissions.remove(p.info.name);
3119 }
3120 } else {
3121 bp.perm = null;
3122 }
3123 if (chatty) {
3124 if (r == null) {
3125 r = new StringBuilder(256);
3126 } else {
3127 r.append(' ');
3128 }
3129 r.append(p.info.name);
3130 }
3131 }
3132 }
3133 if (r != null) {
3134 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3135 }
3136
3137 N = pkg.instrumentation.size();
3138 r = null;
3139 for (i=0; i<N; i++) {
3140 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3141 mInstrumentation.remove(a.component);
3142 if (chatty) {
3143 if (r == null) {
3144 r = new StringBuilder(256);
3145 } else {
3146 r.append(' ');
3147 }
3148 r.append(a.info.name);
3149 }
3150 }
3151 if (r != null) {
3152 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3153 }
3154 }
3155 }
3156
3157 private static final boolean isPackageFilename(String name) {
3158 return name != null && name.endsWith(".apk");
3159 }
3160
3161 private void updatePermissionsLP() {
3162 // Make sure there are no dangling permission trees.
3163 Iterator<BasePermission> it = mSettings.mPermissionTrees
3164 .values().iterator();
3165 while (it.hasNext()) {
3166 BasePermission bp = it.next();
3167 if (bp.perm == null) {
3168 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3169 + " from package " + bp.sourcePackage);
3170 it.remove();
3171 }
3172 }
3173
3174 // Make sure all dynamic permissions have been assigned to a package,
3175 // and make sure there are no dangling permissions.
3176 it = mSettings.mPermissions.values().iterator();
3177 while (it.hasNext()) {
3178 BasePermission bp = it.next();
3179 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3180 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3181 + bp.name + " pkg=" + bp.sourcePackage
3182 + " info=" + bp.pendingInfo);
3183 if (bp.perm == null && bp.pendingInfo != null) {
3184 BasePermission tree = findPermissionTreeLP(bp.name);
3185 if (tree != null) {
3186 bp.perm = new PackageParser.Permission(tree.perm.owner,
3187 new PermissionInfo(bp.pendingInfo));
3188 bp.perm.info.packageName = tree.perm.info.packageName;
3189 bp.perm.info.name = bp.name;
3190 bp.uid = tree.uid;
3191 }
3192 }
3193 }
3194 if (bp.perm == null) {
3195 Log.w(TAG, "Removing dangling permission: " + bp.name
3196 + " from package " + bp.sourcePackage);
3197 it.remove();
3198 }
3199 }
3200
3201 // Now update the permissions for all packages, in particular
3202 // replace the granted permissions of the system packages.
3203 for (PackageParser.Package pkg : mPackages.values()) {
3204 grantPermissionsLP(pkg, false);
3205 }
3206 }
3207
3208 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3209 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3210 if (ps == null) {
3211 return;
3212 }
3213 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3214 boolean addedPermission = false;
3215
3216 if (replace) {
3217 ps.permissionsFixed = false;
3218 if (gp == ps) {
3219 gp.grantedPermissions.clear();
3220 gp.gids = mGlobalGids;
3221 }
3222 }
3223
3224 if (gp.gids == null) {
3225 gp.gids = mGlobalGids;
3226 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07003227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 final int N = pkg.requestedPermissions.size();
3229 for (int i=0; i<N; i++) {
3230 String name = pkg.requestedPermissions.get(i);
3231 BasePermission bp = mSettings.mPermissions.get(name);
3232 PackageParser.Permission p = bp != null ? bp.perm : null;
3233 if (false) {
3234 if (gp != ps) {
3235 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3236 + ": " + p);
3237 }
3238 }
3239 if (p != null) {
3240 final String perm = p.info.name;
3241 boolean allowed;
3242 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3243 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3244 allowed = true;
3245 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3246 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003247 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003249 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 == PackageManager.SIGNATURE_MATCH);
3251 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3252 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3253 // For updated system applications, the signatureOrSystem permission
3254 // is granted only if it had been defined by the original application.
3255 if ((pkg.applicationInfo.flags
3256 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3257 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3258 if(sysPs.grantedPermissions.contains(perm)) {
3259 allowed = true;
3260 } else {
3261 allowed = false;
3262 }
3263 } else {
3264 allowed = true;
3265 }
3266 }
3267 }
3268 } else {
3269 allowed = false;
3270 }
3271 if (false) {
3272 if (gp != ps) {
3273 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3274 }
3275 }
3276 if (allowed) {
3277 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3278 && ps.permissionsFixed) {
3279 // If this is an existing, non-system package, then
3280 // we can't add any new permissions to it.
3281 if (!gp.loadedPermissions.contains(perm)) {
3282 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003283 // Except... if this is a permission that was added
3284 // to the platform (note: need to only do this when
3285 // updating the platform).
3286 final int NP = PackageParser.NEW_PERMISSIONS.length;
3287 for (int ip=0; ip<NP; ip++) {
3288 final PackageParser.NewPermissionInfo npi
3289 = PackageParser.NEW_PERMISSIONS[ip];
3290 if (npi.name.equals(perm)
3291 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3292 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003293 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003294 + pkg.packageName);
3295 break;
3296 }
3297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 }
3299 }
3300 if (allowed) {
3301 if (!gp.grantedPermissions.contains(perm)) {
3302 addedPermission = true;
3303 gp.grantedPermissions.add(perm);
3304 gp.gids = appendInts(gp.gids, bp.gids);
3305 }
3306 } else {
3307 Log.w(TAG, "Not granting permission " + perm
3308 + " to package " + pkg.packageName
3309 + " because it was previously installed without");
3310 }
3311 } else {
3312 Log.w(TAG, "Not granting permission " + perm
3313 + " to package " + pkg.packageName
3314 + " (protectionLevel=" + p.info.protectionLevel
3315 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3316 + ")");
3317 }
3318 } else {
3319 Log.w(TAG, "Unknown permission " + name
3320 + " in package " + pkg.packageName);
3321 }
3322 }
3323
3324 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003325 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3326 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 // This is the first that we have heard about this package, so the
3328 // permissions we have now selected are fixed until explicitly
3329 // changed.
3330 ps.permissionsFixed = true;
3331 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3332 }
3333 }
3334
3335 private final class ActivityIntentResolver
3336 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003337 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003339 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 }
3341
Mihai Preda074edef2009-05-18 17:13:31 +02003342 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003344 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3346 }
3347
Mihai Predaeae850c2009-05-13 10:13:48 +02003348 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3349 ArrayList<PackageParser.Activity> packageActivities) {
3350 if (packageActivities == null) {
3351 return null;
3352 }
3353 mFlags = flags;
3354 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3355 int N = packageActivities.size();
3356 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3357 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003358
3359 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003360 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003361 intentFilters = packageActivities.get(i).intents;
3362 if (intentFilters != null && intentFilters.size() > 0) {
3363 listCut.add(intentFilters);
3364 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003365 }
3366 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3367 }
3368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 public final void addActivity(PackageParser.Activity a, String type) {
3370 mActivities.put(a.component, a);
3371 if (SHOW_INFO || Config.LOGV) Log.v(
3372 TAG, " " + type + " " +
3373 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3374 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3375 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003376 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3378 if (SHOW_INFO || Config.LOGV) {
3379 Log.v(TAG, " IntentFilter:");
3380 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3381 }
3382 if (!intent.debugCheck()) {
3383 Log.w(TAG, "==> For Activity " + a.info.name);
3384 }
3385 addFilter(intent);
3386 }
3387 }
3388
3389 public final void removeActivity(PackageParser.Activity a, String type) {
3390 mActivities.remove(a.component);
3391 if (SHOW_INFO || Config.LOGV) Log.v(
3392 TAG, " " + type + " " +
3393 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3394 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3395 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003396 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3398 if (SHOW_INFO || Config.LOGV) {
3399 Log.v(TAG, " IntentFilter:");
3400 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3401 }
3402 removeFilter(intent);
3403 }
3404 }
3405
3406 @Override
3407 protected boolean allowFilterResult(
3408 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3409 ActivityInfo filterAi = filter.activity.info;
3410 for (int i=dest.size()-1; i>=0; i--) {
3411 ActivityInfo destAi = dest.get(i).activityInfo;
3412 if (destAi.name == filterAi.name
3413 && destAi.packageName == filterAi.packageName) {
3414 return false;
3415 }
3416 }
3417 return true;
3418 }
3419
3420 @Override
3421 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3422 int match) {
3423 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3424 return null;
3425 }
3426 final PackageParser.Activity activity = info.activity;
3427 if (mSafeMode && (activity.info.applicationInfo.flags
3428 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3429 return null;
3430 }
3431 final ResolveInfo res = new ResolveInfo();
3432 res.activityInfo = PackageParser.generateActivityInfo(activity,
3433 mFlags);
3434 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3435 res.filter = info;
3436 }
3437 res.priority = info.getPriority();
3438 res.preferredOrder = activity.owner.mPreferredOrder;
3439 //System.out.println("Result: " + res.activityInfo.className +
3440 // " = " + res.priority);
3441 res.match = match;
3442 res.isDefault = info.hasDefault;
3443 res.labelRes = info.labelRes;
3444 res.nonLocalizedLabel = info.nonLocalizedLabel;
3445 res.icon = info.icon;
3446 return res;
3447 }
3448
3449 @Override
3450 protected void sortResults(List<ResolveInfo> results) {
3451 Collections.sort(results, mResolvePrioritySorter);
3452 }
3453
3454 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003455 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003457 out.print(prefix); out.print(
3458 Integer.toHexString(System.identityHashCode(filter.activity)));
3459 out.print(' ');
3460 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 }
3462
3463// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3464// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3465// final List<ResolveInfo> retList = Lists.newArrayList();
3466// while (i.hasNext()) {
3467// final ResolveInfo resolveInfo = i.next();
3468// if (isEnabledLP(resolveInfo.activityInfo)) {
3469// retList.add(resolveInfo);
3470// }
3471// }
3472// return retList;
3473// }
3474
3475 // Keys are String (activity class name), values are Activity.
3476 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3477 = new HashMap<ComponentName, PackageParser.Activity>();
3478 private int mFlags;
3479 }
3480
3481 private final class ServiceIntentResolver
3482 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003483 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003485 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 }
3487
Mihai Preda074edef2009-05-18 17:13:31 +02003488 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003490 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3492 }
3493
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003494 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3495 ArrayList<PackageParser.Service> packageServices) {
3496 if (packageServices == null) {
3497 return null;
3498 }
3499 mFlags = flags;
3500 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3501 int N = packageServices.size();
3502 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3503 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3504
3505 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3506 for (int i = 0; i < N; ++i) {
3507 intentFilters = packageServices.get(i).intents;
3508 if (intentFilters != null && intentFilters.size() > 0) {
3509 listCut.add(intentFilters);
3510 }
3511 }
3512 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3513 }
3514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 public final void addService(PackageParser.Service s) {
3516 mServices.put(s.component, s);
3517 if (SHOW_INFO || Config.LOGV) Log.v(
3518 TAG, " " + (s.info.nonLocalizedLabel != null
3519 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3520 if (SHOW_INFO || Config.LOGV) Log.v(
3521 TAG, " Class=" + s.info.name);
3522 int NI = s.intents.size();
3523 int j;
3524 for (j=0; j<NI; j++) {
3525 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3526 if (SHOW_INFO || Config.LOGV) {
3527 Log.v(TAG, " IntentFilter:");
3528 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3529 }
3530 if (!intent.debugCheck()) {
3531 Log.w(TAG, "==> For Service " + s.info.name);
3532 }
3533 addFilter(intent);
3534 }
3535 }
3536
3537 public final void removeService(PackageParser.Service s) {
3538 mServices.remove(s.component);
3539 if (SHOW_INFO || Config.LOGV) Log.v(
3540 TAG, " " + (s.info.nonLocalizedLabel != null
3541 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3542 if (SHOW_INFO || Config.LOGV) Log.v(
3543 TAG, " Class=" + s.info.name);
3544 int NI = s.intents.size();
3545 int j;
3546 for (j=0; j<NI; j++) {
3547 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3548 if (SHOW_INFO || Config.LOGV) {
3549 Log.v(TAG, " IntentFilter:");
3550 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3551 }
3552 removeFilter(intent);
3553 }
3554 }
3555
3556 @Override
3557 protected boolean allowFilterResult(
3558 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3559 ServiceInfo filterSi = filter.service.info;
3560 for (int i=dest.size()-1; i>=0; i--) {
3561 ServiceInfo destAi = dest.get(i).serviceInfo;
3562 if (destAi.name == filterSi.name
3563 && destAi.packageName == filterSi.packageName) {
3564 return false;
3565 }
3566 }
3567 return true;
3568 }
3569
3570 @Override
3571 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3572 int match) {
3573 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3574 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3575 return null;
3576 }
3577 final PackageParser.Service service = info.service;
3578 if (mSafeMode && (service.info.applicationInfo.flags
3579 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3580 return null;
3581 }
3582 final ResolveInfo res = new ResolveInfo();
3583 res.serviceInfo = PackageParser.generateServiceInfo(service,
3584 mFlags);
3585 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3586 res.filter = filter;
3587 }
3588 res.priority = info.getPriority();
3589 res.preferredOrder = service.owner.mPreferredOrder;
3590 //System.out.println("Result: " + res.activityInfo.className +
3591 // " = " + res.priority);
3592 res.match = match;
3593 res.isDefault = info.hasDefault;
3594 res.labelRes = info.labelRes;
3595 res.nonLocalizedLabel = info.nonLocalizedLabel;
3596 res.icon = info.icon;
3597 return res;
3598 }
3599
3600 @Override
3601 protected void sortResults(List<ResolveInfo> results) {
3602 Collections.sort(results, mResolvePrioritySorter);
3603 }
3604
3605 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003606 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003608 out.print(prefix); out.print(
3609 Integer.toHexString(System.identityHashCode(filter.service)));
3610 out.print(' ');
3611 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 }
3613
3614// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3615// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3616// final List<ResolveInfo> retList = Lists.newArrayList();
3617// while (i.hasNext()) {
3618// final ResolveInfo resolveInfo = (ResolveInfo) i;
3619// if (isEnabledLP(resolveInfo.serviceInfo)) {
3620// retList.add(resolveInfo);
3621// }
3622// }
3623// return retList;
3624// }
3625
3626 // Keys are String (activity class name), values are Activity.
3627 private final HashMap<ComponentName, PackageParser.Service> mServices
3628 = new HashMap<ComponentName, PackageParser.Service>();
3629 private int mFlags;
3630 };
3631
3632 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3633 new Comparator<ResolveInfo>() {
3634 public int compare(ResolveInfo r1, ResolveInfo r2) {
3635 int v1 = r1.priority;
3636 int v2 = r2.priority;
3637 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3638 if (v1 != v2) {
3639 return (v1 > v2) ? -1 : 1;
3640 }
3641 v1 = r1.preferredOrder;
3642 v2 = r2.preferredOrder;
3643 if (v1 != v2) {
3644 return (v1 > v2) ? -1 : 1;
3645 }
3646 if (r1.isDefault != r2.isDefault) {
3647 return r1.isDefault ? -1 : 1;
3648 }
3649 v1 = r1.match;
3650 v2 = r2.match;
3651 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3652 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3653 }
3654 };
3655
3656 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3657 new Comparator<ProviderInfo>() {
3658 public int compare(ProviderInfo p1, ProviderInfo p2) {
3659 final int v1 = p1.initOrder;
3660 final int v2 = p2.initOrder;
3661 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3662 }
3663 };
3664
3665 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3666 IActivityManager am = ActivityManagerNative.getDefault();
3667 if (am != null) {
3668 try {
3669 final Intent intent = new Intent(action,
3670 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3671 if (extras != null) {
3672 intent.putExtras(extras);
3673 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003674 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 am.broadcastIntent(
3676 null, intent,
3677 null, null, 0, null, null, null, false, false);
3678 } catch (RemoteException ex) {
3679 }
3680 }
3681 }
3682
3683 private final class AppDirObserver extends FileObserver {
3684 public AppDirObserver(String path, int mask, boolean isrom) {
3685 super(path, mask);
3686 mRootDir = path;
3687 mIsRom = isrom;
3688 }
3689
3690 public void onEvent(int event, String path) {
3691 String removedPackage = null;
3692 int removedUid = -1;
3693 String addedPackage = null;
3694 int addedUid = -1;
3695
3696 synchronized (mInstallLock) {
3697 String fullPathStr = null;
3698 File fullPath = null;
3699 if (path != null) {
3700 fullPath = new File(mRootDir, path);
3701 fullPathStr = fullPath.getPath();
3702 }
3703
3704 if (Config.LOGV) Log.v(
3705 TAG, "File " + fullPathStr + " changed: "
3706 + Integer.toHexString(event));
3707
3708 if (!isPackageFilename(path)) {
3709 if (Config.LOGV) Log.v(
3710 TAG, "Ignoring change of non-package file: " + fullPathStr);
3711 return;
3712 }
3713
3714 if ((event&REMOVE_EVENTS) != 0) {
3715 synchronized (mInstallLock) {
3716 PackageParser.Package p = mAppDirs.get(fullPathStr);
3717 if (p != null) {
3718 removePackageLI(p, true);
3719 removedPackage = p.applicationInfo.packageName;
3720 removedUid = p.applicationInfo.uid;
3721 }
3722 }
3723 }
3724
3725 if ((event&ADD_EVENTS) != 0) {
3726 PackageParser.Package p = mAppDirs.get(fullPathStr);
3727 if (p == null) {
3728 p = scanPackageLI(fullPath, fullPath, fullPath,
3729 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3730 PackageParser.PARSE_CHATTY |
3731 PackageParser.PARSE_MUST_BE_APK,
3732 SCAN_MONITOR);
3733 if (p != null) {
3734 synchronized (mPackages) {
3735 grantPermissionsLP(p, false);
3736 }
3737 addedPackage = p.applicationInfo.packageName;
3738 addedUid = p.applicationInfo.uid;
3739 }
3740 }
3741 }
3742
3743 synchronized (mPackages) {
3744 mSettings.writeLP();
3745 }
3746 }
3747
3748 if (removedPackage != null) {
3749 Bundle extras = new Bundle(1);
3750 extras.putInt(Intent.EXTRA_UID, removedUid);
3751 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3752 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3753 }
3754 if (addedPackage != null) {
3755 Bundle extras = new Bundle(1);
3756 extras.putInt(Intent.EXTRA_UID, addedUid);
3757 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3758 }
3759 }
3760
3761 private final String mRootDir;
3762 private final boolean mIsRom;
3763 }
Jacek Surazski65e13172009-04-28 15:26:38 +02003764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 /* Called when a downloaded package installation has been confirmed by the user */
3766 public void installPackage(
3767 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003768 installPackage(packageURI, observer, flags, null);
3769 }
3770
3771 /* Called when a downloaded package installation has been confirmed by the user */
3772 public void installPackage(
3773 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3774 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 mContext.enforceCallingOrSelfPermission(
3776 android.Manifest.permission.INSTALL_PACKAGES, null);
Jacek Surazski65e13172009-04-28 15:26:38 +02003777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 // Queue up an async operation since the package installation may take a little while.
3779 mHandler.post(new Runnable() {
3780 public void run() {
3781 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003782 // Result object to be returned
3783 PackageInstalledInfo res = new PackageInstalledInfo();
3784 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3785 res.uid = -1;
3786 res.pkg = null;
3787 res.removedInfo = new PackageRemovedInfo();
3788 // Make a temporary copy of file from given packageURI
3789 File tmpPackageFile = copyTempInstallFile(packageURI, res);
3790 if (tmpPackageFile != null) {
3791 synchronized (mInstallLock) {
3792 installPackageLI(packageURI, flags, true, installerPackageName, tmpPackageFile, res);
3793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 }
3795 if (observer != null) {
3796 try {
3797 observer.packageInstalled(res.name, res.returnCode);
3798 } catch (RemoteException e) {
3799 Log.i(TAG, "Observer no longer exists.");
3800 }
3801 }
3802 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3803 // call appears in the synchronized block above.
3804 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3805 res.removedInfo.sendBroadcast(false, true);
3806 Bundle extras = new Bundle(1);
3807 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003808 final boolean update = res.removedInfo.removedPackage != null;
3809 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3811 }
3812 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3813 res.pkg.applicationInfo.packageName,
3814 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003815 if (update) {
3816 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3817 res.pkg.applicationInfo.packageName,
3818 extras);
3819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 }
3821 Runtime.getRuntime().gc();
3822 }
3823 });
3824 }
3825
3826 class PackageInstalledInfo {
3827 String name;
3828 int uid;
3829 PackageParser.Package pkg;
3830 int returnCode;
3831 PackageRemovedInfo removedInfo;
3832 }
3833
3834 /*
3835 * Install a non-existing package.
3836 */
3837 private void installNewPackageLI(String pkgName,
3838 File tmpPackageFile,
3839 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003840 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003841 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 // Remember this for later, in case we need to rollback this install
3843 boolean dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3844 res.name = pkgName;
3845 synchronized(mPackages) {
3846 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(destFilePath)) {
3847 // Don't allow installation over an existing package with the same name.
3848 Log.w(TAG, "Attempt to re-install " + pkgName
3849 + " without first uninstalling.");
3850 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3851 return;
3852 }
3853 }
3854 if (destPackageFile.exists()) {
3855 // It's safe to do this because we know (from the above check) that the file
3856 // isn't currently used for an installed package.
3857 destPackageFile.delete();
3858 }
3859 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3860 PackageParser.Package newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3861 destResourceFile, pkg, 0,
3862 SCAN_MONITOR | SCAN_FORCE_DEX
3863 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003864 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3865 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 if (newPackage == null) {
3867 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3868 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3869 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3870 }
3871 } else {
3872 updateSettingsLI(pkgName, tmpPackageFile,
3873 destFilePath, destPackageFile,
3874 destResourceFile, pkg,
3875 newPackage,
3876 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02003877 forwardLocked,
3878 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 res);
3880 // delete the partially installed application. the data directory will have to be
3881 // restored if it was already existing
3882 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3883 // remove package from internal structures. Note that we want deletePackageX to
3884 // delete the package data and cache directories that it created in
3885 // scanPackageLocked, unless those directories existed before we even tried to
3886 // install.
3887 deletePackageLI(
3888 pkgName, true,
3889 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3890 res.removedInfo);
3891 }
3892 }
3893 }
3894
3895 private void replacePackageLI(String pkgName,
3896 File tmpPackageFile,
3897 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003898 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003899 String installerPackageName, PackageInstalledInfo res) {
3900
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003901 PackageParser.Package oldPackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 // First find the old package info and check signatures
3903 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003904 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003905 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
3906 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3908 return;
3909 }
3910 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003911 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 if(sysPkg) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003913 replaceSystemPackageLI(oldPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003915 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003916 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 } else {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003918 replaceNonSystemPackageLI(oldPackage, tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003919 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003920 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 }
3922 }
3923
3924 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
3925 File tmpPackageFile,
3926 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003927 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003928 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 PackageParser.Package newPackage = null;
3930 String pkgName = deletedPackage.packageName;
3931 boolean deletedPkg = true;
3932 boolean updatedSettings = false;
Jacek Surazski65e13172009-04-28 15:26:38 +02003933
3934 String oldInstallerPackageName = null;
3935 synchronized (mPackages) {
3936 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3937 }
3938
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003939 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 // First delete the existing package while retaining the data directory
3941 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3942 res.removedInfo)) {
3943 // If the existing package was'nt successfully deleted
3944 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3945 deletedPkg = false;
3946 } else {
3947 // Successfully deleted the old package. Now proceed with re-installation
3948 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3949 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3950 destResourceFile, pkg, parseFlags,
3951 SCAN_MONITOR | SCAN_FORCE_DEX
3952 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003953 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3954 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 if (newPackage == null) {
3956 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3957 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3958 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3959 }
3960 } else {
3961 updateSettingsLI(pkgName, tmpPackageFile,
3962 destFilePath, destPackageFile,
3963 destResourceFile, pkg,
3964 newPackage,
3965 true,
3966 forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003967 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 res);
3969 updatedSettings = true;
3970 }
3971 }
3972
3973 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3974 // If we deleted an exisiting package, the old source and resource files that we
3975 // were keeping around in case we needed them (see below) can now be deleted
3976 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
3977 final ApplicationInfo installedPackageAppInfo =
3978 newPackage.applicationInfo;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003979 deletePackageResourcesLI(pkgName,
3980 !deletedPackageAppInfo.sourceDir
3981 .equals(installedPackageAppInfo.sourceDir)
3982 ? deletedPackageAppInfo.sourceDir : null,
3983 !deletedPackageAppInfo.publicSourceDir
3984 .equals(installedPackageAppInfo.publicSourceDir)
3985 ? deletedPackageAppInfo.publicSourceDir : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 //update signature on the new package setting
3987 //this should always succeed, since we checked the
3988 //signature earlier.
3989 synchronized(mPackages) {
3990 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
3991 parseFlags, true);
3992 }
3993 } else {
3994 // remove package from internal structures. Note that we want deletePackageX to
3995 // delete the package data and cache directories that it created in
3996 // scanPackageLocked, unless those directories existed before we even tried to
3997 // install.
3998 if(updatedSettings) {
3999 deletePackageLI(
4000 pkgName, true,
4001 PackageManager.DONT_DELETE_DATA,
4002 res.removedInfo);
4003 }
4004 // Since we failed to install the new package we need to restore the old
4005 // package that we deleted.
4006 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004007 File restoreFile = new File(deletedPackage.mPath);
4008 if (restoreFile == null) {
4009 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
4010 return;
4011 }
4012 File restoreTmpFile = createTempPackageFile();
4013 if (restoreTmpFile == null) {
4014 Log.e(TAG, "Failed creating temp file when restoring pkg : " + pkgName);
4015 return;
4016 }
4017 if (!FileUtils.copyFile(restoreFile, restoreTmpFile)) {
4018 Log.e(TAG, "Failed copying temp file when restoring pkg : " + pkgName);
4019 return;
4020 }
4021 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4022 restoreRes.removedInfo = new PackageRemovedInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 installPackageLI(
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004024 Uri.fromFile(restoreFile),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004026 ? PackageManager.INSTALL_FORWARD_LOCK
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004027 : 0, false, oldInstallerPackageName, restoreTmpFile, restoreRes);
4028 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4029 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 }
4032 }
4033 }
4034
4035 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
4036 File tmpPackageFile,
4037 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07004038 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02004039 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 PackageParser.Package newPackage = null;
4041 boolean updatedSettings = false;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004042 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 PackageParser.PARSE_IS_SYSTEM;
4044 String packageName = deletedPackage.packageName;
4045 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4046 if (packageName == null) {
4047 Log.w(TAG, "Attempt to delete null packageName.");
4048 return;
4049 }
4050 PackageParser.Package oldPkg;
4051 PackageSetting oldPkgSetting;
4052 synchronized (mPackages) {
4053 oldPkg = mPackages.get(packageName);
4054 oldPkgSetting = mSettings.mPackages.get(packageName);
4055 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4056 (oldPkgSetting == null)) {
4057 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4058 return;
4059 }
4060 }
4061 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4062 res.removedInfo.removedPackage = packageName;
4063 // Remove existing system package
4064 removePackageLI(oldPkg, true);
4065 synchronized (mPackages) {
4066 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4067 }
4068
4069 // Successfully disabled the old package. Now proceed with re-installation
4070 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4071 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4072 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
4073 destResourceFile, pkg, parseFlags,
4074 SCAN_MONITOR | SCAN_FORCE_DEX
4075 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07004076 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
4077 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 if (newPackage == null) {
4079 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
4080 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4081 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4082 }
4083 } else {
4084 updateSettingsLI(packageName, tmpPackageFile,
4085 destFilePath, destPackageFile,
4086 destResourceFile, pkg,
4087 newPackage,
4088 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02004089 forwardLocked,
4090 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 res);
4092 updatedSettings = true;
4093 }
4094
4095 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4096 //update signature on the new package setting
4097 //this should always succeed, since we checked the
4098 //signature earlier.
4099 synchronized(mPackages) {
4100 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4101 parseFlags, true);
4102 }
4103 } else {
4104 // Re installation failed. Restore old information
4105 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004106 if (newPackage != null) {
4107 removePackageLI(newPackage, true);
4108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 // Add back the old system package
4110 scanPackageLI(oldPkgSetting.codePath, oldPkgSetting.codePath,
4111 oldPkgSetting.resourcePath,
4112 oldPkg, parseFlags,
4113 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004114 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 // Restore the old system information in Settings
4116 synchronized(mPackages) {
4117 if(updatedSettings) {
4118 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004119 mSettings.setInstallerPackageName(packageName,
4120 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 }
4122 mSettings.writeLP();
4123 }
4124 }
4125 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 private void updateSettingsLI(String pkgName, File tmpPackageFile,
4128 String destFilePath, File destPackageFile,
4129 File destResourceFile,
4130 PackageParser.Package pkg,
4131 PackageParser.Package newPackage,
4132 boolean replacingExistingPackage,
4133 boolean forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02004134 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 synchronized (mPackages) {
4136 //write settings. the installStatus will be incomplete at this stage.
4137 //note that the new package setting would have already been
4138 //added to mPackages. It hasn't been persisted yet.
4139 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4140 mSettings.writeLP();
4141 }
4142
4143 int retCode = 0;
4144 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4145 retCode = mInstaller.movedex(tmpPackageFile.toString(),
4146 destPackageFile.toString());
4147 if (retCode != 0) {
4148 Log.e(TAG, "Couldn't rename dex file: " + destPackageFile);
4149 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4150 return;
4151 }
4152 }
4153 // XXX There are probably some big issues here: upon doing
4154 // the rename, we have reached the point of no return (the
4155 // original .apk is gone!), so we can't fail. Yet... we can.
4156 if (!tmpPackageFile.renameTo(destPackageFile)) {
4157 Log.e(TAG, "Couldn't move package file to: " + destPackageFile);
4158 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4159 } else {
4160 res.returnCode = setPermissionsLI(pkgName, newPackage, destFilePath,
4161 destResourceFile,
4162 forwardLocked);
4163 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4164 return;
4165 } else {
4166 Log.d(TAG, "New package installed in " + destPackageFile);
4167 }
4168 }
4169 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4170 if (mInstaller != null) {
4171 mInstaller.rmdex(tmpPackageFile.getPath());
4172 }
4173 }
4174
4175 synchronized (mPackages) {
4176 grantPermissionsLP(newPackage, true);
4177 res.name = pkgName;
4178 res.uid = newPackage.applicationInfo.uid;
4179 res.pkg = newPackage;
4180 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004181 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4183 //to update install status
4184 mSettings.writeLP();
4185 }
4186 }
4187
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07004188 private File getFwdLockedResource(String pkgName) {
4189 final String publicZipFileName = pkgName + ".zip";
4190 return new File(mAppInstallDir, publicZipFileName);
4191 }
4192
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004193 private File copyTempInstallFile(Uri pPackageURI,
4194 PackageInstalledInfo res) {
4195 File tmpPackageFile = createTempPackageFile();
4196 int retCode = PackageManager.INSTALL_SUCCEEDED;
4197 if (tmpPackageFile == null) {
4198 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4199 return null;
4200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004202 if (pPackageURI.getScheme().equals("file")) {
4203 final File srcPackageFile = new File(pPackageURI.getPath());
4204 // We copy the source package file to a temp file and then rename it to the
4205 // destination file in order to eliminate a window where the package directory
4206 // scanner notices the new package file but it's not completely copied yet.
4207 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
4208 Log.e(TAG, "Couldn't copy package file to temp file.");
4209 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004211 } else if (pPackageURI.getScheme().equals("content")) {
4212 ParcelFileDescriptor fd = null;
4213 try {
4214 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
4215 } catch (FileNotFoundException e) {
4216 Log.e(TAG, "Couldn't open file descriptor from download service. Failed with exception " + e);
4217 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4218 }
4219 if (fd == null) {
4220 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
4221 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4222 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 if (Config.LOGV) {
4224 Log.v(TAG, "Opened file descriptor from download service.");
4225 }
4226 ParcelFileDescriptor.AutoCloseInputStream
4227 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
4228 // We copy the source package file to a temp file and then rename it to the
4229 // destination file in order to eliminate a window where the package directory
4230 // scanner notices the new package file but it's not completely copied yet.
4231 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
4232 Log.e(TAG, "Couldn't copy package stream to temp file.");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004233 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004236 } else {
4237 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
4238 retCode = PackageManager.INSTALL_FAILED_INVALID_URI;
4239 }
4240
4241 res.returnCode = retCode;
4242 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
4243 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4244 tmpPackageFile.delete();
4245 }
4246 return null;
4247 }
4248 return tmpPackageFile;
4249 }
4250
4251 private void installPackageLI(Uri pPackageURI,
4252 int pFlags, boolean newInstall, String installerPackageName,
4253 File tmpPackageFile, PackageInstalledInfo res) {
4254 String pkgName = null;
4255 boolean forwardLocked = false;
4256 boolean replacingExistingPackage = false;
4257 // Result object to be returned
4258 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4259
4260 main_flow: try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 pkgName = PackageParser.parsePackageName(
4262 tmpPackageFile.getAbsolutePath(), 0);
4263 if (pkgName == null) {
4264 Log.e(TAG, "Couldn't find a package name in : " + tmpPackageFile);
4265 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4266 break main_flow;
4267 }
4268 res.name = pkgName;
4269 //initialize some variables before installing pkg
4270 final String pkgFileName = pkgName + ".apk";
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004271 final File destDir = ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 ? mDrmAppPrivateInstallDir
4273 : mAppInstallDir;
4274 final File destPackageFile = new File(destDir, pkgFileName);
4275 final String destFilePath = destPackageFile.getAbsolutePath();
4276 File destResourceFile;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004277 if ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0) {
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07004278 destResourceFile = getFwdLockedResource(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 forwardLocked = true;
4280 } else {
4281 destResourceFile = destPackageFile;
4282 }
4283 // Retrieve PackageSettings and parse package
4284 int parseFlags = PackageParser.PARSE_CHATTY;
4285 parseFlags |= mDefParseFlags;
4286 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4287 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
4289 destPackageFile.getAbsolutePath(), mMetrics, parseFlags);
4290 if (pkg == null) {
4291 res.returnCode = pp.getParseError();
4292 break main_flow;
4293 }
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004294 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4295 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4296 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4297 break main_flow;
4298 }
4299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4301 res.returnCode = pp.getParseError();
4302 break main_flow;
4303 }
4304
4305 synchronized (mPackages) {
4306 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004307 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 && mPackages.containsKey(pkgName)) {
4309 replacingExistingPackage = true;
4310 }
4311 }
4312
4313 if(replacingExistingPackage) {
4314 replacePackageLI(pkgName,
4315 tmpPackageFile,
4316 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02004317 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 res);
4319 } else {
4320 installNewPackageLI(pkgName,
4321 tmpPackageFile,
4322 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02004323 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004324 res);
4325 }
4326 } finally {
4327 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4328 tmpPackageFile.delete();
4329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 }
4331 }
4332
4333 private int setPermissionsLI(String pkgName,
4334 PackageParser.Package newPackage,
4335 String destFilePath,
4336 File destResourceFile,
4337 boolean forwardLocked) {
4338 int retCode;
4339 if (forwardLocked) {
4340 try {
4341 extractPublicFiles(newPackage, destResourceFile);
4342 } catch (IOException e) {
4343 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
4344 " forward-locked app.");
4345 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4346 } finally {
4347 //TODO clean up the extracted public files
4348 }
4349 if (mInstaller != null) {
4350 retCode = mInstaller.setForwardLockPerm(pkgName,
4351 newPackage.applicationInfo.uid);
4352 } else {
4353 final int filePermissions =
4354 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
4355 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1,
4356 newPackage.applicationInfo.uid);
4357 }
4358 } else {
4359 final int filePermissions =
4360 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4361 |FileUtils.S_IROTH;
4362 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1, -1);
4363 }
4364 if (retCode != 0) {
4365 Log.e(TAG, "Couldn't set new package file permissions for " + destFilePath
4366 + ". The return code was: " + retCode);
4367 }
4368 return PackageManager.INSTALL_SUCCEEDED;
4369 }
4370
4371 private boolean isForwardLocked(PackageParser.Package deletedPackage) {
4372 final ApplicationInfo applicationInfo = deletedPackage.applicationInfo;
4373 return applicationInfo.sourceDir.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath());
4374 }
4375
4376 private void extractPublicFiles(PackageParser.Package newPackage,
4377 File publicZipFile) throws IOException {
4378 final ZipOutputStream publicZipOutStream =
4379 new ZipOutputStream(new FileOutputStream(publicZipFile));
4380 final ZipFile privateZip = new ZipFile(newPackage.mPath);
4381
4382 // Copy manifest, resources.arsc and res directory to public zip
4383
4384 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
4385 while (privateZipEntries.hasMoreElements()) {
4386 final ZipEntry zipEntry = privateZipEntries.nextElement();
4387 final String zipEntryName = zipEntry.getName();
4388 if ("AndroidManifest.xml".equals(zipEntryName)
4389 || "resources.arsc".equals(zipEntryName)
4390 || zipEntryName.startsWith("res/")) {
4391 try {
4392 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
4393 } catch (IOException e) {
4394 try {
4395 publicZipOutStream.close();
4396 throw e;
4397 } finally {
4398 publicZipFile.delete();
4399 }
4400 }
4401 }
4402 }
4403
4404 publicZipOutStream.close();
4405 FileUtils.setPermissions(
4406 publicZipFile.getAbsolutePath(),
4407 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4408 -1, -1);
4409 }
4410
4411 private static void copyZipEntry(ZipEntry zipEntry,
4412 ZipFile inZipFile,
4413 ZipOutputStream outZipStream) throws IOException {
4414 byte[] buffer = new byte[4096];
4415 int num;
4416
4417 ZipEntry newEntry;
4418 if (zipEntry.getMethod() == ZipEntry.STORED) {
4419 // Preserve the STORED method of the input entry.
4420 newEntry = new ZipEntry(zipEntry);
4421 } else {
4422 // Create a new entry so that the compressed len is recomputed.
4423 newEntry = new ZipEntry(zipEntry.getName());
4424 }
4425 outZipStream.putNextEntry(newEntry);
4426
4427 InputStream data = inZipFile.getInputStream(zipEntry);
4428 while ((num = data.read(buffer)) > 0) {
4429 outZipStream.write(buffer, 0, num);
4430 }
4431 outZipStream.flush();
4432 }
4433
4434 private void deleteTempPackageFiles() {
4435 FilenameFilter filter = new FilenameFilter() {
4436 public boolean accept(File dir, String name) {
4437 return name.startsWith("vmdl") && name.endsWith(".tmp");
4438 }
4439 };
4440 String tmpFilesList[] = mAppInstallDir.list(filter);
4441 if(tmpFilesList == null) {
4442 return;
4443 }
4444 for(int i = 0; i < tmpFilesList.length; i++) {
4445 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4446 tmpFile.delete();
4447 }
4448 }
4449
4450 private File createTempPackageFile() {
4451 File tmpPackageFile;
4452 try {
4453 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
4454 } catch (IOException e) {
4455 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4456 return null;
4457 }
4458 try {
4459 FileUtils.setPermissions(
4460 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4461 -1, -1);
4462 } catch (IOException e) {
4463 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4464 return null;
4465 }
4466 return tmpPackageFile;
4467 }
4468
4469 public void deletePackage(final String packageName,
4470 final IPackageDeleteObserver observer,
4471 final int flags) {
4472 mContext.enforceCallingOrSelfPermission(
4473 android.Manifest.permission.DELETE_PACKAGES, null);
4474 // Queue up an async operation since the package deletion may take a little while.
4475 mHandler.post(new Runnable() {
4476 public void run() {
4477 mHandler.removeCallbacks(this);
4478 final boolean succeded = deletePackageX(packageName, true, true, flags);
4479 if (observer != null) {
4480 try {
4481 observer.packageDeleted(succeded);
4482 } catch (RemoteException e) {
4483 Log.i(TAG, "Observer no longer exists.");
4484 } //end catch
4485 } //end if
4486 } //end run
4487 });
4488 }
4489
4490 /**
4491 * This method is an internal method that could be get invoked either
4492 * to delete an installed package or to clean up a failed installation.
4493 * After deleting an installed package, a broadcast is sent to notify any
4494 * listeners that the package has been installed. For cleaning up a failed
4495 * installation, the broadcast is not necessary since the package's
4496 * installation wouldn't have sent the initial broadcast either
4497 * The key steps in deleting a package are
4498 * deleting the package information in internal structures like mPackages,
4499 * deleting the packages base directories through installd
4500 * updating mSettings to reflect current status
4501 * persisting settings for later use
4502 * sending a broadcast if necessary
4503 */
4504
4505 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4506 boolean deleteCodeAndResources, int flags) {
4507 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004508 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509
4510 synchronized (mInstallLock) {
4511 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4512 }
4513
4514 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004515 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4516 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4517
4518 // If the removed package was a system update, the old system packaged
4519 // was re-enabled; we need to broadcast this information
4520 if (systemUpdate) {
4521 Bundle extras = new Bundle(1);
4522 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4523 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4524
4525 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4526 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004528 }
4529 return res;
4530 }
4531
4532 static class PackageRemovedInfo {
4533 String removedPackage;
4534 int uid = -1;
4535 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004536 boolean isRemovedPackageSystemUpdate = false;
4537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 void sendBroadcast(boolean fullRemove, boolean replacing) {
4539 Bundle extras = new Bundle(1);
4540 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4541 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4542 if (replacing) {
4543 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4544 }
4545 if (removedPackage != null) {
4546 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4547 }
4548 if (removedUid >= 0) {
4549 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4550 }
4551 }
4552 }
4553
4554 /*
4555 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4556 * flag is not set, the data directory is removed as well.
4557 * make sure this flag is set for partially installed apps. If not its meaningless to
4558 * delete a partially installed application.
4559 */
4560 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
4561 int flags) {
4562 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004563 if (outInfo != null) {
4564 outInfo.removedPackage = packageName;
4565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 removePackageLI(p, true);
4567 // Retrieve object to delete permissions for shared user later on
4568 PackageSetting deletedPs;
4569 synchronized (mPackages) {
4570 deletedPs = mSettings.mPackages.get(packageName);
4571 }
4572 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
4573 if (mInstaller != null) {
4574 int retCode = mInstaller.remove(packageName);
4575 if (retCode < 0) {
4576 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4577 + packageName + ", retcode=" + retCode);
4578 // we don't consider this to be a failure of the core package deletion
4579 }
4580 } else {
4581 //for emulator
4582 PackageParser.Package pkg = mPackages.get(packageName);
4583 File dataDir = new File(pkg.applicationInfo.dataDir);
4584 dataDir.delete();
4585 }
4586 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004587 if (outInfo != null) {
4588 outInfo.removedUid = mSettings.removePackageLP(packageName);
4589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 }
4591 }
4592 synchronized (mPackages) {
4593 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4594 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004595 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 }
4597 // Save settings now
4598 mSettings.writeLP ();
4599 }
4600 }
4601
4602 /*
4603 * Tries to delete system package.
4604 */
4605 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004606 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 ApplicationInfo applicationInfo = p.applicationInfo;
4608 //applicable for non-partially installed applications only
4609 if (applicationInfo == null) {
4610 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4611 return false;
4612 }
4613 PackageSetting ps = null;
4614 // Confirm if the system package has been updated
4615 // An updated system app can be deleted. This will also have to restore
4616 // the system pkg from system partition
4617 synchronized (mPackages) {
4618 ps = mSettings.getDisabledSystemPkg(p.packageName);
4619 }
4620 if (ps == null) {
4621 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4622 return false;
4623 } else {
4624 Log.i(TAG, "Deleting system pkg from data partition");
4625 }
4626 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004627 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004628 boolean deleteCodeAndResources = false;
4629 if (ps.versionCode < p.mVersionCode) {
4630 // Delete code and resources for downgrades
4631 deleteCodeAndResources = true;
4632 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4633 flags &= ~PackageManager.DONT_DELETE_DATA;
4634 }
4635 } else {
4636 // Preserve data by setting flag
4637 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4638 flags |= PackageManager.DONT_DELETE_DATA;
4639 }
4640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4642 if (!ret) {
4643 return false;
4644 }
4645 synchronized (mPackages) {
4646 // Reinstate the old system package
4647 mSettings.enableSystemPackageLP(p.packageName);
4648 }
4649 // Install the system package
4650 PackageParser.Package newPkg = scanPackageLI(ps.codePath, ps.codePath, ps.resourcePath,
4651 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
4652 SCAN_MONITOR);
4653
4654 if (newPkg == null) {
4655 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4656 return false;
4657 }
4658 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07004659 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004660 mSettings.writeLP();
4661 }
4662 return true;
4663 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004664
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004665 private void deletePackageResourcesLI(String packageName,
4666 String sourceDir, String publicSourceDir) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004667 if (sourceDir != null) {
4668 File sourceFile = new File(sourceDir);
4669 if (!sourceFile.exists()) {
4670 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4671 }
4672 // Delete application's code and resources
4673 sourceFile.delete();
4674 if (mInstaller != null) {
4675 int retCode = mInstaller.rmdex(sourceFile.toString());
4676 if (retCode < 0) {
4677 Log.w(TAG, "Couldn't remove dex file for package: "
4678 + packageName + " at location "
4679 + sourceFile.toString() + ", retcode=" + retCode);
4680 // we don't consider this to be a failure of the core package deletion
4681 }
4682 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004683 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004684 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4685 final File publicSourceFile = new File(publicSourceDir);
4686 if (!publicSourceFile.exists()) {
4687 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4688 }
4689 if (publicSourceFile.exists()) {
4690 publicSourceFile.delete();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004691 }
4692 }
4693 }
4694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4696 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4697 ApplicationInfo applicationInfo = p.applicationInfo;
4698 if (applicationInfo == null) {
4699 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4700 return false;
4701 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004702 if (outInfo != null) {
4703 outInfo.uid = applicationInfo.uid;
4704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705
4706 // Delete package data from internal structures and also remove data if flag is set
4707 removePackageDataLI(p, outInfo, flags);
4708
4709 // Delete application code and resources
4710 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004711 deletePackageResourcesLI(applicationInfo.packageName,
4712 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 }
4714 return true;
4715 }
4716
4717 /*
4718 * This method handles package deletion in general
4719 */
4720 private boolean deletePackageLI(String packageName,
4721 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4722 if (packageName == null) {
4723 Log.w(TAG, "Attempt to delete null packageName.");
4724 return false;
4725 }
4726 PackageParser.Package p;
4727 boolean dataOnly = false;
4728 synchronized (mPackages) {
4729 p = mPackages.get(packageName);
4730 if (p == null) {
4731 //this retrieves partially installed apps
4732 dataOnly = true;
4733 PackageSetting ps = mSettings.mPackages.get(packageName);
4734 if (ps == null) {
4735 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4736 return false;
4737 }
4738 p = ps.pkg;
4739 }
4740 }
4741 if (p == null) {
4742 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4743 return false;
4744 }
4745
4746 if (dataOnly) {
4747 // Delete application data first
4748 removePackageDataLI(p, outInfo, flags);
4749 return true;
4750 }
4751 // At this point the package should have ApplicationInfo associated with it
4752 if (p.applicationInfo == null) {
4753 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4754 return false;
4755 }
4756 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4757 Log.i(TAG, "Removing system package:"+p.packageName);
4758 // When an updated system application is deleted we delete the existing resources as well and
4759 // fall back to existing code in system partition
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004760 return deleteSystemPackageLI(p, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 }
4762 Log.i(TAG, "Removing non-system package:"+p.packageName);
4763 return deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
4764 }
4765
4766 public void clearApplicationUserData(final String packageName,
4767 final IPackageDataObserver observer) {
4768 mContext.enforceCallingOrSelfPermission(
4769 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4770 // Queue up an async operation since the package deletion may take a little while.
4771 mHandler.post(new Runnable() {
4772 public void run() {
4773 mHandler.removeCallbacks(this);
4774 final boolean succeeded;
4775 synchronized (mInstallLock) {
4776 succeeded = clearApplicationUserDataLI(packageName);
4777 }
4778 if (succeeded) {
4779 // invoke DeviceStorageMonitor's update method to clear any notifications
4780 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4781 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4782 if (dsm != null) {
4783 dsm.updateMemory();
4784 }
4785 }
4786 if(observer != null) {
4787 try {
4788 observer.onRemoveCompleted(packageName, succeeded);
4789 } catch (RemoteException e) {
4790 Log.i(TAG, "Observer no longer exists.");
4791 }
4792 } //end if observer
4793 } //end run
4794 });
4795 }
4796
4797 private boolean clearApplicationUserDataLI(String packageName) {
4798 if (packageName == null) {
4799 Log.w(TAG, "Attempt to delete null packageName.");
4800 return false;
4801 }
4802 PackageParser.Package p;
4803 boolean dataOnly = false;
4804 synchronized (mPackages) {
4805 p = mPackages.get(packageName);
4806 if(p == null) {
4807 dataOnly = true;
4808 PackageSetting ps = mSettings.mPackages.get(packageName);
4809 if((ps == null) || (ps.pkg == null)) {
4810 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4811 return false;
4812 }
4813 p = ps.pkg;
4814 }
4815 }
4816 if(!dataOnly) {
4817 //need to check this only for fully installed applications
4818 if (p == null) {
4819 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4820 return false;
4821 }
4822 final ApplicationInfo applicationInfo = p.applicationInfo;
4823 if (applicationInfo == null) {
4824 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4825 return false;
4826 }
4827 }
4828 if (mInstaller != null) {
4829 int retCode = mInstaller.clearUserData(packageName);
4830 if (retCode < 0) {
4831 Log.w(TAG, "Couldn't remove cache files for package: "
4832 + packageName);
4833 return false;
4834 }
4835 }
4836 return true;
4837 }
4838
4839 public void deleteApplicationCacheFiles(final String packageName,
4840 final IPackageDataObserver observer) {
4841 mContext.enforceCallingOrSelfPermission(
4842 android.Manifest.permission.DELETE_CACHE_FILES, null);
4843 // Queue up an async operation since the package deletion may take a little while.
4844 mHandler.post(new Runnable() {
4845 public void run() {
4846 mHandler.removeCallbacks(this);
4847 final boolean succeded;
4848 synchronized (mInstallLock) {
4849 succeded = deleteApplicationCacheFilesLI(packageName);
4850 }
4851 if(observer != null) {
4852 try {
4853 observer.onRemoveCompleted(packageName, succeded);
4854 } catch (RemoteException e) {
4855 Log.i(TAG, "Observer no longer exists.");
4856 }
4857 } //end if observer
4858 } //end run
4859 });
4860 }
4861
4862 private boolean deleteApplicationCacheFilesLI(String packageName) {
4863 if (packageName == null) {
4864 Log.w(TAG, "Attempt to delete null packageName.");
4865 return false;
4866 }
4867 PackageParser.Package p;
4868 synchronized (mPackages) {
4869 p = mPackages.get(packageName);
4870 }
4871 if (p == null) {
4872 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4873 return false;
4874 }
4875 final ApplicationInfo applicationInfo = p.applicationInfo;
4876 if (applicationInfo == null) {
4877 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4878 return false;
4879 }
4880 if (mInstaller != null) {
4881 int retCode = mInstaller.deleteCacheFiles(packageName);
4882 if (retCode < 0) {
4883 Log.w(TAG, "Couldn't remove cache files for package: "
4884 + packageName);
4885 return false;
4886 }
4887 }
4888 return true;
4889 }
4890
4891 public void getPackageSizeInfo(final String packageName,
4892 final IPackageStatsObserver observer) {
4893 mContext.enforceCallingOrSelfPermission(
4894 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4895 // Queue up an async operation since the package deletion may take a little while.
4896 mHandler.post(new Runnable() {
4897 public void run() {
4898 mHandler.removeCallbacks(this);
4899 PackageStats lStats = new PackageStats(packageName);
4900 final boolean succeded;
4901 synchronized (mInstallLock) {
4902 succeded = getPackageSizeInfoLI(packageName, lStats);
4903 }
4904 if(observer != null) {
4905 try {
4906 observer.onGetStatsCompleted(lStats, succeded);
4907 } catch (RemoteException e) {
4908 Log.i(TAG, "Observer no longer exists.");
4909 }
4910 } //end if observer
4911 } //end run
4912 });
4913 }
4914
4915 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4916 if (packageName == null) {
4917 Log.w(TAG, "Attempt to get size of null packageName.");
4918 return false;
4919 }
4920 PackageParser.Package p;
4921 boolean dataOnly = false;
4922 synchronized (mPackages) {
4923 p = mPackages.get(packageName);
4924 if(p == null) {
4925 dataOnly = true;
4926 PackageSetting ps = mSettings.mPackages.get(packageName);
4927 if((ps == null) || (ps.pkg == null)) {
4928 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4929 return false;
4930 }
4931 p = ps.pkg;
4932 }
4933 }
4934 String publicSrcDir = null;
4935 if(!dataOnly) {
4936 final ApplicationInfo applicationInfo = p.applicationInfo;
4937 if (applicationInfo == null) {
4938 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4939 return false;
4940 }
4941 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4942 }
4943 if (mInstaller != null) {
4944 int res = mInstaller.getSizeInfo(packageName, p.mPath,
4945 publicSrcDir, pStats);
4946 if (res < 0) {
4947 return false;
4948 } else {
4949 return true;
4950 }
4951 }
4952 return true;
4953 }
4954
4955
4956 public void addPackageToPreferred(String packageName) {
4957 mContext.enforceCallingOrSelfPermission(
4958 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004959 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 }
4961
4962 public void removePackageFromPreferred(String packageName) {
4963 mContext.enforceCallingOrSelfPermission(
4964 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004965 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004966 }
4967
4968 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004969 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004970 }
4971
4972 public void addPreferredActivity(IntentFilter filter, int match,
4973 ComponentName[] set, ComponentName activity) {
4974 mContext.enforceCallingOrSelfPermission(
4975 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4976
4977 synchronized (mPackages) {
4978 Log.i(TAG, "Adding preferred activity " + activity + ":");
4979 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4980 mSettings.mPreferredActivities.addFilter(
4981 new PreferredActivity(filter, match, set, activity));
4982 mSettings.writeLP();
4983 }
4984 }
4985
Satish Sampath8dbe6122009-06-02 23:35:54 +01004986 public void replacePreferredActivity(IntentFilter filter, int match,
4987 ComponentName[] set, ComponentName activity) {
4988 mContext.enforceCallingOrSelfPermission(
4989 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4990 if (filter.countActions() != 1) {
4991 throw new IllegalArgumentException(
4992 "replacePreferredActivity expects filter to have only 1 action.");
4993 }
4994 if (filter.countCategories() != 1) {
4995 throw new IllegalArgumentException(
4996 "replacePreferredActivity expects filter to have only 1 category.");
4997 }
4998 if (filter.countDataAuthorities() != 0
4999 || filter.countDataPaths() != 0
5000 || filter.countDataSchemes() != 0
5001 || filter.countDataTypes() != 0) {
5002 throw new IllegalArgumentException(
5003 "replacePreferredActivity expects filter to have no data authorities, " +
5004 "paths, schemes or types.");
5005 }
5006 synchronized (mPackages) {
5007 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5008 String action = filter.getAction(0);
5009 String category = filter.getCategory(0);
5010 while (it.hasNext()) {
5011 PreferredActivity pa = it.next();
5012 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5013 it.remove();
5014 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5015 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5016 }
5017 }
5018 addPreferredActivity(filter, match, set, activity);
5019 }
5020 }
5021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005022 public void clearPackagePreferredActivities(String packageName) {
5023 mContext.enforceCallingOrSelfPermission(
5024 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5025
5026 synchronized (mPackages) {
5027 if (clearPackagePreferredActivitiesLP(packageName)) {
5028 mSettings.writeLP();
5029 }
5030 }
5031 }
5032
5033 boolean clearPackagePreferredActivitiesLP(String packageName) {
5034 boolean changed = false;
5035 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5036 while (it.hasNext()) {
5037 PreferredActivity pa = it.next();
5038 if (pa.mActivity.getPackageName().equals(packageName)) {
5039 it.remove();
5040 changed = true;
5041 }
5042 }
5043 return changed;
5044 }
5045
5046 public int getPreferredActivities(List<IntentFilter> outFilters,
5047 List<ComponentName> outActivities, String packageName) {
5048
5049 int num = 0;
5050 synchronized (mPackages) {
5051 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5052 while (it.hasNext()) {
5053 PreferredActivity pa = it.next();
5054 if (packageName == null
5055 || pa.mActivity.getPackageName().equals(packageName)) {
5056 if (outFilters != null) {
5057 outFilters.add(new IntentFilter(pa));
5058 }
5059 if (outActivities != null) {
5060 outActivities.add(pa.mActivity);
5061 }
5062 }
5063 }
5064 }
5065
5066 return num;
5067 }
5068
5069 public void setApplicationEnabledSetting(String appPackageName,
5070 int newState, int flags) {
5071 setEnabledSetting(appPackageName, null, newState, flags);
5072 }
5073
5074 public void setComponentEnabledSetting(ComponentName componentName,
5075 int newState, int flags) {
5076 setEnabledSetting(componentName.getPackageName(),
5077 componentName.getClassName(), newState, flags);
5078 }
5079
5080 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005081 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5083 || newState == COMPONENT_ENABLED_STATE_ENABLED
5084 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5085 throw new IllegalArgumentException("Invalid new component state: "
5086 + newState);
5087 }
5088 PackageSetting pkgSetting;
5089 final int uid = Binder.getCallingUid();
5090 final int permission = mContext.checkCallingPermission(
5091 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5092 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005093 boolean sendNow = false;
5094 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005095 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005096 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005097 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005099 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005100 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005101 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005103 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 }
5105 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005106 "Unknown component: " + packageName
5107 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005108 }
5109 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5110 throw new SecurityException(
5111 "Permission Denial: attempt to change component state from pid="
5112 + Binder.getCallingPid()
5113 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5114 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005115 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 // We're dealing with an application/package level state change
5117 pkgSetting.enabled = newState;
5118 } else {
5119 // We're dealing with a component level state change
5120 switch (newState) {
5121 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005122 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 break;
5124 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005125 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005126 break;
5127 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005128 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 break;
5130 default:
5131 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005132 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005133 }
5134 }
5135 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005136 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005137 components = mPendingBroadcasts.get(packageName);
5138 boolean newPackage = components == null;
5139 if (newPackage) {
5140 components = new ArrayList<String>();
5141 }
5142 if (!components.contains(componentName)) {
5143 components.add(componentName);
5144 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005145 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5146 sendNow = true;
5147 // Purge entry from pending broadcast list if another one exists already
5148 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005149 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005150 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005151 if (newPackage) {
5152 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005153 }
5154 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5155 // Schedule a message
5156 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5157 }
5158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005159 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 long callingId = Binder.clearCallingIdentity();
5162 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005163 if (sendNow) {
5164 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005165 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005167 } finally {
5168 Binder.restoreCallingIdentity(callingId);
5169 }
5170 }
5171
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005172 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005173 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5174 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5175 + " components=" + componentNames);
5176 Bundle extras = new Bundle(4);
5177 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5178 String nameList[] = new String[componentNames.size()];
5179 componentNames.toArray(nameList);
5180 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005181 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5182 extras.putInt(Intent.EXTRA_UID, packageUid);
5183 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
5184 }
5185
Jacek Surazski65e13172009-04-28 15:26:38 +02005186 public String getInstallerPackageName(String packageName) {
5187 synchronized (mPackages) {
5188 PackageSetting pkg = mSettings.mPackages.get(packageName);
5189 if (pkg == null) {
5190 throw new IllegalArgumentException("Unknown package: " + packageName);
5191 }
5192 return pkg.installerPackageName;
5193 }
5194 }
5195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 public int getApplicationEnabledSetting(String appPackageName) {
5197 synchronized (mPackages) {
5198 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5199 if (pkg == null) {
5200 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5201 }
5202 return pkg.enabled;
5203 }
5204 }
5205
5206 public int getComponentEnabledSetting(ComponentName componentName) {
5207 synchronized (mPackages) {
5208 final String packageNameStr = componentName.getPackageName();
5209 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5210 if (pkg == null) {
5211 throw new IllegalArgumentException("Unknown component: " + componentName);
5212 }
5213 final String classNameStr = componentName.getClassName();
5214 return pkg.currentEnabledStateLP(classNameStr);
5215 }
5216 }
5217
5218 public void enterSafeMode() {
5219 if (!mSystemReady) {
5220 mSafeMode = true;
5221 }
5222 }
5223
5224 public void systemReady() {
5225 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005226
5227 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005228 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005229 mContext.getContentResolver(),
5230 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005231 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005232 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005233 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 }
5236
5237 public boolean isSafeMode() {
5238 return mSafeMode;
5239 }
5240
5241 public boolean hasSystemUidErrors() {
5242 return mHasSystemUidErrors;
5243 }
5244
5245 static String arrayToString(int[] array) {
5246 StringBuffer buf = new StringBuffer(128);
5247 buf.append('[');
5248 if (array != null) {
5249 for (int i=0; i<array.length; i++) {
5250 if (i > 0) buf.append(", ");
5251 buf.append(array[i]);
5252 }
5253 }
5254 buf.append(']');
5255 return buf.toString();
5256 }
5257
5258 @Override
5259 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5260 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5261 != PackageManager.PERMISSION_GRANTED) {
5262 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5263 + Binder.getCallingPid()
5264 + ", uid=" + Binder.getCallingUid()
5265 + " without permission "
5266 + android.Manifest.permission.DUMP);
5267 return;
5268 }
5269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 synchronized (mPackages) {
5271 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005272 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 pw.println(" ");
5274 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005275 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005276 pw.println(" ");
5277 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005278 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005279 pw.println(" ");
5280 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005281 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005283 pw.println("Permissions:");
5284 {
5285 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005286 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5287 pw.print(Integer.toHexString(System.identityHashCode(p)));
5288 pw.println("):");
5289 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5290 pw.print(" uid="); pw.print(p.uid);
5291 pw.print(" gids="); pw.print(arrayToString(p.gids));
5292 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005293 }
5294 }
5295 pw.println(" ");
5296 pw.println("Packages:");
5297 {
5298 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005299 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5300 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5301 pw.println("):");
5302 pw.print(" userId="); pw.print(ps.userId);
5303 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5304 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5305 pw.print(" pkg="); pw.println(ps.pkg);
5306 pw.print(" codePath="); pw.println(ps.codePathString);
5307 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005309 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005310 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005311 pw.print(" supportsScreens=[");
5312 boolean first = true;
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005313 if ((ps.pkg.applicationInfo.flags &
5314 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005315 if (!first) pw.print(", ");
5316 first = false;
5317 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005318 }
5319 if ((ps.pkg.applicationInfo.flags &
5320 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005321 if (!first) pw.print(", ");
5322 first = false;
5323 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005324 }
5325 if ((ps.pkg.applicationInfo.flags &
5326 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005327 if (!first) pw.print(", ");
5328 first = false;
5329 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005330 }
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005331 if ((ps.pkg.applicationInfo.flags &
5332 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005333 if (!first) pw.print(", ");
5334 first = false;
5335 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005336 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005337 if ((ps.pkg.applicationInfo.flags &
5338 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
5339 if (!first) pw.print(", ");
5340 first = false;
5341 pw.print("anyDensity");
5342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005343 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005344 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005345 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
5346 pw.print(" signatures="); pw.println(ps.signatures);
5347 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
5348 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
5349 pw.print(" installStatus="); pw.print(ps.installStatus);
5350 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005351 if (ps.disabledComponents.size() > 0) {
5352 pw.println(" disabledComponents:");
5353 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005354 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005355 }
5356 }
5357 if (ps.enabledComponents.size() > 0) {
5358 pw.println(" enabledComponents:");
5359 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005360 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 }
5362 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005363 if (ps.grantedPermissions.size() > 0) {
5364 pw.println(" grantedPermissions:");
5365 for (String s : ps.grantedPermissions) {
5366 pw.print(" "); pw.println(s);
5367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005368 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005369 if (ps.loadedPermissions.size() > 0) {
5370 pw.println(" loadedPermissions:");
5371 for (String s : ps.loadedPermissions) {
5372 pw.print(" "); pw.println(s);
5373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 }
5375 }
5376 }
5377 pw.println(" ");
5378 pw.println("Shared Users:");
5379 {
5380 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005381 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5382 pw.print(Integer.toHexString(System.identityHashCode(su)));
5383 pw.println("):");
5384 pw.print(" userId="); pw.print(su.userId);
5385 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 pw.println(" grantedPermissions:");
5387 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005388 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 }
5390 pw.println(" loadedPermissions:");
5391 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005392 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 }
5394 }
5395 }
5396 pw.println(" ");
5397 pw.println("Settings parse messages:");
5398 pw.println(mSettings.mReadMessages.toString());
5399 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05005400
5401 synchronized (mProviders) {
5402 pw.println(" ");
5403 pw.println("Registered ContentProviders:");
5404 for (PackageParser.Provider p : mProviders.values()) {
5405 pw.println(" ["); pw.println(p.info.authority); pw.println("]: ");
5406 pw.println(p.toString());
5407 }
5408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 }
5410
5411 static final class BasePermission {
5412 final static int TYPE_NORMAL = 0;
5413 final static int TYPE_BUILTIN = 1;
5414 final static int TYPE_DYNAMIC = 2;
5415
5416 final String name;
5417 final String sourcePackage;
5418 final int type;
5419 PackageParser.Permission perm;
5420 PermissionInfo pendingInfo;
5421 int uid;
5422 int[] gids;
5423
5424 BasePermission(String _name, String _sourcePackage, int _type) {
5425 name = _name;
5426 sourcePackage = _sourcePackage;
5427 type = _type;
5428 }
5429 }
5430
5431 static class PackageSignatures {
5432 private Signature[] mSignatures;
5433
5434 PackageSignatures(Signature[] sigs) {
5435 assignSignatures(sigs);
5436 }
5437
5438 PackageSignatures() {
5439 }
5440
5441 void writeXml(XmlSerializer serializer, String tagName,
5442 ArrayList<Signature> pastSignatures) throws IOException {
5443 if (mSignatures == null) {
5444 return;
5445 }
5446 serializer.startTag(null, tagName);
5447 serializer.attribute(null, "count",
5448 Integer.toString(mSignatures.length));
5449 for (int i=0; i<mSignatures.length; i++) {
5450 serializer.startTag(null, "cert");
5451 final Signature sig = mSignatures[i];
5452 final int sigHash = sig.hashCode();
5453 final int numPast = pastSignatures.size();
5454 int j;
5455 for (j=0; j<numPast; j++) {
5456 Signature pastSig = pastSignatures.get(j);
5457 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5458 serializer.attribute(null, "index", Integer.toString(j));
5459 break;
5460 }
5461 }
5462 if (j >= numPast) {
5463 pastSignatures.add(sig);
5464 serializer.attribute(null, "index", Integer.toString(numPast));
5465 serializer.attribute(null, "key", sig.toCharsString());
5466 }
5467 serializer.endTag(null, "cert");
5468 }
5469 serializer.endTag(null, tagName);
5470 }
5471
5472 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5473 throws IOException, XmlPullParserException {
5474 String countStr = parser.getAttributeValue(null, "count");
5475 if (countStr == null) {
5476 reportSettingsProblem(Log.WARN,
5477 "Error in package manager settings: <signatures> has"
5478 + " no count at " + parser.getPositionDescription());
5479 XmlUtils.skipCurrentTag(parser);
5480 }
5481 final int count = Integer.parseInt(countStr);
5482 mSignatures = new Signature[count];
5483 int pos = 0;
5484
5485 int outerDepth = parser.getDepth();
5486 int type;
5487 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5488 && (type != XmlPullParser.END_TAG
5489 || parser.getDepth() > outerDepth)) {
5490 if (type == XmlPullParser.END_TAG
5491 || type == XmlPullParser.TEXT) {
5492 continue;
5493 }
5494
5495 String tagName = parser.getName();
5496 if (tagName.equals("cert")) {
5497 if (pos < count) {
5498 String index = parser.getAttributeValue(null, "index");
5499 if (index != null) {
5500 try {
5501 int idx = Integer.parseInt(index);
5502 String key = parser.getAttributeValue(null, "key");
5503 if (key == null) {
5504 if (idx >= 0 && idx < pastSignatures.size()) {
5505 Signature sig = pastSignatures.get(idx);
5506 if (sig != null) {
5507 mSignatures[pos] = pastSignatures.get(idx);
5508 pos++;
5509 } else {
5510 reportSettingsProblem(Log.WARN,
5511 "Error in package manager settings: <cert> "
5512 + "index " + index + " is not defined at "
5513 + parser.getPositionDescription());
5514 }
5515 } else {
5516 reportSettingsProblem(Log.WARN,
5517 "Error in package manager settings: <cert> "
5518 + "index " + index + " is out of bounds at "
5519 + parser.getPositionDescription());
5520 }
5521 } else {
5522 while (pastSignatures.size() <= idx) {
5523 pastSignatures.add(null);
5524 }
5525 Signature sig = new Signature(key);
5526 pastSignatures.set(idx, sig);
5527 mSignatures[pos] = sig;
5528 pos++;
5529 }
5530 } catch (NumberFormatException e) {
5531 reportSettingsProblem(Log.WARN,
5532 "Error in package manager settings: <cert> "
5533 + "index " + index + " is not a number at "
5534 + parser.getPositionDescription());
5535 }
5536 } else {
5537 reportSettingsProblem(Log.WARN,
5538 "Error in package manager settings: <cert> has"
5539 + " no index at " + parser.getPositionDescription());
5540 }
5541 } else {
5542 reportSettingsProblem(Log.WARN,
5543 "Error in package manager settings: too "
5544 + "many <cert> tags, expected " + count
5545 + " at " + parser.getPositionDescription());
5546 }
5547 } else {
5548 reportSettingsProblem(Log.WARN,
5549 "Unknown element under <cert>: "
5550 + parser.getName());
5551 }
5552 XmlUtils.skipCurrentTag(parser);
5553 }
5554
5555 if (pos < count) {
5556 // Should never happen -- there is an error in the written
5557 // settings -- but if it does we don't want to generate
5558 // a bad array.
5559 Signature[] newSigs = new Signature[pos];
5560 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5561 mSignatures = newSigs;
5562 }
5563 }
5564
5565 /**
5566 * If any of the given 'sigs' is contained in the existing signatures,
5567 * then completely replace the current signatures with the ones in
5568 * 'sigs'. This is used for updating an existing package to a newly
5569 * installed version.
5570 */
5571 boolean updateSignatures(Signature[] sigs, boolean update) {
5572 if (mSignatures == null) {
5573 if (update) {
5574 assignSignatures(sigs);
5575 }
5576 return true;
5577 }
5578 if (sigs == null) {
5579 return false;
5580 }
5581
5582 for (int i=0; i<sigs.length; i++) {
5583 Signature sig = sigs[i];
5584 for (int j=0; j<mSignatures.length; j++) {
5585 if (mSignatures[j].equals(sig)) {
5586 if (update) {
5587 assignSignatures(sigs);
5588 }
5589 return true;
5590 }
5591 }
5592 }
5593 return false;
5594 }
5595
5596 /**
5597 * If any of the given 'sigs' is contained in the existing signatures,
5598 * then add in any new signatures found in 'sigs'. This is used for
5599 * including a new package into an existing shared user id.
5600 */
5601 boolean mergeSignatures(Signature[] sigs, boolean update) {
5602 if (mSignatures == null) {
5603 if (update) {
5604 assignSignatures(sigs);
5605 }
5606 return true;
5607 }
5608 if (sigs == null) {
5609 return false;
5610 }
5611
5612 Signature[] added = null;
5613 int addedCount = 0;
5614 boolean haveMatch = false;
5615 for (int i=0; i<sigs.length; i++) {
5616 Signature sig = sigs[i];
5617 boolean found = false;
5618 for (int j=0; j<mSignatures.length; j++) {
5619 if (mSignatures[j].equals(sig)) {
5620 found = true;
5621 haveMatch = true;
5622 break;
5623 }
5624 }
5625
5626 if (!found) {
5627 if (added == null) {
5628 added = new Signature[sigs.length];
5629 }
5630 added[i] = sig;
5631 addedCount++;
5632 }
5633 }
5634
5635 if (!haveMatch) {
5636 // Nothing matched -- reject the new signatures.
5637 return false;
5638 }
5639 if (added == null) {
5640 // Completely matched -- nothing else to do.
5641 return true;
5642 }
5643
5644 // Add additional signatures in.
5645 if (update) {
5646 Signature[] total = new Signature[addedCount+mSignatures.length];
5647 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5648 int j = mSignatures.length;
5649 for (int i=0; i<added.length; i++) {
5650 if (added[i] != null) {
5651 total[j] = added[i];
5652 j++;
5653 }
5654 }
5655 mSignatures = total;
5656 }
5657 return true;
5658 }
5659
5660 private void assignSignatures(Signature[] sigs) {
5661 if (sigs == null) {
5662 mSignatures = null;
5663 return;
5664 }
5665 mSignatures = new Signature[sigs.length];
5666 for (int i=0; i<sigs.length; i++) {
5667 mSignatures[i] = sigs[i];
5668 }
5669 }
5670
5671 @Override
5672 public String toString() {
5673 StringBuffer buf = new StringBuffer(128);
5674 buf.append("PackageSignatures{");
5675 buf.append(Integer.toHexString(System.identityHashCode(this)));
5676 buf.append(" [");
5677 if (mSignatures != null) {
5678 for (int i=0; i<mSignatures.length; i++) {
5679 if (i > 0) buf.append(", ");
5680 buf.append(Integer.toHexString(
5681 System.identityHashCode(mSignatures[i])));
5682 }
5683 }
5684 buf.append("]}");
5685 return buf.toString();
5686 }
5687 }
5688
5689 static class PreferredActivity extends IntentFilter {
5690 final int mMatch;
5691 final String[] mSetPackages;
5692 final String[] mSetClasses;
5693 final String[] mSetComponents;
5694 final ComponentName mActivity;
5695 final String mShortActivity;
5696 String mParseError;
5697
5698 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5699 ComponentName activity) {
5700 super(filter);
5701 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5702 mActivity = activity;
5703 mShortActivity = activity.flattenToShortString();
5704 mParseError = null;
5705 if (set != null) {
5706 final int N = set.length;
5707 String[] myPackages = new String[N];
5708 String[] myClasses = new String[N];
5709 String[] myComponents = new String[N];
5710 for (int i=0; i<N; i++) {
5711 ComponentName cn = set[i];
5712 if (cn == null) {
5713 mSetPackages = null;
5714 mSetClasses = null;
5715 mSetComponents = null;
5716 return;
5717 }
5718 myPackages[i] = cn.getPackageName().intern();
5719 myClasses[i] = cn.getClassName().intern();
5720 myComponents[i] = cn.flattenToShortString().intern();
5721 }
5722 mSetPackages = myPackages;
5723 mSetClasses = myClasses;
5724 mSetComponents = myComponents;
5725 } else {
5726 mSetPackages = null;
5727 mSetClasses = null;
5728 mSetComponents = null;
5729 }
5730 }
5731
5732 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5733 IOException {
5734 mShortActivity = parser.getAttributeValue(null, "name");
5735 mActivity = ComponentName.unflattenFromString(mShortActivity);
5736 if (mActivity == null) {
5737 mParseError = "Bad activity name " + mShortActivity;
5738 }
5739 String matchStr = parser.getAttributeValue(null, "match");
5740 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5741 String setCountStr = parser.getAttributeValue(null, "set");
5742 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5743
5744 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5745 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5746 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5747
5748 int setPos = 0;
5749
5750 int outerDepth = parser.getDepth();
5751 int type;
5752 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5753 && (type != XmlPullParser.END_TAG
5754 || parser.getDepth() > outerDepth)) {
5755 if (type == XmlPullParser.END_TAG
5756 || type == XmlPullParser.TEXT) {
5757 continue;
5758 }
5759
5760 String tagName = parser.getName();
5761 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5762 // + parser.getDepth() + " tag=" + tagName);
5763 if (tagName.equals("set")) {
5764 String name = parser.getAttributeValue(null, "name");
5765 if (name == null) {
5766 if (mParseError == null) {
5767 mParseError = "No name in set tag in preferred activity "
5768 + mShortActivity;
5769 }
5770 } else if (setPos >= setCount) {
5771 if (mParseError == null) {
5772 mParseError = "Too many set tags in preferred activity "
5773 + mShortActivity;
5774 }
5775 } else {
5776 ComponentName cn = ComponentName.unflattenFromString(name);
5777 if (cn == null) {
5778 if (mParseError == null) {
5779 mParseError = "Bad set name " + name + " in preferred activity "
5780 + mShortActivity;
5781 }
5782 } else {
5783 myPackages[setPos] = cn.getPackageName();
5784 myClasses[setPos] = cn.getClassName();
5785 myComponents[setPos] = name;
5786 setPos++;
5787 }
5788 }
5789 XmlUtils.skipCurrentTag(parser);
5790 } else if (tagName.equals("filter")) {
5791 //Log.i(TAG, "Starting to parse filter...");
5792 readFromXml(parser);
5793 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5794 // + parser.getDepth() + " tag=" + parser.getName());
5795 } else {
5796 reportSettingsProblem(Log.WARN,
5797 "Unknown element under <preferred-activities>: "
5798 + parser.getName());
5799 XmlUtils.skipCurrentTag(parser);
5800 }
5801 }
5802
5803 if (setPos != setCount) {
5804 if (mParseError == null) {
5805 mParseError = "Not enough set tags (expected " + setCount
5806 + " but found " + setPos + ") in " + mShortActivity;
5807 }
5808 }
5809
5810 mSetPackages = myPackages;
5811 mSetClasses = myClasses;
5812 mSetComponents = myComponents;
5813 }
5814
5815 public void writeToXml(XmlSerializer serializer) throws IOException {
5816 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5817 serializer.attribute(null, "name", mShortActivity);
5818 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5819 serializer.attribute(null, "set", Integer.toString(NS));
5820 for (int s=0; s<NS; s++) {
5821 serializer.startTag(null, "set");
5822 serializer.attribute(null, "name", mSetComponents[s]);
5823 serializer.endTag(null, "set");
5824 }
5825 serializer.startTag(null, "filter");
5826 super.writeToXml(serializer);
5827 serializer.endTag(null, "filter");
5828 }
5829
5830 boolean sameSet(List<ResolveInfo> query, int priority) {
5831 if (mSetPackages == null) return false;
5832 final int NQ = query.size();
5833 final int NS = mSetPackages.length;
5834 int numMatch = 0;
5835 for (int i=0; i<NQ; i++) {
5836 ResolveInfo ri = query.get(i);
5837 if (ri.priority != priority) continue;
5838 ActivityInfo ai = ri.activityInfo;
5839 boolean good = false;
5840 for (int j=0; j<NS; j++) {
5841 if (mSetPackages[j].equals(ai.packageName)
5842 && mSetClasses[j].equals(ai.name)) {
5843 numMatch++;
5844 good = true;
5845 break;
5846 }
5847 }
5848 if (!good) return false;
5849 }
5850 return numMatch == NS;
5851 }
5852 }
5853
5854 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07005855 int pkgFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856
5857 HashSet<String> grantedPermissions = new HashSet<String>();
5858 int[] gids;
5859
5860 HashSet<String> loadedPermissions = new HashSet<String>();
5861
5862 GrantedPermissions(int pkgFlags) {
5863 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5864 }
5865 }
5866
5867 /**
5868 * Settings base class for pending and resolved classes.
5869 */
5870 static class PackageSettingBase extends GrantedPermissions {
5871 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005872 File codePath;
5873 String codePathString;
5874 File resourcePath;
5875 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005876 private long timeStamp;
5877 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005878 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879
5880 PackageSignatures signatures = new PackageSignatures();
5881
5882 boolean permissionsFixed;
5883
5884 /* Explicitly disabled components */
5885 HashSet<String> disabledComponents = new HashSet<String>(0);
5886 /* Explicitly enabled components */
5887 HashSet<String> enabledComponents = new HashSet<String>(0);
5888 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5889 int installStatus = PKG_INSTALL_COMPLETE;
Jacek Surazski65e13172009-04-28 15:26:38 +02005890
5891 /* package name of the app that installed this package */
5892 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893
5894 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005895 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005896 super(pkgFlags);
5897 this.name = name;
5898 this.codePath = codePath;
5899 this.codePathString = codePath.toString();
5900 this.resourcePath = resourcePath;
5901 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005902 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 }
5904
Jacek Surazski65e13172009-04-28 15:26:38 +02005905 public void setInstallerPackageName(String packageName) {
5906 installerPackageName = packageName;
5907 }
5908
5909 String getInstallerPackageName() {
5910 return installerPackageName;
5911 }
5912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913 public void setInstallStatus(int newStatus) {
5914 installStatus = newStatus;
5915 }
5916
5917 public int getInstallStatus() {
5918 return installStatus;
5919 }
5920
5921 public void setTimeStamp(long newStamp) {
5922 if (newStamp != timeStamp) {
5923 timeStamp = newStamp;
5924 timeStampString = Long.toString(newStamp);
5925 }
5926 }
5927
5928 public void setTimeStamp(long newStamp, String newStampStr) {
5929 timeStamp = newStamp;
5930 timeStampString = newStampStr;
5931 }
5932
5933 public long getTimeStamp() {
5934 return timeStamp;
5935 }
5936
5937 public String getTimeStampStr() {
5938 return timeStampString;
5939 }
5940
5941 public void copyFrom(PackageSettingBase base) {
5942 grantedPermissions = base.grantedPermissions;
5943 gids = base.gids;
5944 loadedPermissions = base.loadedPermissions;
5945
5946 timeStamp = base.timeStamp;
5947 timeStampString = base.timeStampString;
5948 signatures = base.signatures;
5949 permissionsFixed = base.permissionsFixed;
5950 disabledComponents = base.disabledComponents;
5951 enabledComponents = base.enabledComponents;
5952 enabled = base.enabled;
5953 installStatus = base.installStatus;
5954 }
5955
5956 void enableComponentLP(String componentClassName) {
5957 disabledComponents.remove(componentClassName);
5958 enabledComponents.add(componentClassName);
5959 }
5960
5961 void disableComponentLP(String componentClassName) {
5962 enabledComponents.remove(componentClassName);
5963 disabledComponents.add(componentClassName);
5964 }
5965
5966 void restoreComponentLP(String componentClassName) {
5967 enabledComponents.remove(componentClassName);
5968 disabledComponents.remove(componentClassName);
5969 }
5970
5971 int currentEnabledStateLP(String componentName) {
5972 if (enabledComponents.contains(componentName)) {
5973 return COMPONENT_ENABLED_STATE_ENABLED;
5974 } else if (disabledComponents.contains(componentName)) {
5975 return COMPONENT_ENABLED_STATE_DISABLED;
5976 } else {
5977 return COMPONENT_ENABLED_STATE_DEFAULT;
5978 }
5979 }
5980 }
5981
5982 /**
5983 * Settings data for a particular package we know about.
5984 */
5985 static final class PackageSetting extends PackageSettingBase {
5986 int userId;
5987 PackageParser.Package pkg;
5988 SharedUserSetting sharedUser;
5989
5990 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005991 int pVersionCode, int pkgFlags) {
5992 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 }
5994
5995 @Override
5996 public String toString() {
5997 return "PackageSetting{"
5998 + Integer.toHexString(System.identityHashCode(this))
5999 + " " + name + "/" + userId + "}";
6000 }
6001 }
6002
6003 /**
6004 * Settings data for a particular shared user ID we know about.
6005 */
6006 static final class SharedUserSetting extends GrantedPermissions {
6007 final String name;
6008 int userId;
6009 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6010 final PackageSignatures signatures = new PackageSignatures();
6011
6012 SharedUserSetting(String _name, int _pkgFlags) {
6013 super(_pkgFlags);
6014 name = _name;
6015 }
6016
6017 @Override
6018 public String toString() {
6019 return "SharedUserSetting{"
6020 + Integer.toHexString(System.identityHashCode(this))
6021 + " " + name + "/" + userId + "}";
6022 }
6023 }
6024
6025 /**
6026 * Holds information about dynamic settings.
6027 */
6028 private static final class Settings {
6029 private final File mSettingsFilename;
6030 private final File mBackupSettingsFilename;
6031 private final HashMap<String, PackageSetting> mPackages =
6032 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 // List of replaced system applications
6034 final HashMap<String, PackageSetting> mDisabledSysPackages =
6035 new HashMap<String, PackageSetting>();
6036
6037 // The user's preferred activities associated with particular intent
6038 // filters.
6039 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6040 new IntentResolver<PreferredActivity, PreferredActivity>() {
6041 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006042 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006044 out.print(prefix); out.print(
6045 Integer.toHexString(System.identityHashCode(filter)));
6046 out.print(' ');
6047 out.print(filter.mActivity.flattenToShortString());
6048 out.print(" match=0x");
6049 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006051 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006053 out.print(prefix); out.print(" ");
6054 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 }
6056 }
6057 }
6058 };
6059 private final HashMap<String, SharedUserSetting> mSharedUsers =
6060 new HashMap<String, SharedUserSetting>();
6061 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6062 private final SparseArray<Object> mOtherUserIds =
6063 new SparseArray<Object>();
6064
6065 // For reading/writing settings file.
6066 private final ArrayList<Signature> mPastSignatures =
6067 new ArrayList<Signature>();
6068
6069 // Mapping from permission names to info about them.
6070 final HashMap<String, BasePermission> mPermissions =
6071 new HashMap<String, BasePermission>();
6072
6073 // Mapping from permission tree names to info about them.
6074 final HashMap<String, BasePermission> mPermissionTrees =
6075 new HashMap<String, BasePermission>();
6076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 private final StringBuilder mReadMessages = new StringBuilder();
6078
6079 private static final class PendingPackage extends PackageSettingBase {
6080 final int sharedId;
6081
6082 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006083 int sharedId, int pVersionCode, int pkgFlags) {
6084 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 this.sharedId = sharedId;
6086 }
6087 }
6088 private final ArrayList<PendingPackage> mPendingPackages
6089 = new ArrayList<PendingPackage>();
6090
6091 Settings() {
6092 File dataDir = Environment.getDataDirectory();
6093 File systemDir = new File(dataDir, "system");
6094 systemDir.mkdirs();
6095 FileUtils.setPermissions(systemDir.toString(),
6096 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6097 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6098 -1, -1);
6099 mSettingsFilename = new File(systemDir, "packages.xml");
6100 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6101 }
6102
6103 PackageSetting getPackageLP(PackageParser.Package pkg,
6104 SharedUserSetting sharedUser, File codePath, File resourcePath,
6105 int pkgFlags, boolean create, boolean add) {
6106 final String name = pkg.packageName;
6107 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006108 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 return p;
6110 }
6111
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006112 PackageSetting peekPackageLP(String name) {
6113 return mPackages.get(name);
6114 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 PackageSetting p = mPackages.get(name);
6116 if (p != null && p.codePath.getPath().equals(codePath)) {
6117 return p;
6118 }
6119 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006120 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 }
6122
6123 void setInstallStatus(String pkgName, int status) {
6124 PackageSetting p = mPackages.get(pkgName);
6125 if(p != null) {
6126 if(p.getInstallStatus() != status) {
6127 p.setInstallStatus(status);
6128 }
6129 }
6130 }
6131
Jacek Surazski65e13172009-04-28 15:26:38 +02006132 void setInstallerPackageName(String pkgName,
6133 String installerPkgName) {
6134 PackageSetting p = mPackages.get(pkgName);
6135 if(p != null) {
6136 p.setInstallerPackageName(installerPkgName);
6137 }
6138 }
6139
6140 String getInstallerPackageName(String pkgName) {
6141 PackageSetting p = mPackages.get(pkgName);
6142 return (p == null) ? null : p.getInstallerPackageName();
6143 }
6144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 int getInstallStatus(String pkgName) {
6146 PackageSetting p = mPackages.get(pkgName);
6147 if(p != null) {
6148 return p.getInstallStatus();
6149 }
6150 return -1;
6151 }
6152
6153 SharedUserSetting getSharedUserLP(String name,
6154 int pkgFlags, boolean create) {
6155 SharedUserSetting s = mSharedUsers.get(name);
6156 if (s == null) {
6157 if (!create) {
6158 return null;
6159 }
6160 s = new SharedUserSetting(name, pkgFlags);
6161 if (MULTIPLE_APPLICATION_UIDS) {
6162 s.userId = newUserIdLP(s);
6163 } else {
6164 s.userId = FIRST_APPLICATION_UID;
6165 }
6166 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6167 // < 0 means we couldn't assign a userid; fall out and return
6168 // s, which is currently null
6169 if (s.userId >= 0) {
6170 mSharedUsers.put(name, s);
6171 }
6172 }
6173
6174 return s;
6175 }
6176
6177 int disableSystemPackageLP(String name) {
6178 PackageSetting p = mPackages.get(name);
6179 if(p == null) {
6180 Log.w(TAG, "Package:"+name+" is not an installed package");
6181 return -1;
6182 }
6183 PackageSetting dp = mDisabledSysPackages.get(name);
6184 // always make sure the system package code and resource paths dont change
6185 if(dp == null) {
6186 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6187 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6188 }
6189 mDisabledSysPackages.put(name, p);
6190 }
6191 return removePackageLP(name);
6192 }
6193
6194 PackageSetting enableSystemPackageLP(String name) {
6195 PackageSetting p = mDisabledSysPackages.get(name);
6196 if(p == null) {
6197 Log.w(TAG, "Package:"+name+" is not disabled");
6198 return null;
6199 }
6200 // Reset flag in ApplicationInfo object
6201 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6202 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6203 }
6204 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006205 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 mDisabledSysPackages.remove(name);
6207 return ret;
6208 }
6209
6210 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006211 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 PackageSetting p = mPackages.get(name);
6213 if (p != null) {
6214 if (p.userId == uid) {
6215 return p;
6216 }
6217 reportSettingsProblem(Log.ERROR,
6218 "Adding duplicate package, keeping first: " + name);
6219 return null;
6220 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006221 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 p.userId = uid;
6223 if (addUserIdLP(uid, p, name)) {
6224 mPackages.put(name, p);
6225 return p;
6226 }
6227 return null;
6228 }
6229
6230 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6231 SharedUserSetting s = mSharedUsers.get(name);
6232 if (s != null) {
6233 if (s.userId == uid) {
6234 return s;
6235 }
6236 reportSettingsProblem(Log.ERROR,
6237 "Adding duplicate shared user, keeping first: " + name);
6238 return null;
6239 }
6240 s = new SharedUserSetting(name, pkgFlags);
6241 s.userId = uid;
6242 if (addUserIdLP(uid, s, name)) {
6243 mSharedUsers.put(name, s);
6244 return s;
6245 }
6246 return null;
6247 }
6248
6249 private PackageSetting getPackageLP(String name,
6250 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006251 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 PackageSetting p = mPackages.get(name);
6253 if (p != null) {
6254 if (!p.codePath.equals(codePath)) {
6255 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006256 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006257 // This is an updated system app with versions in both system
6258 // and data partition. Just let the most recent version
6259 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006260 Log.w(TAG, "Trying to update system app code path from " +
6261 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006262 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006263 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07006264 reportSettingsProblem(Log.WARN,
6265 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006266 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006268 }
6269 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 reportSettingsProblem(Log.WARN,
6271 "Package " + name + " shared user changed from "
6272 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
6273 + " to "
6274 + (sharedUser != null ? sharedUser.name : "<nothing>")
6275 + "; replacing with new");
6276 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006277 } else {
6278 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6279 // If what we are scanning is a system package, then
6280 // make it so, regardless of whether it was previously
6281 // installed only in the data partition.
6282 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 }
6285 }
6286 if (p == null) {
6287 // Create a new PackageSettings entry. this can end up here because
6288 // of code path mismatch or user id mismatch of an updated system partition
6289 if (!create) {
6290 return null;
6291 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006292 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07006294 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 if (sharedUser != null) {
6296 p.userId = sharedUser.userId;
6297 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006298 // Clone the setting here for disabled system packages
6299 PackageSetting dis = mDisabledSysPackages.get(name);
6300 if (dis != null) {
6301 // For disabled packages a new setting is created
6302 // from the existing user id. This still has to be
6303 // added to list of user id's
6304 // Copy signatures from previous setting
6305 if (dis.signatures.mSignatures != null) {
6306 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
6307 }
6308 p.userId = dis.userId;
6309 // Clone permissions
6310 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
6311 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
6312 // Clone component info
6313 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
6314 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
6315 // Add new setting to list of user ids
6316 addUserIdLP(p.userId, p, name);
6317 } else {
6318 // Assign new user id
6319 p.userId = newUserIdLP(p);
6320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 } else {
6322 p.userId = FIRST_APPLICATION_UID;
6323 }
6324 if (p.userId < 0) {
6325 reportSettingsProblem(Log.WARN,
6326 "Package " + name + " could not be assigned a valid uid");
6327 return null;
6328 }
6329 if (add) {
6330 // Finish adding new package by adding it and updating shared
6331 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006332 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 }
6334 }
6335 return p;
6336 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006337
6338 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg,
6339 File codePath, File resourcePath) {
6340 p.pkg = pkg;
6341 // Update code path if needed
6342 if (!codePath.toString().equalsIgnoreCase(p.codePathString)) {
6343 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006344 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006345 p.codePath = codePath;
6346 p.codePathString = codePath.toString();
6347 }
6348 //Update resource path if needed
6349 if (!resourcePath.toString().equalsIgnoreCase(p.resourcePathString)) {
6350 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006351 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006352 p.resourcePath = resourcePath;
6353 p.resourcePathString = resourcePath.toString();
6354 }
6355 // Update version code if needed
6356 if (pkg.mVersionCode != p.versionCode) {
6357 p.versionCode = pkg.mVersionCode;
6358 }
6359 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
6360 }
6361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 // Utility method that adds a PackageSetting to mPackages and
6363 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006364 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 SharedUserSetting sharedUser) {
6366 mPackages.put(name, p);
6367 if (sharedUser != null) {
6368 if (p.sharedUser != null && p.sharedUser != sharedUser) {
6369 reportSettingsProblem(Log.ERROR,
6370 "Package " + p.name + " was user "
6371 + p.sharedUser + " but is now " + sharedUser
6372 + "; I am not changing its files so it will probably fail!");
6373 p.sharedUser.packages.remove(p);
6374 } else if (p.userId != sharedUser.userId) {
6375 reportSettingsProblem(Log.ERROR,
6376 "Package " + p.name + " was user id " + p.userId
6377 + " but is now user " + sharedUser
6378 + " with id " + sharedUser.userId
6379 + "; I am not changing its files so it will probably fail!");
6380 }
6381
6382 sharedUser.packages.add(p);
6383 p.sharedUser = sharedUser;
6384 p.userId = sharedUser.userId;
6385 }
6386 }
6387
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006388 /*
6389 * Update the shared user setting when a package using
6390 * specifying the shared user id is removed. The gids
6391 * associated with each permission of the deleted package
6392 * are removed from the shared user's gid list only if its
6393 * not in use by other permissions of packages in the
6394 * shared user setting.
6395 */
6396 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6398 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6399 return;
6400 }
6401 // No sharedUserId
6402 if (deletedPs.sharedUser == null) {
6403 return;
6404 }
6405 SharedUserSetting sus = deletedPs.sharedUser;
6406 // Update permissions
6407 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6408 boolean used = false;
6409 if (!sus.grantedPermissions.contains (eachPerm)) {
6410 continue;
6411 }
6412 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006413 if (pkg.pkg != null &&
6414 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
6415 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 used = true;
6417 break;
6418 }
6419 }
6420 if (!used) {
6421 // can safely delete this permission from list
6422 sus.grantedPermissions.remove(eachPerm);
6423 sus.loadedPermissions.remove(eachPerm);
6424 }
6425 }
6426 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006427 int newGids[] = globalGids;
6428 for (String eachPerm : sus.grantedPermissions) {
6429 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006430 if (bp != null) {
6431 newGids = appendInts(newGids, bp.gids);
6432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 }
6434 sus.gids = newGids;
6435 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 private int removePackageLP(String name) {
6438 PackageSetting p = mPackages.get(name);
6439 if (p != null) {
6440 mPackages.remove(name);
6441 if (p.sharedUser != null) {
6442 p.sharedUser.packages.remove(p);
6443 if (p.sharedUser.packages.size() == 0) {
6444 mSharedUsers.remove(p.sharedUser.name);
6445 removeUserIdLP(p.sharedUser.userId);
6446 return p.sharedUser.userId;
6447 }
6448 } else {
6449 removeUserIdLP(p.userId);
6450 return p.userId;
6451 }
6452 }
6453 return -1;
6454 }
6455
6456 private boolean addUserIdLP(int uid, Object obj, Object name) {
6457 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6458 return false;
6459 }
6460
6461 if (uid >= FIRST_APPLICATION_UID) {
6462 int N = mUserIds.size();
6463 final int index = uid - FIRST_APPLICATION_UID;
6464 while (index >= N) {
6465 mUserIds.add(null);
6466 N++;
6467 }
6468 if (mUserIds.get(index) != null) {
6469 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006470 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 + " name=" + name);
6472 return false;
6473 }
6474 mUserIds.set(index, obj);
6475 } else {
6476 if (mOtherUserIds.get(uid) != null) {
6477 reportSettingsProblem(Log.ERROR,
6478 "Adding duplicate shared id: " + uid
6479 + " name=" + name);
6480 return false;
6481 }
6482 mOtherUserIds.put(uid, obj);
6483 }
6484 return true;
6485 }
6486
6487 public Object getUserIdLP(int uid) {
6488 if (uid >= FIRST_APPLICATION_UID) {
6489 int N = mUserIds.size();
6490 final int index = uid - FIRST_APPLICATION_UID;
6491 return index < N ? mUserIds.get(index) : null;
6492 } else {
6493 return mOtherUserIds.get(uid);
6494 }
6495 }
6496
6497 private void removeUserIdLP(int uid) {
6498 if (uid >= FIRST_APPLICATION_UID) {
6499 int N = mUserIds.size();
6500 final int index = uid - FIRST_APPLICATION_UID;
6501 if (index < N) mUserIds.set(index, null);
6502 } else {
6503 mOtherUserIds.remove(uid);
6504 }
6505 }
6506
6507 void writeLP() {
6508 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6509
6510 // Keep the old settings around until we know the new ones have
6511 // been successfully written.
6512 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006513 // Presence of backup settings file indicates that we failed
6514 // to persist settings earlier. So preserve the older
6515 // backup for future reference since the current settings
6516 // might have been corrupted.
6517 if (!mBackupSettingsFilename.exists()) {
6518 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
6519 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
6520 return;
6521 }
6522 } else {
6523 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07006524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 }
6526
6527 mPastSignatures.clear();
6528
6529 try {
6530 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6531
6532 //XmlSerializer serializer = XmlUtils.serializerInstance();
6533 XmlSerializer serializer = new FastXmlSerializer();
6534 serializer.setOutput(str, "utf-8");
6535 serializer.startDocument(null, true);
6536 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6537
6538 serializer.startTag(null, "packages");
6539
6540 serializer.startTag(null, "permission-trees");
6541 for (BasePermission bp : mPermissionTrees.values()) {
6542 writePermission(serializer, bp);
6543 }
6544 serializer.endTag(null, "permission-trees");
6545
6546 serializer.startTag(null, "permissions");
6547 for (BasePermission bp : mPermissions.values()) {
6548 writePermission(serializer, bp);
6549 }
6550 serializer.endTag(null, "permissions");
6551
6552 for (PackageSetting pkg : mPackages.values()) {
6553 writePackage(serializer, pkg);
6554 }
6555
6556 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6557 writeDisabledSysPackage(serializer, pkg);
6558 }
6559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 serializer.startTag(null, "preferred-activities");
6561 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6562 serializer.startTag(null, "item");
6563 pa.writeToXml(serializer);
6564 serializer.endTag(null, "item");
6565 }
6566 serializer.endTag(null, "preferred-activities");
6567
6568 for (SharedUserSetting usr : mSharedUsers.values()) {
6569 serializer.startTag(null, "shared-user");
6570 serializer.attribute(null, "name", usr.name);
6571 serializer.attribute(null, "userId",
6572 Integer.toString(usr.userId));
6573 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6574 serializer.startTag(null, "perms");
6575 for (String name : usr.grantedPermissions) {
6576 serializer.startTag(null, "item");
6577 serializer.attribute(null, "name", name);
6578 serializer.endTag(null, "item");
6579 }
6580 serializer.endTag(null, "perms");
6581 serializer.endTag(null, "shared-user");
6582 }
6583
6584 serializer.endTag(null, "packages");
6585
6586 serializer.endDocument();
6587
6588 str.flush();
6589 str.close();
6590
6591 // New settings successfully written, old ones are no longer
6592 // needed.
6593 mBackupSettingsFilename.delete();
6594 FileUtils.setPermissions(mSettingsFilename.toString(),
6595 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6596 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6597 |FileUtils.S_IROTH,
6598 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006599 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600
6601 } catch(XmlPullParserException e) {
6602 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 -08006603 } catch(java.io.IOException e) {
6604 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 -08006605 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006606 // Clean up partially written file
6607 if (mSettingsFilename.exists()) {
6608 if (!mSettingsFilename.delete()) {
6609 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
6610 }
6611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 //Debug.stopMethodTracing();
6613 }
6614
6615 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
6616 throws java.io.IOException {
6617 serializer.startTag(null, "updated-package");
6618 serializer.attribute(null, "name", pkg.name);
6619 serializer.attribute(null, "codePath", pkg.codePathString);
6620 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006621 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006622 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6623 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6624 }
6625 if (pkg.sharedUser == null) {
6626 serializer.attribute(null, "userId",
6627 Integer.toString(pkg.userId));
6628 } else {
6629 serializer.attribute(null, "sharedUserId",
6630 Integer.toString(pkg.userId));
6631 }
6632 serializer.startTag(null, "perms");
6633 if (pkg.sharedUser == null) {
6634 // If this is a shared user, the permissions will
6635 // be written there. We still need to write an
6636 // empty permissions list so permissionsFixed will
6637 // be set.
6638 for (final String name : pkg.grantedPermissions) {
6639 BasePermission bp = mPermissions.get(name);
6640 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6641 // We only need to write signature or system permissions but this wont
6642 // match the semantics of grantedPermissions. So write all permissions.
6643 serializer.startTag(null, "item");
6644 serializer.attribute(null, "name", name);
6645 serializer.endTag(null, "item");
6646 }
6647 }
6648 }
6649 serializer.endTag(null, "perms");
6650 serializer.endTag(null, "updated-package");
6651 }
6652
6653 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
6654 throws java.io.IOException {
6655 serializer.startTag(null, "package");
6656 serializer.attribute(null, "name", pkg.name);
6657 serializer.attribute(null, "codePath", pkg.codePathString);
6658 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6659 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6660 }
6661 serializer.attribute(null, "system",
6662 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6663 ? "true" : "false");
6664 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006665 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 if (pkg.sharedUser == null) {
6667 serializer.attribute(null, "userId",
6668 Integer.toString(pkg.userId));
6669 } else {
6670 serializer.attribute(null, "sharedUserId",
6671 Integer.toString(pkg.userId));
6672 }
6673 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6674 serializer.attribute(null, "enabled",
6675 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6676 ? "true" : "false");
6677 }
6678 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6679 serializer.attribute(null, "installStatus", "false");
6680 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006681 if (pkg.installerPackageName != null) {
6682 serializer.attribute(null, "installer", pkg.installerPackageName);
6683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006684 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6685 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6686 serializer.startTag(null, "perms");
6687 if (pkg.sharedUser == null) {
6688 // If this is a shared user, the permissions will
6689 // be written there. We still need to write an
6690 // empty permissions list so permissionsFixed will
6691 // be set.
6692 for (final String name : pkg.grantedPermissions) {
6693 serializer.startTag(null, "item");
6694 serializer.attribute(null, "name", name);
6695 serializer.endTag(null, "item");
6696 }
6697 }
6698 serializer.endTag(null, "perms");
6699 }
6700 if (pkg.disabledComponents.size() > 0) {
6701 serializer.startTag(null, "disabled-components");
6702 for (final String name : pkg.disabledComponents) {
6703 serializer.startTag(null, "item");
6704 serializer.attribute(null, "name", name);
6705 serializer.endTag(null, "item");
6706 }
6707 serializer.endTag(null, "disabled-components");
6708 }
6709 if (pkg.enabledComponents.size() > 0) {
6710 serializer.startTag(null, "enabled-components");
6711 for (final String name : pkg.enabledComponents) {
6712 serializer.startTag(null, "item");
6713 serializer.attribute(null, "name", name);
6714 serializer.endTag(null, "item");
6715 }
6716 serializer.endTag(null, "enabled-components");
6717 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 serializer.endTag(null, "package");
6720 }
6721
6722 void writePermission(XmlSerializer serializer, BasePermission bp)
6723 throws XmlPullParserException, java.io.IOException {
6724 if (bp.type != BasePermission.TYPE_BUILTIN
6725 && bp.sourcePackage != null) {
6726 serializer.startTag(null, "item");
6727 serializer.attribute(null, "name", bp.name);
6728 serializer.attribute(null, "package", bp.sourcePackage);
6729 if (DEBUG_SETTINGS) Log.v(TAG,
6730 "Writing perm: name=" + bp.name + " type=" + bp.type);
6731 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6732 PermissionInfo pi = bp.perm != null ? bp.perm.info
6733 : bp.pendingInfo;
6734 if (pi != null) {
6735 serializer.attribute(null, "type", "dynamic");
6736 if (pi.icon != 0) {
6737 serializer.attribute(null, "icon",
6738 Integer.toString(pi.icon));
6739 }
6740 if (pi.nonLocalizedLabel != null) {
6741 serializer.attribute(null, "label",
6742 pi.nonLocalizedLabel.toString());
6743 }
6744 if (pi.protectionLevel !=
6745 PermissionInfo.PROTECTION_NORMAL) {
6746 serializer.attribute(null, "protection",
6747 Integer.toString(pi.protectionLevel));
6748 }
6749 }
6750 }
6751 serializer.endTag(null, "item");
6752 }
6753 }
6754
6755 String getReadMessagesLP() {
6756 return mReadMessages.toString();
6757 }
6758
Dianne Hackborne6620b22010-01-22 14:46:21 -08006759 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6761 Iterator<String> its = kList.iterator();
Dianne Hackborne6620b22010-01-22 14:46:21 -08006762 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 while(its.hasNext()) {
6764 String key = its.next();
6765 PackageSetting ps = mPackages.get(key);
6766 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Dianne Hackborne6620b22010-01-22 14:46:21 -08006767 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 }
6769 }
6770 return ret;
6771 }
6772
6773 boolean readLP() {
6774 FileInputStream str = null;
6775 if (mBackupSettingsFilename.exists()) {
6776 try {
6777 str = new FileInputStream(mBackupSettingsFilename);
6778 mReadMessages.append("Reading from backup settings file\n");
6779 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006780 if (mSettingsFilename.exists()) {
6781 // If both the backup and settings file exist, we
6782 // ignore the settings since it might have been
6783 // corrupted.
6784 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
6785 mSettingsFilename.delete();
6786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 } catch (java.io.IOException e) {
6788 // We'll try for the normal settings file.
6789 }
6790 }
6791
6792 mPastSignatures.clear();
6793
6794 try {
6795 if (str == null) {
6796 if (!mSettingsFilename.exists()) {
6797 mReadMessages.append("No settings file found\n");
6798 Log.i(TAG, "No current settings file!");
6799 return false;
6800 }
6801 str = new FileInputStream(mSettingsFilename);
6802 }
6803 XmlPullParser parser = Xml.newPullParser();
6804 parser.setInput(str, null);
6805
6806 int type;
6807 while ((type=parser.next()) != XmlPullParser.START_TAG
6808 && type != XmlPullParser.END_DOCUMENT) {
6809 ;
6810 }
6811
6812 if (type != XmlPullParser.START_TAG) {
6813 mReadMessages.append("No start tag found in settings file\n");
6814 Log.e(TAG, "No start tag found in package manager settings");
6815 return false;
6816 }
6817
6818 int outerDepth = parser.getDepth();
6819 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6820 && (type != XmlPullParser.END_TAG
6821 || parser.getDepth() > outerDepth)) {
6822 if (type == XmlPullParser.END_TAG
6823 || type == XmlPullParser.TEXT) {
6824 continue;
6825 }
6826
6827 String tagName = parser.getName();
6828 if (tagName.equals("package")) {
6829 readPackageLP(parser);
6830 } else if (tagName.equals("permissions")) {
6831 readPermissionsLP(mPermissions, parser);
6832 } else if (tagName.equals("permission-trees")) {
6833 readPermissionsLP(mPermissionTrees, parser);
6834 } else if (tagName.equals("shared-user")) {
6835 readSharedUserLP(parser);
6836 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006837 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 } else if (tagName.equals("preferred-activities")) {
6839 readPreferredActivitiesLP(parser);
6840 } else if(tagName.equals("updated-package")) {
6841 readDisabledSysPackageLP(parser);
6842 } else {
6843 Log.w(TAG, "Unknown element under <packages>: "
6844 + parser.getName());
6845 XmlUtils.skipCurrentTag(parser);
6846 }
6847 }
6848
6849 str.close();
6850
6851 } catch(XmlPullParserException e) {
6852 mReadMessages.append("Error reading: " + e.toString());
6853 Log.e(TAG, "Error reading package manager settings", e);
6854
6855 } catch(java.io.IOException e) {
6856 mReadMessages.append("Error reading: " + e.toString());
6857 Log.e(TAG, "Error reading package manager settings", e);
6858
6859 }
6860
6861 int N = mPendingPackages.size();
6862 for (int i=0; i<N; i++) {
6863 final PendingPackage pp = mPendingPackages.get(i);
6864 Object idObj = getUserIdLP(pp.sharedId);
6865 if (idObj != null && idObj instanceof SharedUserSetting) {
6866 PackageSetting p = getPackageLP(pp.name,
6867 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006868 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006869 if (p == null) {
6870 Log.w(TAG, "Unable to create application package for "
6871 + pp.name);
6872 continue;
6873 }
6874 p.copyFrom(pp);
6875 } else if (idObj != null) {
6876 String msg = "Bad package setting: package " + pp.name
6877 + " has shared uid " + pp.sharedId
6878 + " that is not a shared uid\n";
6879 mReadMessages.append(msg);
6880 Log.e(TAG, msg);
6881 } else {
6882 String msg = "Bad package setting: package " + pp.name
6883 + " has shared uid " + pp.sharedId
6884 + " that is not defined\n";
6885 mReadMessages.append(msg);
6886 Log.e(TAG, msg);
6887 }
6888 }
6889 mPendingPackages.clear();
6890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006891 mReadMessages.append("Read completed successfully: "
6892 + mPackages.size() + " packages, "
6893 + mSharedUsers.size() + " shared uids\n");
6894
6895 return true;
6896 }
6897
6898 private int readInt(XmlPullParser parser, String ns, String name,
6899 int defValue) {
6900 String v = parser.getAttributeValue(ns, name);
6901 try {
6902 if (v == null) {
6903 return defValue;
6904 }
6905 return Integer.parseInt(v);
6906 } catch (NumberFormatException e) {
6907 reportSettingsProblem(Log.WARN,
6908 "Error in package manager settings: attribute " +
6909 name + " has bad integer value " + v + " at "
6910 + parser.getPositionDescription());
6911 }
6912 return defValue;
6913 }
6914
6915 private void readPermissionsLP(HashMap<String, BasePermission> out,
6916 XmlPullParser parser)
6917 throws IOException, XmlPullParserException {
6918 int outerDepth = parser.getDepth();
6919 int type;
6920 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6921 && (type != XmlPullParser.END_TAG
6922 || parser.getDepth() > outerDepth)) {
6923 if (type == XmlPullParser.END_TAG
6924 || type == XmlPullParser.TEXT) {
6925 continue;
6926 }
6927
6928 String tagName = parser.getName();
6929 if (tagName.equals("item")) {
6930 String name = parser.getAttributeValue(null, "name");
6931 String sourcePackage = parser.getAttributeValue(null, "package");
6932 String ptype = parser.getAttributeValue(null, "type");
6933 if (name != null && sourcePackage != null) {
6934 boolean dynamic = "dynamic".equals(ptype);
6935 BasePermission bp = new BasePermission(name, sourcePackage,
6936 dynamic
6937 ? BasePermission.TYPE_DYNAMIC
6938 : BasePermission.TYPE_NORMAL);
6939 if (dynamic) {
6940 PermissionInfo pi = new PermissionInfo();
6941 pi.packageName = sourcePackage.intern();
6942 pi.name = name.intern();
6943 pi.icon = readInt(parser, null, "icon", 0);
6944 pi.nonLocalizedLabel = parser.getAttributeValue(
6945 null, "label");
6946 pi.protectionLevel = readInt(parser, null, "protection",
6947 PermissionInfo.PROTECTION_NORMAL);
6948 bp.pendingInfo = pi;
6949 }
6950 out.put(bp.name, bp);
6951 } else {
6952 reportSettingsProblem(Log.WARN,
6953 "Error in package manager settings: permissions has"
6954 + " no name at " + parser.getPositionDescription());
6955 }
6956 } else {
6957 reportSettingsProblem(Log.WARN,
6958 "Unknown element reading permissions: "
6959 + parser.getName() + " at "
6960 + parser.getPositionDescription());
6961 }
6962 XmlUtils.skipCurrentTag(parser);
6963 }
6964 }
6965
6966 private void readDisabledSysPackageLP(XmlPullParser parser)
6967 throws XmlPullParserException, IOException {
6968 String name = parser.getAttributeValue(null, "name");
6969 String codePathStr = parser.getAttributeValue(null, "codePath");
6970 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6971 if(resourcePathStr == null) {
6972 resourcePathStr = codePathStr;
6973 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006974 String version = parser.getAttributeValue(null, "version");
6975 int versionCode = 0;
6976 if (version != null) {
6977 try {
6978 versionCode = Integer.parseInt(version);
6979 } catch (NumberFormatException e) {
6980 }
6981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006982
6983 int pkgFlags = 0;
6984 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6985 PackageSetting ps = new PackageSetting(name,
6986 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006987 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 String timeStampStr = parser.getAttributeValue(null, "ts");
6989 if (timeStampStr != null) {
6990 try {
6991 long timeStamp = Long.parseLong(timeStampStr);
6992 ps.setTimeStamp(timeStamp, timeStampStr);
6993 } catch (NumberFormatException e) {
6994 }
6995 }
6996 String idStr = parser.getAttributeValue(null, "userId");
6997 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
6998 if(ps.userId <= 0) {
6999 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7000 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7001 }
7002 int outerDepth = parser.getDepth();
7003 int type;
7004 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7005 && (type != XmlPullParser.END_TAG
7006 || parser.getDepth() > outerDepth)) {
7007 if (type == XmlPullParser.END_TAG
7008 || type == XmlPullParser.TEXT) {
7009 continue;
7010 }
7011
7012 String tagName = parser.getName();
7013 if (tagName.equals("perms")) {
7014 readGrantedPermissionsLP(parser,
7015 ps.grantedPermissions);
7016 } else {
7017 reportSettingsProblem(Log.WARN,
7018 "Unknown element under <updated-package>: "
7019 + parser.getName());
7020 XmlUtils.skipCurrentTag(parser);
7021 }
7022 }
7023 mDisabledSysPackages.put(name, ps);
7024 }
7025
7026 private void readPackageLP(XmlPullParser parser)
7027 throws XmlPullParserException, IOException {
7028 String name = null;
7029 String idStr = null;
7030 String sharedIdStr = null;
7031 String codePathStr = null;
7032 String resourcePathStr = null;
7033 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007034 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 int pkgFlags = 0;
7036 String timeStampStr;
7037 long timeStamp = 0;
7038 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007039 String version = null;
7040 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 try {
7042 name = parser.getAttributeValue(null, "name");
7043 idStr = parser.getAttributeValue(null, "userId");
7044 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7045 codePathStr = parser.getAttributeValue(null, "codePath");
7046 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007047 version = parser.getAttributeValue(null, "version");
7048 if (version != null) {
7049 try {
7050 versionCode = Integer.parseInt(version);
7051 } catch (NumberFormatException e) {
7052 }
7053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazski65e13172009-04-28 15:26:38 +02007055 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 if (systemStr != null) {
7057 if ("true".equals(systemStr)) {
7058 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7059 }
7060 } else {
7061 // Old settings that don't specify system... just treat
7062 // them as system, good enough.
7063 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7064 }
7065 timeStampStr = parser.getAttributeValue(null, "ts");
7066 if (timeStampStr != null) {
7067 try {
7068 timeStamp = Long.parseLong(timeStampStr);
7069 } catch (NumberFormatException e) {
7070 }
7071 }
7072 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7073 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7074 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7075 if (resourcePathStr == null) {
7076 resourcePathStr = codePathStr;
7077 }
7078 if (name == null) {
7079 reportSettingsProblem(Log.WARN,
7080 "Error in package manager settings: <package> has no name at "
7081 + parser.getPositionDescription());
7082 } else if (codePathStr == null) {
7083 reportSettingsProblem(Log.WARN,
7084 "Error in package manager settings: <package> has no codePath at "
7085 + parser.getPositionDescription());
7086 } else if (userId > 0) {
7087 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007088 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007089 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7090 + ": userId=" + userId + " pkg=" + packageSetting);
7091 if (packageSetting == null) {
7092 reportSettingsProblem(Log.ERROR,
7093 "Failure adding uid " + userId
7094 + " while parsing settings at "
7095 + parser.getPositionDescription());
7096 } else {
7097 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7098 }
7099 } else if (sharedIdStr != null) {
7100 userId = sharedIdStr != null
7101 ? Integer.parseInt(sharedIdStr) : 0;
7102 if (userId > 0) {
7103 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007104 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7106 mPendingPackages.add((PendingPackage) packageSetting);
7107 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7108 + ": sharedUserId=" + userId + " pkg="
7109 + packageSetting);
7110 } else {
7111 reportSettingsProblem(Log.WARN,
7112 "Error in package manager settings: package "
7113 + name + " has bad sharedId " + sharedIdStr
7114 + " at " + parser.getPositionDescription());
7115 }
7116 } else {
7117 reportSettingsProblem(Log.WARN,
7118 "Error in package manager settings: package "
7119 + name + " has bad userId " + idStr + " at "
7120 + parser.getPositionDescription());
7121 }
7122 } catch (NumberFormatException e) {
7123 reportSettingsProblem(Log.WARN,
7124 "Error in package manager settings: package "
7125 + name + " has bad userId " + idStr + " at "
7126 + parser.getPositionDescription());
7127 }
7128 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02007129 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007130 final String enabledStr = parser.getAttributeValue(null, "enabled");
7131 if (enabledStr != null) {
7132 if (enabledStr.equalsIgnoreCase("true")) {
7133 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7134 } else if (enabledStr.equalsIgnoreCase("false")) {
7135 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7136 } else if (enabledStr.equalsIgnoreCase("default")) {
7137 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7138 } else {
7139 reportSettingsProblem(Log.WARN,
7140 "Error in package manager settings: package "
7141 + name + " has bad enabled value: " + idStr
7142 + " at " + parser.getPositionDescription());
7143 }
7144 } else {
7145 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7146 }
7147 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7148 if (installStatusStr != null) {
7149 if (installStatusStr.equalsIgnoreCase("false")) {
7150 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7151 } else {
7152 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7153 }
7154 }
7155
7156 int outerDepth = parser.getDepth();
7157 int type;
7158 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7159 && (type != XmlPullParser.END_TAG
7160 || parser.getDepth() > outerDepth)) {
7161 if (type == XmlPullParser.END_TAG
7162 || type == XmlPullParser.TEXT) {
7163 continue;
7164 }
7165
7166 String tagName = parser.getName();
7167 if (tagName.equals("disabled-components")) {
7168 readDisabledComponentsLP(packageSetting, parser);
7169 } else if (tagName.equals("enabled-components")) {
7170 readEnabledComponentsLP(packageSetting, parser);
7171 } else if (tagName.equals("sigs")) {
7172 packageSetting.signatures.readXml(parser, mPastSignatures);
7173 } else if (tagName.equals("perms")) {
7174 readGrantedPermissionsLP(parser,
7175 packageSetting.loadedPermissions);
7176 packageSetting.permissionsFixed = true;
7177 } else {
7178 reportSettingsProblem(Log.WARN,
7179 "Unknown element under <package>: "
7180 + parser.getName());
7181 XmlUtils.skipCurrentTag(parser);
7182 }
7183 }
7184 } else {
7185 XmlUtils.skipCurrentTag(parser);
7186 }
7187 }
7188
7189 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7190 XmlPullParser parser)
7191 throws IOException, XmlPullParserException {
7192 int outerDepth = parser.getDepth();
7193 int type;
7194 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7195 && (type != XmlPullParser.END_TAG
7196 || parser.getDepth() > outerDepth)) {
7197 if (type == XmlPullParser.END_TAG
7198 || type == XmlPullParser.TEXT) {
7199 continue;
7200 }
7201
7202 String tagName = parser.getName();
7203 if (tagName.equals("item")) {
7204 String name = parser.getAttributeValue(null, "name");
7205 if (name != null) {
7206 packageSetting.disabledComponents.add(name.intern());
7207 } else {
7208 reportSettingsProblem(Log.WARN,
7209 "Error in package manager settings: <disabled-components> has"
7210 + " no name at " + parser.getPositionDescription());
7211 }
7212 } else {
7213 reportSettingsProblem(Log.WARN,
7214 "Unknown element under <disabled-components>: "
7215 + parser.getName());
7216 }
7217 XmlUtils.skipCurrentTag(parser);
7218 }
7219 }
7220
7221 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
7222 XmlPullParser parser)
7223 throws IOException, XmlPullParserException {
7224 int outerDepth = parser.getDepth();
7225 int type;
7226 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7227 && (type != XmlPullParser.END_TAG
7228 || parser.getDepth() > outerDepth)) {
7229 if (type == XmlPullParser.END_TAG
7230 || type == XmlPullParser.TEXT) {
7231 continue;
7232 }
7233
7234 String tagName = parser.getName();
7235 if (tagName.equals("item")) {
7236 String name = parser.getAttributeValue(null, "name");
7237 if (name != null) {
7238 packageSetting.enabledComponents.add(name.intern());
7239 } else {
7240 reportSettingsProblem(Log.WARN,
7241 "Error in package manager settings: <enabled-components> has"
7242 + " no name at " + parser.getPositionDescription());
7243 }
7244 } else {
7245 reportSettingsProblem(Log.WARN,
7246 "Unknown element under <enabled-components>: "
7247 + parser.getName());
7248 }
7249 XmlUtils.skipCurrentTag(parser);
7250 }
7251 }
7252
7253 private void readSharedUserLP(XmlPullParser parser)
7254 throws XmlPullParserException, IOException {
7255 String name = null;
7256 String idStr = null;
7257 int pkgFlags = 0;
7258 SharedUserSetting su = null;
7259 try {
7260 name = parser.getAttributeValue(null, "name");
7261 idStr = parser.getAttributeValue(null, "userId");
7262 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7263 if ("true".equals(parser.getAttributeValue(null, "system"))) {
7264 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7265 }
7266 if (name == null) {
7267 reportSettingsProblem(Log.WARN,
7268 "Error in package manager settings: <shared-user> has no name at "
7269 + parser.getPositionDescription());
7270 } else if (userId == 0) {
7271 reportSettingsProblem(Log.WARN,
7272 "Error in package manager settings: shared-user "
7273 + name + " has bad userId " + idStr + " at "
7274 + parser.getPositionDescription());
7275 } else {
7276 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
7277 reportSettingsProblem(Log.ERROR,
7278 "Occurred while parsing settings at "
7279 + parser.getPositionDescription());
7280 }
7281 }
7282 } catch (NumberFormatException e) {
7283 reportSettingsProblem(Log.WARN,
7284 "Error in package manager settings: package "
7285 + name + " has bad userId " + idStr + " at "
7286 + parser.getPositionDescription());
7287 };
7288
7289 if (su != null) {
7290 int outerDepth = parser.getDepth();
7291 int type;
7292 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7293 && (type != XmlPullParser.END_TAG
7294 || parser.getDepth() > outerDepth)) {
7295 if (type == XmlPullParser.END_TAG
7296 || type == XmlPullParser.TEXT) {
7297 continue;
7298 }
7299
7300 String tagName = parser.getName();
7301 if (tagName.equals("sigs")) {
7302 su.signatures.readXml(parser, mPastSignatures);
7303 } else if (tagName.equals("perms")) {
7304 readGrantedPermissionsLP(parser, su.loadedPermissions);
7305 } else {
7306 reportSettingsProblem(Log.WARN,
7307 "Unknown element under <shared-user>: "
7308 + parser.getName());
7309 XmlUtils.skipCurrentTag(parser);
7310 }
7311 }
7312
7313 } else {
7314 XmlUtils.skipCurrentTag(parser);
7315 }
7316 }
7317
7318 private void readGrantedPermissionsLP(XmlPullParser parser,
7319 HashSet<String> outPerms) throws IOException, XmlPullParserException {
7320 int outerDepth = parser.getDepth();
7321 int type;
7322 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7323 && (type != XmlPullParser.END_TAG
7324 || parser.getDepth() > outerDepth)) {
7325 if (type == XmlPullParser.END_TAG
7326 || type == XmlPullParser.TEXT) {
7327 continue;
7328 }
7329
7330 String tagName = parser.getName();
7331 if (tagName.equals("item")) {
7332 String name = parser.getAttributeValue(null, "name");
7333 if (name != null) {
7334 outPerms.add(name.intern());
7335 } else {
7336 reportSettingsProblem(Log.WARN,
7337 "Error in package manager settings: <perms> has"
7338 + " no name at " + parser.getPositionDescription());
7339 }
7340 } else {
7341 reportSettingsProblem(Log.WARN,
7342 "Unknown element under <perms>: "
7343 + parser.getName());
7344 }
7345 XmlUtils.skipCurrentTag(parser);
7346 }
7347 }
7348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007349 private void readPreferredActivitiesLP(XmlPullParser parser)
7350 throws XmlPullParserException, IOException {
7351 int outerDepth = parser.getDepth();
7352 int type;
7353 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7354 && (type != XmlPullParser.END_TAG
7355 || parser.getDepth() > outerDepth)) {
7356 if (type == XmlPullParser.END_TAG
7357 || type == XmlPullParser.TEXT) {
7358 continue;
7359 }
7360
7361 String tagName = parser.getName();
7362 if (tagName.equals("item")) {
7363 PreferredActivity pa = new PreferredActivity(parser);
7364 if (pa.mParseError == null) {
7365 mPreferredActivities.addFilter(pa);
7366 } else {
7367 reportSettingsProblem(Log.WARN,
7368 "Error in package manager settings: <preferred-activity> "
7369 + pa.mParseError + " at "
7370 + parser.getPositionDescription());
7371 }
7372 } else {
7373 reportSettingsProblem(Log.WARN,
7374 "Unknown element under <preferred-activities>: "
7375 + parser.getName());
7376 XmlUtils.skipCurrentTag(parser);
7377 }
7378 }
7379 }
7380
7381 // Returns -1 if we could not find an available UserId to assign
7382 private int newUserIdLP(Object obj) {
7383 // Let's be stupidly inefficient for now...
7384 final int N = mUserIds.size();
7385 for (int i=0; i<N; i++) {
7386 if (mUserIds.get(i) == null) {
7387 mUserIds.set(i, obj);
7388 return FIRST_APPLICATION_UID + i;
7389 }
7390 }
7391
7392 // None left?
7393 if (N >= MAX_APPLICATION_UIDS) {
7394 return -1;
7395 }
7396
7397 mUserIds.add(obj);
7398 return FIRST_APPLICATION_UID + N;
7399 }
7400
7401 public PackageSetting getDisabledSystemPkg(String name) {
7402 synchronized(mPackages) {
7403 PackageSetting ps = mDisabledSysPackages.get(name);
7404 return ps;
7405 }
7406 }
7407
7408 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7409 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7410 if (Config.LOGV) {
7411 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7412 + " componentName = " + componentInfo.name);
7413 Log.v(TAG, "enabledComponents: "
7414 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7415 Log.v(TAG, "disabledComponents: "
7416 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7417 }
7418 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7419 || ((componentInfo.enabled
7420 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7421 || (componentInfo.applicationInfo.enabled
7422 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7423 && !packageSettings.disabledComponents.contains(componentInfo.name))
7424 || packageSettings.enabledComponents.contains(componentInfo.name));
7425 }
7426 }
7427}