blob: 5ed2d35678860ea20e8dc9bc398830696c45dc94 [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
576 ArrayList<String> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
577 //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
631 void cleanupInstallFailedPackage(String packageName) {
632 if (mInstaller != null) {
633 int retCode = mInstaller.remove(packageName);
634 if (retCode < 0) {
635 Log.w(TAG, "Couldn't remove app data directory for package: "
636 + packageName + ", retcode=" + retCode);
637 }
638 } else {
639 //for emulator
640 PackageParser.Package pkg = mPackages.get(packageName);
641 File dataDir = new File(pkg.applicationInfo.dataDir);
642 dataDir.delete();
643 }
644 mSettings.removePackageLP(packageName);
645 }
646
647 void readPermissions() {
648 // Read permissions from .../etc/permission directory.
649 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
650 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
651 Log.w(TAG, "No directory " + libraryDir + ", skipping");
652 return;
653 }
654 if (!libraryDir.canRead()) {
655 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
656 return;
657 }
658
659 // Iterate over the files in the directory and scan .xml files
660 for (File f : libraryDir.listFiles()) {
661 // We'll read platform.xml last
662 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
663 continue;
664 }
665
666 if (!f.getPath().endsWith(".xml")) {
667 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
668 continue;
669 }
670 if (!f.canRead()) {
671 Log.w(TAG, "Permissions library file " + f + " cannot be read");
672 continue;
673 }
674
675 readPermissionsFromXml(f);
676 }
677
678 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
679 final File permFile = new File(Environment.getRootDirectory(),
680 "etc/permissions/platform.xml");
681 readPermissionsFromXml(permFile);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700682
683 StringBuilder sb = new StringBuilder(128);
684 sb.append("Libs:");
685 Iterator<String> it = mSharedLibraries.keySet().iterator();
686 while (it.hasNext()) {
687 sb.append(' ');
688 String name = it.next();
689 sb.append(name);
690 sb.append(':');
691 sb.append(mSharedLibraries.get(name));
692 }
693 Log.i(TAG, sb.toString());
694
695 sb.setLength(0);
696 sb.append("Features:");
697 it = mAvailableFeatures.keySet().iterator();
698 while (it.hasNext()) {
699 sb.append(' ');
700 sb.append(it.next());
701 }
702 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
704
705 private void readPermissionsFromXml(File permFile) {
706 FileReader permReader = null;
707 try {
708 permReader = new FileReader(permFile);
709 } catch (FileNotFoundException e) {
710 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
711 return;
712 }
713
714 try {
715 XmlPullParser parser = Xml.newPullParser();
716 parser.setInput(permReader);
717
718 XmlUtils.beginDocument(parser, "permissions");
719
720 while (true) {
721 XmlUtils.nextElement(parser);
722 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
723 break;
724 }
725
726 String name = parser.getName();
727 if ("group".equals(name)) {
728 String gidStr = parser.getAttributeValue(null, "gid");
729 if (gidStr != null) {
730 int gid = Integer.parseInt(gidStr);
731 mGlobalGids = appendInt(mGlobalGids, gid);
732 } else {
733 Log.w(TAG, "<group> without gid at "
734 + parser.getPositionDescription());
735 }
736
737 XmlUtils.skipCurrentTag(parser);
738 continue;
739 } else if ("permission".equals(name)) {
740 String perm = parser.getAttributeValue(null, "name");
741 if (perm == null) {
742 Log.w(TAG, "<permission> without name at "
743 + parser.getPositionDescription());
744 XmlUtils.skipCurrentTag(parser);
745 continue;
746 }
747 perm = perm.intern();
748 readPermission(parser, perm);
749
750 } else if ("assign-permission".equals(name)) {
751 String perm = parser.getAttributeValue(null, "name");
752 if (perm == null) {
753 Log.w(TAG, "<assign-permission> without name at "
754 + parser.getPositionDescription());
755 XmlUtils.skipCurrentTag(parser);
756 continue;
757 }
758 String uidStr = parser.getAttributeValue(null, "uid");
759 if (uidStr == null) {
760 Log.w(TAG, "<assign-permission> without uid at "
761 + parser.getPositionDescription());
762 XmlUtils.skipCurrentTag(parser);
763 continue;
764 }
765 int uid = Process.getUidForName(uidStr);
766 if (uid < 0) {
767 Log.w(TAG, "<assign-permission> with unknown uid \""
768 + uidStr + "\" at "
769 + parser.getPositionDescription());
770 XmlUtils.skipCurrentTag(parser);
771 continue;
772 }
773 perm = perm.intern();
774 HashSet<String> perms = mSystemPermissions.get(uid);
775 if (perms == null) {
776 perms = new HashSet<String>();
777 mSystemPermissions.put(uid, perms);
778 }
779 perms.add(perm);
780 XmlUtils.skipCurrentTag(parser);
781
782 } else if ("library".equals(name)) {
783 String lname = parser.getAttributeValue(null, "name");
784 String lfile = parser.getAttributeValue(null, "file");
785 if (lname == null) {
786 Log.w(TAG, "<library> without name at "
787 + parser.getPositionDescription());
788 } else if (lfile == null) {
789 Log.w(TAG, "<library> without file at "
790 + parser.getPositionDescription());
791 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700792 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700793 mSharedLibraries.put(lname, lfile);
794 }
795 XmlUtils.skipCurrentTag(parser);
796 continue;
797
798 } else if ("feature".equals(name)) {
799 String fname = parser.getAttributeValue(null, "name");
800 if (fname == null) {
801 Log.w(TAG, "<feature> without name at "
802 + parser.getPositionDescription());
803 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700804 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700805 FeatureInfo fi = new FeatureInfo();
806 fi.name = fname;
807 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 }
809 XmlUtils.skipCurrentTag(parser);
810 continue;
811
812 } else {
813 XmlUtils.skipCurrentTag(parser);
814 continue;
815 }
816
817 }
818 } catch (XmlPullParserException e) {
819 Log.w(TAG, "Got execption parsing permissions.", e);
820 } catch (IOException e) {
821 Log.w(TAG, "Got execption parsing permissions.", e);
822 }
823 }
824
825 void readPermission(XmlPullParser parser, String name)
826 throws IOException, XmlPullParserException {
827
828 name = name.intern();
829
830 BasePermission bp = mSettings.mPermissions.get(name);
831 if (bp == null) {
832 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
833 mSettings.mPermissions.put(name, bp);
834 }
835 int outerDepth = parser.getDepth();
836 int type;
837 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
838 && (type != XmlPullParser.END_TAG
839 || parser.getDepth() > outerDepth)) {
840 if (type == XmlPullParser.END_TAG
841 || type == XmlPullParser.TEXT) {
842 continue;
843 }
844
845 String tagName = parser.getName();
846 if ("group".equals(tagName)) {
847 String gidStr = parser.getAttributeValue(null, "gid");
848 if (gidStr != null) {
849 int gid = Process.getGidForName(gidStr);
850 bp.gids = appendInt(bp.gids, gid);
851 } else {
852 Log.w(TAG, "<group> without gid at "
853 + parser.getPositionDescription());
854 }
855 }
856 XmlUtils.skipCurrentTag(parser);
857 }
858 }
859
860 static int[] appendInt(int[] cur, int val) {
861 if (cur == null) {
862 return new int[] { val };
863 }
864 final int N = cur.length;
865 for (int i=0; i<N; i++) {
866 if (cur[i] == val) {
867 return cur;
868 }
869 }
870 int[] ret = new int[N+1];
871 System.arraycopy(cur, 0, ret, 0, N);
872 ret[N] = val;
873 return ret;
874 }
875
876 static int[] appendInts(int[] cur, int[] add) {
877 if (add == null) return cur;
878 if (cur == null) return add;
879 final int N = add.length;
880 for (int i=0; i<N; i++) {
881 cur = appendInt(cur, add[i]);
882 }
883 return cur;
884 }
885
886 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -0700887 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
888 // The package has been uninstalled but has retained data and resources.
889 return PackageParser.generatePackageInfo(p, null, flags);
890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 final PackageSetting ps = (PackageSetting)p.mExtras;
892 if (ps == null) {
893 return null;
894 }
895 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
896 return PackageParser.generatePackageInfo(p, gp.gids, flags);
897 }
898
899 public PackageInfo getPackageInfo(String packageName, int flags) {
900 synchronized (mPackages) {
901 PackageParser.Package p = mPackages.get(packageName);
902 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700903 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 + ": " + p);
905 if (p != null) {
906 return generatePackageInfo(p, flags);
907 }
908 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
909 return generatePackageInfoFromSettingsLP(packageName, flags);
910 }
911 }
912 return null;
913 }
914
915 public int getPackageUid(String packageName) {
916 synchronized (mPackages) {
917 PackageParser.Package p = mPackages.get(packageName);
918 if(p != null) {
919 return p.applicationInfo.uid;
920 }
921 PackageSetting ps = mSettings.mPackages.get(packageName);
922 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
923 return -1;
924 }
925 p = ps.pkg;
926 return p != null ? p.applicationInfo.uid : -1;
927 }
928 }
929
930 public int[] getPackageGids(String packageName) {
931 synchronized (mPackages) {
932 PackageParser.Package p = mPackages.get(packageName);
933 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700934 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 + ": " + p);
936 if (p != null) {
937 final PackageSetting ps = (PackageSetting)p.mExtras;
938 final SharedUserSetting suid = ps.sharedUser;
939 return suid != null ? suid.gids : ps.gids;
940 }
941 }
942 // stupid thing to indicate an error.
943 return new int[0];
944 }
945
946 public PermissionInfo getPermissionInfo(String name, int flags) {
947 synchronized (mPackages) {
948 final BasePermission p = mSettings.mPermissions.get(name);
949 if (p != null && p.perm != null) {
950 return PackageParser.generatePermissionInfo(p.perm, flags);
951 }
952 return null;
953 }
954 }
955
956 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
957 synchronized (mPackages) {
958 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
959 for (BasePermission p : mSettings.mPermissions.values()) {
960 if (group == null) {
961 if (p.perm.info.group == null) {
962 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
963 }
964 } else {
965 if (group.equals(p.perm.info.group)) {
966 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
967 }
968 }
969 }
970
971 if (out.size() > 0) {
972 return out;
973 }
974 return mPermissionGroups.containsKey(group) ? out : null;
975 }
976 }
977
978 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
979 synchronized (mPackages) {
980 return PackageParser.generatePermissionGroupInfo(
981 mPermissionGroups.get(name), flags);
982 }
983 }
984
985 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
986 synchronized (mPackages) {
987 final int N = mPermissionGroups.size();
988 ArrayList<PermissionGroupInfo> out
989 = new ArrayList<PermissionGroupInfo>(N);
990 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
991 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
992 }
993 return out;
994 }
995 }
996
997 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
998 PackageSetting ps = mSettings.mPackages.get(packageName);
999 if(ps != null) {
1000 if(ps.pkg == null) {
1001 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1002 if(pInfo != null) {
1003 return pInfo.applicationInfo;
1004 }
1005 return null;
1006 }
1007 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1008 }
1009 return null;
1010 }
1011
1012 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1013 PackageSetting ps = mSettings.mPackages.get(packageName);
1014 if(ps != null) {
1015 if(ps.pkg == null) {
1016 ps.pkg = new PackageParser.Package(packageName);
1017 ps.pkg.applicationInfo.packageName = packageName;
1018 }
1019 return generatePackageInfo(ps.pkg, flags);
1020 }
1021 return null;
1022 }
1023
1024 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1025 synchronized (mPackages) {
1026 PackageParser.Package p = mPackages.get(packageName);
1027 if (Config.LOGV) Log.v(
1028 TAG, "getApplicationInfo " + packageName
1029 + ": " + p);
1030 if (p != null) {
1031 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001032 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 }
1034 if ("android".equals(packageName)||"system".equals(packageName)) {
1035 return mAndroidApplication;
1036 }
1037 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1038 return generateApplicationInfoFromSettingsLP(packageName, flags);
1039 }
1040 }
1041 return null;
1042 }
1043
1044
1045 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1046 mContext.enforceCallingOrSelfPermission(
1047 android.Manifest.permission.CLEAR_APP_CACHE, null);
1048 // Queue up an async operation since clearing cache may take a little while.
1049 mHandler.post(new Runnable() {
1050 public void run() {
1051 mHandler.removeCallbacks(this);
1052 int retCode = -1;
1053 if (mInstaller != null) {
1054 retCode = mInstaller.freeCache(freeStorageSize);
1055 if (retCode < 0) {
1056 Log.w(TAG, "Couldn't clear application caches");
1057 }
1058 } //end if mInstaller
1059 if (observer != null) {
1060 try {
1061 observer.onRemoveCompleted(null, (retCode >= 0));
1062 } catch (RemoteException e) {
1063 Log.w(TAG, "RemoveException when invoking call back");
1064 }
1065 }
1066 }
1067 });
1068 }
1069
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001070 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001071 mContext.enforceCallingOrSelfPermission(
1072 android.Manifest.permission.CLEAR_APP_CACHE, null);
1073 // Queue up an async operation since clearing cache may take a little while.
1074 mHandler.post(new Runnable() {
1075 public void run() {
1076 mHandler.removeCallbacks(this);
1077 int retCode = -1;
1078 if (mInstaller != null) {
1079 retCode = mInstaller.freeCache(freeStorageSize);
1080 if (retCode < 0) {
1081 Log.w(TAG, "Couldn't clear application caches");
1082 }
1083 }
1084 if(pi != null) {
1085 try {
1086 // Callback via pending intent
1087 int code = (retCode >= 0) ? 1 : 0;
1088 pi.sendIntent(null, code, null,
1089 null, null);
1090 } catch (SendIntentException e1) {
1091 Log.i(TAG, "Failed to send pending intent");
1092 }
1093 }
1094 }
1095 });
1096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097
1098 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1099 synchronized (mPackages) {
1100 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001101
1102 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001104 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 }
1106 if (mResolveComponentName.equals(component)) {
1107 return mResolveActivity;
1108 }
1109 }
1110 return null;
1111 }
1112
1113 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1114 synchronized (mPackages) {
1115 PackageParser.Activity a = mReceivers.mActivities.get(component);
1116 if (Config.LOGV) Log.v(
1117 TAG, "getReceiverInfo " + component + ": " + a);
1118 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1119 return PackageParser.generateActivityInfo(a, flags);
1120 }
1121 }
1122 return null;
1123 }
1124
1125 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1126 synchronized (mPackages) {
1127 PackageParser.Service s = mServices.mServices.get(component);
1128 if (Config.LOGV) Log.v(
1129 TAG, "getServiceInfo " + component + ": " + s);
1130 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1131 return PackageParser.generateServiceInfo(s, flags);
1132 }
1133 }
1134 return null;
1135 }
1136
1137 public String[] getSystemSharedLibraryNames() {
1138 Set<String> libSet;
1139 synchronized (mPackages) {
1140 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001141 int size = libSet.size();
1142 if (size > 0) {
1143 String[] libs = new String[size];
1144 libSet.toArray(libs);
1145 return libs;
1146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001148 return null;
1149 }
1150
1151 public FeatureInfo[] getSystemAvailableFeatures() {
1152 Collection<FeatureInfo> featSet;
1153 synchronized (mPackages) {
1154 featSet = mAvailableFeatures.values();
1155 int size = featSet.size();
1156 if (size > 0) {
1157 FeatureInfo[] features = new FeatureInfo[size+1];
1158 featSet.toArray(features);
1159 FeatureInfo fi = new FeatureInfo();
1160 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1161 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1162 features[size] = fi;
1163 return features;
1164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
1166 return null;
1167 }
1168
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001169 public boolean hasSystemFeature(String name) {
1170 synchronized (mPackages) {
1171 return mAvailableFeatures.containsKey(name);
1172 }
1173 }
1174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 public int checkPermission(String permName, String pkgName) {
1176 synchronized (mPackages) {
1177 PackageParser.Package p = mPackages.get(pkgName);
1178 if (p != null && p.mExtras != null) {
1179 PackageSetting ps = (PackageSetting)p.mExtras;
1180 if (ps.sharedUser != null) {
1181 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1182 return PackageManager.PERMISSION_GRANTED;
1183 }
1184 } else if (ps.grantedPermissions.contains(permName)) {
1185 return PackageManager.PERMISSION_GRANTED;
1186 }
1187 }
1188 }
1189 return PackageManager.PERMISSION_DENIED;
1190 }
1191
1192 public int checkUidPermission(String permName, int uid) {
1193 synchronized (mPackages) {
1194 Object obj = mSettings.getUserIdLP(uid);
1195 if (obj != null) {
1196 if (obj instanceof SharedUserSetting) {
1197 SharedUserSetting sus = (SharedUserSetting)obj;
1198 if (sus.grantedPermissions.contains(permName)) {
1199 return PackageManager.PERMISSION_GRANTED;
1200 }
1201 } else if (obj instanceof PackageSetting) {
1202 PackageSetting ps = (PackageSetting)obj;
1203 if (ps.grantedPermissions.contains(permName)) {
1204 return PackageManager.PERMISSION_GRANTED;
1205 }
1206 }
1207 } else {
1208 HashSet<String> perms = mSystemPermissions.get(uid);
1209 if (perms != null && perms.contains(permName)) {
1210 return PackageManager.PERMISSION_GRANTED;
1211 }
1212 }
1213 }
1214 return PackageManager.PERMISSION_DENIED;
1215 }
1216
1217 private BasePermission findPermissionTreeLP(String permName) {
1218 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1219 if (permName.startsWith(bp.name) &&
1220 permName.length() > bp.name.length() &&
1221 permName.charAt(bp.name.length()) == '.') {
1222 return bp;
1223 }
1224 }
1225 return null;
1226 }
1227
1228 private BasePermission checkPermissionTreeLP(String permName) {
1229 if (permName != null) {
1230 BasePermission bp = findPermissionTreeLP(permName);
1231 if (bp != null) {
1232 if (bp.uid == Binder.getCallingUid()) {
1233 return bp;
1234 }
1235 throw new SecurityException("Calling uid "
1236 + Binder.getCallingUid()
1237 + " is not allowed to add to permission tree "
1238 + bp.name + " owned by uid " + bp.uid);
1239 }
1240 }
1241 throw new SecurityException("No permission tree found for " + permName);
1242 }
1243
1244 public boolean addPermission(PermissionInfo info) {
1245 synchronized (mPackages) {
1246 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1247 throw new SecurityException("Label must be specified in permission");
1248 }
1249 BasePermission tree = checkPermissionTreeLP(info.name);
1250 BasePermission bp = mSettings.mPermissions.get(info.name);
1251 boolean added = bp == null;
1252 if (added) {
1253 bp = new BasePermission(info.name, tree.sourcePackage,
1254 BasePermission.TYPE_DYNAMIC);
1255 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1256 throw new SecurityException(
1257 "Not allowed to modify non-dynamic permission "
1258 + info.name);
1259 }
1260 bp.perm = new PackageParser.Permission(tree.perm.owner,
1261 new PermissionInfo(info));
1262 bp.perm.info.packageName = tree.perm.info.packageName;
1263 bp.uid = tree.uid;
1264 if (added) {
1265 mSettings.mPermissions.put(info.name, bp);
1266 }
1267 mSettings.writeLP();
1268 return added;
1269 }
1270 }
1271
1272 public void removePermission(String name) {
1273 synchronized (mPackages) {
1274 checkPermissionTreeLP(name);
1275 BasePermission bp = mSettings.mPermissions.get(name);
1276 if (bp != null) {
1277 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1278 throw new SecurityException(
1279 "Not allowed to modify non-dynamic permission "
1280 + name);
1281 }
1282 mSettings.mPermissions.remove(name);
1283 mSettings.writeLP();
1284 }
1285 }
1286 }
1287
Dianne Hackborn854060af2009-07-09 18:14:31 -07001288 public boolean isProtectedBroadcast(String actionName) {
1289 synchronized (mPackages) {
1290 return mProtectedBroadcasts.contains(actionName);
1291 }
1292 }
1293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 public int checkSignatures(String pkg1, String pkg2) {
1295 synchronized (mPackages) {
1296 PackageParser.Package p1 = mPackages.get(pkg1);
1297 PackageParser.Package p2 = mPackages.get(pkg2);
1298 if (p1 == null || p1.mExtras == null
1299 || p2 == null || p2.mExtras == null) {
1300 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1301 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001302 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
1304 }
1305
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001306 public int checkUidSignatures(int uid1, int uid2) {
1307 synchronized (mPackages) {
1308 Signature[] s1;
1309 Signature[] s2;
1310 Object obj = mSettings.getUserIdLP(uid1);
1311 if (obj != null) {
1312 if (obj instanceof SharedUserSetting) {
1313 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1314 } else if (obj instanceof PackageSetting) {
1315 s1 = ((PackageSetting)obj).signatures.mSignatures;
1316 } else {
1317 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1318 }
1319 } else {
1320 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1321 }
1322 obj = mSettings.getUserIdLP(uid2);
1323 if (obj != null) {
1324 if (obj instanceof SharedUserSetting) {
1325 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1326 } else if (obj instanceof PackageSetting) {
1327 s2 = ((PackageSetting)obj).signatures.mSignatures;
1328 } else {
1329 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1330 }
1331 } else {
1332 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1333 }
1334 return checkSignaturesLP(s1, s2);
1335 }
1336 }
1337
1338 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1339 if (s1 == null) {
1340 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1342 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1343 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001344 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1346 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001347 final int N1 = s1.length;
1348 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 for (int i=0; i<N1; i++) {
1350 boolean match = false;
1351 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001352 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 match = true;
1354 break;
1355 }
1356 }
1357 if (!match) {
1358 return PackageManager.SIGNATURE_NO_MATCH;
1359 }
1360 }
1361 return PackageManager.SIGNATURE_MATCH;
1362 }
1363
1364 public String[] getPackagesForUid(int uid) {
1365 synchronized (mPackages) {
1366 Object obj = mSettings.getUserIdLP(uid);
1367 if (obj instanceof SharedUserSetting) {
1368 SharedUserSetting sus = (SharedUserSetting)obj;
1369 final int N = sus.packages.size();
1370 String[] res = new String[N];
1371 Iterator<PackageSetting> it = sus.packages.iterator();
1372 int i=0;
1373 while (it.hasNext()) {
1374 res[i++] = it.next().name;
1375 }
1376 return res;
1377 } else if (obj instanceof PackageSetting) {
1378 PackageSetting ps = (PackageSetting)obj;
1379 return new String[] { ps.name };
1380 }
1381 }
1382 return null;
1383 }
1384
1385 public String getNameForUid(int uid) {
1386 synchronized (mPackages) {
1387 Object obj = mSettings.getUserIdLP(uid);
1388 if (obj instanceof SharedUserSetting) {
1389 SharedUserSetting sus = (SharedUserSetting)obj;
1390 return sus.name + ":" + sus.userId;
1391 } else if (obj instanceof PackageSetting) {
1392 PackageSetting ps = (PackageSetting)obj;
1393 return ps.name;
1394 }
1395 }
1396 return null;
1397 }
1398
1399 public int getUidForSharedUser(String sharedUserName) {
1400 if(sharedUserName == null) {
1401 return -1;
1402 }
1403 synchronized (mPackages) {
1404 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1405 if(suid == null) {
1406 return -1;
1407 }
1408 return suid.userId;
1409 }
1410 }
1411
1412 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1413 int flags) {
1414 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001415 return chooseBestActivity(intent, resolvedType, flags, query);
1416 }
1417
Mihai Predaeae850c2009-05-13 10:13:48 +02001418 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1419 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 if (query != null) {
1421 final int N = query.size();
1422 if (N == 1) {
1423 return query.get(0);
1424 } else if (N > 1) {
1425 // If there is more than one activity with the same priority,
1426 // then let the user decide between them.
1427 ResolveInfo r0 = query.get(0);
1428 ResolveInfo r1 = query.get(1);
1429 if (false) {
1430 System.out.println(r0.activityInfo.name +
1431 "=" + r0.priority + " vs " +
1432 r1.activityInfo.name +
1433 "=" + r1.priority);
1434 }
1435 // If the first activity has a higher priority, or a different
1436 // default, then it is always desireable to pick it.
1437 if (r0.priority != r1.priority
1438 || r0.preferredOrder != r1.preferredOrder
1439 || r0.isDefault != r1.isDefault) {
1440 return query.get(0);
1441 }
1442 // If we have saved a preference for a preferred activity for
1443 // this Intent, use that.
1444 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1445 flags, query, r0.priority);
1446 if (ri != null) {
1447 return ri;
1448 }
1449 return mResolveInfo;
1450 }
1451 }
1452 return null;
1453 }
1454
1455 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1456 int flags, List<ResolveInfo> query, int priority) {
1457 synchronized (mPackages) {
1458 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1459 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001460 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1462 if (prefs != null && prefs.size() > 0) {
1463 // First figure out how good the original match set is.
1464 // We will only allow preferred activities that came
1465 // from the same match quality.
1466 int match = 0;
1467 final int N = query.size();
1468 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1469 for (int j=0; j<N; j++) {
1470 ResolveInfo ri = query.get(j);
1471 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1472 + ": 0x" + Integer.toHexString(match));
1473 if (ri.match > match) match = ri.match;
1474 }
1475 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1476 + Integer.toHexString(match));
1477 match &= IntentFilter.MATCH_CATEGORY_MASK;
1478 final int M = prefs.size();
1479 for (int i=0; i<M; i++) {
1480 PreferredActivity pa = prefs.get(i);
1481 if (pa.mMatch != match) {
1482 continue;
1483 }
1484 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1485 if (DEBUG_PREFERRED) {
1486 Log.v(TAG, "Got preferred activity:");
1487 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1488 }
1489 if (ai != null) {
1490 for (int j=0; j<N; j++) {
1491 ResolveInfo ri = query.get(j);
1492 if (!ri.activityInfo.applicationInfo.packageName
1493 .equals(ai.applicationInfo.packageName)) {
1494 continue;
1495 }
1496 if (!ri.activityInfo.name.equals(ai.name)) {
1497 continue;
1498 }
1499
1500 // Okay we found a previously set preferred app.
1501 // If the result set is different from when this
1502 // was created, we need to clear it and re-ask the
1503 // user their preference.
1504 if (!pa.sameSet(query, priority)) {
1505 Log.i(TAG, "Result set changed, dropping preferred activity for "
1506 + intent + " type " + resolvedType);
1507 mSettings.mPreferredActivities.removeFilter(pa);
1508 return null;
1509 }
1510
1511 // Yay!
1512 return ri;
1513 }
1514 }
1515 }
1516 }
1517 }
1518 return null;
1519 }
1520
1521 public List<ResolveInfo> queryIntentActivities(Intent intent,
1522 String resolvedType, int flags) {
1523 ComponentName comp = intent.getComponent();
1524 if (comp != null) {
1525 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1526 ActivityInfo ai = getActivityInfo(comp, flags);
1527 if (ai != null) {
1528 ResolveInfo ri = new ResolveInfo();
1529 ri.activityInfo = ai;
1530 list.add(ri);
1531 }
1532 return list;
1533 }
1534
1535 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001536 String pkgName = intent.getPackage();
1537 if (pkgName == null) {
1538 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1539 resolvedType, flags);
1540 }
1541 PackageParser.Package pkg = mPackages.get(pkgName);
1542 if (pkg != null) {
1543 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1544 resolvedType, flags, pkg.activities);
1545 }
1546 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
1549
1550 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1551 Intent[] specifics, String[] specificTypes, Intent intent,
1552 String resolvedType, int flags) {
1553 final String resultsAction = intent.getAction();
1554
1555 List<ResolveInfo> results = queryIntentActivities(
1556 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1557 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1558
1559 int specificsPos = 0;
1560 int N;
1561
1562 // todo: note that the algorithm used here is O(N^2). This
1563 // isn't a problem in our current environment, but if we start running
1564 // into situations where we have more than 5 or 10 matches then this
1565 // should probably be changed to something smarter...
1566
1567 // First we go through and resolve each of the specific items
1568 // that were supplied, taking care of removing any corresponding
1569 // duplicate items in the generic resolve list.
1570 if (specifics != null) {
1571 for (int i=0; i<specifics.length; i++) {
1572 final Intent sintent = specifics[i];
1573 if (sintent == null) {
1574 continue;
1575 }
1576
1577 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1578 String action = sintent.getAction();
1579 if (resultsAction != null && resultsAction.equals(action)) {
1580 // If this action was explicitly requested, then don't
1581 // remove things that have it.
1582 action = null;
1583 }
1584 ComponentName comp = sintent.getComponent();
1585 ResolveInfo ri = null;
1586 ActivityInfo ai = null;
1587 if (comp == null) {
1588 ri = resolveIntent(
1589 sintent,
1590 specificTypes != null ? specificTypes[i] : null,
1591 flags);
1592 if (ri == null) {
1593 continue;
1594 }
1595 if (ri == mResolveInfo) {
1596 // ACK! Must do something better with this.
1597 }
1598 ai = ri.activityInfo;
1599 comp = new ComponentName(ai.applicationInfo.packageName,
1600 ai.name);
1601 } else {
1602 ai = getActivityInfo(comp, flags);
1603 if (ai == null) {
1604 continue;
1605 }
1606 }
1607
1608 // Look for any generic query activities that are duplicates
1609 // of this specific one, and remove them from the results.
1610 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1611 N = results.size();
1612 int j;
1613 for (j=specificsPos; j<N; j++) {
1614 ResolveInfo sri = results.get(j);
1615 if ((sri.activityInfo.name.equals(comp.getClassName())
1616 && sri.activityInfo.applicationInfo.packageName.equals(
1617 comp.getPackageName()))
1618 || (action != null && sri.filter.matchAction(action))) {
1619 results.remove(j);
1620 if (Config.LOGV) Log.v(
1621 TAG, "Removing duplicate item from " + j
1622 + " due to specific " + specificsPos);
1623 if (ri == null) {
1624 ri = sri;
1625 }
1626 j--;
1627 N--;
1628 }
1629 }
1630
1631 // Add this specific item to its proper place.
1632 if (ri == null) {
1633 ri = new ResolveInfo();
1634 ri.activityInfo = ai;
1635 }
1636 results.add(specificsPos, ri);
1637 ri.specificIndex = i;
1638 specificsPos++;
1639 }
1640 }
1641
1642 // Now we go through the remaining generic results and remove any
1643 // duplicate actions that are found here.
1644 N = results.size();
1645 for (int i=specificsPos; i<N-1; i++) {
1646 final ResolveInfo rii = results.get(i);
1647 if (rii.filter == null) {
1648 continue;
1649 }
1650
1651 // Iterate over all of the actions of this result's intent
1652 // filter... typically this should be just one.
1653 final Iterator<String> it = rii.filter.actionsIterator();
1654 if (it == null) {
1655 continue;
1656 }
1657 while (it.hasNext()) {
1658 final String action = it.next();
1659 if (resultsAction != null && resultsAction.equals(action)) {
1660 // If this action was explicitly requested, then don't
1661 // remove things that have it.
1662 continue;
1663 }
1664 for (int j=i+1; j<N; j++) {
1665 final ResolveInfo rij = results.get(j);
1666 if (rij.filter != null && rij.filter.hasAction(action)) {
1667 results.remove(j);
1668 if (Config.LOGV) Log.v(
1669 TAG, "Removing duplicate item from " + j
1670 + " due to action " + action + " at " + i);
1671 j--;
1672 N--;
1673 }
1674 }
1675 }
1676
1677 // If the caller didn't request filter information, drop it now
1678 // so we don't have to marshall/unmarshall it.
1679 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1680 rii.filter = null;
1681 }
1682 }
1683
1684 // Filter out the caller activity if so requested.
1685 if (caller != null) {
1686 N = results.size();
1687 for (int i=0; i<N; i++) {
1688 ActivityInfo ainfo = results.get(i).activityInfo;
1689 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1690 && caller.getClassName().equals(ainfo.name)) {
1691 results.remove(i);
1692 break;
1693 }
1694 }
1695 }
1696
1697 // If the caller didn't request filter information,
1698 // drop them now so we don't have to
1699 // marshall/unmarshall it.
1700 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1701 N = results.size();
1702 for (int i=0; i<N; i++) {
1703 results.get(i).filter = null;
1704 }
1705 }
1706
1707 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1708 return results;
1709 }
1710
1711 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1712 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001713 ComponentName comp = intent.getComponent();
1714 if (comp != null) {
1715 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1716 ActivityInfo ai = getReceiverInfo(comp, flags);
1717 if (ai != null) {
1718 ResolveInfo ri = new ResolveInfo();
1719 ri.activityInfo = ai;
1720 list.add(ri);
1721 }
1722 return list;
1723 }
1724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001726 String pkgName = intent.getPackage();
1727 if (pkgName == null) {
1728 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1729 resolvedType, flags);
1730 }
1731 PackageParser.Package pkg = mPackages.get(pkgName);
1732 if (pkg != null) {
1733 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1734 resolvedType, flags, pkg.receivers);
1735 }
1736 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
1738 }
1739
1740 public ResolveInfo resolveService(Intent intent, String resolvedType,
1741 int flags) {
1742 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1743 flags);
1744 if (query != null) {
1745 if (query.size() >= 1) {
1746 // If there is more than one service with the same priority,
1747 // just arbitrarily pick the first one.
1748 return query.get(0);
1749 }
1750 }
1751 return null;
1752 }
1753
1754 public List<ResolveInfo> queryIntentServices(Intent intent,
1755 String resolvedType, int flags) {
1756 ComponentName comp = intent.getComponent();
1757 if (comp != null) {
1758 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1759 ServiceInfo si = getServiceInfo(comp, flags);
1760 if (si != null) {
1761 ResolveInfo ri = new ResolveInfo();
1762 ri.serviceInfo = si;
1763 list.add(ri);
1764 }
1765 return list;
1766 }
1767
1768 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001769 String pkgName = intent.getPackage();
1770 if (pkgName == null) {
1771 return (List<ResolveInfo>)mServices.queryIntent(intent,
1772 resolvedType, flags);
1773 }
1774 PackageParser.Package pkg = mPackages.get(pkgName);
1775 if (pkg != null) {
1776 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1777 resolvedType, flags, pkg.services);
1778 }
1779 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
1781 }
1782
1783 public List<PackageInfo> getInstalledPackages(int flags) {
1784 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1785
1786 synchronized (mPackages) {
1787 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1788 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1789 while (i.hasNext()) {
1790 final PackageSetting ps = i.next();
1791 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1792 if(psPkg != null) {
1793 finalList.add(psPkg);
1794 }
1795 }
1796 }
1797 else {
1798 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1799 while (i.hasNext()) {
1800 final PackageParser.Package p = i.next();
1801 if (p.applicationInfo != null) {
1802 PackageInfo pi = generatePackageInfo(p, flags);
1803 if(pi != null) {
1804 finalList.add(pi);
1805 }
1806 }
1807 }
1808 }
1809 }
1810 return finalList;
1811 }
1812
1813 public List<ApplicationInfo> getInstalledApplications(int flags) {
1814 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1815 synchronized(mPackages) {
1816 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1817 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1818 while (i.hasNext()) {
1819 final PackageSetting ps = i.next();
1820 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1821 if(ai != null) {
1822 finalList.add(ai);
1823 }
1824 }
1825 }
1826 else {
1827 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1828 while (i.hasNext()) {
1829 final PackageParser.Package p = i.next();
1830 if (p.applicationInfo != null) {
1831 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1832 if(ai != null) {
1833 finalList.add(ai);
1834 }
1835 }
1836 }
1837 }
1838 }
1839 return finalList;
1840 }
1841
1842 public List<ApplicationInfo> getPersistentApplications(int flags) {
1843 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1844
1845 synchronized (mPackages) {
1846 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1847 while (i.hasNext()) {
1848 PackageParser.Package p = i.next();
1849 if (p.applicationInfo != null
1850 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
1851 && (!mSafeMode || (p.applicationInfo.flags
1852 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1853 finalList.add(p.applicationInfo);
1854 }
1855 }
1856 }
1857
1858 return finalList;
1859 }
1860
1861 public ProviderInfo resolveContentProvider(String name, int flags) {
1862 synchronized (mPackages) {
1863 final PackageParser.Provider provider = mProviders.get(name);
1864 return provider != null
1865 && mSettings.isEnabledLP(provider.info, flags)
1866 && (!mSafeMode || (provider.info.applicationInfo.flags
1867 &ApplicationInfo.FLAG_SYSTEM) != 0)
1868 ? PackageParser.generateProviderInfo(provider, flags)
1869 : null;
1870 }
1871 }
1872
Fred Quintana718d8a22009-04-29 17:53:20 -07001873 /**
1874 * @deprecated
1875 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 public void querySyncProviders(List outNames, List outInfo) {
1877 synchronized (mPackages) {
1878 Iterator<Map.Entry<String, PackageParser.Provider>> i
1879 = mProviders.entrySet().iterator();
1880
1881 while (i.hasNext()) {
1882 Map.Entry<String, PackageParser.Provider> entry = i.next();
1883 PackageParser.Provider p = entry.getValue();
1884
1885 if (p.syncable
1886 && (!mSafeMode || (p.info.applicationInfo.flags
1887 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1888 outNames.add(entry.getKey());
1889 outInfo.add(PackageParser.generateProviderInfo(p, 0));
1890 }
1891 }
1892 }
1893 }
1894
1895 public List<ProviderInfo> queryContentProviders(String processName,
1896 int uid, int flags) {
1897 ArrayList<ProviderInfo> finalList = null;
1898
1899 synchronized (mPackages) {
1900 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
1901 while (i.hasNext()) {
1902 PackageParser.Provider p = i.next();
1903 if (p.info.authority != null
1904 && (processName == null ||
1905 (p.info.processName.equals(processName)
1906 && p.info.applicationInfo.uid == uid))
1907 && mSettings.isEnabledLP(p.info, flags)
1908 && (!mSafeMode || (p.info.applicationInfo.flags
1909 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1910 if (finalList == null) {
1911 finalList = new ArrayList<ProviderInfo>(3);
1912 }
1913 finalList.add(PackageParser.generateProviderInfo(p,
1914 flags));
1915 }
1916 }
1917 }
1918
1919 if (finalList != null) {
1920 Collections.sort(finalList, mProviderInitOrderSorter);
1921 }
1922
1923 return finalList;
1924 }
1925
1926 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
1927 int flags) {
1928 synchronized (mPackages) {
1929 final PackageParser.Instrumentation i = mInstrumentation.get(name);
1930 return PackageParser.generateInstrumentationInfo(i, flags);
1931 }
1932 }
1933
1934 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
1935 int flags) {
1936 ArrayList<InstrumentationInfo> finalList =
1937 new ArrayList<InstrumentationInfo>();
1938
1939 synchronized (mPackages) {
1940 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
1941 while (i.hasNext()) {
1942 PackageParser.Instrumentation p = i.next();
1943 if (targetPackage == null
1944 || targetPackage.equals(p.info.targetPackage)) {
1945 finalList.add(PackageParser.generateInstrumentationInfo(p,
1946 flags));
1947 }
1948 }
1949 }
1950
1951 return finalList;
1952 }
1953
1954 private void scanDirLI(File dir, int flags, int scanMode) {
1955 Log.d(TAG, "Scanning app dir " + dir);
1956
1957 String[] files = dir.list();
1958
1959 int i;
1960 for (i=0; i<files.length; i++) {
1961 File file = new File(dir, files[i]);
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07001962 File resFile = file;
1963 // Pick up the resource path from settings for fwd locked apps
1964 if ((scanMode & SCAN_FORWARD_LOCKED) != 0) {
1965 resFile = null;
1966 }
1967 PackageParser.Package pkg = scanPackageLI(file, file, resFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
1969 }
1970 }
1971
1972 private static void reportSettingsProblem(int priority, String msg) {
1973 try {
1974 File dataDir = Environment.getDataDirectory();
1975 File systemDir = new File(dataDir, "system");
1976 File fname = new File(systemDir, "uiderrors.txt");
1977 FileOutputStream out = new FileOutputStream(fname, true);
1978 PrintWriter pw = new PrintWriter(out);
1979 pw.println(msg);
1980 pw.close();
1981 FileUtils.setPermissions(
1982 fname.toString(),
1983 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
1984 -1, -1);
1985 } catch (java.io.IOException e) {
1986 }
1987 Log.println(priority, TAG, msg);
1988 }
1989
1990 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
1991 PackageParser.Package pkg, File srcFile, int parseFlags) {
1992 if (GET_CERTIFICATES) {
1993 if (ps == null || !ps.codePath.equals(srcFile)
1994 || ps.getTimeStamp() != srcFile.lastModified()) {
1995 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
1996 if (!pp.collectCertificates(pkg, parseFlags)) {
1997 mLastScanError = pp.getParseError();
1998 return false;
1999 }
2000 }
2001 }
2002 return true;
2003 }
2004
2005 /*
2006 * Scan a package and return the newly parsed package.
2007 * Returns null in case of errors and the error code is stored in mLastScanError
2008 */
2009 private PackageParser.Package scanPackageLI(File scanFile,
2010 File destCodeFile, File destResourceFile, int parseFlags,
2011 int scanMode) {
2012 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2013 parseFlags |= mDefParseFlags;
2014 PackageParser pp = new PackageParser(scanFile.getPath());
2015 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 final PackageParser.Package pkg = pp.parsePackage(scanFile,
2017 destCodeFile.getAbsolutePath(), mMetrics, parseFlags);
2018 if (pkg == null) {
2019 mLastScanError = pp.getParseError();
2020 return null;
2021 }
2022 PackageSetting ps;
2023 PackageSetting updatedPkg;
2024 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002025 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2027 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002028 // Verify certificates first
2029 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2030 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2031 return null;
2032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 if (updatedPkg != null) {
2034 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2035 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2036 }
2037 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2038 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002039 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2040 if (pkg.mVersionCode < ps.versionCode) {
2041 // The system package has been updated and the code path does not match
2042 // Ignore entry. Just return
2043 Log.w(TAG, "Package:" + pkg.packageName +
2044 " has been updated. Ignoring the one from path:"+scanFile);
2045 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2046 return null;
2047 } else {
2048 // Delete the older apk pointed to by ps
2049 // At this point, its safely assumed that package installation for
2050 // apps in system partition will go through. If not there won't be a working
2051 // version of the app
2052 synchronized (mPackages) {
2053 // Just remove the loaded entries from package lists.
2054 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002055 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002056 deletePackageResourcesLI(ps.name, ps.codePathString, ps.resourcePathString);
2057 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
2060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 // The apk is forward locked (not public) if its code and resources
2062 // are kept in different files.
2063 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
2064 scanMode |= SCAN_FORWARD_LOCKED;
2065 }
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002066 File resFile = destResourceFile;
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07002067 if (ps != null && ((scanMode & SCAN_FORWARD_LOCKED) != 0)) {
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002068 resFile = getFwdLockedResource(ps.name);
2069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002071 return scanPackageLI(scanFile, destCodeFile, resFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
2073 }
2074
2075 private static String fixProcessName(String defProcessName,
2076 String processName, int uid) {
2077 if (processName == null) {
2078 return defProcessName;
2079 }
2080 return processName;
2081 }
2082
2083 private boolean verifySignaturesLP(PackageSetting pkgSetting,
2084 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2085 if (pkg.mSignatures != null) {
2086 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2087 updateSignature)) {
2088 Log.e(TAG, "Package " + pkg.packageName
2089 + " signatures do not match the previously installed version; ignoring!");
2090 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2091 return false;
2092 }
2093
2094 if (pkgSetting.sharedUser != null) {
2095 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2096 pkg.mSignatures, updateSignature)) {
2097 Log.e(TAG, "Package " + pkg.packageName
2098 + " has no signatures that match those in shared user "
2099 + pkgSetting.sharedUser.name + "; ignoring!");
2100 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2101 return false;
2102 }
2103 }
2104 } else {
2105 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2106 }
2107 return true;
2108 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002109
2110 public boolean performDexOpt(String packageName) {
2111 if (!mNoDexOpt) {
2112 return false;
2113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002115 PackageParser.Package p;
2116 synchronized (mPackages) {
2117 p = mPackages.get(packageName);
2118 if (p == null || p.mDidDexOpt) {
2119 return false;
2120 }
2121 }
2122 synchronized (mInstallLock) {
2123 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2124 }
2125 }
2126
2127 static final int DEX_OPT_SKIPPED = 0;
2128 static final int DEX_OPT_PERFORMED = 1;
2129 static final int DEX_OPT_FAILED = -1;
2130
2131 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2132 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002133 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002134 String path = pkg.mScanPath;
2135 int ret = 0;
2136 try {
2137 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
2138 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
2139 !pkg.mForwardLocked);
2140 pkg.mDidDexOpt = true;
2141 performed = true;
2142 }
2143 } catch (FileNotFoundException e) {
2144 Log.w(TAG, "Apk not found for dexopt: " + path);
2145 ret = -1;
2146 } catch (IOException e) {
2147 Log.w(TAG, "Exception reading apk: " + path, e);
2148 ret = -1;
2149 }
2150 if (ret < 0) {
2151 //error from installer
2152 return DEX_OPT_FAILED;
2153 }
2154 }
2155
2156 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2157 }
2158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 private PackageParser.Package scanPackageLI(
2160 File scanFile, File destCodeFile, File destResourceFile,
2161 PackageParser.Package pkg, int parseFlags, int scanMode) {
2162
2163 mScanningPath = scanFile;
2164 if (pkg == null) {
2165 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2166 return null;
2167 }
2168
2169 final String pkgName = pkg.applicationInfo.packageName;
2170 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2171 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2172 }
2173
2174 if (pkgName.equals("android")) {
2175 synchronized (mPackages) {
2176 if (mAndroidApplication != null) {
2177 Log.w(TAG, "*************************************************");
2178 Log.w(TAG, "Core android package being redefined. Skipping.");
2179 Log.w(TAG, " file=" + mScanningPath);
2180 Log.w(TAG, "*************************************************");
2181 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2182 return null;
2183 }
2184
2185 // Set up information for our fall-back user intent resolution
2186 // activity.
2187 mPlatformPackage = pkg;
2188 pkg.mVersionCode = mSdkVersion;
2189 mAndroidApplication = pkg.applicationInfo;
2190 mResolveActivity.applicationInfo = mAndroidApplication;
2191 mResolveActivity.name = ResolverActivity.class.getName();
2192 mResolveActivity.packageName = mAndroidApplication.packageName;
2193 mResolveActivity.processName = mAndroidApplication.processName;
2194 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2195 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2196 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2197 mResolveActivity.exported = true;
2198 mResolveActivity.enabled = true;
2199 mResolveInfo.activityInfo = mResolveActivity;
2200 mResolveInfo.priority = 0;
2201 mResolveInfo.preferredOrder = 0;
2202 mResolveInfo.match = 0;
2203 mResolveComponentName = new ComponentName(
2204 mAndroidApplication.packageName, mResolveActivity.name);
2205 }
2206 }
2207
2208 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2209 TAG, "Scanning package " + pkgName);
2210 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2211 Log.w(TAG, "*************************************************");
2212 Log.w(TAG, "Application package " + pkgName
2213 + " already installed. Skipping duplicate.");
2214 Log.w(TAG, "*************************************************");
2215 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2216 return null;
2217 }
2218
2219 SharedUserSetting suid = null;
2220 PackageSetting pkgSetting = null;
2221
2222 boolean removeExisting = false;
2223
2224 synchronized (mPackages) {
2225 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002226 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2227 if (mTmpSharedLibraries == null ||
2228 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2229 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2230 }
2231 int num = 0;
2232 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2233 for (int i=0; i<N; i++) {
2234 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 if (file == null) {
2236 Log.e(TAG, "Package " + pkg.packageName
2237 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002238 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2240 return null;
2241 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002242 mTmpSharedLibraries[num] = file;
2243 num++;
2244 }
2245 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2246 for (int i=0; i<N; i++) {
2247 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2248 if (file == null) {
2249 Log.w(TAG, "Package " + pkg.packageName
2250 + " desires unavailable shared library "
2251 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2252 } else {
2253 mTmpSharedLibraries[num] = file;
2254 num++;
2255 }
2256 }
2257 if (num > 0) {
2258 pkg.usesLibraryFiles = new String[num];
2259 System.arraycopy(mTmpSharedLibraries, 0,
2260 pkg.usesLibraryFiles, 0, num);
2261 }
2262
2263 if (pkg.reqFeatures != null) {
2264 N = pkg.reqFeatures.size();
2265 for (int i=0; i<N; i++) {
2266 FeatureInfo fi = pkg.reqFeatures.get(i);
2267 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2268 // Don't care.
2269 continue;
2270 }
2271
2272 if (fi.name != null) {
2273 if (mAvailableFeatures.get(fi.name) == null) {
2274 Log.e(TAG, "Package " + pkg.packageName
2275 + " requires unavailable feature "
2276 + fi.name + "; failing!");
2277 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2278 return null;
2279 }
2280 }
2281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 }
2283 }
2284
2285 if (pkg.mSharedUserId != null) {
2286 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2287 pkg.applicationInfo.flags, true);
2288 if (suid == null) {
2289 Log.w(TAG, "Creating application package " + pkgName
2290 + " for shared user failed");
2291 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2292 return null;
2293 }
2294 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2295 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2296 + suid.userId + "): packages=" + suid.packages);
2297 }
2298 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002299
2300 // Just create the setting, don't add it yet. For already existing packages
2301 // the PkgSetting exists already and doesn't have to be created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
2303 destResourceFile, pkg.applicationInfo.flags, true, false);
2304 if (pkgSetting == null) {
2305 Log.w(TAG, "Creating application package " + pkgName + " failed");
2306 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2307 return null;
2308 }
2309 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
2310 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2311 }
2312
2313 pkg.applicationInfo.uid = pkgSetting.userId;
2314 pkg.mExtras = pkgSetting;
2315
2316 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
2317 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2318 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2319 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2320 return null;
2321 }
2322 // The signature has changed, but this package is in the system
2323 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002324 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 // However... if this package is part of a shared user, but it
2326 // doesn't match the signature of the shared user, let's fail.
2327 // What this means is that you can't change the signatures
2328 // associated with an overall shared user, which doesn't seem all
2329 // that unreasonable.
2330 if (pkgSetting.sharedUser != null) {
2331 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2332 pkg.mSignatures, false)) {
2333 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2334 return null;
2335 }
2336 }
2337 removeExisting = true;
2338 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002339
2340 // Verify that this new package doesn't have any content providers
2341 // that conflict with existing packages. Only do this if the
2342 // package isn't already installed, since we don't want to break
2343 // things that are installed.
2344 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2345 int N = pkg.providers.size();
2346 int i;
2347 for (i=0; i<N; i++) {
2348 PackageParser.Provider p = pkg.providers.get(i);
2349 String names[] = p.info.authority.split(";");
2350 for (int j = 0; j < names.length; j++) {
2351 if (mProviders.containsKey(names[j])) {
2352 PackageParser.Provider other = mProviders.get(names[j]);
2353 Log.w(TAG, "Can't install because provider name " + names[j] +
2354 " (in package " + pkg.applicationInfo.packageName +
2355 ") is already used by "
2356 + ((other != null && other.component != null)
2357 ? other.component.getPackageName() : "?"));
2358 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2359 return null;
2360 }
2361 }
2362 }
2363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 }
2365
2366 if (removeExisting) {
2367 if (mInstaller != null) {
2368 int ret = mInstaller.remove(pkgName);
2369 if (ret != 0) {
2370 String msg = "System package " + pkg.packageName
2371 + " could not have data directory erased after signature change.";
2372 reportSettingsProblem(Log.WARN, msg);
2373 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2374 return null;
2375 }
2376 }
2377 Log.w(TAG, "System package " + pkg.packageName
2378 + " signature changed: existing data removed.");
2379 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2380 }
2381
2382 long scanFileTime = scanFile.lastModified();
2383 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2384 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2385 pkg.applicationInfo.processName = fixProcessName(
2386 pkg.applicationInfo.packageName,
2387 pkg.applicationInfo.processName,
2388 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002389 pkg.applicationInfo.publicSourceDir = destResourceFile.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390
2391 File dataPath;
2392 if (mPlatformPackage == pkg) {
2393 // The system package is special.
2394 dataPath = new File (Environment.getDataDirectory(), "system");
2395 pkg.applicationInfo.dataDir = dataPath.getPath();
2396 } else {
2397 // This is a normal package, need to make its data directory.
2398 dataPath = new File(mAppDataDir, pkgName);
2399 if (dataPath.exists()) {
2400 mOutPermissions[1] = 0;
2401 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2402 if (mOutPermissions[1] == pkg.applicationInfo.uid
2403 || !Process.supportsProcesses()) {
2404 pkg.applicationInfo.dataDir = dataPath.getPath();
2405 } else {
2406 boolean recovered = false;
2407 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2408 // If this is a system app, we can at least delete its
2409 // current data so the application will still work.
2410 if (mInstaller != null) {
2411 int ret = mInstaller.remove(pkgName);
2412 if(ret >= 0) {
2413 // Old data gone!
2414 String msg = "System package " + pkg.packageName
2415 + " has changed from uid: "
2416 + mOutPermissions[1] + " to "
2417 + pkg.applicationInfo.uid + "; old data erased";
2418 reportSettingsProblem(Log.WARN, msg);
2419 recovered = true;
2420
2421 // And now re-install the app.
2422 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2423 pkg.applicationInfo.uid);
2424 if (ret == -1) {
2425 // Ack should not happen!
2426 msg = "System package " + pkg.packageName
2427 + " could not have data directory re-created after delete.";
2428 reportSettingsProblem(Log.WARN, msg);
2429 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2430 return null;
2431 }
2432 }
2433 }
2434 if (!recovered) {
2435 mHasSystemUidErrors = true;
2436 }
2437 }
2438 if (!recovered) {
2439 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2440 + pkg.applicationInfo.uid + "/fs_"
2441 + mOutPermissions[1];
2442 String msg = "Package " + pkg.packageName
2443 + " has mismatched uid: "
2444 + mOutPermissions[1] + " on disk, "
2445 + pkg.applicationInfo.uid + " in settings";
2446 synchronized (mPackages) {
2447 if (!mReportedUidError) {
2448 mReportedUidError = true;
2449 msg = msg + "; read messages:\n"
2450 + mSettings.getReadMessagesLP();
2451 }
2452 reportSettingsProblem(Log.ERROR, msg);
2453 }
2454 }
2455 }
2456 pkg.applicationInfo.dataDir = dataPath.getPath();
2457 } else {
2458 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2459 Log.v(TAG, "Want this data dir: " + dataPath);
2460 //invoke installer to do the actual installation
2461 if (mInstaller != null) {
2462 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2463 pkg.applicationInfo.uid);
2464 if(ret < 0) {
2465 // Error from installer
2466 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2467 return null;
2468 }
2469 } else {
2470 dataPath.mkdirs();
2471 if (dataPath.exists()) {
2472 FileUtils.setPermissions(
2473 dataPath.toString(),
2474 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2475 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2476 }
2477 }
2478 if (dataPath.exists()) {
2479 pkg.applicationInfo.dataDir = dataPath.getPath();
2480 } else {
2481 Log.w(TAG, "Unable to create data directory: " + dataPath);
2482 pkg.applicationInfo.dataDir = null;
2483 }
2484 }
2485 }
2486
2487 // Perform shared library installation and dex validation and
2488 // optimization, if this is not a system app.
2489 if (mInstaller != null) {
2490 String path = scanFile.getPath();
2491 if (scanFileNewer) {
2492 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002493 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2494 if (err != PackageManager.INSTALL_SUCCEEDED) {
2495 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 return null;
2497 }
2498 }
2499
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002500 pkg.mForwardLocked = (scanMode&SCAN_FORWARD_LOCKED) != 0;
2501 pkg.mScanPath = path;
2502
2503 if ((scanMode&SCAN_NO_DEX) == 0) {
2504 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2506 return null;
2507 }
2508 }
2509 }
2510
2511 if (mFactoryTest && pkg.requestedPermissions.contains(
2512 android.Manifest.permission.FACTORY_TEST)) {
2513 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2514 }
2515
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002516 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 if ((scanMode&SCAN_MONITOR) != 0) {
2518 pkg.mPath = destCodeFile.getAbsolutePath();
2519 mAppDirs.put(pkg.mPath, pkg);
2520 }
2521
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002522 // Request the ActivityManager to kill the process(only for existing packages)
2523 // so that we do not end up in a confused state while the user is still using the older
2524 // version of the application while the new one gets installed.
2525 IActivityManager am = ActivityManagerNative.getDefault();
2526 if ((am != null) && ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0)) {
2527 try {
2528 am.killApplicationWithUid(pkg.applicationInfo.packageName,
2529 pkg.applicationInfo.uid);
2530 } catch (RemoteException e) {
2531 }
2532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 // Add the new setting to mSettings
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002535 mSettings.insertPackageSettingLP(pkgSetting, pkg, destCodeFile, destResourceFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002537 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 int N = pkg.providers.size();
2539 StringBuilder r = null;
2540 int i;
2541 for (i=0; i<N; i++) {
2542 PackageParser.Provider p = pkg.providers.get(i);
2543 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2544 p.info.processName, pkg.applicationInfo.uid);
2545 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2546 p.info.name), p);
2547 p.syncable = p.info.isSyncable;
2548 String names[] = p.info.authority.split(";");
2549 p.info.authority = null;
2550 for (int j = 0; j < names.length; j++) {
2551 if (j == 1 && p.syncable) {
2552 // We only want the first authority for a provider to possibly be
2553 // syncable, so if we already added this provider using a different
2554 // authority clear the syncable flag. We copy the provider before
2555 // changing it because the mProviders object contains a reference
2556 // to a provider that we don't want to change.
2557 // Only do this for the second authority since the resulting provider
2558 // object can be the same for all future authorities for this provider.
2559 p = new PackageParser.Provider(p);
2560 p.syncable = false;
2561 }
2562 if (!mProviders.containsKey(names[j])) {
2563 mProviders.put(names[j], p);
2564 if (p.info.authority == null) {
2565 p.info.authority = names[j];
2566 } else {
2567 p.info.authority = p.info.authority + ";" + names[j];
2568 }
2569 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2570 Log.d(TAG, "Registered content provider: " + names[j] +
2571 ", className = " + p.info.name +
2572 ", isSyncable = " + p.info.isSyncable);
2573 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002574 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 Log.w(TAG, "Skipping provider name " + names[j] +
2576 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002577 "): name already used by "
2578 + ((other != null && other.component != null)
2579 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 }
2581 }
2582 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2583 if (r == null) {
2584 r = new StringBuilder(256);
2585 } else {
2586 r.append(' ');
2587 }
2588 r.append(p.info.name);
2589 }
2590 }
2591 if (r != null) {
2592 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2593 }
2594
2595 N = pkg.services.size();
2596 r = null;
2597 for (i=0; i<N; i++) {
2598 PackageParser.Service s = pkg.services.get(i);
2599 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2600 s.info.processName, pkg.applicationInfo.uid);
2601 mServices.addService(s);
2602 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2603 if (r == null) {
2604 r = new StringBuilder(256);
2605 } else {
2606 r.append(' ');
2607 }
2608 r.append(s.info.name);
2609 }
2610 }
2611 if (r != null) {
2612 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2613 }
2614
2615 N = pkg.receivers.size();
2616 r = null;
2617 for (i=0; i<N; i++) {
2618 PackageParser.Activity a = pkg.receivers.get(i);
2619 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2620 a.info.processName, pkg.applicationInfo.uid);
2621 mReceivers.addActivity(a, "receiver");
2622 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2623 if (r == null) {
2624 r = new StringBuilder(256);
2625 } else {
2626 r.append(' ');
2627 }
2628 r.append(a.info.name);
2629 }
2630 }
2631 if (r != null) {
2632 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2633 }
2634
2635 N = pkg.activities.size();
2636 r = null;
2637 for (i=0; i<N; i++) {
2638 PackageParser.Activity a = pkg.activities.get(i);
2639 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2640 a.info.processName, pkg.applicationInfo.uid);
2641 mActivities.addActivity(a, "activity");
2642 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2643 if (r == null) {
2644 r = new StringBuilder(256);
2645 } else {
2646 r.append(' ');
2647 }
2648 r.append(a.info.name);
2649 }
2650 }
2651 if (r != null) {
2652 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2653 }
2654
2655 N = pkg.permissionGroups.size();
2656 r = null;
2657 for (i=0; i<N; i++) {
2658 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2659 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2660 if (cur == null) {
2661 mPermissionGroups.put(pg.info.name, pg);
2662 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2663 if (r == null) {
2664 r = new StringBuilder(256);
2665 } else {
2666 r.append(' ');
2667 }
2668 r.append(pg.info.name);
2669 }
2670 } else {
2671 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2672 + pg.info.packageName + " ignored: original from "
2673 + cur.info.packageName);
2674 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2675 if (r == null) {
2676 r = new StringBuilder(256);
2677 } else {
2678 r.append(' ');
2679 }
2680 r.append("DUP:");
2681 r.append(pg.info.name);
2682 }
2683 }
2684 }
2685 if (r != null) {
2686 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2687 }
2688
2689 N = pkg.permissions.size();
2690 r = null;
2691 for (i=0; i<N; i++) {
2692 PackageParser.Permission p = pkg.permissions.get(i);
2693 HashMap<String, BasePermission> permissionMap =
2694 p.tree ? mSettings.mPermissionTrees
2695 : mSettings.mPermissions;
2696 p.group = mPermissionGroups.get(p.info.group);
2697 if (p.info.group == null || p.group != null) {
2698 BasePermission bp = permissionMap.get(p.info.name);
2699 if (bp == null) {
2700 bp = new BasePermission(p.info.name, p.info.packageName,
2701 BasePermission.TYPE_NORMAL);
2702 permissionMap.put(p.info.name, bp);
2703 }
2704 if (bp.perm == null) {
2705 if (bp.sourcePackage == null
2706 || bp.sourcePackage.equals(p.info.packageName)) {
2707 BasePermission tree = findPermissionTreeLP(p.info.name);
2708 if (tree == null
2709 || tree.sourcePackage.equals(p.info.packageName)) {
2710 bp.perm = p;
2711 bp.uid = pkg.applicationInfo.uid;
2712 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2713 if (r == null) {
2714 r = new StringBuilder(256);
2715 } else {
2716 r.append(' ');
2717 }
2718 r.append(p.info.name);
2719 }
2720 } else {
2721 Log.w(TAG, "Permission " + p.info.name + " from package "
2722 + p.info.packageName + " ignored: base tree "
2723 + tree.name + " is from package "
2724 + tree.sourcePackage);
2725 }
2726 } else {
2727 Log.w(TAG, "Permission " + p.info.name + " from package "
2728 + p.info.packageName + " ignored: original from "
2729 + bp.sourcePackage);
2730 }
2731 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2732 if (r == null) {
2733 r = new StringBuilder(256);
2734 } else {
2735 r.append(' ');
2736 }
2737 r.append("DUP:");
2738 r.append(p.info.name);
2739 }
2740 } else {
2741 Log.w(TAG, "Permission " + p.info.name + " from package "
2742 + p.info.packageName + " ignored: no group "
2743 + p.group);
2744 }
2745 }
2746 if (r != null) {
2747 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2748 }
2749
2750 N = pkg.instrumentation.size();
2751 r = null;
2752 for (i=0; i<N; i++) {
2753 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2754 a.info.packageName = pkg.applicationInfo.packageName;
2755 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2756 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2757 a.info.dataDir = pkg.applicationInfo.dataDir;
2758 mInstrumentation.put(a.component, a);
2759 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2760 if (r == null) {
2761 r = new StringBuilder(256);
2762 } else {
2763 r.append(' ');
2764 }
2765 r.append(a.info.name);
2766 }
2767 }
2768 if (r != null) {
2769 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2770 }
2771
Dianne Hackborn854060af2009-07-09 18:14:31 -07002772 if (pkg.protectedBroadcasts != null) {
2773 N = pkg.protectedBroadcasts.size();
2774 for (i=0; i<N; i++) {
2775 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
2776 }
2777 }
2778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 pkgSetting.setTimeStamp(scanFileTime);
2780 }
2781
2782 return pkg;
2783 }
2784
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002785 // The following constants are returned by cachePackageSharedLibsForAbiLI
2786 // to indicate if native shared libraries were found in the package.
2787 // Values are:
2788 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
2789 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
2790 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
2791 // in package (and not installed)
2792 //
2793 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
2794 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
2795 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002797 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
2798 // and automatically copy them to /data/data/<appname>/lib if present.
2799 //
2800 // NOTE: this method may throw an IOException if the library cannot
2801 // be copied to its final destination, e.g. if there isn't enough
2802 // room left on the data partition, or a ZipException if the package
2803 // file is malformed.
2804 //
2805 private int cachePackageSharedLibsForAbiLI( PackageParser.Package pkg,
2806 File dataPath, File scanFile, String cpuAbi)
2807 throws IOException, ZipException {
2808 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
2809 final String apkLib = "lib/";
2810 final int apkLibLen = apkLib.length();
2811 final int cpuAbiLen = cpuAbi.length();
2812 final String libPrefix = "lib";
2813 final int libPrefixLen = libPrefix.length();
2814 final String libSuffix = ".so";
2815 final int libSuffixLen = libSuffix.length();
2816 boolean hasNativeLibraries = false;
2817 boolean installedNativeLibraries = false;
2818
2819 // the minimum length of a valid native shared library of the form
2820 // lib/<something>/lib<name>.so.
2821 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
2822
2823 ZipFile zipFile = new ZipFile(scanFile);
2824 Enumeration<ZipEntry> entries =
2825 (Enumeration<ZipEntry>) zipFile.entries();
2826
2827 while (entries.hasMoreElements()) {
2828 ZipEntry entry = entries.nextElement();
2829 // skip directories
2830 if (entry.isDirectory()) {
2831 continue;
2832 }
2833 String entryName = entry.getName();
2834
2835 // check that the entry looks like lib/<something>/lib<name>.so
2836 // here, but don't check the ABI just yet.
2837 //
2838 // - must be sufficiently long
2839 // - must end with libSuffix, i.e. ".so"
2840 // - must start with apkLib, i.e. "lib/"
2841 if (entryName.length() < minEntryLen ||
2842 !entryName.endsWith(libSuffix) ||
2843 !entryName.startsWith(apkLib) ) {
2844 continue;
2845 }
2846
2847 // file name must start with libPrefix, i.e. "lib"
2848 int lastSlash = entryName.lastIndexOf('/');
2849
2850 if (lastSlash < 0 ||
2851 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
2852 continue;
2853 }
2854
2855 hasNativeLibraries = true;
2856
2857 // check the cpuAbi now, between lib/ and /lib<name>.so
2858 //
2859 if (lastSlash != apkLibLen + cpuAbiLen ||
2860 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
2861 continue;
2862
2863 // extract the library file name, ensure it doesn't contain
2864 // weird characters. we're guaranteed here that it doesn't contain
2865 // a directory separator though.
2866 String libFileName = entryName.substring(lastSlash+1);
2867 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
2868 continue;
2869 }
2870
2871 installedNativeLibraries = true;
2872
2873 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
2874 File.separator + libFileName;
2875 File sharedLibraryFile = new File(sharedLibraryFilePath);
2876 if (! sharedLibraryFile.exists() ||
2877 sharedLibraryFile.length() != entry.getSize() ||
2878 sharedLibraryFile.lastModified() != entry.getTime()) {
2879 if (Config.LOGD) {
2880 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002882 if (mInstaller == null) {
2883 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07002884 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002885 cacheSharedLibLI(pkg, zipFile, entry, sharedLibraryDir,
2886 sharedLibraryFile);
2887 }
2888 }
2889 if (!hasNativeLibraries)
2890 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
2891
2892 if (!installedNativeLibraries)
2893 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
2894
2895 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
2896 }
2897
2898 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
2899 // and copy them to /data/data/<appname>/lib.
2900 //
2901 // This function will first try the main CPU ABI defined by Build.CPU_ABI
2902 // (which corresponds to ro.product.cpu.abi), and also try an alternate
2903 // one if ro.product.cpu.abi2 is defined.
2904 //
2905 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
2906 File dataPath, File scanFile) {
2907 final String cpuAbi = Build.CPU_ABI;
2908 try {
2909 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
2910
2911 // some architectures are capable of supporting several CPU ABIs
2912 // for example, 'armeabi-v7a' also supports 'armeabi' native code
2913 // this is indicated by the definition of the ro.product.cpu.abi2
2914 // system property.
2915 //
2916 // only scan the package twice in case of ABI mismatch
2917 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
2918 String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
2919 if (cpuAbi2 != null) {
2920 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002922
2923 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
2924 Log.w(TAG,"Native ABI mismatch from package file");
2925 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 }
2927 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002928 } catch (ZipException e) {
2929 Log.w(TAG, "Failed to extract data from package file", e);
2930 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002932 Log.w(TAG, "Failed to cache package shared libs", e);
2933 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002935 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 }
2937
2938 private void cacheSharedLibLI(PackageParser.Package pkg,
2939 ZipFile zipFile, ZipEntry entry,
2940 File sharedLibraryDir,
2941 File sharedLibraryFile) throws IOException {
2942 InputStream inputStream = zipFile.getInputStream(entry);
2943 try {
2944 File tempFile = File.createTempFile("tmp", "tmp", sharedLibraryDir);
2945 String tempFilePath = tempFile.getPath();
2946 // XXX package manager can't change owner, so the lib files for
2947 // now need to be left as world readable and owned by the system.
2948 if (! FileUtils.copyToFile(inputStream, tempFile) ||
2949 ! tempFile.setLastModified(entry.getTime()) ||
2950 FileUtils.setPermissions(tempFilePath,
2951 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
2952 |FileUtils.S_IROTH, -1, -1) != 0 ||
2953 ! tempFile.renameTo(sharedLibraryFile)) {
2954 // Failed to properly write file.
2955 tempFile.delete();
2956 throw new IOException("Couldn't create cached shared lib "
2957 + sharedLibraryFile + " in " + sharedLibraryDir);
2958 }
2959 } finally {
2960 inputStream.close();
2961 }
2962 }
2963
2964 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
2965 if (chatty && Config.LOGD) Log.d(
2966 TAG, "Removing package " + pkg.applicationInfo.packageName );
2967
2968 synchronized (mPackages) {
2969 if (pkg.mPreferredOrder > 0) {
2970 mSettings.mPreferredPackages.remove(pkg);
2971 pkg.mPreferredOrder = 0;
2972 updatePreferredIndicesLP();
2973 }
2974
2975 clearPackagePreferredActivitiesLP(pkg.packageName);
2976
2977 mPackages.remove(pkg.applicationInfo.packageName);
2978 if (pkg.mPath != null) {
2979 mAppDirs.remove(pkg.mPath);
2980 }
2981
2982 PackageSetting ps = (PackageSetting)pkg.mExtras;
2983 if (ps != null && ps.sharedUser != null) {
2984 // XXX don't do this until the data is removed.
2985 if (false) {
2986 ps.sharedUser.packages.remove(ps);
2987 if (ps.sharedUser.packages.size() == 0) {
2988 // Remove.
2989 }
2990 }
2991 }
2992
2993 int N = pkg.providers.size();
2994 StringBuilder r = null;
2995 int i;
2996 for (i=0; i<N; i++) {
2997 PackageParser.Provider p = pkg.providers.get(i);
2998 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
2999 p.info.name));
3000 if (p.info.authority == null) {
3001
3002 /* The is another ContentProvider with this authority when
3003 * this app was installed so this authority is null,
3004 * Ignore it as we don't have to unregister the provider.
3005 */
3006 continue;
3007 }
3008 String names[] = p.info.authority.split(";");
3009 for (int j = 0; j < names.length; j++) {
3010 if (mProviders.get(names[j]) == p) {
3011 mProviders.remove(names[j]);
3012 if (chatty && Config.LOGD) Log.d(
3013 TAG, "Unregistered content provider: " + names[j] +
3014 ", className = " + p.info.name +
3015 ", isSyncable = " + p.info.isSyncable);
3016 }
3017 }
3018 if (chatty) {
3019 if (r == null) {
3020 r = new StringBuilder(256);
3021 } else {
3022 r.append(' ');
3023 }
3024 r.append(p.info.name);
3025 }
3026 }
3027 if (r != null) {
3028 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3029 }
3030
3031 N = pkg.services.size();
3032 r = null;
3033 for (i=0; i<N; i++) {
3034 PackageParser.Service s = pkg.services.get(i);
3035 mServices.removeService(s);
3036 if (chatty) {
3037 if (r == null) {
3038 r = new StringBuilder(256);
3039 } else {
3040 r.append(' ');
3041 }
3042 r.append(s.info.name);
3043 }
3044 }
3045 if (r != null) {
3046 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3047 }
3048
3049 N = pkg.receivers.size();
3050 r = null;
3051 for (i=0; i<N; i++) {
3052 PackageParser.Activity a = pkg.receivers.get(i);
3053 mReceivers.removeActivity(a, "receiver");
3054 if (chatty) {
3055 if (r == null) {
3056 r = new StringBuilder(256);
3057 } else {
3058 r.append(' ');
3059 }
3060 r.append(a.info.name);
3061 }
3062 }
3063 if (r != null) {
3064 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3065 }
3066
3067 N = pkg.activities.size();
3068 r = null;
3069 for (i=0; i<N; i++) {
3070 PackageParser.Activity a = pkg.activities.get(i);
3071 mActivities.removeActivity(a, "activity");
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, " Activities: " + r);
3083 }
3084
3085 N = pkg.permissions.size();
3086 r = null;
3087 for (i=0; i<N; i++) {
3088 PackageParser.Permission p = pkg.permissions.get(i);
3089 boolean tree = false;
3090 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3091 if (bp == null) {
3092 tree = true;
3093 bp = mSettings.mPermissionTrees.get(p.info.name);
3094 }
3095 if (bp != null && bp.perm == p) {
3096 if (bp.type != BasePermission.TYPE_BUILTIN) {
3097 if (tree) {
3098 mSettings.mPermissionTrees.remove(p.info.name);
3099 } else {
3100 mSettings.mPermissions.remove(p.info.name);
3101 }
3102 } else {
3103 bp.perm = null;
3104 }
3105 if (chatty) {
3106 if (r == null) {
3107 r = new StringBuilder(256);
3108 } else {
3109 r.append(' ');
3110 }
3111 r.append(p.info.name);
3112 }
3113 }
3114 }
3115 if (r != null) {
3116 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3117 }
3118
3119 N = pkg.instrumentation.size();
3120 r = null;
3121 for (i=0; i<N; i++) {
3122 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3123 mInstrumentation.remove(a.component);
3124 if (chatty) {
3125 if (r == null) {
3126 r = new StringBuilder(256);
3127 } else {
3128 r.append(' ');
3129 }
3130 r.append(a.info.name);
3131 }
3132 }
3133 if (r != null) {
3134 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3135 }
3136 }
3137 }
3138
3139 private static final boolean isPackageFilename(String name) {
3140 return name != null && name.endsWith(".apk");
3141 }
3142
3143 private void updatePermissionsLP() {
3144 // Make sure there are no dangling permission trees.
3145 Iterator<BasePermission> it = mSettings.mPermissionTrees
3146 .values().iterator();
3147 while (it.hasNext()) {
3148 BasePermission bp = it.next();
3149 if (bp.perm == null) {
3150 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3151 + " from package " + bp.sourcePackage);
3152 it.remove();
3153 }
3154 }
3155
3156 // Make sure all dynamic permissions have been assigned to a package,
3157 // and make sure there are no dangling permissions.
3158 it = mSettings.mPermissions.values().iterator();
3159 while (it.hasNext()) {
3160 BasePermission bp = it.next();
3161 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3162 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3163 + bp.name + " pkg=" + bp.sourcePackage
3164 + " info=" + bp.pendingInfo);
3165 if (bp.perm == null && bp.pendingInfo != null) {
3166 BasePermission tree = findPermissionTreeLP(bp.name);
3167 if (tree != null) {
3168 bp.perm = new PackageParser.Permission(tree.perm.owner,
3169 new PermissionInfo(bp.pendingInfo));
3170 bp.perm.info.packageName = tree.perm.info.packageName;
3171 bp.perm.info.name = bp.name;
3172 bp.uid = tree.uid;
3173 }
3174 }
3175 }
3176 if (bp.perm == null) {
3177 Log.w(TAG, "Removing dangling permission: " + bp.name
3178 + " from package " + bp.sourcePackage);
3179 it.remove();
3180 }
3181 }
3182
3183 // Now update the permissions for all packages, in particular
3184 // replace the granted permissions of the system packages.
3185 for (PackageParser.Package pkg : mPackages.values()) {
3186 grantPermissionsLP(pkg, false);
3187 }
3188 }
3189
3190 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3191 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3192 if (ps == null) {
3193 return;
3194 }
3195 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3196 boolean addedPermission = false;
3197
3198 if (replace) {
3199 ps.permissionsFixed = false;
3200 if (gp == ps) {
3201 gp.grantedPermissions.clear();
3202 gp.gids = mGlobalGids;
3203 }
3204 }
3205
3206 if (gp.gids == null) {
3207 gp.gids = mGlobalGids;
3208 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07003209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 final int N = pkg.requestedPermissions.size();
3211 for (int i=0; i<N; i++) {
3212 String name = pkg.requestedPermissions.get(i);
3213 BasePermission bp = mSettings.mPermissions.get(name);
3214 PackageParser.Permission p = bp != null ? bp.perm : null;
3215 if (false) {
3216 if (gp != ps) {
3217 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3218 + ": " + p);
3219 }
3220 }
3221 if (p != null) {
3222 final String perm = p.info.name;
3223 boolean allowed;
3224 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3225 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3226 allowed = true;
3227 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3228 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003229 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003231 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 == PackageManager.SIGNATURE_MATCH);
3233 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3234 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3235 // For updated system applications, the signatureOrSystem permission
3236 // is granted only if it had been defined by the original application.
3237 if ((pkg.applicationInfo.flags
3238 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3239 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3240 if(sysPs.grantedPermissions.contains(perm)) {
3241 allowed = true;
3242 } else {
3243 allowed = false;
3244 }
3245 } else {
3246 allowed = true;
3247 }
3248 }
3249 }
3250 } else {
3251 allowed = false;
3252 }
3253 if (false) {
3254 if (gp != ps) {
3255 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3256 }
3257 }
3258 if (allowed) {
3259 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3260 && ps.permissionsFixed) {
3261 // If this is an existing, non-system package, then
3262 // we can't add any new permissions to it.
3263 if (!gp.loadedPermissions.contains(perm)) {
3264 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003265 // Except... if this is a permission that was added
3266 // to the platform (note: need to only do this when
3267 // updating the platform).
3268 final int NP = PackageParser.NEW_PERMISSIONS.length;
3269 for (int ip=0; ip<NP; ip++) {
3270 final PackageParser.NewPermissionInfo npi
3271 = PackageParser.NEW_PERMISSIONS[ip];
3272 if (npi.name.equals(perm)
3273 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3274 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003275 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003276 + pkg.packageName);
3277 break;
3278 }
3279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 }
3281 }
3282 if (allowed) {
3283 if (!gp.grantedPermissions.contains(perm)) {
3284 addedPermission = true;
3285 gp.grantedPermissions.add(perm);
3286 gp.gids = appendInts(gp.gids, bp.gids);
3287 }
3288 } else {
3289 Log.w(TAG, "Not granting permission " + perm
3290 + " to package " + pkg.packageName
3291 + " because it was previously installed without");
3292 }
3293 } else {
3294 Log.w(TAG, "Not granting permission " + perm
3295 + " to package " + pkg.packageName
3296 + " (protectionLevel=" + p.info.protectionLevel
3297 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3298 + ")");
3299 }
3300 } else {
3301 Log.w(TAG, "Unknown permission " + name
3302 + " in package " + pkg.packageName);
3303 }
3304 }
3305
3306 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003307 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3308 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 // This is the first that we have heard about this package, so the
3310 // permissions we have now selected are fixed until explicitly
3311 // changed.
3312 ps.permissionsFixed = true;
3313 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3314 }
3315 }
3316
3317 private final class ActivityIntentResolver
3318 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003319 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003321 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 }
3323
Mihai Preda074edef2009-05-18 17:13:31 +02003324 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003326 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3328 }
3329
Mihai Predaeae850c2009-05-13 10:13:48 +02003330 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3331 ArrayList<PackageParser.Activity> packageActivities) {
3332 if (packageActivities == null) {
3333 return null;
3334 }
3335 mFlags = flags;
3336 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3337 int N = packageActivities.size();
3338 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3339 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003340
3341 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003342 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003343 intentFilters = packageActivities.get(i).intents;
3344 if (intentFilters != null && intentFilters.size() > 0) {
3345 listCut.add(intentFilters);
3346 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003347 }
3348 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3349 }
3350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 public final void addActivity(PackageParser.Activity a, String type) {
3352 mActivities.put(a.component, a);
3353 if (SHOW_INFO || Config.LOGV) Log.v(
3354 TAG, " " + type + " " +
3355 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3356 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3357 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003358 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3360 if (SHOW_INFO || Config.LOGV) {
3361 Log.v(TAG, " IntentFilter:");
3362 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3363 }
3364 if (!intent.debugCheck()) {
3365 Log.w(TAG, "==> For Activity " + a.info.name);
3366 }
3367 addFilter(intent);
3368 }
3369 }
3370
3371 public final void removeActivity(PackageParser.Activity a, String type) {
3372 mActivities.remove(a.component);
3373 if (SHOW_INFO || Config.LOGV) Log.v(
3374 TAG, " " + type + " " +
3375 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3376 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3377 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003378 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3380 if (SHOW_INFO || Config.LOGV) {
3381 Log.v(TAG, " IntentFilter:");
3382 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3383 }
3384 removeFilter(intent);
3385 }
3386 }
3387
3388 @Override
3389 protected boolean allowFilterResult(
3390 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3391 ActivityInfo filterAi = filter.activity.info;
3392 for (int i=dest.size()-1; i>=0; i--) {
3393 ActivityInfo destAi = dest.get(i).activityInfo;
3394 if (destAi.name == filterAi.name
3395 && destAi.packageName == filterAi.packageName) {
3396 return false;
3397 }
3398 }
3399 return true;
3400 }
3401
3402 @Override
3403 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3404 int match) {
3405 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3406 return null;
3407 }
3408 final PackageParser.Activity activity = info.activity;
3409 if (mSafeMode && (activity.info.applicationInfo.flags
3410 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3411 return null;
3412 }
3413 final ResolveInfo res = new ResolveInfo();
3414 res.activityInfo = PackageParser.generateActivityInfo(activity,
3415 mFlags);
3416 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3417 res.filter = info;
3418 }
3419 res.priority = info.getPriority();
3420 res.preferredOrder = activity.owner.mPreferredOrder;
3421 //System.out.println("Result: " + res.activityInfo.className +
3422 // " = " + res.priority);
3423 res.match = match;
3424 res.isDefault = info.hasDefault;
3425 res.labelRes = info.labelRes;
3426 res.nonLocalizedLabel = info.nonLocalizedLabel;
3427 res.icon = info.icon;
3428 return res;
3429 }
3430
3431 @Override
3432 protected void sortResults(List<ResolveInfo> results) {
3433 Collections.sort(results, mResolvePrioritySorter);
3434 }
3435
3436 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003437 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003439 out.print(prefix); out.print(
3440 Integer.toHexString(System.identityHashCode(filter.activity)));
3441 out.print(' ');
3442 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 }
3444
3445// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3446// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3447// final List<ResolveInfo> retList = Lists.newArrayList();
3448// while (i.hasNext()) {
3449// final ResolveInfo resolveInfo = i.next();
3450// if (isEnabledLP(resolveInfo.activityInfo)) {
3451// retList.add(resolveInfo);
3452// }
3453// }
3454// return retList;
3455// }
3456
3457 // Keys are String (activity class name), values are Activity.
3458 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3459 = new HashMap<ComponentName, PackageParser.Activity>();
3460 private int mFlags;
3461 }
3462
3463 private final class ServiceIntentResolver
3464 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003465 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003467 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 }
3469
Mihai Preda074edef2009-05-18 17:13:31 +02003470 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003472 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3474 }
3475
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003476 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3477 ArrayList<PackageParser.Service> packageServices) {
3478 if (packageServices == null) {
3479 return null;
3480 }
3481 mFlags = flags;
3482 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3483 int N = packageServices.size();
3484 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3485 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3486
3487 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3488 for (int i = 0; i < N; ++i) {
3489 intentFilters = packageServices.get(i).intents;
3490 if (intentFilters != null && intentFilters.size() > 0) {
3491 listCut.add(intentFilters);
3492 }
3493 }
3494 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3495 }
3496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 public final void addService(PackageParser.Service s) {
3498 mServices.put(s.component, s);
3499 if (SHOW_INFO || Config.LOGV) Log.v(
3500 TAG, " " + (s.info.nonLocalizedLabel != null
3501 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3502 if (SHOW_INFO || Config.LOGV) Log.v(
3503 TAG, " Class=" + s.info.name);
3504 int NI = s.intents.size();
3505 int j;
3506 for (j=0; j<NI; j++) {
3507 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3508 if (SHOW_INFO || Config.LOGV) {
3509 Log.v(TAG, " IntentFilter:");
3510 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3511 }
3512 if (!intent.debugCheck()) {
3513 Log.w(TAG, "==> For Service " + s.info.name);
3514 }
3515 addFilter(intent);
3516 }
3517 }
3518
3519 public final void removeService(PackageParser.Service s) {
3520 mServices.remove(s.component);
3521 if (SHOW_INFO || Config.LOGV) Log.v(
3522 TAG, " " + (s.info.nonLocalizedLabel != null
3523 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3524 if (SHOW_INFO || Config.LOGV) Log.v(
3525 TAG, " Class=" + s.info.name);
3526 int NI = s.intents.size();
3527 int j;
3528 for (j=0; j<NI; j++) {
3529 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3530 if (SHOW_INFO || Config.LOGV) {
3531 Log.v(TAG, " IntentFilter:");
3532 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3533 }
3534 removeFilter(intent);
3535 }
3536 }
3537
3538 @Override
3539 protected boolean allowFilterResult(
3540 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3541 ServiceInfo filterSi = filter.service.info;
3542 for (int i=dest.size()-1; i>=0; i--) {
3543 ServiceInfo destAi = dest.get(i).serviceInfo;
3544 if (destAi.name == filterSi.name
3545 && destAi.packageName == filterSi.packageName) {
3546 return false;
3547 }
3548 }
3549 return true;
3550 }
3551
3552 @Override
3553 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3554 int match) {
3555 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3556 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3557 return null;
3558 }
3559 final PackageParser.Service service = info.service;
3560 if (mSafeMode && (service.info.applicationInfo.flags
3561 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3562 return null;
3563 }
3564 final ResolveInfo res = new ResolveInfo();
3565 res.serviceInfo = PackageParser.generateServiceInfo(service,
3566 mFlags);
3567 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3568 res.filter = filter;
3569 }
3570 res.priority = info.getPriority();
3571 res.preferredOrder = service.owner.mPreferredOrder;
3572 //System.out.println("Result: " + res.activityInfo.className +
3573 // " = " + res.priority);
3574 res.match = match;
3575 res.isDefault = info.hasDefault;
3576 res.labelRes = info.labelRes;
3577 res.nonLocalizedLabel = info.nonLocalizedLabel;
3578 res.icon = info.icon;
3579 return res;
3580 }
3581
3582 @Override
3583 protected void sortResults(List<ResolveInfo> results) {
3584 Collections.sort(results, mResolvePrioritySorter);
3585 }
3586
3587 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003588 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003590 out.print(prefix); out.print(
3591 Integer.toHexString(System.identityHashCode(filter.service)));
3592 out.print(' ');
3593 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 }
3595
3596// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3597// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3598// final List<ResolveInfo> retList = Lists.newArrayList();
3599// while (i.hasNext()) {
3600// final ResolveInfo resolveInfo = (ResolveInfo) i;
3601// if (isEnabledLP(resolveInfo.serviceInfo)) {
3602// retList.add(resolveInfo);
3603// }
3604// }
3605// return retList;
3606// }
3607
3608 // Keys are String (activity class name), values are Activity.
3609 private final HashMap<ComponentName, PackageParser.Service> mServices
3610 = new HashMap<ComponentName, PackageParser.Service>();
3611 private int mFlags;
3612 };
3613
3614 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3615 new Comparator<ResolveInfo>() {
3616 public int compare(ResolveInfo r1, ResolveInfo r2) {
3617 int v1 = r1.priority;
3618 int v2 = r2.priority;
3619 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3620 if (v1 != v2) {
3621 return (v1 > v2) ? -1 : 1;
3622 }
3623 v1 = r1.preferredOrder;
3624 v2 = r2.preferredOrder;
3625 if (v1 != v2) {
3626 return (v1 > v2) ? -1 : 1;
3627 }
3628 if (r1.isDefault != r2.isDefault) {
3629 return r1.isDefault ? -1 : 1;
3630 }
3631 v1 = r1.match;
3632 v2 = r2.match;
3633 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3634 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3635 }
3636 };
3637
3638 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3639 new Comparator<ProviderInfo>() {
3640 public int compare(ProviderInfo p1, ProviderInfo p2) {
3641 final int v1 = p1.initOrder;
3642 final int v2 = p2.initOrder;
3643 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3644 }
3645 };
3646
3647 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3648 IActivityManager am = ActivityManagerNative.getDefault();
3649 if (am != null) {
3650 try {
3651 final Intent intent = new Intent(action,
3652 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3653 if (extras != null) {
3654 intent.putExtras(extras);
3655 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003656 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 am.broadcastIntent(
3658 null, intent,
3659 null, null, 0, null, null, null, false, false);
3660 } catch (RemoteException ex) {
3661 }
3662 }
3663 }
3664
3665 private final class AppDirObserver extends FileObserver {
3666 public AppDirObserver(String path, int mask, boolean isrom) {
3667 super(path, mask);
3668 mRootDir = path;
3669 mIsRom = isrom;
3670 }
3671
3672 public void onEvent(int event, String path) {
3673 String removedPackage = null;
3674 int removedUid = -1;
3675 String addedPackage = null;
3676 int addedUid = -1;
3677
3678 synchronized (mInstallLock) {
3679 String fullPathStr = null;
3680 File fullPath = null;
3681 if (path != null) {
3682 fullPath = new File(mRootDir, path);
3683 fullPathStr = fullPath.getPath();
3684 }
3685
3686 if (Config.LOGV) Log.v(
3687 TAG, "File " + fullPathStr + " changed: "
3688 + Integer.toHexString(event));
3689
3690 if (!isPackageFilename(path)) {
3691 if (Config.LOGV) Log.v(
3692 TAG, "Ignoring change of non-package file: " + fullPathStr);
3693 return;
3694 }
3695
3696 if ((event&REMOVE_EVENTS) != 0) {
3697 synchronized (mInstallLock) {
3698 PackageParser.Package p = mAppDirs.get(fullPathStr);
3699 if (p != null) {
3700 removePackageLI(p, true);
3701 removedPackage = p.applicationInfo.packageName;
3702 removedUid = p.applicationInfo.uid;
3703 }
3704 }
3705 }
3706
3707 if ((event&ADD_EVENTS) != 0) {
3708 PackageParser.Package p = mAppDirs.get(fullPathStr);
3709 if (p == null) {
3710 p = scanPackageLI(fullPath, fullPath, fullPath,
3711 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3712 PackageParser.PARSE_CHATTY |
3713 PackageParser.PARSE_MUST_BE_APK,
3714 SCAN_MONITOR);
3715 if (p != null) {
3716 synchronized (mPackages) {
3717 grantPermissionsLP(p, false);
3718 }
3719 addedPackage = p.applicationInfo.packageName;
3720 addedUid = p.applicationInfo.uid;
3721 }
3722 }
3723 }
3724
3725 synchronized (mPackages) {
3726 mSettings.writeLP();
3727 }
3728 }
3729
3730 if (removedPackage != null) {
3731 Bundle extras = new Bundle(1);
3732 extras.putInt(Intent.EXTRA_UID, removedUid);
3733 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3734 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3735 }
3736 if (addedPackage != null) {
3737 Bundle extras = new Bundle(1);
3738 extras.putInt(Intent.EXTRA_UID, addedUid);
3739 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3740 }
3741 }
3742
3743 private final String mRootDir;
3744 private final boolean mIsRom;
3745 }
Jacek Surazski65e13172009-04-28 15:26:38 +02003746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747 /* Called when a downloaded package installation has been confirmed by the user */
3748 public void installPackage(
3749 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003750 installPackage(packageURI, observer, flags, null);
3751 }
3752
3753 /* Called when a downloaded package installation has been confirmed by the user */
3754 public void installPackage(
3755 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3756 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 mContext.enforceCallingOrSelfPermission(
3758 android.Manifest.permission.INSTALL_PACKAGES, null);
Jacek Surazski65e13172009-04-28 15:26:38 +02003759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 // Queue up an async operation since the package installation may take a little while.
3761 mHandler.post(new Runnable() {
3762 public void run() {
3763 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003764 // Result object to be returned
3765 PackageInstalledInfo res = new PackageInstalledInfo();
3766 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3767 res.uid = -1;
3768 res.pkg = null;
3769 res.removedInfo = new PackageRemovedInfo();
3770 // Make a temporary copy of file from given packageURI
3771 File tmpPackageFile = copyTempInstallFile(packageURI, res);
3772 if (tmpPackageFile != null) {
3773 synchronized (mInstallLock) {
3774 installPackageLI(packageURI, flags, true, installerPackageName, tmpPackageFile, res);
3775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 }
3777 if (observer != null) {
3778 try {
3779 observer.packageInstalled(res.name, res.returnCode);
3780 } catch (RemoteException e) {
3781 Log.i(TAG, "Observer no longer exists.");
3782 }
3783 }
3784 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3785 // call appears in the synchronized block above.
3786 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3787 res.removedInfo.sendBroadcast(false, true);
3788 Bundle extras = new Bundle(1);
3789 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003790 final boolean update = res.removedInfo.removedPackage != null;
3791 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3793 }
3794 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3795 res.pkg.applicationInfo.packageName,
3796 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003797 if (update) {
3798 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3799 res.pkg.applicationInfo.packageName,
3800 extras);
3801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 }
3803 Runtime.getRuntime().gc();
3804 }
3805 });
3806 }
3807
3808 class PackageInstalledInfo {
3809 String name;
3810 int uid;
3811 PackageParser.Package pkg;
3812 int returnCode;
3813 PackageRemovedInfo removedInfo;
3814 }
3815
3816 /*
3817 * Install a non-existing package.
3818 */
3819 private void installNewPackageLI(String pkgName,
3820 File tmpPackageFile,
3821 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003822 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003823 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824 // Remember this for later, in case we need to rollback this install
3825 boolean dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3826 res.name = pkgName;
3827 synchronized(mPackages) {
3828 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(destFilePath)) {
3829 // Don't allow installation over an existing package with the same name.
3830 Log.w(TAG, "Attempt to re-install " + pkgName
3831 + " without first uninstalling.");
3832 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3833 return;
3834 }
3835 }
3836 if (destPackageFile.exists()) {
3837 // It's safe to do this because we know (from the above check) that the file
3838 // isn't currently used for an installed package.
3839 destPackageFile.delete();
3840 }
3841 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3842 PackageParser.Package newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3843 destResourceFile, pkg, 0,
3844 SCAN_MONITOR | SCAN_FORCE_DEX
3845 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003846 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3847 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848 if (newPackage == null) {
3849 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3850 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3851 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3852 }
3853 } else {
3854 updateSettingsLI(pkgName, tmpPackageFile,
3855 destFilePath, destPackageFile,
3856 destResourceFile, pkg,
3857 newPackage,
3858 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02003859 forwardLocked,
3860 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 res);
3862 // delete the partially installed application. the data directory will have to be
3863 // restored if it was already existing
3864 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3865 // remove package from internal structures. Note that we want deletePackageX to
3866 // delete the package data and cache directories that it created in
3867 // scanPackageLocked, unless those directories existed before we even tried to
3868 // install.
3869 deletePackageLI(
3870 pkgName, true,
3871 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3872 res.removedInfo);
3873 }
3874 }
3875 }
3876
3877 private void replacePackageLI(String pkgName,
3878 File tmpPackageFile,
3879 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003880 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003881 String installerPackageName, PackageInstalledInfo res) {
3882
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003883 PackageParser.Package oldPackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 // First find the old package info and check signatures
3885 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003886 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003887 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
3888 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3890 return;
3891 }
3892 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003893 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 if(sysPkg) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003895 replaceSystemPackageLI(oldPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003897 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003898 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 } else {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003900 replaceNonSystemPackageLI(oldPackage, tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003901 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003902 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 }
3904 }
3905
3906 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
3907 File tmpPackageFile,
3908 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003909 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003910 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 PackageParser.Package newPackage = null;
3912 String pkgName = deletedPackage.packageName;
3913 boolean deletedPkg = true;
3914 boolean updatedSettings = false;
Jacek Surazski65e13172009-04-28 15:26:38 +02003915
3916 String oldInstallerPackageName = null;
3917 synchronized (mPackages) {
3918 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3919 }
3920
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003921 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 // First delete the existing package while retaining the data directory
3923 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3924 res.removedInfo)) {
3925 // If the existing package was'nt successfully deleted
3926 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3927 deletedPkg = false;
3928 } else {
3929 // Successfully deleted the old package. Now proceed with re-installation
3930 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3931 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3932 destResourceFile, pkg, parseFlags,
3933 SCAN_MONITOR | SCAN_FORCE_DEX
3934 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003935 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3936 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 if (newPackage == null) {
3938 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3939 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3940 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3941 }
3942 } else {
3943 updateSettingsLI(pkgName, tmpPackageFile,
3944 destFilePath, destPackageFile,
3945 destResourceFile, pkg,
3946 newPackage,
3947 true,
3948 forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003949 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 res);
3951 updatedSettings = true;
3952 }
3953 }
3954
3955 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3956 // If we deleted an exisiting package, the old source and resource files that we
3957 // were keeping around in case we needed them (see below) can now be deleted
3958 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
3959 final ApplicationInfo installedPackageAppInfo =
3960 newPackage.applicationInfo;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003961 deletePackageResourcesLI(pkgName,
3962 !deletedPackageAppInfo.sourceDir
3963 .equals(installedPackageAppInfo.sourceDir)
3964 ? deletedPackageAppInfo.sourceDir : null,
3965 !deletedPackageAppInfo.publicSourceDir
3966 .equals(installedPackageAppInfo.publicSourceDir)
3967 ? deletedPackageAppInfo.publicSourceDir : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 //update signature on the new package setting
3969 //this should always succeed, since we checked the
3970 //signature earlier.
3971 synchronized(mPackages) {
3972 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
3973 parseFlags, true);
3974 }
3975 } else {
3976 // remove package from internal structures. Note that we want deletePackageX to
3977 // delete the package data and cache directories that it created in
3978 // scanPackageLocked, unless those directories existed before we even tried to
3979 // install.
3980 if(updatedSettings) {
3981 deletePackageLI(
3982 pkgName, true,
3983 PackageManager.DONT_DELETE_DATA,
3984 res.removedInfo);
3985 }
3986 // Since we failed to install the new package we need to restore the old
3987 // package that we deleted.
3988 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003989 File restoreFile = new File(deletedPackage.mPath);
3990 if (restoreFile == null) {
3991 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
3992 return;
3993 }
3994 File restoreTmpFile = createTempPackageFile();
3995 if (restoreTmpFile == null) {
3996 Log.e(TAG, "Failed creating temp file when restoring pkg : " + pkgName);
3997 return;
3998 }
3999 if (!FileUtils.copyFile(restoreFile, restoreTmpFile)) {
4000 Log.e(TAG, "Failed copying temp file when restoring pkg : " + pkgName);
4001 return;
4002 }
4003 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4004 restoreRes.removedInfo = new PackageRemovedInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 installPackageLI(
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004006 Uri.fromFile(restoreFile),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004008 ? PackageManager.INSTALL_FORWARD_LOCK
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004009 : 0, false, oldInstallerPackageName, restoreTmpFile, restoreRes);
4010 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4011 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 }
4014 }
4015 }
4016
4017 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
4018 File tmpPackageFile,
4019 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07004020 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02004021 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 PackageParser.Package newPackage = null;
4023 boolean updatedSettings = false;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004024 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 PackageParser.PARSE_IS_SYSTEM;
4026 String packageName = deletedPackage.packageName;
4027 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4028 if (packageName == null) {
4029 Log.w(TAG, "Attempt to delete null packageName.");
4030 return;
4031 }
4032 PackageParser.Package oldPkg;
4033 PackageSetting oldPkgSetting;
4034 synchronized (mPackages) {
4035 oldPkg = mPackages.get(packageName);
4036 oldPkgSetting = mSettings.mPackages.get(packageName);
4037 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4038 (oldPkgSetting == null)) {
4039 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4040 return;
4041 }
4042 }
4043 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4044 res.removedInfo.removedPackage = packageName;
4045 // Remove existing system package
4046 removePackageLI(oldPkg, true);
4047 synchronized (mPackages) {
4048 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4049 }
4050
4051 // Successfully disabled the old package. Now proceed with re-installation
4052 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4053 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4054 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
4055 destResourceFile, pkg, parseFlags,
4056 SCAN_MONITOR | SCAN_FORCE_DEX
4057 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07004058 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
4059 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 if (newPackage == null) {
4061 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
4062 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4063 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4064 }
4065 } else {
4066 updateSettingsLI(packageName, tmpPackageFile,
4067 destFilePath, destPackageFile,
4068 destResourceFile, pkg,
4069 newPackage,
4070 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02004071 forwardLocked,
4072 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 res);
4074 updatedSettings = true;
4075 }
4076
4077 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4078 //update signature on the new package setting
4079 //this should always succeed, since we checked the
4080 //signature earlier.
4081 synchronized(mPackages) {
4082 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4083 parseFlags, true);
4084 }
4085 } else {
4086 // Re installation failed. Restore old information
4087 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004088 if (newPackage != null) {
4089 removePackageLI(newPackage, true);
4090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 // Add back the old system package
4092 scanPackageLI(oldPkgSetting.codePath, oldPkgSetting.codePath,
4093 oldPkgSetting.resourcePath,
4094 oldPkg, parseFlags,
4095 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004096 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 // Restore the old system information in Settings
4098 synchronized(mPackages) {
4099 if(updatedSettings) {
4100 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004101 mSettings.setInstallerPackageName(packageName,
4102 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 }
4104 mSettings.writeLP();
4105 }
4106 }
4107 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 private void updateSettingsLI(String pkgName, File tmpPackageFile,
4110 String destFilePath, File destPackageFile,
4111 File destResourceFile,
4112 PackageParser.Package pkg,
4113 PackageParser.Package newPackage,
4114 boolean replacingExistingPackage,
4115 boolean forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02004116 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 synchronized (mPackages) {
4118 //write settings. the installStatus will be incomplete at this stage.
4119 //note that the new package setting would have already been
4120 //added to mPackages. It hasn't been persisted yet.
4121 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4122 mSettings.writeLP();
4123 }
4124
4125 int retCode = 0;
4126 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4127 retCode = mInstaller.movedex(tmpPackageFile.toString(),
4128 destPackageFile.toString());
4129 if (retCode != 0) {
4130 Log.e(TAG, "Couldn't rename dex file: " + destPackageFile);
4131 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4132 return;
4133 }
4134 }
4135 // XXX There are probably some big issues here: upon doing
4136 // the rename, we have reached the point of no return (the
4137 // original .apk is gone!), so we can't fail. Yet... we can.
4138 if (!tmpPackageFile.renameTo(destPackageFile)) {
4139 Log.e(TAG, "Couldn't move package file to: " + destPackageFile);
4140 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4141 } else {
4142 res.returnCode = setPermissionsLI(pkgName, newPackage, destFilePath,
4143 destResourceFile,
4144 forwardLocked);
4145 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4146 return;
4147 } else {
4148 Log.d(TAG, "New package installed in " + destPackageFile);
4149 }
4150 }
4151 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4152 if (mInstaller != null) {
4153 mInstaller.rmdex(tmpPackageFile.getPath());
4154 }
4155 }
4156
4157 synchronized (mPackages) {
4158 grantPermissionsLP(newPackage, true);
4159 res.name = pkgName;
4160 res.uid = newPackage.applicationInfo.uid;
4161 res.pkg = newPackage;
4162 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004163 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4165 //to update install status
4166 mSettings.writeLP();
4167 }
4168 }
4169
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07004170 private File getFwdLockedResource(String pkgName) {
4171 final String publicZipFileName = pkgName + ".zip";
4172 return new File(mAppInstallDir, publicZipFileName);
4173 }
4174
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004175 private File copyTempInstallFile(Uri pPackageURI,
4176 PackageInstalledInfo res) {
4177 File tmpPackageFile = createTempPackageFile();
4178 int retCode = PackageManager.INSTALL_SUCCEEDED;
4179 if (tmpPackageFile == null) {
4180 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4181 return null;
4182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004184 if (pPackageURI.getScheme().equals("file")) {
4185 final File srcPackageFile = new File(pPackageURI.getPath());
4186 // We copy the source package file to a temp file and then rename it to the
4187 // destination file in order to eliminate a window where the package directory
4188 // scanner notices the new package file but it's not completely copied yet.
4189 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
4190 Log.e(TAG, "Couldn't copy package file to temp file.");
4191 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004193 } else if (pPackageURI.getScheme().equals("content")) {
4194 ParcelFileDescriptor fd = null;
4195 try {
4196 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
4197 } catch (FileNotFoundException e) {
4198 Log.e(TAG, "Couldn't open file descriptor from download service. Failed with exception " + e);
4199 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4200 }
4201 if (fd == null) {
4202 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
4203 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4204 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 if (Config.LOGV) {
4206 Log.v(TAG, "Opened file descriptor from download service.");
4207 }
4208 ParcelFileDescriptor.AutoCloseInputStream
4209 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
4210 // We copy the source package file to a temp file and then rename it to the
4211 // destination file in order to eliminate a window where the package directory
4212 // scanner notices the new package file but it's not completely copied yet.
4213 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
4214 Log.e(TAG, "Couldn't copy package stream to temp file.");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004215 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004218 } else {
4219 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
4220 retCode = PackageManager.INSTALL_FAILED_INVALID_URI;
4221 }
4222
4223 res.returnCode = retCode;
4224 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
4225 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4226 tmpPackageFile.delete();
4227 }
4228 return null;
4229 }
4230 return tmpPackageFile;
4231 }
4232
4233 private void installPackageLI(Uri pPackageURI,
4234 int pFlags, boolean newInstall, String installerPackageName,
4235 File tmpPackageFile, PackageInstalledInfo res) {
4236 String pkgName = null;
4237 boolean forwardLocked = false;
4238 boolean replacingExistingPackage = false;
4239 // Result object to be returned
4240 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4241
4242 main_flow: try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 pkgName = PackageParser.parsePackageName(
4244 tmpPackageFile.getAbsolutePath(), 0);
4245 if (pkgName == null) {
4246 Log.e(TAG, "Couldn't find a package name in : " + tmpPackageFile);
4247 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4248 break main_flow;
4249 }
4250 res.name = pkgName;
4251 //initialize some variables before installing pkg
4252 final String pkgFileName = pkgName + ".apk";
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004253 final File destDir = ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 ? mDrmAppPrivateInstallDir
4255 : mAppInstallDir;
4256 final File destPackageFile = new File(destDir, pkgFileName);
4257 final String destFilePath = destPackageFile.getAbsolutePath();
4258 File destResourceFile;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004259 if ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0) {
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07004260 destResourceFile = getFwdLockedResource(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 forwardLocked = true;
4262 } else {
4263 destResourceFile = destPackageFile;
4264 }
4265 // Retrieve PackageSettings and parse package
4266 int parseFlags = PackageParser.PARSE_CHATTY;
4267 parseFlags |= mDefParseFlags;
4268 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4269 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
4271 destPackageFile.getAbsolutePath(), mMetrics, parseFlags);
4272 if (pkg == null) {
4273 res.returnCode = pp.getParseError();
4274 break main_flow;
4275 }
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004276 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4277 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4278 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4279 break main_flow;
4280 }
4281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4283 res.returnCode = pp.getParseError();
4284 break main_flow;
4285 }
4286
4287 synchronized (mPackages) {
4288 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004289 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 && mPackages.containsKey(pkgName)) {
4291 replacingExistingPackage = true;
4292 }
4293 }
4294
4295 if(replacingExistingPackage) {
4296 replacePackageLI(pkgName,
4297 tmpPackageFile,
4298 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02004299 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 res);
4301 } else {
4302 installNewPackageLI(pkgName,
4303 tmpPackageFile,
4304 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02004305 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 res);
4307 }
4308 } finally {
4309 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4310 tmpPackageFile.delete();
4311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 }
4313 }
4314
4315 private int setPermissionsLI(String pkgName,
4316 PackageParser.Package newPackage,
4317 String destFilePath,
4318 File destResourceFile,
4319 boolean forwardLocked) {
4320 int retCode;
4321 if (forwardLocked) {
4322 try {
4323 extractPublicFiles(newPackage, destResourceFile);
4324 } catch (IOException e) {
4325 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
4326 " forward-locked app.");
4327 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4328 } finally {
4329 //TODO clean up the extracted public files
4330 }
4331 if (mInstaller != null) {
4332 retCode = mInstaller.setForwardLockPerm(pkgName,
4333 newPackage.applicationInfo.uid);
4334 } else {
4335 final int filePermissions =
4336 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
4337 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1,
4338 newPackage.applicationInfo.uid);
4339 }
4340 } else {
4341 final int filePermissions =
4342 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4343 |FileUtils.S_IROTH;
4344 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1, -1);
4345 }
4346 if (retCode != 0) {
4347 Log.e(TAG, "Couldn't set new package file permissions for " + destFilePath
4348 + ". The return code was: " + retCode);
4349 }
4350 return PackageManager.INSTALL_SUCCEEDED;
4351 }
4352
4353 private boolean isForwardLocked(PackageParser.Package deletedPackage) {
4354 final ApplicationInfo applicationInfo = deletedPackage.applicationInfo;
4355 return applicationInfo.sourceDir.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath());
4356 }
4357
4358 private void extractPublicFiles(PackageParser.Package newPackage,
4359 File publicZipFile) throws IOException {
4360 final ZipOutputStream publicZipOutStream =
4361 new ZipOutputStream(new FileOutputStream(publicZipFile));
4362 final ZipFile privateZip = new ZipFile(newPackage.mPath);
4363
4364 // Copy manifest, resources.arsc and res directory to public zip
4365
4366 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
4367 while (privateZipEntries.hasMoreElements()) {
4368 final ZipEntry zipEntry = privateZipEntries.nextElement();
4369 final String zipEntryName = zipEntry.getName();
4370 if ("AndroidManifest.xml".equals(zipEntryName)
4371 || "resources.arsc".equals(zipEntryName)
4372 || zipEntryName.startsWith("res/")) {
4373 try {
4374 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
4375 } catch (IOException e) {
4376 try {
4377 publicZipOutStream.close();
4378 throw e;
4379 } finally {
4380 publicZipFile.delete();
4381 }
4382 }
4383 }
4384 }
4385
4386 publicZipOutStream.close();
4387 FileUtils.setPermissions(
4388 publicZipFile.getAbsolutePath(),
4389 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4390 -1, -1);
4391 }
4392
4393 private static void copyZipEntry(ZipEntry zipEntry,
4394 ZipFile inZipFile,
4395 ZipOutputStream outZipStream) throws IOException {
4396 byte[] buffer = new byte[4096];
4397 int num;
4398
4399 ZipEntry newEntry;
4400 if (zipEntry.getMethod() == ZipEntry.STORED) {
4401 // Preserve the STORED method of the input entry.
4402 newEntry = new ZipEntry(zipEntry);
4403 } else {
4404 // Create a new entry so that the compressed len is recomputed.
4405 newEntry = new ZipEntry(zipEntry.getName());
4406 }
4407 outZipStream.putNextEntry(newEntry);
4408
4409 InputStream data = inZipFile.getInputStream(zipEntry);
4410 while ((num = data.read(buffer)) > 0) {
4411 outZipStream.write(buffer, 0, num);
4412 }
4413 outZipStream.flush();
4414 }
4415
4416 private void deleteTempPackageFiles() {
4417 FilenameFilter filter = new FilenameFilter() {
4418 public boolean accept(File dir, String name) {
4419 return name.startsWith("vmdl") && name.endsWith(".tmp");
4420 }
4421 };
4422 String tmpFilesList[] = mAppInstallDir.list(filter);
4423 if(tmpFilesList == null) {
4424 return;
4425 }
4426 for(int i = 0; i < tmpFilesList.length; i++) {
4427 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4428 tmpFile.delete();
4429 }
4430 }
4431
4432 private File createTempPackageFile() {
4433 File tmpPackageFile;
4434 try {
4435 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
4436 } catch (IOException e) {
4437 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4438 return null;
4439 }
4440 try {
4441 FileUtils.setPermissions(
4442 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4443 -1, -1);
4444 } catch (IOException e) {
4445 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4446 return null;
4447 }
4448 return tmpPackageFile;
4449 }
4450
4451 public void deletePackage(final String packageName,
4452 final IPackageDeleteObserver observer,
4453 final int flags) {
4454 mContext.enforceCallingOrSelfPermission(
4455 android.Manifest.permission.DELETE_PACKAGES, null);
4456 // Queue up an async operation since the package deletion may take a little while.
4457 mHandler.post(new Runnable() {
4458 public void run() {
4459 mHandler.removeCallbacks(this);
4460 final boolean succeded = deletePackageX(packageName, true, true, flags);
4461 if (observer != null) {
4462 try {
4463 observer.packageDeleted(succeded);
4464 } catch (RemoteException e) {
4465 Log.i(TAG, "Observer no longer exists.");
4466 } //end catch
4467 } //end if
4468 } //end run
4469 });
4470 }
4471
4472 /**
4473 * This method is an internal method that could be get invoked either
4474 * to delete an installed package or to clean up a failed installation.
4475 * After deleting an installed package, a broadcast is sent to notify any
4476 * listeners that the package has been installed. For cleaning up a failed
4477 * installation, the broadcast is not necessary since the package's
4478 * installation wouldn't have sent the initial broadcast either
4479 * The key steps in deleting a package are
4480 * deleting the package information in internal structures like mPackages,
4481 * deleting the packages base directories through installd
4482 * updating mSettings to reflect current status
4483 * persisting settings for later use
4484 * sending a broadcast if necessary
4485 */
4486
4487 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4488 boolean deleteCodeAndResources, int flags) {
4489 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004490 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491
4492 synchronized (mInstallLock) {
4493 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4494 }
4495
4496 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004497 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4498 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4499
4500 // If the removed package was a system update, the old system packaged
4501 // was re-enabled; we need to broadcast this information
4502 if (systemUpdate) {
4503 Bundle extras = new Bundle(1);
4504 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4505 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4506
4507 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4508 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 }
4511 return res;
4512 }
4513
4514 static class PackageRemovedInfo {
4515 String removedPackage;
4516 int uid = -1;
4517 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004518 boolean isRemovedPackageSystemUpdate = false;
4519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 void sendBroadcast(boolean fullRemove, boolean replacing) {
4521 Bundle extras = new Bundle(1);
4522 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4523 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4524 if (replacing) {
4525 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4526 }
4527 if (removedPackage != null) {
4528 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4529 }
4530 if (removedUid >= 0) {
4531 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4532 }
4533 }
4534 }
4535
4536 /*
4537 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4538 * flag is not set, the data directory is removed as well.
4539 * make sure this flag is set for partially installed apps. If not its meaningless to
4540 * delete a partially installed application.
4541 */
4542 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
4543 int flags) {
4544 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004545 if (outInfo != null) {
4546 outInfo.removedPackage = packageName;
4547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004548 removePackageLI(p, true);
4549 // Retrieve object to delete permissions for shared user later on
4550 PackageSetting deletedPs;
4551 synchronized (mPackages) {
4552 deletedPs = mSettings.mPackages.get(packageName);
4553 }
4554 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
4555 if (mInstaller != null) {
4556 int retCode = mInstaller.remove(packageName);
4557 if (retCode < 0) {
4558 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4559 + packageName + ", retcode=" + retCode);
4560 // we don't consider this to be a failure of the core package deletion
4561 }
4562 } else {
4563 //for emulator
4564 PackageParser.Package pkg = mPackages.get(packageName);
4565 File dataDir = new File(pkg.applicationInfo.dataDir);
4566 dataDir.delete();
4567 }
4568 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004569 if (outInfo != null) {
4570 outInfo.removedUid = mSettings.removePackageLP(packageName);
4571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 }
4573 }
4574 synchronized (mPackages) {
4575 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4576 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004577 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 }
4579 // Save settings now
4580 mSettings.writeLP ();
4581 }
4582 }
4583
4584 /*
4585 * Tries to delete system package.
4586 */
4587 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004588 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 ApplicationInfo applicationInfo = p.applicationInfo;
4590 //applicable for non-partially installed applications only
4591 if (applicationInfo == null) {
4592 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4593 return false;
4594 }
4595 PackageSetting ps = null;
4596 // Confirm if the system package has been updated
4597 // An updated system app can be deleted. This will also have to restore
4598 // the system pkg from system partition
4599 synchronized (mPackages) {
4600 ps = mSettings.getDisabledSystemPkg(p.packageName);
4601 }
4602 if (ps == null) {
4603 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4604 return false;
4605 } else {
4606 Log.i(TAG, "Deleting system pkg from data partition");
4607 }
4608 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004609 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004610 boolean deleteCodeAndResources = false;
4611 if (ps.versionCode < p.mVersionCode) {
4612 // Delete code and resources for downgrades
4613 deleteCodeAndResources = true;
4614 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4615 flags &= ~PackageManager.DONT_DELETE_DATA;
4616 }
4617 } else {
4618 // Preserve data by setting flag
4619 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4620 flags |= PackageManager.DONT_DELETE_DATA;
4621 }
4622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4624 if (!ret) {
4625 return false;
4626 }
4627 synchronized (mPackages) {
4628 // Reinstate the old system package
4629 mSettings.enableSystemPackageLP(p.packageName);
4630 }
4631 // Install the system package
4632 PackageParser.Package newPkg = scanPackageLI(ps.codePath, ps.codePath, ps.resourcePath,
4633 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
4634 SCAN_MONITOR);
4635
4636 if (newPkg == null) {
4637 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4638 return false;
4639 }
4640 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07004641 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004642 mSettings.writeLP();
4643 }
4644 return true;
4645 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004646
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004647 private void deletePackageResourcesLI(String packageName,
4648 String sourceDir, String publicSourceDir) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004649 if (sourceDir != null) {
4650 File sourceFile = new File(sourceDir);
4651 if (!sourceFile.exists()) {
4652 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4653 }
4654 // Delete application's code and resources
4655 sourceFile.delete();
4656 if (mInstaller != null) {
4657 int retCode = mInstaller.rmdex(sourceFile.toString());
4658 if (retCode < 0) {
4659 Log.w(TAG, "Couldn't remove dex file for package: "
4660 + packageName + " at location "
4661 + sourceFile.toString() + ", retcode=" + retCode);
4662 // we don't consider this to be a failure of the core package deletion
4663 }
4664 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004665 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004666 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4667 final File publicSourceFile = new File(publicSourceDir);
4668 if (!publicSourceFile.exists()) {
4669 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4670 }
4671 if (publicSourceFile.exists()) {
4672 publicSourceFile.delete();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004673 }
4674 }
4675 }
4676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4678 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4679 ApplicationInfo applicationInfo = p.applicationInfo;
4680 if (applicationInfo == null) {
4681 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4682 return false;
4683 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004684 if (outInfo != null) {
4685 outInfo.uid = applicationInfo.uid;
4686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687
4688 // Delete package data from internal structures and also remove data if flag is set
4689 removePackageDataLI(p, outInfo, flags);
4690
4691 // Delete application code and resources
4692 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004693 deletePackageResourcesLI(applicationInfo.packageName,
4694 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 }
4696 return true;
4697 }
4698
4699 /*
4700 * This method handles package deletion in general
4701 */
4702 private boolean deletePackageLI(String packageName,
4703 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4704 if (packageName == null) {
4705 Log.w(TAG, "Attempt to delete null packageName.");
4706 return false;
4707 }
4708 PackageParser.Package p;
4709 boolean dataOnly = false;
4710 synchronized (mPackages) {
4711 p = mPackages.get(packageName);
4712 if (p == null) {
4713 //this retrieves partially installed apps
4714 dataOnly = true;
4715 PackageSetting ps = mSettings.mPackages.get(packageName);
4716 if (ps == null) {
4717 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4718 return false;
4719 }
4720 p = ps.pkg;
4721 }
4722 }
4723 if (p == null) {
4724 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4725 return false;
4726 }
4727
4728 if (dataOnly) {
4729 // Delete application data first
4730 removePackageDataLI(p, outInfo, flags);
4731 return true;
4732 }
4733 // At this point the package should have ApplicationInfo associated with it
4734 if (p.applicationInfo == null) {
4735 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4736 return false;
4737 }
4738 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4739 Log.i(TAG, "Removing system package:"+p.packageName);
4740 // When an updated system application is deleted we delete the existing resources as well and
4741 // fall back to existing code in system partition
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004742 return deleteSystemPackageLI(p, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004743 }
4744 Log.i(TAG, "Removing non-system package:"+p.packageName);
4745 return deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
4746 }
4747
4748 public void clearApplicationUserData(final String packageName,
4749 final IPackageDataObserver observer) {
4750 mContext.enforceCallingOrSelfPermission(
4751 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4752 // Queue up an async operation since the package deletion may take a little while.
4753 mHandler.post(new Runnable() {
4754 public void run() {
4755 mHandler.removeCallbacks(this);
4756 final boolean succeeded;
4757 synchronized (mInstallLock) {
4758 succeeded = clearApplicationUserDataLI(packageName);
4759 }
4760 if (succeeded) {
4761 // invoke DeviceStorageMonitor's update method to clear any notifications
4762 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4763 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4764 if (dsm != null) {
4765 dsm.updateMemory();
4766 }
4767 }
4768 if(observer != null) {
4769 try {
4770 observer.onRemoveCompleted(packageName, succeeded);
4771 } catch (RemoteException e) {
4772 Log.i(TAG, "Observer no longer exists.");
4773 }
4774 } //end if observer
4775 } //end run
4776 });
4777 }
4778
4779 private boolean clearApplicationUserDataLI(String packageName) {
4780 if (packageName == null) {
4781 Log.w(TAG, "Attempt to delete null packageName.");
4782 return false;
4783 }
4784 PackageParser.Package p;
4785 boolean dataOnly = false;
4786 synchronized (mPackages) {
4787 p = mPackages.get(packageName);
4788 if(p == null) {
4789 dataOnly = true;
4790 PackageSetting ps = mSettings.mPackages.get(packageName);
4791 if((ps == null) || (ps.pkg == null)) {
4792 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4793 return false;
4794 }
4795 p = ps.pkg;
4796 }
4797 }
4798 if(!dataOnly) {
4799 //need to check this only for fully installed applications
4800 if (p == null) {
4801 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4802 return false;
4803 }
4804 final ApplicationInfo applicationInfo = p.applicationInfo;
4805 if (applicationInfo == null) {
4806 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4807 return false;
4808 }
4809 }
4810 if (mInstaller != null) {
4811 int retCode = mInstaller.clearUserData(packageName);
4812 if (retCode < 0) {
4813 Log.w(TAG, "Couldn't remove cache files for package: "
4814 + packageName);
4815 return false;
4816 }
4817 }
4818 return true;
4819 }
4820
4821 public void deleteApplicationCacheFiles(final String packageName,
4822 final IPackageDataObserver observer) {
4823 mContext.enforceCallingOrSelfPermission(
4824 android.Manifest.permission.DELETE_CACHE_FILES, null);
4825 // Queue up an async operation since the package deletion may take a little while.
4826 mHandler.post(new Runnable() {
4827 public void run() {
4828 mHandler.removeCallbacks(this);
4829 final boolean succeded;
4830 synchronized (mInstallLock) {
4831 succeded = deleteApplicationCacheFilesLI(packageName);
4832 }
4833 if(observer != null) {
4834 try {
4835 observer.onRemoveCompleted(packageName, succeded);
4836 } catch (RemoteException e) {
4837 Log.i(TAG, "Observer no longer exists.");
4838 }
4839 } //end if observer
4840 } //end run
4841 });
4842 }
4843
4844 private boolean deleteApplicationCacheFilesLI(String packageName) {
4845 if (packageName == null) {
4846 Log.w(TAG, "Attempt to delete null packageName.");
4847 return false;
4848 }
4849 PackageParser.Package p;
4850 synchronized (mPackages) {
4851 p = mPackages.get(packageName);
4852 }
4853 if (p == null) {
4854 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4855 return false;
4856 }
4857 final ApplicationInfo applicationInfo = p.applicationInfo;
4858 if (applicationInfo == null) {
4859 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4860 return false;
4861 }
4862 if (mInstaller != null) {
4863 int retCode = mInstaller.deleteCacheFiles(packageName);
4864 if (retCode < 0) {
4865 Log.w(TAG, "Couldn't remove cache files for package: "
4866 + packageName);
4867 return false;
4868 }
4869 }
4870 return true;
4871 }
4872
4873 public void getPackageSizeInfo(final String packageName,
4874 final IPackageStatsObserver observer) {
4875 mContext.enforceCallingOrSelfPermission(
4876 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4877 // Queue up an async operation since the package deletion may take a little while.
4878 mHandler.post(new Runnable() {
4879 public void run() {
4880 mHandler.removeCallbacks(this);
4881 PackageStats lStats = new PackageStats(packageName);
4882 final boolean succeded;
4883 synchronized (mInstallLock) {
4884 succeded = getPackageSizeInfoLI(packageName, lStats);
4885 }
4886 if(observer != null) {
4887 try {
4888 observer.onGetStatsCompleted(lStats, succeded);
4889 } catch (RemoteException e) {
4890 Log.i(TAG, "Observer no longer exists.");
4891 }
4892 } //end if observer
4893 } //end run
4894 });
4895 }
4896
4897 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4898 if (packageName == null) {
4899 Log.w(TAG, "Attempt to get size of null packageName.");
4900 return false;
4901 }
4902 PackageParser.Package p;
4903 boolean dataOnly = false;
4904 synchronized (mPackages) {
4905 p = mPackages.get(packageName);
4906 if(p == null) {
4907 dataOnly = true;
4908 PackageSetting ps = mSettings.mPackages.get(packageName);
4909 if((ps == null) || (ps.pkg == null)) {
4910 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4911 return false;
4912 }
4913 p = ps.pkg;
4914 }
4915 }
4916 String publicSrcDir = null;
4917 if(!dataOnly) {
4918 final ApplicationInfo applicationInfo = p.applicationInfo;
4919 if (applicationInfo == null) {
4920 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4921 return false;
4922 }
4923 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4924 }
4925 if (mInstaller != null) {
4926 int res = mInstaller.getSizeInfo(packageName, p.mPath,
4927 publicSrcDir, pStats);
4928 if (res < 0) {
4929 return false;
4930 } else {
4931 return true;
4932 }
4933 }
4934 return true;
4935 }
4936
4937
4938 public void addPackageToPreferred(String packageName) {
4939 mContext.enforceCallingOrSelfPermission(
4940 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4941
4942 synchronized (mPackages) {
4943 PackageParser.Package p = mPackages.get(packageName);
4944 if (p == null) {
4945 return;
4946 }
4947 PackageSetting ps = (PackageSetting)p.mExtras;
4948 if (ps != null) {
4949 mSettings.mPreferredPackages.remove(ps);
4950 mSettings.mPreferredPackages.add(0, ps);
4951 updatePreferredIndicesLP();
4952 mSettings.writeLP();
4953 }
4954 }
4955 }
4956
4957 public void removePackageFromPreferred(String packageName) {
4958 mContext.enforceCallingOrSelfPermission(
4959 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4960
4961 synchronized (mPackages) {
4962 PackageParser.Package p = mPackages.get(packageName);
4963 if (p == null) {
4964 return;
4965 }
4966 if (p.mPreferredOrder > 0) {
4967 PackageSetting ps = (PackageSetting)p.mExtras;
4968 if (ps != null) {
4969 mSettings.mPreferredPackages.remove(ps);
4970 p.mPreferredOrder = 0;
4971 updatePreferredIndicesLP();
4972 mSettings.writeLP();
4973 }
4974 }
4975 }
4976 }
4977
4978 private void updatePreferredIndicesLP() {
4979 final ArrayList<PackageSetting> pkgs
4980 = mSettings.mPreferredPackages;
4981 final int N = pkgs.size();
4982 for (int i=0; i<N; i++) {
4983 pkgs.get(i).pkg.mPreferredOrder = N - i;
4984 }
4985 }
4986
4987 public List<PackageInfo> getPreferredPackages(int flags) {
4988 synchronized (mPackages) {
4989 final ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
4990 final ArrayList<PackageSetting> pref = mSettings.mPreferredPackages;
4991 final int N = pref.size();
4992 for (int i=0; i<N; i++) {
4993 res.add(generatePackageInfo(pref.get(i).pkg, flags));
4994 }
4995 return res;
4996 }
4997 }
4998
4999 public void addPreferredActivity(IntentFilter filter, int match,
5000 ComponentName[] set, ComponentName activity) {
5001 mContext.enforceCallingOrSelfPermission(
5002 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5003
5004 synchronized (mPackages) {
5005 Log.i(TAG, "Adding preferred activity " + activity + ":");
5006 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5007 mSettings.mPreferredActivities.addFilter(
5008 new PreferredActivity(filter, match, set, activity));
5009 mSettings.writeLP();
5010 }
5011 }
5012
Satish Sampath8dbe6122009-06-02 23:35:54 +01005013 public void replacePreferredActivity(IntentFilter filter, int match,
5014 ComponentName[] set, ComponentName activity) {
5015 mContext.enforceCallingOrSelfPermission(
5016 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5017 if (filter.countActions() != 1) {
5018 throw new IllegalArgumentException(
5019 "replacePreferredActivity expects filter to have only 1 action.");
5020 }
5021 if (filter.countCategories() != 1) {
5022 throw new IllegalArgumentException(
5023 "replacePreferredActivity expects filter to have only 1 category.");
5024 }
5025 if (filter.countDataAuthorities() != 0
5026 || filter.countDataPaths() != 0
5027 || filter.countDataSchemes() != 0
5028 || filter.countDataTypes() != 0) {
5029 throw new IllegalArgumentException(
5030 "replacePreferredActivity expects filter to have no data authorities, " +
5031 "paths, schemes or types.");
5032 }
5033 synchronized (mPackages) {
5034 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5035 String action = filter.getAction(0);
5036 String category = filter.getCategory(0);
5037 while (it.hasNext()) {
5038 PreferredActivity pa = it.next();
5039 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5040 it.remove();
5041 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5042 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5043 }
5044 }
5045 addPreferredActivity(filter, match, set, activity);
5046 }
5047 }
5048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005049 public void clearPackagePreferredActivities(String packageName) {
5050 mContext.enforceCallingOrSelfPermission(
5051 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5052
5053 synchronized (mPackages) {
5054 if (clearPackagePreferredActivitiesLP(packageName)) {
5055 mSettings.writeLP();
5056 }
5057 }
5058 }
5059
5060 boolean clearPackagePreferredActivitiesLP(String packageName) {
5061 boolean changed = false;
5062 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5063 while (it.hasNext()) {
5064 PreferredActivity pa = it.next();
5065 if (pa.mActivity.getPackageName().equals(packageName)) {
5066 it.remove();
5067 changed = true;
5068 }
5069 }
5070 return changed;
5071 }
5072
5073 public int getPreferredActivities(List<IntentFilter> outFilters,
5074 List<ComponentName> outActivities, String packageName) {
5075
5076 int num = 0;
5077 synchronized (mPackages) {
5078 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5079 while (it.hasNext()) {
5080 PreferredActivity pa = it.next();
5081 if (packageName == null
5082 || pa.mActivity.getPackageName().equals(packageName)) {
5083 if (outFilters != null) {
5084 outFilters.add(new IntentFilter(pa));
5085 }
5086 if (outActivities != null) {
5087 outActivities.add(pa.mActivity);
5088 }
5089 }
5090 }
5091 }
5092
5093 return num;
5094 }
5095
5096 public void setApplicationEnabledSetting(String appPackageName,
5097 int newState, int flags) {
5098 setEnabledSetting(appPackageName, null, newState, flags);
5099 }
5100
5101 public void setComponentEnabledSetting(ComponentName componentName,
5102 int newState, int flags) {
5103 setEnabledSetting(componentName.getPackageName(),
5104 componentName.getClassName(), newState, flags);
5105 }
5106
5107 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005108 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5110 || newState == COMPONENT_ENABLED_STATE_ENABLED
5111 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5112 throw new IllegalArgumentException("Invalid new component state: "
5113 + newState);
5114 }
5115 PackageSetting pkgSetting;
5116 final int uid = Binder.getCallingUid();
5117 final int permission = mContext.checkCallingPermission(
5118 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5119 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005120 boolean sendNow = false;
5121 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005122 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005124 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005126 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005127 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005128 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005130 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005131 }
5132 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005133 "Unknown component: " + packageName
5134 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 }
5136 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5137 throw new SecurityException(
5138 "Permission Denial: attempt to change component state from pid="
5139 + Binder.getCallingPid()
5140 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5141 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005142 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 // We're dealing with an application/package level state change
5144 pkgSetting.enabled = newState;
5145 } else {
5146 // We're dealing with a component level state change
5147 switch (newState) {
5148 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005149 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 break;
5151 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005152 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153 break;
5154 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005155 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 break;
5157 default:
5158 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005159 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005160 }
5161 }
5162 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005163 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005164 components = mPendingBroadcasts.get(packageName);
5165 boolean newPackage = components == null;
5166 if (newPackage) {
5167 components = new ArrayList<String>();
5168 }
5169 if (!components.contains(componentName)) {
5170 components.add(componentName);
5171 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005172 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5173 sendNow = true;
5174 // Purge entry from pending broadcast list if another one exists already
5175 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005176 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005177 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005178 if (newPackage) {
5179 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005180 }
5181 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5182 // Schedule a message
5183 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5184 }
5185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188 long callingId = Binder.clearCallingIdentity();
5189 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005190 if (sendNow) {
5191 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005192 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005194 } finally {
5195 Binder.restoreCallingIdentity(callingId);
5196 }
5197 }
5198
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005199 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005200 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5201 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5202 + " components=" + componentNames);
5203 Bundle extras = new Bundle(4);
5204 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5205 String nameList[] = new String[componentNames.size()];
5206 componentNames.toArray(nameList);
5207 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005208 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5209 extras.putInt(Intent.EXTRA_UID, packageUid);
5210 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
5211 }
5212
Jacek Surazski65e13172009-04-28 15:26:38 +02005213 public String getInstallerPackageName(String packageName) {
5214 synchronized (mPackages) {
5215 PackageSetting pkg = mSettings.mPackages.get(packageName);
5216 if (pkg == null) {
5217 throw new IllegalArgumentException("Unknown package: " + packageName);
5218 }
5219 return pkg.installerPackageName;
5220 }
5221 }
5222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 public int getApplicationEnabledSetting(String appPackageName) {
5224 synchronized (mPackages) {
5225 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5226 if (pkg == null) {
5227 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5228 }
5229 return pkg.enabled;
5230 }
5231 }
5232
5233 public int getComponentEnabledSetting(ComponentName componentName) {
5234 synchronized (mPackages) {
5235 final String packageNameStr = componentName.getPackageName();
5236 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5237 if (pkg == null) {
5238 throw new IllegalArgumentException("Unknown component: " + componentName);
5239 }
5240 final String classNameStr = componentName.getClassName();
5241 return pkg.currentEnabledStateLP(classNameStr);
5242 }
5243 }
5244
5245 public void enterSafeMode() {
5246 if (!mSystemReady) {
5247 mSafeMode = true;
5248 }
5249 }
5250
5251 public void systemReady() {
5252 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005253
5254 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005255 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005256 mContext.getContentResolver(),
5257 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005258 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005259 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005260 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005262 }
5263
5264 public boolean isSafeMode() {
5265 return mSafeMode;
5266 }
5267
5268 public boolean hasSystemUidErrors() {
5269 return mHasSystemUidErrors;
5270 }
5271
5272 static String arrayToString(int[] array) {
5273 StringBuffer buf = new StringBuffer(128);
5274 buf.append('[');
5275 if (array != null) {
5276 for (int i=0; i<array.length; i++) {
5277 if (i > 0) buf.append(", ");
5278 buf.append(array[i]);
5279 }
5280 }
5281 buf.append(']');
5282 return buf.toString();
5283 }
5284
5285 @Override
5286 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5287 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5288 != PackageManager.PERMISSION_GRANTED) {
5289 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5290 + Binder.getCallingPid()
5291 + ", uid=" + Binder.getCallingUid()
5292 + " without permission "
5293 + android.Manifest.permission.DUMP);
5294 return;
5295 }
5296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 synchronized (mPackages) {
5298 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005299 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005300 pw.println(" ");
5301 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005302 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 pw.println(" ");
5304 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005305 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005306 pw.println(" ");
5307 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005308 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005309 pw.println(" ");
5310 pw.println("Preferred Packages:");
5311 {
5312 for (PackageSetting ps : mSettings.mPreferredPackages) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005313 pw.print(" "); pw.println(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 }
5315 }
5316 pw.println(" ");
5317 pw.println("Permissions:");
5318 {
5319 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005320 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5321 pw.print(Integer.toHexString(System.identityHashCode(p)));
5322 pw.println("):");
5323 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5324 pw.print(" uid="); pw.print(p.uid);
5325 pw.print(" gids="); pw.print(arrayToString(p.gids));
5326 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 }
5328 }
5329 pw.println(" ");
5330 pw.println("Packages:");
5331 {
5332 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005333 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5334 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5335 pw.println("):");
5336 pw.print(" userId="); pw.print(ps.userId);
5337 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5338 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5339 pw.print(" pkg="); pw.println(ps.pkg);
5340 pw.print(" codePath="); pw.println(ps.codePathString);
5341 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005343 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005344 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005345 pw.print(" supportsScreens=[");
5346 boolean first = true;
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005347 if ((ps.pkg.applicationInfo.flags &
5348 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005349 if (!first) pw.print(", ");
5350 first = false;
5351 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005352 }
5353 if ((ps.pkg.applicationInfo.flags &
5354 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005355 if (!first) pw.print(", ");
5356 first = false;
5357 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005358 }
5359 if ((ps.pkg.applicationInfo.flags &
5360 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005361 if (!first) pw.print(", ");
5362 first = false;
5363 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005364 }
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005365 if ((ps.pkg.applicationInfo.flags &
5366 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005367 if (!first) pw.print(", ");
5368 first = false;
5369 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005370 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005371 if ((ps.pkg.applicationInfo.flags &
5372 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
5373 if (!first) pw.print(", ");
5374 first = false;
5375 pw.print("anyDensity");
5376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005377 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005378 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005379 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
5380 pw.print(" signatures="); pw.println(ps.signatures);
5381 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
5382 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
5383 pw.print(" installStatus="); pw.print(ps.installStatus);
5384 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 if (ps.disabledComponents.size() > 0) {
5386 pw.println(" disabledComponents:");
5387 for (String s : ps.disabledComponents) {
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 }
5391 if (ps.enabledComponents.size() > 0) {
5392 pw.println(" enabledComponents:");
5393 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005394 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 }
5396 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005397 if (ps.grantedPermissions.size() > 0) {
5398 pw.println(" grantedPermissions:");
5399 for (String s : ps.grantedPermissions) {
5400 pw.print(" "); pw.println(s);
5401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005402 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005403 if (ps.loadedPermissions.size() > 0) {
5404 pw.println(" loadedPermissions:");
5405 for (String s : ps.loadedPermissions) {
5406 pw.print(" "); pw.println(s);
5407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408 }
5409 }
5410 }
5411 pw.println(" ");
5412 pw.println("Shared Users:");
5413 {
5414 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005415 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5416 pw.print(Integer.toHexString(System.identityHashCode(su)));
5417 pw.println("):");
5418 pw.print(" userId="); pw.print(su.userId);
5419 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 pw.println(" grantedPermissions:");
5421 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005422 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 }
5424 pw.println(" loadedPermissions:");
5425 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005426 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 }
5428 }
5429 }
5430 pw.println(" ");
5431 pw.println("Settings parse messages:");
5432 pw.println(mSettings.mReadMessages.toString());
5433 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05005434
5435 synchronized (mProviders) {
5436 pw.println(" ");
5437 pw.println("Registered ContentProviders:");
5438 for (PackageParser.Provider p : mProviders.values()) {
5439 pw.println(" ["); pw.println(p.info.authority); pw.println("]: ");
5440 pw.println(p.toString());
5441 }
5442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 }
5444
5445 static final class BasePermission {
5446 final static int TYPE_NORMAL = 0;
5447 final static int TYPE_BUILTIN = 1;
5448 final static int TYPE_DYNAMIC = 2;
5449
5450 final String name;
5451 final String sourcePackage;
5452 final int type;
5453 PackageParser.Permission perm;
5454 PermissionInfo pendingInfo;
5455 int uid;
5456 int[] gids;
5457
5458 BasePermission(String _name, String _sourcePackage, int _type) {
5459 name = _name;
5460 sourcePackage = _sourcePackage;
5461 type = _type;
5462 }
5463 }
5464
5465 static class PackageSignatures {
5466 private Signature[] mSignatures;
5467
5468 PackageSignatures(Signature[] sigs) {
5469 assignSignatures(sigs);
5470 }
5471
5472 PackageSignatures() {
5473 }
5474
5475 void writeXml(XmlSerializer serializer, String tagName,
5476 ArrayList<Signature> pastSignatures) throws IOException {
5477 if (mSignatures == null) {
5478 return;
5479 }
5480 serializer.startTag(null, tagName);
5481 serializer.attribute(null, "count",
5482 Integer.toString(mSignatures.length));
5483 for (int i=0; i<mSignatures.length; i++) {
5484 serializer.startTag(null, "cert");
5485 final Signature sig = mSignatures[i];
5486 final int sigHash = sig.hashCode();
5487 final int numPast = pastSignatures.size();
5488 int j;
5489 for (j=0; j<numPast; j++) {
5490 Signature pastSig = pastSignatures.get(j);
5491 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5492 serializer.attribute(null, "index", Integer.toString(j));
5493 break;
5494 }
5495 }
5496 if (j >= numPast) {
5497 pastSignatures.add(sig);
5498 serializer.attribute(null, "index", Integer.toString(numPast));
5499 serializer.attribute(null, "key", sig.toCharsString());
5500 }
5501 serializer.endTag(null, "cert");
5502 }
5503 serializer.endTag(null, tagName);
5504 }
5505
5506 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5507 throws IOException, XmlPullParserException {
5508 String countStr = parser.getAttributeValue(null, "count");
5509 if (countStr == null) {
5510 reportSettingsProblem(Log.WARN,
5511 "Error in package manager settings: <signatures> has"
5512 + " no count at " + parser.getPositionDescription());
5513 XmlUtils.skipCurrentTag(parser);
5514 }
5515 final int count = Integer.parseInt(countStr);
5516 mSignatures = new Signature[count];
5517 int pos = 0;
5518
5519 int outerDepth = parser.getDepth();
5520 int type;
5521 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5522 && (type != XmlPullParser.END_TAG
5523 || parser.getDepth() > outerDepth)) {
5524 if (type == XmlPullParser.END_TAG
5525 || type == XmlPullParser.TEXT) {
5526 continue;
5527 }
5528
5529 String tagName = parser.getName();
5530 if (tagName.equals("cert")) {
5531 if (pos < count) {
5532 String index = parser.getAttributeValue(null, "index");
5533 if (index != null) {
5534 try {
5535 int idx = Integer.parseInt(index);
5536 String key = parser.getAttributeValue(null, "key");
5537 if (key == null) {
5538 if (idx >= 0 && idx < pastSignatures.size()) {
5539 Signature sig = pastSignatures.get(idx);
5540 if (sig != null) {
5541 mSignatures[pos] = pastSignatures.get(idx);
5542 pos++;
5543 } else {
5544 reportSettingsProblem(Log.WARN,
5545 "Error in package manager settings: <cert> "
5546 + "index " + index + " is not defined at "
5547 + parser.getPositionDescription());
5548 }
5549 } else {
5550 reportSettingsProblem(Log.WARN,
5551 "Error in package manager settings: <cert> "
5552 + "index " + index + " is out of bounds at "
5553 + parser.getPositionDescription());
5554 }
5555 } else {
5556 while (pastSignatures.size() <= idx) {
5557 pastSignatures.add(null);
5558 }
5559 Signature sig = new Signature(key);
5560 pastSignatures.set(idx, sig);
5561 mSignatures[pos] = sig;
5562 pos++;
5563 }
5564 } catch (NumberFormatException e) {
5565 reportSettingsProblem(Log.WARN,
5566 "Error in package manager settings: <cert> "
5567 + "index " + index + " is not a number at "
5568 + parser.getPositionDescription());
5569 }
5570 } else {
5571 reportSettingsProblem(Log.WARN,
5572 "Error in package manager settings: <cert> has"
5573 + " no index at " + parser.getPositionDescription());
5574 }
5575 } else {
5576 reportSettingsProblem(Log.WARN,
5577 "Error in package manager settings: too "
5578 + "many <cert> tags, expected " + count
5579 + " at " + parser.getPositionDescription());
5580 }
5581 } else {
5582 reportSettingsProblem(Log.WARN,
5583 "Unknown element under <cert>: "
5584 + parser.getName());
5585 }
5586 XmlUtils.skipCurrentTag(parser);
5587 }
5588
5589 if (pos < count) {
5590 // Should never happen -- there is an error in the written
5591 // settings -- but if it does we don't want to generate
5592 // a bad array.
5593 Signature[] newSigs = new Signature[pos];
5594 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5595 mSignatures = newSigs;
5596 }
5597 }
5598
5599 /**
5600 * If any of the given 'sigs' is contained in the existing signatures,
5601 * then completely replace the current signatures with the ones in
5602 * 'sigs'. This is used for updating an existing package to a newly
5603 * installed version.
5604 */
5605 boolean updateSignatures(Signature[] sigs, boolean update) {
5606 if (mSignatures == null) {
5607 if (update) {
5608 assignSignatures(sigs);
5609 }
5610 return true;
5611 }
5612 if (sigs == null) {
5613 return false;
5614 }
5615
5616 for (int i=0; i<sigs.length; i++) {
5617 Signature sig = sigs[i];
5618 for (int j=0; j<mSignatures.length; j++) {
5619 if (mSignatures[j].equals(sig)) {
5620 if (update) {
5621 assignSignatures(sigs);
5622 }
5623 return true;
5624 }
5625 }
5626 }
5627 return false;
5628 }
5629
5630 /**
5631 * If any of the given 'sigs' is contained in the existing signatures,
5632 * then add in any new signatures found in 'sigs'. This is used for
5633 * including a new package into an existing shared user id.
5634 */
5635 boolean mergeSignatures(Signature[] sigs, boolean update) {
5636 if (mSignatures == null) {
5637 if (update) {
5638 assignSignatures(sigs);
5639 }
5640 return true;
5641 }
5642 if (sigs == null) {
5643 return false;
5644 }
5645
5646 Signature[] added = null;
5647 int addedCount = 0;
5648 boolean haveMatch = false;
5649 for (int i=0; i<sigs.length; i++) {
5650 Signature sig = sigs[i];
5651 boolean found = false;
5652 for (int j=0; j<mSignatures.length; j++) {
5653 if (mSignatures[j].equals(sig)) {
5654 found = true;
5655 haveMatch = true;
5656 break;
5657 }
5658 }
5659
5660 if (!found) {
5661 if (added == null) {
5662 added = new Signature[sigs.length];
5663 }
5664 added[i] = sig;
5665 addedCount++;
5666 }
5667 }
5668
5669 if (!haveMatch) {
5670 // Nothing matched -- reject the new signatures.
5671 return false;
5672 }
5673 if (added == null) {
5674 // Completely matched -- nothing else to do.
5675 return true;
5676 }
5677
5678 // Add additional signatures in.
5679 if (update) {
5680 Signature[] total = new Signature[addedCount+mSignatures.length];
5681 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5682 int j = mSignatures.length;
5683 for (int i=0; i<added.length; i++) {
5684 if (added[i] != null) {
5685 total[j] = added[i];
5686 j++;
5687 }
5688 }
5689 mSignatures = total;
5690 }
5691 return true;
5692 }
5693
5694 private void assignSignatures(Signature[] sigs) {
5695 if (sigs == null) {
5696 mSignatures = null;
5697 return;
5698 }
5699 mSignatures = new Signature[sigs.length];
5700 for (int i=0; i<sigs.length; i++) {
5701 mSignatures[i] = sigs[i];
5702 }
5703 }
5704
5705 @Override
5706 public String toString() {
5707 StringBuffer buf = new StringBuffer(128);
5708 buf.append("PackageSignatures{");
5709 buf.append(Integer.toHexString(System.identityHashCode(this)));
5710 buf.append(" [");
5711 if (mSignatures != null) {
5712 for (int i=0; i<mSignatures.length; i++) {
5713 if (i > 0) buf.append(", ");
5714 buf.append(Integer.toHexString(
5715 System.identityHashCode(mSignatures[i])));
5716 }
5717 }
5718 buf.append("]}");
5719 return buf.toString();
5720 }
5721 }
5722
5723 static class PreferredActivity extends IntentFilter {
5724 final int mMatch;
5725 final String[] mSetPackages;
5726 final String[] mSetClasses;
5727 final String[] mSetComponents;
5728 final ComponentName mActivity;
5729 final String mShortActivity;
5730 String mParseError;
5731
5732 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5733 ComponentName activity) {
5734 super(filter);
5735 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5736 mActivity = activity;
5737 mShortActivity = activity.flattenToShortString();
5738 mParseError = null;
5739 if (set != null) {
5740 final int N = set.length;
5741 String[] myPackages = new String[N];
5742 String[] myClasses = new String[N];
5743 String[] myComponents = new String[N];
5744 for (int i=0; i<N; i++) {
5745 ComponentName cn = set[i];
5746 if (cn == null) {
5747 mSetPackages = null;
5748 mSetClasses = null;
5749 mSetComponents = null;
5750 return;
5751 }
5752 myPackages[i] = cn.getPackageName().intern();
5753 myClasses[i] = cn.getClassName().intern();
5754 myComponents[i] = cn.flattenToShortString().intern();
5755 }
5756 mSetPackages = myPackages;
5757 mSetClasses = myClasses;
5758 mSetComponents = myComponents;
5759 } else {
5760 mSetPackages = null;
5761 mSetClasses = null;
5762 mSetComponents = null;
5763 }
5764 }
5765
5766 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5767 IOException {
5768 mShortActivity = parser.getAttributeValue(null, "name");
5769 mActivity = ComponentName.unflattenFromString(mShortActivity);
5770 if (mActivity == null) {
5771 mParseError = "Bad activity name " + mShortActivity;
5772 }
5773 String matchStr = parser.getAttributeValue(null, "match");
5774 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5775 String setCountStr = parser.getAttributeValue(null, "set");
5776 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5777
5778 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5779 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5780 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5781
5782 int setPos = 0;
5783
5784 int outerDepth = parser.getDepth();
5785 int type;
5786 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5787 && (type != XmlPullParser.END_TAG
5788 || parser.getDepth() > outerDepth)) {
5789 if (type == XmlPullParser.END_TAG
5790 || type == XmlPullParser.TEXT) {
5791 continue;
5792 }
5793
5794 String tagName = parser.getName();
5795 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5796 // + parser.getDepth() + " tag=" + tagName);
5797 if (tagName.equals("set")) {
5798 String name = parser.getAttributeValue(null, "name");
5799 if (name == null) {
5800 if (mParseError == null) {
5801 mParseError = "No name in set tag in preferred activity "
5802 + mShortActivity;
5803 }
5804 } else if (setPos >= setCount) {
5805 if (mParseError == null) {
5806 mParseError = "Too many set tags in preferred activity "
5807 + mShortActivity;
5808 }
5809 } else {
5810 ComponentName cn = ComponentName.unflattenFromString(name);
5811 if (cn == null) {
5812 if (mParseError == null) {
5813 mParseError = "Bad set name " + name + " in preferred activity "
5814 + mShortActivity;
5815 }
5816 } else {
5817 myPackages[setPos] = cn.getPackageName();
5818 myClasses[setPos] = cn.getClassName();
5819 myComponents[setPos] = name;
5820 setPos++;
5821 }
5822 }
5823 XmlUtils.skipCurrentTag(parser);
5824 } else if (tagName.equals("filter")) {
5825 //Log.i(TAG, "Starting to parse filter...");
5826 readFromXml(parser);
5827 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5828 // + parser.getDepth() + " tag=" + parser.getName());
5829 } else {
5830 reportSettingsProblem(Log.WARN,
5831 "Unknown element under <preferred-activities>: "
5832 + parser.getName());
5833 XmlUtils.skipCurrentTag(parser);
5834 }
5835 }
5836
5837 if (setPos != setCount) {
5838 if (mParseError == null) {
5839 mParseError = "Not enough set tags (expected " + setCount
5840 + " but found " + setPos + ") in " + mShortActivity;
5841 }
5842 }
5843
5844 mSetPackages = myPackages;
5845 mSetClasses = myClasses;
5846 mSetComponents = myComponents;
5847 }
5848
5849 public void writeToXml(XmlSerializer serializer) throws IOException {
5850 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5851 serializer.attribute(null, "name", mShortActivity);
5852 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5853 serializer.attribute(null, "set", Integer.toString(NS));
5854 for (int s=0; s<NS; s++) {
5855 serializer.startTag(null, "set");
5856 serializer.attribute(null, "name", mSetComponents[s]);
5857 serializer.endTag(null, "set");
5858 }
5859 serializer.startTag(null, "filter");
5860 super.writeToXml(serializer);
5861 serializer.endTag(null, "filter");
5862 }
5863
5864 boolean sameSet(List<ResolveInfo> query, int priority) {
5865 if (mSetPackages == null) return false;
5866 final int NQ = query.size();
5867 final int NS = mSetPackages.length;
5868 int numMatch = 0;
5869 for (int i=0; i<NQ; i++) {
5870 ResolveInfo ri = query.get(i);
5871 if (ri.priority != priority) continue;
5872 ActivityInfo ai = ri.activityInfo;
5873 boolean good = false;
5874 for (int j=0; j<NS; j++) {
5875 if (mSetPackages[j].equals(ai.packageName)
5876 && mSetClasses[j].equals(ai.name)) {
5877 numMatch++;
5878 good = true;
5879 break;
5880 }
5881 }
5882 if (!good) return false;
5883 }
5884 return numMatch == NS;
5885 }
5886 }
5887
5888 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07005889 int pkgFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890
5891 HashSet<String> grantedPermissions = new HashSet<String>();
5892 int[] gids;
5893
5894 HashSet<String> loadedPermissions = new HashSet<String>();
5895
5896 GrantedPermissions(int pkgFlags) {
5897 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5898 }
5899 }
5900
5901 /**
5902 * Settings base class for pending and resolved classes.
5903 */
5904 static class PackageSettingBase extends GrantedPermissions {
5905 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005906 File codePath;
5907 String codePathString;
5908 File resourcePath;
5909 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 private long timeStamp;
5911 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005912 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913
5914 PackageSignatures signatures = new PackageSignatures();
5915
5916 boolean permissionsFixed;
5917
5918 /* Explicitly disabled components */
5919 HashSet<String> disabledComponents = new HashSet<String>(0);
5920 /* Explicitly enabled components */
5921 HashSet<String> enabledComponents = new HashSet<String>(0);
5922 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5923 int installStatus = PKG_INSTALL_COMPLETE;
Jacek Surazski65e13172009-04-28 15:26:38 +02005924
5925 /* package name of the app that installed this package */
5926 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927
5928 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005929 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 super(pkgFlags);
5931 this.name = name;
5932 this.codePath = codePath;
5933 this.codePathString = codePath.toString();
5934 this.resourcePath = resourcePath;
5935 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005936 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 }
5938
Jacek Surazski65e13172009-04-28 15:26:38 +02005939 public void setInstallerPackageName(String packageName) {
5940 installerPackageName = packageName;
5941 }
5942
5943 String getInstallerPackageName() {
5944 return installerPackageName;
5945 }
5946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 public void setInstallStatus(int newStatus) {
5948 installStatus = newStatus;
5949 }
5950
5951 public int getInstallStatus() {
5952 return installStatus;
5953 }
5954
5955 public void setTimeStamp(long newStamp) {
5956 if (newStamp != timeStamp) {
5957 timeStamp = newStamp;
5958 timeStampString = Long.toString(newStamp);
5959 }
5960 }
5961
5962 public void setTimeStamp(long newStamp, String newStampStr) {
5963 timeStamp = newStamp;
5964 timeStampString = newStampStr;
5965 }
5966
5967 public long getTimeStamp() {
5968 return timeStamp;
5969 }
5970
5971 public String getTimeStampStr() {
5972 return timeStampString;
5973 }
5974
5975 public void copyFrom(PackageSettingBase base) {
5976 grantedPermissions = base.grantedPermissions;
5977 gids = base.gids;
5978 loadedPermissions = base.loadedPermissions;
5979
5980 timeStamp = base.timeStamp;
5981 timeStampString = base.timeStampString;
5982 signatures = base.signatures;
5983 permissionsFixed = base.permissionsFixed;
5984 disabledComponents = base.disabledComponents;
5985 enabledComponents = base.enabledComponents;
5986 enabled = base.enabled;
5987 installStatus = base.installStatus;
5988 }
5989
5990 void enableComponentLP(String componentClassName) {
5991 disabledComponents.remove(componentClassName);
5992 enabledComponents.add(componentClassName);
5993 }
5994
5995 void disableComponentLP(String componentClassName) {
5996 enabledComponents.remove(componentClassName);
5997 disabledComponents.add(componentClassName);
5998 }
5999
6000 void restoreComponentLP(String componentClassName) {
6001 enabledComponents.remove(componentClassName);
6002 disabledComponents.remove(componentClassName);
6003 }
6004
6005 int currentEnabledStateLP(String componentName) {
6006 if (enabledComponents.contains(componentName)) {
6007 return COMPONENT_ENABLED_STATE_ENABLED;
6008 } else if (disabledComponents.contains(componentName)) {
6009 return COMPONENT_ENABLED_STATE_DISABLED;
6010 } else {
6011 return COMPONENT_ENABLED_STATE_DEFAULT;
6012 }
6013 }
6014 }
6015
6016 /**
6017 * Settings data for a particular package we know about.
6018 */
6019 static final class PackageSetting extends PackageSettingBase {
6020 int userId;
6021 PackageParser.Package pkg;
6022 SharedUserSetting sharedUser;
6023
6024 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006025 int pVersionCode, int pkgFlags) {
6026 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 }
6028
6029 @Override
6030 public String toString() {
6031 return "PackageSetting{"
6032 + Integer.toHexString(System.identityHashCode(this))
6033 + " " + name + "/" + userId + "}";
6034 }
6035 }
6036
6037 /**
6038 * Settings data for a particular shared user ID we know about.
6039 */
6040 static final class SharedUserSetting extends GrantedPermissions {
6041 final String name;
6042 int userId;
6043 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6044 final PackageSignatures signatures = new PackageSignatures();
6045
6046 SharedUserSetting(String _name, int _pkgFlags) {
6047 super(_pkgFlags);
6048 name = _name;
6049 }
6050
6051 @Override
6052 public String toString() {
6053 return "SharedUserSetting{"
6054 + Integer.toHexString(System.identityHashCode(this))
6055 + " " + name + "/" + userId + "}";
6056 }
6057 }
6058
6059 /**
6060 * Holds information about dynamic settings.
6061 */
6062 private static final class Settings {
6063 private final File mSettingsFilename;
6064 private final File mBackupSettingsFilename;
6065 private final HashMap<String, PackageSetting> mPackages =
6066 new HashMap<String, PackageSetting>();
6067 // The user's preferred packages/applications, in order of preference.
6068 // First is the most preferred.
6069 private final ArrayList<PackageSetting> mPreferredPackages =
6070 new ArrayList<PackageSetting>();
6071 // List of replaced system applications
6072 final HashMap<String, PackageSetting> mDisabledSysPackages =
6073 new HashMap<String, PackageSetting>();
6074
6075 // The user's preferred activities associated with particular intent
6076 // filters.
6077 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6078 new IntentResolver<PreferredActivity, PreferredActivity>() {
6079 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006080 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006082 out.print(prefix); out.print(
6083 Integer.toHexString(System.identityHashCode(filter)));
6084 out.print(' ');
6085 out.print(filter.mActivity.flattenToShortString());
6086 out.print(" match=0x");
6087 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006089 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006090 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006091 out.print(prefix); out.print(" ");
6092 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 }
6094 }
6095 }
6096 };
6097 private final HashMap<String, SharedUserSetting> mSharedUsers =
6098 new HashMap<String, SharedUserSetting>();
6099 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6100 private final SparseArray<Object> mOtherUserIds =
6101 new SparseArray<Object>();
6102
6103 // For reading/writing settings file.
6104 private final ArrayList<Signature> mPastSignatures =
6105 new ArrayList<Signature>();
6106
6107 // Mapping from permission names to info about them.
6108 final HashMap<String, BasePermission> mPermissions =
6109 new HashMap<String, BasePermission>();
6110
6111 // Mapping from permission tree names to info about them.
6112 final HashMap<String, BasePermission> mPermissionTrees =
6113 new HashMap<String, BasePermission>();
6114
6115 private final ArrayList<String> mPendingPreferredPackages
6116 = new ArrayList<String>();
6117
6118 private final StringBuilder mReadMessages = new StringBuilder();
6119
6120 private static final class PendingPackage extends PackageSettingBase {
6121 final int sharedId;
6122
6123 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006124 int sharedId, int pVersionCode, int pkgFlags) {
6125 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 this.sharedId = sharedId;
6127 }
6128 }
6129 private final ArrayList<PendingPackage> mPendingPackages
6130 = new ArrayList<PendingPackage>();
6131
6132 Settings() {
6133 File dataDir = Environment.getDataDirectory();
6134 File systemDir = new File(dataDir, "system");
6135 systemDir.mkdirs();
6136 FileUtils.setPermissions(systemDir.toString(),
6137 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6138 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6139 -1, -1);
6140 mSettingsFilename = new File(systemDir, "packages.xml");
6141 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6142 }
6143
6144 PackageSetting getPackageLP(PackageParser.Package pkg,
6145 SharedUserSetting sharedUser, File codePath, File resourcePath,
6146 int pkgFlags, boolean create, boolean add) {
6147 final String name = pkg.packageName;
6148 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006149 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 return p;
6151 }
6152
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006153 PackageSetting peekPackageLP(String name) {
6154 return mPackages.get(name);
6155 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 PackageSetting p = mPackages.get(name);
6157 if (p != null && p.codePath.getPath().equals(codePath)) {
6158 return p;
6159 }
6160 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006161 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 }
6163
6164 void setInstallStatus(String pkgName, int status) {
6165 PackageSetting p = mPackages.get(pkgName);
6166 if(p != null) {
6167 if(p.getInstallStatus() != status) {
6168 p.setInstallStatus(status);
6169 }
6170 }
6171 }
6172
Jacek Surazski65e13172009-04-28 15:26:38 +02006173 void setInstallerPackageName(String pkgName,
6174 String installerPkgName) {
6175 PackageSetting p = mPackages.get(pkgName);
6176 if(p != null) {
6177 p.setInstallerPackageName(installerPkgName);
6178 }
6179 }
6180
6181 String getInstallerPackageName(String pkgName) {
6182 PackageSetting p = mPackages.get(pkgName);
6183 return (p == null) ? null : p.getInstallerPackageName();
6184 }
6185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 int getInstallStatus(String pkgName) {
6187 PackageSetting p = mPackages.get(pkgName);
6188 if(p != null) {
6189 return p.getInstallStatus();
6190 }
6191 return -1;
6192 }
6193
6194 SharedUserSetting getSharedUserLP(String name,
6195 int pkgFlags, boolean create) {
6196 SharedUserSetting s = mSharedUsers.get(name);
6197 if (s == null) {
6198 if (!create) {
6199 return null;
6200 }
6201 s = new SharedUserSetting(name, pkgFlags);
6202 if (MULTIPLE_APPLICATION_UIDS) {
6203 s.userId = newUserIdLP(s);
6204 } else {
6205 s.userId = FIRST_APPLICATION_UID;
6206 }
6207 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6208 // < 0 means we couldn't assign a userid; fall out and return
6209 // s, which is currently null
6210 if (s.userId >= 0) {
6211 mSharedUsers.put(name, s);
6212 }
6213 }
6214
6215 return s;
6216 }
6217
6218 int disableSystemPackageLP(String name) {
6219 PackageSetting p = mPackages.get(name);
6220 if(p == null) {
6221 Log.w(TAG, "Package:"+name+" is not an installed package");
6222 return -1;
6223 }
6224 PackageSetting dp = mDisabledSysPackages.get(name);
6225 // always make sure the system package code and resource paths dont change
6226 if(dp == null) {
6227 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6228 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6229 }
6230 mDisabledSysPackages.put(name, p);
6231 }
6232 return removePackageLP(name);
6233 }
6234
6235 PackageSetting enableSystemPackageLP(String name) {
6236 PackageSetting p = mDisabledSysPackages.get(name);
6237 if(p == null) {
6238 Log.w(TAG, "Package:"+name+" is not disabled");
6239 return null;
6240 }
6241 // Reset flag in ApplicationInfo object
6242 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6243 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6244 }
6245 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006246 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 mDisabledSysPackages.remove(name);
6248 return ret;
6249 }
6250
6251 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006252 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 PackageSetting p = mPackages.get(name);
6254 if (p != null) {
6255 if (p.userId == uid) {
6256 return p;
6257 }
6258 reportSettingsProblem(Log.ERROR,
6259 "Adding duplicate package, keeping first: " + name);
6260 return null;
6261 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006262 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 p.userId = uid;
6264 if (addUserIdLP(uid, p, name)) {
6265 mPackages.put(name, p);
6266 return p;
6267 }
6268 return null;
6269 }
6270
6271 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6272 SharedUserSetting s = mSharedUsers.get(name);
6273 if (s != null) {
6274 if (s.userId == uid) {
6275 return s;
6276 }
6277 reportSettingsProblem(Log.ERROR,
6278 "Adding duplicate shared user, keeping first: " + name);
6279 return null;
6280 }
6281 s = new SharedUserSetting(name, pkgFlags);
6282 s.userId = uid;
6283 if (addUserIdLP(uid, s, name)) {
6284 mSharedUsers.put(name, s);
6285 return s;
6286 }
6287 return null;
6288 }
6289
6290 private PackageSetting getPackageLP(String name,
6291 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006292 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293 PackageSetting p = mPackages.get(name);
6294 if (p != null) {
6295 if (!p.codePath.equals(codePath)) {
6296 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006297 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006298 // This is an updated system app with versions in both system
6299 // and data partition. Just let the most recent version
6300 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006301 Log.w(TAG, "Trying to update system app code path from " +
6302 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006303 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006304 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07006305 reportSettingsProblem(Log.WARN,
6306 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006307 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006309 }
6310 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 reportSettingsProblem(Log.WARN,
6312 "Package " + name + " shared user changed from "
6313 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
6314 + " to "
6315 + (sharedUser != null ? sharedUser.name : "<nothing>")
6316 + "; replacing with new");
6317 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006318 } else {
6319 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6320 // If what we are scanning is a system package, then
6321 // make it so, regardless of whether it was previously
6322 // installed only in the data partition.
6323 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 }
6326 }
6327 if (p == null) {
6328 // Create a new PackageSettings entry. this can end up here because
6329 // of code path mismatch or user id mismatch of an updated system partition
6330 if (!create) {
6331 return null;
6332 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006333 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07006335 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 if (sharedUser != null) {
6337 p.userId = sharedUser.userId;
6338 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006339 // Clone the setting here for disabled system packages
6340 PackageSetting dis = mDisabledSysPackages.get(name);
6341 if (dis != null) {
6342 // For disabled packages a new setting is created
6343 // from the existing user id. This still has to be
6344 // added to list of user id's
6345 // Copy signatures from previous setting
6346 if (dis.signatures.mSignatures != null) {
6347 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
6348 }
6349 p.userId = dis.userId;
6350 // Clone permissions
6351 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
6352 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
6353 // Clone component info
6354 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
6355 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
6356 // Add new setting to list of user ids
6357 addUserIdLP(p.userId, p, name);
6358 } else {
6359 // Assign new user id
6360 p.userId = newUserIdLP(p);
6361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 } else {
6363 p.userId = FIRST_APPLICATION_UID;
6364 }
6365 if (p.userId < 0) {
6366 reportSettingsProblem(Log.WARN,
6367 "Package " + name + " could not be assigned a valid uid");
6368 return null;
6369 }
6370 if (add) {
6371 // Finish adding new package by adding it and updating shared
6372 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006373 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 }
6375 }
6376 return p;
6377 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006378
6379 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg,
6380 File codePath, File resourcePath) {
6381 p.pkg = pkg;
6382 // Update code path if needed
6383 if (!codePath.toString().equalsIgnoreCase(p.codePathString)) {
6384 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006385 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006386 p.codePath = codePath;
6387 p.codePathString = codePath.toString();
6388 }
6389 //Update resource path if needed
6390 if (!resourcePath.toString().equalsIgnoreCase(p.resourcePathString)) {
6391 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006392 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006393 p.resourcePath = resourcePath;
6394 p.resourcePathString = resourcePath.toString();
6395 }
6396 // Update version code if needed
6397 if (pkg.mVersionCode != p.versionCode) {
6398 p.versionCode = pkg.mVersionCode;
6399 }
6400 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
6401 }
6402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 // Utility method that adds a PackageSetting to mPackages and
6404 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006405 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 SharedUserSetting sharedUser) {
6407 mPackages.put(name, p);
6408 if (sharedUser != null) {
6409 if (p.sharedUser != null && p.sharedUser != sharedUser) {
6410 reportSettingsProblem(Log.ERROR,
6411 "Package " + p.name + " was user "
6412 + p.sharedUser + " but is now " + sharedUser
6413 + "; I am not changing its files so it will probably fail!");
6414 p.sharedUser.packages.remove(p);
6415 } else if (p.userId != sharedUser.userId) {
6416 reportSettingsProblem(Log.ERROR,
6417 "Package " + p.name + " was user id " + p.userId
6418 + " but is now user " + sharedUser
6419 + " with id " + sharedUser.userId
6420 + "; I am not changing its files so it will probably fail!");
6421 }
6422
6423 sharedUser.packages.add(p);
6424 p.sharedUser = sharedUser;
6425 p.userId = sharedUser.userId;
6426 }
6427 }
6428
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006429 /*
6430 * Update the shared user setting when a package using
6431 * specifying the shared user id is removed. The gids
6432 * associated with each permission of the deleted package
6433 * are removed from the shared user's gid list only if its
6434 * not in use by other permissions of packages in the
6435 * shared user setting.
6436 */
6437 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6439 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6440 return;
6441 }
6442 // No sharedUserId
6443 if (deletedPs.sharedUser == null) {
6444 return;
6445 }
6446 SharedUserSetting sus = deletedPs.sharedUser;
6447 // Update permissions
6448 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6449 boolean used = false;
6450 if (!sus.grantedPermissions.contains (eachPerm)) {
6451 continue;
6452 }
6453 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006454 if (pkg.pkg != null &&
6455 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
6456 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 used = true;
6458 break;
6459 }
6460 }
6461 if (!used) {
6462 // can safely delete this permission from list
6463 sus.grantedPermissions.remove(eachPerm);
6464 sus.loadedPermissions.remove(eachPerm);
6465 }
6466 }
6467 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006468 int newGids[] = globalGids;
6469 for (String eachPerm : sus.grantedPermissions) {
6470 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006471 if (bp != null) {
6472 newGids = appendInts(newGids, bp.gids);
6473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 }
6475 sus.gids = newGids;
6476 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 private int removePackageLP(String name) {
6479 PackageSetting p = mPackages.get(name);
6480 if (p != null) {
6481 mPackages.remove(name);
6482 if (p.sharedUser != null) {
6483 p.sharedUser.packages.remove(p);
6484 if (p.sharedUser.packages.size() == 0) {
6485 mSharedUsers.remove(p.sharedUser.name);
6486 removeUserIdLP(p.sharedUser.userId);
6487 return p.sharedUser.userId;
6488 }
6489 } else {
6490 removeUserIdLP(p.userId);
6491 return p.userId;
6492 }
6493 }
6494 return -1;
6495 }
6496
6497 private boolean addUserIdLP(int uid, Object obj, Object name) {
6498 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6499 return false;
6500 }
6501
6502 if (uid >= FIRST_APPLICATION_UID) {
6503 int N = mUserIds.size();
6504 final int index = uid - FIRST_APPLICATION_UID;
6505 while (index >= N) {
6506 mUserIds.add(null);
6507 N++;
6508 }
6509 if (mUserIds.get(index) != null) {
6510 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006511 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 + " name=" + name);
6513 return false;
6514 }
6515 mUserIds.set(index, obj);
6516 } else {
6517 if (mOtherUserIds.get(uid) != null) {
6518 reportSettingsProblem(Log.ERROR,
6519 "Adding duplicate shared id: " + uid
6520 + " name=" + name);
6521 return false;
6522 }
6523 mOtherUserIds.put(uid, obj);
6524 }
6525 return true;
6526 }
6527
6528 public Object getUserIdLP(int uid) {
6529 if (uid >= FIRST_APPLICATION_UID) {
6530 int N = mUserIds.size();
6531 final int index = uid - FIRST_APPLICATION_UID;
6532 return index < N ? mUserIds.get(index) : null;
6533 } else {
6534 return mOtherUserIds.get(uid);
6535 }
6536 }
6537
6538 private void removeUserIdLP(int uid) {
6539 if (uid >= FIRST_APPLICATION_UID) {
6540 int N = mUserIds.size();
6541 final int index = uid - FIRST_APPLICATION_UID;
6542 if (index < N) mUserIds.set(index, null);
6543 } else {
6544 mOtherUserIds.remove(uid);
6545 }
6546 }
6547
6548 void writeLP() {
6549 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6550
6551 // Keep the old settings around until we know the new ones have
6552 // been successfully written.
6553 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006554 // Presence of backup settings file indicates that we failed
6555 // to persist settings earlier. So preserve the older
6556 // backup for future reference since the current settings
6557 // might have been corrupted.
6558 if (!mBackupSettingsFilename.exists()) {
6559 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
6560 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
6561 return;
6562 }
6563 } else {
6564 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07006565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 }
6567
6568 mPastSignatures.clear();
6569
6570 try {
6571 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6572
6573 //XmlSerializer serializer = XmlUtils.serializerInstance();
6574 XmlSerializer serializer = new FastXmlSerializer();
6575 serializer.setOutput(str, "utf-8");
6576 serializer.startDocument(null, true);
6577 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6578
6579 serializer.startTag(null, "packages");
6580
6581 serializer.startTag(null, "permission-trees");
6582 for (BasePermission bp : mPermissionTrees.values()) {
6583 writePermission(serializer, bp);
6584 }
6585 serializer.endTag(null, "permission-trees");
6586
6587 serializer.startTag(null, "permissions");
6588 for (BasePermission bp : mPermissions.values()) {
6589 writePermission(serializer, bp);
6590 }
6591 serializer.endTag(null, "permissions");
6592
6593 for (PackageSetting pkg : mPackages.values()) {
6594 writePackage(serializer, pkg);
6595 }
6596
6597 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6598 writeDisabledSysPackage(serializer, pkg);
6599 }
6600
6601 serializer.startTag(null, "preferred-packages");
6602 int N = mPreferredPackages.size();
6603 for (int i=0; i<N; i++) {
6604 PackageSetting pkg = mPreferredPackages.get(i);
6605 serializer.startTag(null, "item");
6606 serializer.attribute(null, "name", pkg.name);
6607 serializer.endTag(null, "item");
6608 }
6609 serializer.endTag(null, "preferred-packages");
6610
6611 serializer.startTag(null, "preferred-activities");
6612 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6613 serializer.startTag(null, "item");
6614 pa.writeToXml(serializer);
6615 serializer.endTag(null, "item");
6616 }
6617 serializer.endTag(null, "preferred-activities");
6618
6619 for (SharedUserSetting usr : mSharedUsers.values()) {
6620 serializer.startTag(null, "shared-user");
6621 serializer.attribute(null, "name", usr.name);
6622 serializer.attribute(null, "userId",
6623 Integer.toString(usr.userId));
6624 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6625 serializer.startTag(null, "perms");
6626 for (String name : usr.grantedPermissions) {
6627 serializer.startTag(null, "item");
6628 serializer.attribute(null, "name", name);
6629 serializer.endTag(null, "item");
6630 }
6631 serializer.endTag(null, "perms");
6632 serializer.endTag(null, "shared-user");
6633 }
6634
6635 serializer.endTag(null, "packages");
6636
6637 serializer.endDocument();
6638
6639 str.flush();
6640 str.close();
6641
6642 // New settings successfully written, old ones are no longer
6643 // needed.
6644 mBackupSettingsFilename.delete();
6645 FileUtils.setPermissions(mSettingsFilename.toString(),
6646 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6647 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6648 |FileUtils.S_IROTH,
6649 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006650 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651
6652 } catch(XmlPullParserException e) {
6653 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 -08006654 } catch(java.io.IOException e) {
6655 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 -08006656 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006657 // Clean up partially written file
6658 if (mSettingsFilename.exists()) {
6659 if (!mSettingsFilename.delete()) {
6660 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
6661 }
6662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 //Debug.stopMethodTracing();
6664 }
6665
6666 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
6667 throws java.io.IOException {
6668 serializer.startTag(null, "updated-package");
6669 serializer.attribute(null, "name", pkg.name);
6670 serializer.attribute(null, "codePath", pkg.codePathString);
6671 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006672 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6674 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6675 }
6676 if (pkg.sharedUser == null) {
6677 serializer.attribute(null, "userId",
6678 Integer.toString(pkg.userId));
6679 } else {
6680 serializer.attribute(null, "sharedUserId",
6681 Integer.toString(pkg.userId));
6682 }
6683 serializer.startTag(null, "perms");
6684 if (pkg.sharedUser == null) {
6685 // If this is a shared user, the permissions will
6686 // be written there. We still need to write an
6687 // empty permissions list so permissionsFixed will
6688 // be set.
6689 for (final String name : pkg.grantedPermissions) {
6690 BasePermission bp = mPermissions.get(name);
6691 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6692 // We only need to write signature or system permissions but this wont
6693 // match the semantics of grantedPermissions. So write all permissions.
6694 serializer.startTag(null, "item");
6695 serializer.attribute(null, "name", name);
6696 serializer.endTag(null, "item");
6697 }
6698 }
6699 }
6700 serializer.endTag(null, "perms");
6701 serializer.endTag(null, "updated-package");
6702 }
6703
6704 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
6705 throws java.io.IOException {
6706 serializer.startTag(null, "package");
6707 serializer.attribute(null, "name", pkg.name);
6708 serializer.attribute(null, "codePath", pkg.codePathString);
6709 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6710 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6711 }
6712 serializer.attribute(null, "system",
6713 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6714 ? "true" : "false");
6715 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006716 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 if (pkg.sharedUser == null) {
6718 serializer.attribute(null, "userId",
6719 Integer.toString(pkg.userId));
6720 } else {
6721 serializer.attribute(null, "sharedUserId",
6722 Integer.toString(pkg.userId));
6723 }
6724 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6725 serializer.attribute(null, "enabled",
6726 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6727 ? "true" : "false");
6728 }
6729 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6730 serializer.attribute(null, "installStatus", "false");
6731 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006732 if (pkg.installerPackageName != null) {
6733 serializer.attribute(null, "installer", pkg.installerPackageName);
6734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6736 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6737 serializer.startTag(null, "perms");
6738 if (pkg.sharedUser == null) {
6739 // If this is a shared user, the permissions will
6740 // be written there. We still need to write an
6741 // empty permissions list so permissionsFixed will
6742 // be set.
6743 for (final String name : pkg.grantedPermissions) {
6744 serializer.startTag(null, "item");
6745 serializer.attribute(null, "name", name);
6746 serializer.endTag(null, "item");
6747 }
6748 }
6749 serializer.endTag(null, "perms");
6750 }
6751 if (pkg.disabledComponents.size() > 0) {
6752 serializer.startTag(null, "disabled-components");
6753 for (final String name : pkg.disabledComponents) {
6754 serializer.startTag(null, "item");
6755 serializer.attribute(null, "name", name);
6756 serializer.endTag(null, "item");
6757 }
6758 serializer.endTag(null, "disabled-components");
6759 }
6760 if (pkg.enabledComponents.size() > 0) {
6761 serializer.startTag(null, "enabled-components");
6762 for (final String name : pkg.enabledComponents) {
6763 serializer.startTag(null, "item");
6764 serializer.attribute(null, "name", name);
6765 serializer.endTag(null, "item");
6766 }
6767 serializer.endTag(null, "enabled-components");
6768 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 serializer.endTag(null, "package");
6771 }
6772
6773 void writePermission(XmlSerializer serializer, BasePermission bp)
6774 throws XmlPullParserException, java.io.IOException {
6775 if (bp.type != BasePermission.TYPE_BUILTIN
6776 && bp.sourcePackage != null) {
6777 serializer.startTag(null, "item");
6778 serializer.attribute(null, "name", bp.name);
6779 serializer.attribute(null, "package", bp.sourcePackage);
6780 if (DEBUG_SETTINGS) Log.v(TAG,
6781 "Writing perm: name=" + bp.name + " type=" + bp.type);
6782 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6783 PermissionInfo pi = bp.perm != null ? bp.perm.info
6784 : bp.pendingInfo;
6785 if (pi != null) {
6786 serializer.attribute(null, "type", "dynamic");
6787 if (pi.icon != 0) {
6788 serializer.attribute(null, "icon",
6789 Integer.toString(pi.icon));
6790 }
6791 if (pi.nonLocalizedLabel != null) {
6792 serializer.attribute(null, "label",
6793 pi.nonLocalizedLabel.toString());
6794 }
6795 if (pi.protectionLevel !=
6796 PermissionInfo.PROTECTION_NORMAL) {
6797 serializer.attribute(null, "protection",
6798 Integer.toString(pi.protectionLevel));
6799 }
6800 }
6801 }
6802 serializer.endTag(null, "item");
6803 }
6804 }
6805
6806 String getReadMessagesLP() {
6807 return mReadMessages.toString();
6808 }
6809
6810 ArrayList<String> getListOfIncompleteInstallPackages() {
6811 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6812 Iterator<String> its = kList.iterator();
6813 ArrayList<String> ret = new ArrayList<String>();
6814 while(its.hasNext()) {
6815 String key = its.next();
6816 PackageSetting ps = mPackages.get(key);
6817 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
6818 ret.add(key);
6819 }
6820 }
6821 return ret;
6822 }
6823
6824 boolean readLP() {
6825 FileInputStream str = null;
6826 if (mBackupSettingsFilename.exists()) {
6827 try {
6828 str = new FileInputStream(mBackupSettingsFilename);
6829 mReadMessages.append("Reading from backup settings file\n");
6830 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006831 if (mSettingsFilename.exists()) {
6832 // If both the backup and settings file exist, we
6833 // ignore the settings since it might have been
6834 // corrupted.
6835 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
6836 mSettingsFilename.delete();
6837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 } catch (java.io.IOException e) {
6839 // We'll try for the normal settings file.
6840 }
6841 }
6842
6843 mPastSignatures.clear();
6844
6845 try {
6846 if (str == null) {
6847 if (!mSettingsFilename.exists()) {
6848 mReadMessages.append("No settings file found\n");
6849 Log.i(TAG, "No current settings file!");
6850 return false;
6851 }
6852 str = new FileInputStream(mSettingsFilename);
6853 }
6854 XmlPullParser parser = Xml.newPullParser();
6855 parser.setInput(str, null);
6856
6857 int type;
6858 while ((type=parser.next()) != XmlPullParser.START_TAG
6859 && type != XmlPullParser.END_DOCUMENT) {
6860 ;
6861 }
6862
6863 if (type != XmlPullParser.START_TAG) {
6864 mReadMessages.append("No start tag found in settings file\n");
6865 Log.e(TAG, "No start tag found in package manager settings");
6866 return false;
6867 }
6868
6869 int outerDepth = parser.getDepth();
6870 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6871 && (type != XmlPullParser.END_TAG
6872 || parser.getDepth() > outerDepth)) {
6873 if (type == XmlPullParser.END_TAG
6874 || type == XmlPullParser.TEXT) {
6875 continue;
6876 }
6877
6878 String tagName = parser.getName();
6879 if (tagName.equals("package")) {
6880 readPackageLP(parser);
6881 } else if (tagName.equals("permissions")) {
6882 readPermissionsLP(mPermissions, parser);
6883 } else if (tagName.equals("permission-trees")) {
6884 readPermissionsLP(mPermissionTrees, parser);
6885 } else if (tagName.equals("shared-user")) {
6886 readSharedUserLP(parser);
6887 } else if (tagName.equals("preferred-packages")) {
6888 readPreferredPackagesLP(parser);
6889 } else if (tagName.equals("preferred-activities")) {
6890 readPreferredActivitiesLP(parser);
6891 } else if(tagName.equals("updated-package")) {
6892 readDisabledSysPackageLP(parser);
6893 } else {
6894 Log.w(TAG, "Unknown element under <packages>: "
6895 + parser.getName());
6896 XmlUtils.skipCurrentTag(parser);
6897 }
6898 }
6899
6900 str.close();
6901
6902 } catch(XmlPullParserException e) {
6903 mReadMessages.append("Error reading: " + e.toString());
6904 Log.e(TAG, "Error reading package manager settings", e);
6905
6906 } catch(java.io.IOException e) {
6907 mReadMessages.append("Error reading: " + e.toString());
6908 Log.e(TAG, "Error reading package manager settings", e);
6909
6910 }
6911
6912 int N = mPendingPackages.size();
6913 for (int i=0; i<N; i++) {
6914 final PendingPackage pp = mPendingPackages.get(i);
6915 Object idObj = getUserIdLP(pp.sharedId);
6916 if (idObj != null && idObj instanceof SharedUserSetting) {
6917 PackageSetting p = getPackageLP(pp.name,
6918 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006919 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006920 if (p == null) {
6921 Log.w(TAG, "Unable to create application package for "
6922 + pp.name);
6923 continue;
6924 }
6925 p.copyFrom(pp);
6926 } else if (idObj != null) {
6927 String msg = "Bad package setting: package " + pp.name
6928 + " has shared uid " + pp.sharedId
6929 + " that is not a shared uid\n";
6930 mReadMessages.append(msg);
6931 Log.e(TAG, msg);
6932 } else {
6933 String msg = "Bad package setting: package " + pp.name
6934 + " has shared uid " + pp.sharedId
6935 + " that is not defined\n";
6936 mReadMessages.append(msg);
6937 Log.e(TAG, msg);
6938 }
6939 }
6940 mPendingPackages.clear();
6941
6942 N = mPendingPreferredPackages.size();
6943 mPreferredPackages.clear();
6944 for (int i=0; i<N; i++) {
6945 final String name = mPendingPreferredPackages.get(i);
6946 final PackageSetting p = mPackages.get(name);
6947 if (p != null) {
6948 mPreferredPackages.add(p);
6949 } else {
6950 Log.w(TAG, "Unknown preferred package: " + name);
6951 }
6952 }
6953 mPendingPreferredPackages.clear();
6954
6955 mReadMessages.append("Read completed successfully: "
6956 + mPackages.size() + " packages, "
6957 + mSharedUsers.size() + " shared uids\n");
6958
6959 return true;
6960 }
6961
6962 private int readInt(XmlPullParser parser, String ns, String name,
6963 int defValue) {
6964 String v = parser.getAttributeValue(ns, name);
6965 try {
6966 if (v == null) {
6967 return defValue;
6968 }
6969 return Integer.parseInt(v);
6970 } catch (NumberFormatException e) {
6971 reportSettingsProblem(Log.WARN,
6972 "Error in package manager settings: attribute " +
6973 name + " has bad integer value " + v + " at "
6974 + parser.getPositionDescription());
6975 }
6976 return defValue;
6977 }
6978
6979 private void readPermissionsLP(HashMap<String, BasePermission> out,
6980 XmlPullParser parser)
6981 throws IOException, XmlPullParserException {
6982 int outerDepth = parser.getDepth();
6983 int type;
6984 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6985 && (type != XmlPullParser.END_TAG
6986 || parser.getDepth() > outerDepth)) {
6987 if (type == XmlPullParser.END_TAG
6988 || type == XmlPullParser.TEXT) {
6989 continue;
6990 }
6991
6992 String tagName = parser.getName();
6993 if (tagName.equals("item")) {
6994 String name = parser.getAttributeValue(null, "name");
6995 String sourcePackage = parser.getAttributeValue(null, "package");
6996 String ptype = parser.getAttributeValue(null, "type");
6997 if (name != null && sourcePackage != null) {
6998 boolean dynamic = "dynamic".equals(ptype);
6999 BasePermission bp = new BasePermission(name, sourcePackage,
7000 dynamic
7001 ? BasePermission.TYPE_DYNAMIC
7002 : BasePermission.TYPE_NORMAL);
7003 if (dynamic) {
7004 PermissionInfo pi = new PermissionInfo();
7005 pi.packageName = sourcePackage.intern();
7006 pi.name = name.intern();
7007 pi.icon = readInt(parser, null, "icon", 0);
7008 pi.nonLocalizedLabel = parser.getAttributeValue(
7009 null, "label");
7010 pi.protectionLevel = readInt(parser, null, "protection",
7011 PermissionInfo.PROTECTION_NORMAL);
7012 bp.pendingInfo = pi;
7013 }
7014 out.put(bp.name, bp);
7015 } else {
7016 reportSettingsProblem(Log.WARN,
7017 "Error in package manager settings: permissions has"
7018 + " no name at " + parser.getPositionDescription());
7019 }
7020 } else {
7021 reportSettingsProblem(Log.WARN,
7022 "Unknown element reading permissions: "
7023 + parser.getName() + " at "
7024 + parser.getPositionDescription());
7025 }
7026 XmlUtils.skipCurrentTag(parser);
7027 }
7028 }
7029
7030 private void readDisabledSysPackageLP(XmlPullParser parser)
7031 throws XmlPullParserException, IOException {
7032 String name = parser.getAttributeValue(null, "name");
7033 String codePathStr = parser.getAttributeValue(null, "codePath");
7034 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
7035 if(resourcePathStr == null) {
7036 resourcePathStr = codePathStr;
7037 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007038 String version = parser.getAttributeValue(null, "version");
7039 int versionCode = 0;
7040 if (version != null) {
7041 try {
7042 versionCode = Integer.parseInt(version);
7043 } catch (NumberFormatException e) {
7044 }
7045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007046
7047 int pkgFlags = 0;
7048 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7049 PackageSetting ps = new PackageSetting(name,
7050 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007051 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 String timeStampStr = parser.getAttributeValue(null, "ts");
7053 if (timeStampStr != null) {
7054 try {
7055 long timeStamp = Long.parseLong(timeStampStr);
7056 ps.setTimeStamp(timeStamp, timeStampStr);
7057 } catch (NumberFormatException e) {
7058 }
7059 }
7060 String idStr = parser.getAttributeValue(null, "userId");
7061 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
7062 if(ps.userId <= 0) {
7063 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7064 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7065 }
7066 int outerDepth = parser.getDepth();
7067 int type;
7068 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7069 && (type != XmlPullParser.END_TAG
7070 || parser.getDepth() > outerDepth)) {
7071 if (type == XmlPullParser.END_TAG
7072 || type == XmlPullParser.TEXT) {
7073 continue;
7074 }
7075
7076 String tagName = parser.getName();
7077 if (tagName.equals("perms")) {
7078 readGrantedPermissionsLP(parser,
7079 ps.grantedPermissions);
7080 } else {
7081 reportSettingsProblem(Log.WARN,
7082 "Unknown element under <updated-package>: "
7083 + parser.getName());
7084 XmlUtils.skipCurrentTag(parser);
7085 }
7086 }
7087 mDisabledSysPackages.put(name, ps);
7088 }
7089
7090 private void readPackageLP(XmlPullParser parser)
7091 throws XmlPullParserException, IOException {
7092 String name = null;
7093 String idStr = null;
7094 String sharedIdStr = null;
7095 String codePathStr = null;
7096 String resourcePathStr = null;
7097 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007098 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 int pkgFlags = 0;
7100 String timeStampStr;
7101 long timeStamp = 0;
7102 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007103 String version = null;
7104 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 try {
7106 name = parser.getAttributeValue(null, "name");
7107 idStr = parser.getAttributeValue(null, "userId");
7108 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7109 codePathStr = parser.getAttributeValue(null, "codePath");
7110 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007111 version = parser.getAttributeValue(null, "version");
7112 if (version != null) {
7113 try {
7114 versionCode = Integer.parseInt(version);
7115 } catch (NumberFormatException e) {
7116 }
7117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazski65e13172009-04-28 15:26:38 +02007119 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007120 if (systemStr != null) {
7121 if ("true".equals(systemStr)) {
7122 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7123 }
7124 } else {
7125 // Old settings that don't specify system... just treat
7126 // them as system, good enough.
7127 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7128 }
7129 timeStampStr = parser.getAttributeValue(null, "ts");
7130 if (timeStampStr != null) {
7131 try {
7132 timeStamp = Long.parseLong(timeStampStr);
7133 } catch (NumberFormatException e) {
7134 }
7135 }
7136 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7137 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7138 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7139 if (resourcePathStr == null) {
7140 resourcePathStr = codePathStr;
7141 }
7142 if (name == null) {
7143 reportSettingsProblem(Log.WARN,
7144 "Error in package manager settings: <package> has no name at "
7145 + parser.getPositionDescription());
7146 } else if (codePathStr == null) {
7147 reportSettingsProblem(Log.WARN,
7148 "Error in package manager settings: <package> has no codePath at "
7149 + parser.getPositionDescription());
7150 } else if (userId > 0) {
7151 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007152 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7154 + ": userId=" + userId + " pkg=" + packageSetting);
7155 if (packageSetting == null) {
7156 reportSettingsProblem(Log.ERROR,
7157 "Failure adding uid " + userId
7158 + " while parsing settings at "
7159 + parser.getPositionDescription());
7160 } else {
7161 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7162 }
7163 } else if (sharedIdStr != null) {
7164 userId = sharedIdStr != null
7165 ? Integer.parseInt(sharedIdStr) : 0;
7166 if (userId > 0) {
7167 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007168 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7170 mPendingPackages.add((PendingPackage) packageSetting);
7171 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7172 + ": sharedUserId=" + userId + " pkg="
7173 + packageSetting);
7174 } else {
7175 reportSettingsProblem(Log.WARN,
7176 "Error in package manager settings: package "
7177 + name + " has bad sharedId " + sharedIdStr
7178 + " at " + parser.getPositionDescription());
7179 }
7180 } else {
7181 reportSettingsProblem(Log.WARN,
7182 "Error in package manager settings: package "
7183 + name + " has bad userId " + idStr + " at "
7184 + parser.getPositionDescription());
7185 }
7186 } catch (NumberFormatException e) {
7187 reportSettingsProblem(Log.WARN,
7188 "Error in package manager settings: package "
7189 + name + " has bad userId " + idStr + " at "
7190 + parser.getPositionDescription());
7191 }
7192 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02007193 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007194 final String enabledStr = parser.getAttributeValue(null, "enabled");
7195 if (enabledStr != null) {
7196 if (enabledStr.equalsIgnoreCase("true")) {
7197 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7198 } else if (enabledStr.equalsIgnoreCase("false")) {
7199 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7200 } else if (enabledStr.equalsIgnoreCase("default")) {
7201 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7202 } else {
7203 reportSettingsProblem(Log.WARN,
7204 "Error in package manager settings: package "
7205 + name + " has bad enabled value: " + idStr
7206 + " at " + parser.getPositionDescription());
7207 }
7208 } else {
7209 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7210 }
7211 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7212 if (installStatusStr != null) {
7213 if (installStatusStr.equalsIgnoreCase("false")) {
7214 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7215 } else {
7216 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7217 }
7218 }
7219
7220 int outerDepth = parser.getDepth();
7221 int type;
7222 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7223 && (type != XmlPullParser.END_TAG
7224 || parser.getDepth() > outerDepth)) {
7225 if (type == XmlPullParser.END_TAG
7226 || type == XmlPullParser.TEXT) {
7227 continue;
7228 }
7229
7230 String tagName = parser.getName();
7231 if (tagName.equals("disabled-components")) {
7232 readDisabledComponentsLP(packageSetting, parser);
7233 } else if (tagName.equals("enabled-components")) {
7234 readEnabledComponentsLP(packageSetting, parser);
7235 } else if (tagName.equals("sigs")) {
7236 packageSetting.signatures.readXml(parser, mPastSignatures);
7237 } else if (tagName.equals("perms")) {
7238 readGrantedPermissionsLP(parser,
7239 packageSetting.loadedPermissions);
7240 packageSetting.permissionsFixed = true;
7241 } else {
7242 reportSettingsProblem(Log.WARN,
7243 "Unknown element under <package>: "
7244 + parser.getName());
7245 XmlUtils.skipCurrentTag(parser);
7246 }
7247 }
7248 } else {
7249 XmlUtils.skipCurrentTag(parser);
7250 }
7251 }
7252
7253 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7254 XmlPullParser parser)
7255 throws IOException, XmlPullParserException {
7256 int outerDepth = parser.getDepth();
7257 int type;
7258 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7259 && (type != XmlPullParser.END_TAG
7260 || parser.getDepth() > outerDepth)) {
7261 if (type == XmlPullParser.END_TAG
7262 || type == XmlPullParser.TEXT) {
7263 continue;
7264 }
7265
7266 String tagName = parser.getName();
7267 if (tagName.equals("item")) {
7268 String name = parser.getAttributeValue(null, "name");
7269 if (name != null) {
7270 packageSetting.disabledComponents.add(name.intern());
7271 } else {
7272 reportSettingsProblem(Log.WARN,
7273 "Error in package manager settings: <disabled-components> has"
7274 + " no name at " + parser.getPositionDescription());
7275 }
7276 } else {
7277 reportSettingsProblem(Log.WARN,
7278 "Unknown element under <disabled-components>: "
7279 + parser.getName());
7280 }
7281 XmlUtils.skipCurrentTag(parser);
7282 }
7283 }
7284
7285 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
7286 XmlPullParser parser)
7287 throws IOException, XmlPullParserException {
7288 int outerDepth = parser.getDepth();
7289 int type;
7290 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7291 && (type != XmlPullParser.END_TAG
7292 || parser.getDepth() > outerDepth)) {
7293 if (type == XmlPullParser.END_TAG
7294 || type == XmlPullParser.TEXT) {
7295 continue;
7296 }
7297
7298 String tagName = parser.getName();
7299 if (tagName.equals("item")) {
7300 String name = parser.getAttributeValue(null, "name");
7301 if (name != null) {
7302 packageSetting.enabledComponents.add(name.intern());
7303 } else {
7304 reportSettingsProblem(Log.WARN,
7305 "Error in package manager settings: <enabled-components> has"
7306 + " no name at " + parser.getPositionDescription());
7307 }
7308 } else {
7309 reportSettingsProblem(Log.WARN,
7310 "Unknown element under <enabled-components>: "
7311 + parser.getName());
7312 }
7313 XmlUtils.skipCurrentTag(parser);
7314 }
7315 }
7316
7317 private void readSharedUserLP(XmlPullParser parser)
7318 throws XmlPullParserException, IOException {
7319 String name = null;
7320 String idStr = null;
7321 int pkgFlags = 0;
7322 SharedUserSetting su = null;
7323 try {
7324 name = parser.getAttributeValue(null, "name");
7325 idStr = parser.getAttributeValue(null, "userId");
7326 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7327 if ("true".equals(parser.getAttributeValue(null, "system"))) {
7328 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7329 }
7330 if (name == null) {
7331 reportSettingsProblem(Log.WARN,
7332 "Error in package manager settings: <shared-user> has no name at "
7333 + parser.getPositionDescription());
7334 } else if (userId == 0) {
7335 reportSettingsProblem(Log.WARN,
7336 "Error in package manager settings: shared-user "
7337 + name + " has bad userId " + idStr + " at "
7338 + parser.getPositionDescription());
7339 } else {
7340 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
7341 reportSettingsProblem(Log.ERROR,
7342 "Occurred while parsing settings at "
7343 + parser.getPositionDescription());
7344 }
7345 }
7346 } catch (NumberFormatException e) {
7347 reportSettingsProblem(Log.WARN,
7348 "Error in package manager settings: package "
7349 + name + " has bad userId " + idStr + " at "
7350 + parser.getPositionDescription());
7351 };
7352
7353 if (su != null) {
7354 int outerDepth = parser.getDepth();
7355 int type;
7356 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7357 && (type != XmlPullParser.END_TAG
7358 || parser.getDepth() > outerDepth)) {
7359 if (type == XmlPullParser.END_TAG
7360 || type == XmlPullParser.TEXT) {
7361 continue;
7362 }
7363
7364 String tagName = parser.getName();
7365 if (tagName.equals("sigs")) {
7366 su.signatures.readXml(parser, mPastSignatures);
7367 } else if (tagName.equals("perms")) {
7368 readGrantedPermissionsLP(parser, su.loadedPermissions);
7369 } else {
7370 reportSettingsProblem(Log.WARN,
7371 "Unknown element under <shared-user>: "
7372 + parser.getName());
7373 XmlUtils.skipCurrentTag(parser);
7374 }
7375 }
7376
7377 } else {
7378 XmlUtils.skipCurrentTag(parser);
7379 }
7380 }
7381
7382 private void readGrantedPermissionsLP(XmlPullParser parser,
7383 HashSet<String> outPerms) throws IOException, XmlPullParserException {
7384 int outerDepth = parser.getDepth();
7385 int type;
7386 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7387 && (type != XmlPullParser.END_TAG
7388 || parser.getDepth() > outerDepth)) {
7389 if (type == XmlPullParser.END_TAG
7390 || type == XmlPullParser.TEXT) {
7391 continue;
7392 }
7393
7394 String tagName = parser.getName();
7395 if (tagName.equals("item")) {
7396 String name = parser.getAttributeValue(null, "name");
7397 if (name != null) {
7398 outPerms.add(name.intern());
7399 } else {
7400 reportSettingsProblem(Log.WARN,
7401 "Error in package manager settings: <perms> has"
7402 + " no name at " + parser.getPositionDescription());
7403 }
7404 } else {
7405 reportSettingsProblem(Log.WARN,
7406 "Unknown element under <perms>: "
7407 + parser.getName());
7408 }
7409 XmlUtils.skipCurrentTag(parser);
7410 }
7411 }
7412
7413 private void readPreferredPackagesLP(XmlPullParser parser)
7414 throws XmlPullParserException, IOException {
7415 int outerDepth = parser.getDepth();
7416 int type;
7417 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7418 && (type != XmlPullParser.END_TAG
7419 || parser.getDepth() > outerDepth)) {
7420 if (type == XmlPullParser.END_TAG
7421 || type == XmlPullParser.TEXT) {
7422 continue;
7423 }
7424
7425 String tagName = parser.getName();
7426 if (tagName.equals("item")) {
7427 String name = parser.getAttributeValue(null, "name");
7428 if (name != null) {
7429 mPendingPreferredPackages.add(name);
7430 } else {
7431 reportSettingsProblem(Log.WARN,
7432 "Error in package manager settings: <preferred-package> has no name at "
7433 + parser.getPositionDescription());
7434 }
7435 } else {
7436 reportSettingsProblem(Log.WARN,
7437 "Unknown element under <preferred-packages>: "
7438 + parser.getName());
7439 }
7440 XmlUtils.skipCurrentTag(parser);
7441 }
7442 }
7443
7444 private void readPreferredActivitiesLP(XmlPullParser parser)
7445 throws XmlPullParserException, IOException {
7446 int outerDepth = parser.getDepth();
7447 int type;
7448 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7449 && (type != XmlPullParser.END_TAG
7450 || parser.getDepth() > outerDepth)) {
7451 if (type == XmlPullParser.END_TAG
7452 || type == XmlPullParser.TEXT) {
7453 continue;
7454 }
7455
7456 String tagName = parser.getName();
7457 if (tagName.equals("item")) {
7458 PreferredActivity pa = new PreferredActivity(parser);
7459 if (pa.mParseError == null) {
7460 mPreferredActivities.addFilter(pa);
7461 } else {
7462 reportSettingsProblem(Log.WARN,
7463 "Error in package manager settings: <preferred-activity> "
7464 + pa.mParseError + " at "
7465 + parser.getPositionDescription());
7466 }
7467 } else {
7468 reportSettingsProblem(Log.WARN,
7469 "Unknown element under <preferred-activities>: "
7470 + parser.getName());
7471 XmlUtils.skipCurrentTag(parser);
7472 }
7473 }
7474 }
7475
7476 // Returns -1 if we could not find an available UserId to assign
7477 private int newUserIdLP(Object obj) {
7478 // Let's be stupidly inefficient for now...
7479 final int N = mUserIds.size();
7480 for (int i=0; i<N; i++) {
7481 if (mUserIds.get(i) == null) {
7482 mUserIds.set(i, obj);
7483 return FIRST_APPLICATION_UID + i;
7484 }
7485 }
7486
7487 // None left?
7488 if (N >= MAX_APPLICATION_UIDS) {
7489 return -1;
7490 }
7491
7492 mUserIds.add(obj);
7493 return FIRST_APPLICATION_UID + N;
7494 }
7495
7496 public PackageSetting getDisabledSystemPkg(String name) {
7497 synchronized(mPackages) {
7498 PackageSetting ps = mDisabledSysPackages.get(name);
7499 return ps;
7500 }
7501 }
7502
7503 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7504 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7505 if (Config.LOGV) {
7506 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7507 + " componentName = " + componentInfo.name);
7508 Log.v(TAG, "enabledComponents: "
7509 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7510 Log.v(TAG, "disabledComponents: "
7511 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7512 }
7513 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7514 || ((componentInfo.enabled
7515 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7516 || (componentInfo.applicationInfo.enabled
7517 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7518 && !packageSettings.disabledComponents.contains(componentInfo.name))
7519 || packageSettings.enabledComponents.contains(componentInfo.name));
7520 }
7521 }
7522}