blob: 93821464c243c59479a3f62a8719226e63780c88 [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) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 clearPackagePreferredActivitiesLP(pkg.packageName);
2970
2971 mPackages.remove(pkg.applicationInfo.packageName);
2972 if (pkg.mPath != null) {
2973 mAppDirs.remove(pkg.mPath);
2974 }
2975
2976 PackageSetting ps = (PackageSetting)pkg.mExtras;
2977 if (ps != null && ps.sharedUser != null) {
2978 // XXX don't do this until the data is removed.
2979 if (false) {
2980 ps.sharedUser.packages.remove(ps);
2981 if (ps.sharedUser.packages.size() == 0) {
2982 // Remove.
2983 }
2984 }
2985 }
2986
2987 int N = pkg.providers.size();
2988 StringBuilder r = null;
2989 int i;
2990 for (i=0; i<N; i++) {
2991 PackageParser.Provider p = pkg.providers.get(i);
2992 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
2993 p.info.name));
2994 if (p.info.authority == null) {
2995
2996 /* The is another ContentProvider with this authority when
2997 * this app was installed so this authority is null,
2998 * Ignore it as we don't have to unregister the provider.
2999 */
3000 continue;
3001 }
3002 String names[] = p.info.authority.split(";");
3003 for (int j = 0; j < names.length; j++) {
3004 if (mProviders.get(names[j]) == p) {
3005 mProviders.remove(names[j]);
3006 if (chatty && Config.LOGD) Log.d(
3007 TAG, "Unregistered content provider: " + names[j] +
3008 ", className = " + p.info.name +
3009 ", isSyncable = " + p.info.isSyncable);
3010 }
3011 }
3012 if (chatty) {
3013 if (r == null) {
3014 r = new StringBuilder(256);
3015 } else {
3016 r.append(' ');
3017 }
3018 r.append(p.info.name);
3019 }
3020 }
3021 if (r != null) {
3022 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3023 }
3024
3025 N = pkg.services.size();
3026 r = null;
3027 for (i=0; i<N; i++) {
3028 PackageParser.Service s = pkg.services.get(i);
3029 mServices.removeService(s);
3030 if (chatty) {
3031 if (r == null) {
3032 r = new StringBuilder(256);
3033 } else {
3034 r.append(' ');
3035 }
3036 r.append(s.info.name);
3037 }
3038 }
3039 if (r != null) {
3040 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3041 }
3042
3043 N = pkg.receivers.size();
3044 r = null;
3045 for (i=0; i<N; i++) {
3046 PackageParser.Activity a = pkg.receivers.get(i);
3047 mReceivers.removeActivity(a, "receiver");
3048 if (chatty) {
3049 if (r == null) {
3050 r = new StringBuilder(256);
3051 } else {
3052 r.append(' ');
3053 }
3054 r.append(a.info.name);
3055 }
3056 }
3057 if (r != null) {
3058 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3059 }
3060
3061 N = pkg.activities.size();
3062 r = null;
3063 for (i=0; i<N; i++) {
3064 PackageParser.Activity a = pkg.activities.get(i);
3065 mActivities.removeActivity(a, "activity");
3066 if (chatty) {
3067 if (r == null) {
3068 r = new StringBuilder(256);
3069 } else {
3070 r.append(' ');
3071 }
3072 r.append(a.info.name);
3073 }
3074 }
3075 if (r != null) {
3076 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3077 }
3078
3079 N = pkg.permissions.size();
3080 r = null;
3081 for (i=0; i<N; i++) {
3082 PackageParser.Permission p = pkg.permissions.get(i);
3083 boolean tree = false;
3084 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3085 if (bp == null) {
3086 tree = true;
3087 bp = mSettings.mPermissionTrees.get(p.info.name);
3088 }
3089 if (bp != null && bp.perm == p) {
3090 if (bp.type != BasePermission.TYPE_BUILTIN) {
3091 if (tree) {
3092 mSettings.mPermissionTrees.remove(p.info.name);
3093 } else {
3094 mSettings.mPermissions.remove(p.info.name);
3095 }
3096 } else {
3097 bp.perm = null;
3098 }
3099 if (chatty) {
3100 if (r == null) {
3101 r = new StringBuilder(256);
3102 } else {
3103 r.append(' ');
3104 }
3105 r.append(p.info.name);
3106 }
3107 }
3108 }
3109 if (r != null) {
3110 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3111 }
3112
3113 N = pkg.instrumentation.size();
3114 r = null;
3115 for (i=0; i<N; i++) {
3116 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3117 mInstrumentation.remove(a.component);
3118 if (chatty) {
3119 if (r == null) {
3120 r = new StringBuilder(256);
3121 } else {
3122 r.append(' ');
3123 }
3124 r.append(a.info.name);
3125 }
3126 }
3127 if (r != null) {
3128 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3129 }
3130 }
3131 }
3132
3133 private static final boolean isPackageFilename(String name) {
3134 return name != null && name.endsWith(".apk");
3135 }
3136
3137 private void updatePermissionsLP() {
3138 // Make sure there are no dangling permission trees.
3139 Iterator<BasePermission> it = mSettings.mPermissionTrees
3140 .values().iterator();
3141 while (it.hasNext()) {
3142 BasePermission bp = it.next();
3143 if (bp.perm == null) {
3144 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3145 + " from package " + bp.sourcePackage);
3146 it.remove();
3147 }
3148 }
3149
3150 // Make sure all dynamic permissions have been assigned to a package,
3151 // and make sure there are no dangling permissions.
3152 it = mSettings.mPermissions.values().iterator();
3153 while (it.hasNext()) {
3154 BasePermission bp = it.next();
3155 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3156 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3157 + bp.name + " pkg=" + bp.sourcePackage
3158 + " info=" + bp.pendingInfo);
3159 if (bp.perm == null && bp.pendingInfo != null) {
3160 BasePermission tree = findPermissionTreeLP(bp.name);
3161 if (tree != null) {
3162 bp.perm = new PackageParser.Permission(tree.perm.owner,
3163 new PermissionInfo(bp.pendingInfo));
3164 bp.perm.info.packageName = tree.perm.info.packageName;
3165 bp.perm.info.name = bp.name;
3166 bp.uid = tree.uid;
3167 }
3168 }
3169 }
3170 if (bp.perm == null) {
3171 Log.w(TAG, "Removing dangling permission: " + bp.name
3172 + " from package " + bp.sourcePackage);
3173 it.remove();
3174 }
3175 }
3176
3177 // Now update the permissions for all packages, in particular
3178 // replace the granted permissions of the system packages.
3179 for (PackageParser.Package pkg : mPackages.values()) {
3180 grantPermissionsLP(pkg, false);
3181 }
3182 }
3183
3184 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3185 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3186 if (ps == null) {
3187 return;
3188 }
3189 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3190 boolean addedPermission = false;
3191
3192 if (replace) {
3193 ps.permissionsFixed = false;
3194 if (gp == ps) {
3195 gp.grantedPermissions.clear();
3196 gp.gids = mGlobalGids;
3197 }
3198 }
3199
3200 if (gp.gids == null) {
3201 gp.gids = mGlobalGids;
3202 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07003203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 final int N = pkg.requestedPermissions.size();
3205 for (int i=0; i<N; i++) {
3206 String name = pkg.requestedPermissions.get(i);
3207 BasePermission bp = mSettings.mPermissions.get(name);
3208 PackageParser.Permission p = bp != null ? bp.perm : null;
3209 if (false) {
3210 if (gp != ps) {
3211 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3212 + ": " + p);
3213 }
3214 }
3215 if (p != null) {
3216 final String perm = p.info.name;
3217 boolean allowed;
3218 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3219 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3220 allowed = true;
3221 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3222 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003223 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003225 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 == PackageManager.SIGNATURE_MATCH);
3227 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3228 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3229 // For updated system applications, the signatureOrSystem permission
3230 // is granted only if it had been defined by the original application.
3231 if ((pkg.applicationInfo.flags
3232 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3233 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3234 if(sysPs.grantedPermissions.contains(perm)) {
3235 allowed = true;
3236 } else {
3237 allowed = false;
3238 }
3239 } else {
3240 allowed = true;
3241 }
3242 }
3243 }
3244 } else {
3245 allowed = false;
3246 }
3247 if (false) {
3248 if (gp != ps) {
3249 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3250 }
3251 }
3252 if (allowed) {
3253 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3254 && ps.permissionsFixed) {
3255 // If this is an existing, non-system package, then
3256 // we can't add any new permissions to it.
3257 if (!gp.loadedPermissions.contains(perm)) {
3258 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003259 // Except... if this is a permission that was added
3260 // to the platform (note: need to only do this when
3261 // updating the platform).
3262 final int NP = PackageParser.NEW_PERMISSIONS.length;
3263 for (int ip=0; ip<NP; ip++) {
3264 final PackageParser.NewPermissionInfo npi
3265 = PackageParser.NEW_PERMISSIONS[ip];
3266 if (npi.name.equals(perm)
3267 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3268 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003269 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003270 + pkg.packageName);
3271 break;
3272 }
3273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 }
3275 }
3276 if (allowed) {
3277 if (!gp.grantedPermissions.contains(perm)) {
3278 addedPermission = true;
3279 gp.grantedPermissions.add(perm);
3280 gp.gids = appendInts(gp.gids, bp.gids);
3281 }
3282 } else {
3283 Log.w(TAG, "Not granting permission " + perm
3284 + " to package " + pkg.packageName
3285 + " because it was previously installed without");
3286 }
3287 } else {
3288 Log.w(TAG, "Not granting permission " + perm
3289 + " to package " + pkg.packageName
3290 + " (protectionLevel=" + p.info.protectionLevel
3291 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3292 + ")");
3293 }
3294 } else {
3295 Log.w(TAG, "Unknown permission " + name
3296 + " in package " + pkg.packageName);
3297 }
3298 }
3299
3300 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003301 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3302 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 // This is the first that we have heard about this package, so the
3304 // permissions we have now selected are fixed until explicitly
3305 // changed.
3306 ps.permissionsFixed = true;
3307 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3308 }
3309 }
3310
3311 private final class ActivityIntentResolver
3312 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003313 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003315 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 }
3317
Mihai Preda074edef2009-05-18 17:13:31 +02003318 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003320 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3322 }
3323
Mihai Predaeae850c2009-05-13 10:13:48 +02003324 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3325 ArrayList<PackageParser.Activity> packageActivities) {
3326 if (packageActivities == null) {
3327 return null;
3328 }
3329 mFlags = flags;
3330 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3331 int N = packageActivities.size();
3332 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3333 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003334
3335 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003336 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003337 intentFilters = packageActivities.get(i).intents;
3338 if (intentFilters != null && intentFilters.size() > 0) {
3339 listCut.add(intentFilters);
3340 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003341 }
3342 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3343 }
3344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 public final void addActivity(PackageParser.Activity a, String type) {
3346 mActivities.put(a.component, a);
3347 if (SHOW_INFO || Config.LOGV) Log.v(
3348 TAG, " " + type + " " +
3349 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3350 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3351 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003352 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3354 if (SHOW_INFO || Config.LOGV) {
3355 Log.v(TAG, " IntentFilter:");
3356 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3357 }
3358 if (!intent.debugCheck()) {
3359 Log.w(TAG, "==> For Activity " + a.info.name);
3360 }
3361 addFilter(intent);
3362 }
3363 }
3364
3365 public final void removeActivity(PackageParser.Activity a, String type) {
3366 mActivities.remove(a.component);
3367 if (SHOW_INFO || Config.LOGV) Log.v(
3368 TAG, " " + type + " " +
3369 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3370 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3371 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003372 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3374 if (SHOW_INFO || Config.LOGV) {
3375 Log.v(TAG, " IntentFilter:");
3376 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3377 }
3378 removeFilter(intent);
3379 }
3380 }
3381
3382 @Override
3383 protected boolean allowFilterResult(
3384 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3385 ActivityInfo filterAi = filter.activity.info;
3386 for (int i=dest.size()-1; i>=0; i--) {
3387 ActivityInfo destAi = dest.get(i).activityInfo;
3388 if (destAi.name == filterAi.name
3389 && destAi.packageName == filterAi.packageName) {
3390 return false;
3391 }
3392 }
3393 return true;
3394 }
3395
3396 @Override
3397 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3398 int match) {
3399 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3400 return null;
3401 }
3402 final PackageParser.Activity activity = info.activity;
3403 if (mSafeMode && (activity.info.applicationInfo.flags
3404 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3405 return null;
3406 }
3407 final ResolveInfo res = new ResolveInfo();
3408 res.activityInfo = PackageParser.generateActivityInfo(activity,
3409 mFlags);
3410 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3411 res.filter = info;
3412 }
3413 res.priority = info.getPriority();
3414 res.preferredOrder = activity.owner.mPreferredOrder;
3415 //System.out.println("Result: " + res.activityInfo.className +
3416 // " = " + res.priority);
3417 res.match = match;
3418 res.isDefault = info.hasDefault;
3419 res.labelRes = info.labelRes;
3420 res.nonLocalizedLabel = info.nonLocalizedLabel;
3421 res.icon = info.icon;
3422 return res;
3423 }
3424
3425 @Override
3426 protected void sortResults(List<ResolveInfo> results) {
3427 Collections.sort(results, mResolvePrioritySorter);
3428 }
3429
3430 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003431 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003433 out.print(prefix); out.print(
3434 Integer.toHexString(System.identityHashCode(filter.activity)));
3435 out.print(' ');
3436 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 }
3438
3439// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3440// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3441// final List<ResolveInfo> retList = Lists.newArrayList();
3442// while (i.hasNext()) {
3443// final ResolveInfo resolveInfo = i.next();
3444// if (isEnabledLP(resolveInfo.activityInfo)) {
3445// retList.add(resolveInfo);
3446// }
3447// }
3448// return retList;
3449// }
3450
3451 // Keys are String (activity class name), values are Activity.
3452 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3453 = new HashMap<ComponentName, PackageParser.Activity>();
3454 private int mFlags;
3455 }
3456
3457 private final class ServiceIntentResolver
3458 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003459 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003461 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 }
3463
Mihai Preda074edef2009-05-18 17:13:31 +02003464 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003466 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3468 }
3469
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003470 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3471 ArrayList<PackageParser.Service> packageServices) {
3472 if (packageServices == null) {
3473 return null;
3474 }
3475 mFlags = flags;
3476 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3477 int N = packageServices.size();
3478 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3479 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3480
3481 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3482 for (int i = 0; i < N; ++i) {
3483 intentFilters = packageServices.get(i).intents;
3484 if (intentFilters != null && intentFilters.size() > 0) {
3485 listCut.add(intentFilters);
3486 }
3487 }
3488 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3489 }
3490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 public final void addService(PackageParser.Service s) {
3492 mServices.put(s.component, s);
3493 if (SHOW_INFO || Config.LOGV) Log.v(
3494 TAG, " " + (s.info.nonLocalizedLabel != null
3495 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3496 if (SHOW_INFO || Config.LOGV) Log.v(
3497 TAG, " Class=" + s.info.name);
3498 int NI = s.intents.size();
3499 int j;
3500 for (j=0; j<NI; j++) {
3501 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3502 if (SHOW_INFO || Config.LOGV) {
3503 Log.v(TAG, " IntentFilter:");
3504 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3505 }
3506 if (!intent.debugCheck()) {
3507 Log.w(TAG, "==> For Service " + s.info.name);
3508 }
3509 addFilter(intent);
3510 }
3511 }
3512
3513 public final void removeService(PackageParser.Service s) {
3514 mServices.remove(s.component);
3515 if (SHOW_INFO || Config.LOGV) Log.v(
3516 TAG, " " + (s.info.nonLocalizedLabel != null
3517 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3518 if (SHOW_INFO || Config.LOGV) Log.v(
3519 TAG, " Class=" + s.info.name);
3520 int NI = s.intents.size();
3521 int j;
3522 for (j=0; j<NI; j++) {
3523 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3524 if (SHOW_INFO || Config.LOGV) {
3525 Log.v(TAG, " IntentFilter:");
3526 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3527 }
3528 removeFilter(intent);
3529 }
3530 }
3531
3532 @Override
3533 protected boolean allowFilterResult(
3534 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3535 ServiceInfo filterSi = filter.service.info;
3536 for (int i=dest.size()-1; i>=0; i--) {
3537 ServiceInfo destAi = dest.get(i).serviceInfo;
3538 if (destAi.name == filterSi.name
3539 && destAi.packageName == filterSi.packageName) {
3540 return false;
3541 }
3542 }
3543 return true;
3544 }
3545
3546 @Override
3547 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3548 int match) {
3549 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3550 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3551 return null;
3552 }
3553 final PackageParser.Service service = info.service;
3554 if (mSafeMode && (service.info.applicationInfo.flags
3555 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3556 return null;
3557 }
3558 final ResolveInfo res = new ResolveInfo();
3559 res.serviceInfo = PackageParser.generateServiceInfo(service,
3560 mFlags);
3561 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3562 res.filter = filter;
3563 }
3564 res.priority = info.getPriority();
3565 res.preferredOrder = service.owner.mPreferredOrder;
3566 //System.out.println("Result: " + res.activityInfo.className +
3567 // " = " + res.priority);
3568 res.match = match;
3569 res.isDefault = info.hasDefault;
3570 res.labelRes = info.labelRes;
3571 res.nonLocalizedLabel = info.nonLocalizedLabel;
3572 res.icon = info.icon;
3573 return res;
3574 }
3575
3576 @Override
3577 protected void sortResults(List<ResolveInfo> results) {
3578 Collections.sort(results, mResolvePrioritySorter);
3579 }
3580
3581 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003582 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003584 out.print(prefix); out.print(
3585 Integer.toHexString(System.identityHashCode(filter.service)));
3586 out.print(' ');
3587 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 }
3589
3590// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3591// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3592// final List<ResolveInfo> retList = Lists.newArrayList();
3593// while (i.hasNext()) {
3594// final ResolveInfo resolveInfo = (ResolveInfo) i;
3595// if (isEnabledLP(resolveInfo.serviceInfo)) {
3596// retList.add(resolveInfo);
3597// }
3598// }
3599// return retList;
3600// }
3601
3602 // Keys are String (activity class name), values are Activity.
3603 private final HashMap<ComponentName, PackageParser.Service> mServices
3604 = new HashMap<ComponentName, PackageParser.Service>();
3605 private int mFlags;
3606 };
3607
3608 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3609 new Comparator<ResolveInfo>() {
3610 public int compare(ResolveInfo r1, ResolveInfo r2) {
3611 int v1 = r1.priority;
3612 int v2 = r2.priority;
3613 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3614 if (v1 != v2) {
3615 return (v1 > v2) ? -1 : 1;
3616 }
3617 v1 = r1.preferredOrder;
3618 v2 = r2.preferredOrder;
3619 if (v1 != v2) {
3620 return (v1 > v2) ? -1 : 1;
3621 }
3622 if (r1.isDefault != r2.isDefault) {
3623 return r1.isDefault ? -1 : 1;
3624 }
3625 v1 = r1.match;
3626 v2 = r2.match;
3627 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3628 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3629 }
3630 };
3631
3632 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3633 new Comparator<ProviderInfo>() {
3634 public int compare(ProviderInfo p1, ProviderInfo p2) {
3635 final int v1 = p1.initOrder;
3636 final int v2 = p2.initOrder;
3637 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3638 }
3639 };
3640
3641 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3642 IActivityManager am = ActivityManagerNative.getDefault();
3643 if (am != null) {
3644 try {
3645 final Intent intent = new Intent(action,
3646 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3647 if (extras != null) {
3648 intent.putExtras(extras);
3649 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003650 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 am.broadcastIntent(
3652 null, intent,
3653 null, null, 0, null, null, null, false, false);
3654 } catch (RemoteException ex) {
3655 }
3656 }
3657 }
3658
3659 private final class AppDirObserver extends FileObserver {
3660 public AppDirObserver(String path, int mask, boolean isrom) {
3661 super(path, mask);
3662 mRootDir = path;
3663 mIsRom = isrom;
3664 }
3665
3666 public void onEvent(int event, String path) {
3667 String removedPackage = null;
3668 int removedUid = -1;
3669 String addedPackage = null;
3670 int addedUid = -1;
3671
3672 synchronized (mInstallLock) {
3673 String fullPathStr = null;
3674 File fullPath = null;
3675 if (path != null) {
3676 fullPath = new File(mRootDir, path);
3677 fullPathStr = fullPath.getPath();
3678 }
3679
3680 if (Config.LOGV) Log.v(
3681 TAG, "File " + fullPathStr + " changed: "
3682 + Integer.toHexString(event));
3683
3684 if (!isPackageFilename(path)) {
3685 if (Config.LOGV) Log.v(
3686 TAG, "Ignoring change of non-package file: " + fullPathStr);
3687 return;
3688 }
3689
3690 if ((event&REMOVE_EVENTS) != 0) {
3691 synchronized (mInstallLock) {
3692 PackageParser.Package p = mAppDirs.get(fullPathStr);
3693 if (p != null) {
3694 removePackageLI(p, true);
3695 removedPackage = p.applicationInfo.packageName;
3696 removedUid = p.applicationInfo.uid;
3697 }
3698 }
3699 }
3700
3701 if ((event&ADD_EVENTS) != 0) {
3702 PackageParser.Package p = mAppDirs.get(fullPathStr);
3703 if (p == null) {
3704 p = scanPackageLI(fullPath, fullPath, fullPath,
3705 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3706 PackageParser.PARSE_CHATTY |
3707 PackageParser.PARSE_MUST_BE_APK,
3708 SCAN_MONITOR);
3709 if (p != null) {
3710 synchronized (mPackages) {
3711 grantPermissionsLP(p, false);
3712 }
3713 addedPackage = p.applicationInfo.packageName;
3714 addedUid = p.applicationInfo.uid;
3715 }
3716 }
3717 }
3718
3719 synchronized (mPackages) {
3720 mSettings.writeLP();
3721 }
3722 }
3723
3724 if (removedPackage != null) {
3725 Bundle extras = new Bundle(1);
3726 extras.putInt(Intent.EXTRA_UID, removedUid);
3727 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3728 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3729 }
3730 if (addedPackage != null) {
3731 Bundle extras = new Bundle(1);
3732 extras.putInt(Intent.EXTRA_UID, addedUid);
3733 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3734 }
3735 }
3736
3737 private final String mRootDir;
3738 private final boolean mIsRom;
3739 }
Jacek Surazski65e13172009-04-28 15:26:38 +02003740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 /* Called when a downloaded package installation has been confirmed by the user */
3742 public void installPackage(
3743 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003744 installPackage(packageURI, observer, flags, null);
3745 }
3746
3747 /* 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,
3750 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 mContext.enforceCallingOrSelfPermission(
3752 android.Manifest.permission.INSTALL_PACKAGES, null);
Jacek Surazski65e13172009-04-28 15:26:38 +02003753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 // Queue up an async operation since the package installation may take a little while.
3755 mHandler.post(new Runnable() {
3756 public void run() {
3757 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003758 // Result object to be returned
3759 PackageInstalledInfo res = new PackageInstalledInfo();
3760 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3761 res.uid = -1;
3762 res.pkg = null;
3763 res.removedInfo = new PackageRemovedInfo();
3764 // Make a temporary copy of file from given packageURI
3765 File tmpPackageFile = copyTempInstallFile(packageURI, res);
3766 if (tmpPackageFile != null) {
3767 synchronized (mInstallLock) {
3768 installPackageLI(packageURI, flags, true, installerPackageName, tmpPackageFile, res);
3769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 }
3771 if (observer != null) {
3772 try {
3773 observer.packageInstalled(res.name, res.returnCode);
3774 } catch (RemoteException e) {
3775 Log.i(TAG, "Observer no longer exists.");
3776 }
3777 }
3778 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3779 // call appears in the synchronized block above.
3780 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3781 res.removedInfo.sendBroadcast(false, true);
3782 Bundle extras = new Bundle(1);
3783 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003784 final boolean update = res.removedInfo.removedPackage != null;
3785 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3787 }
3788 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3789 res.pkg.applicationInfo.packageName,
3790 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003791 if (update) {
3792 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3793 res.pkg.applicationInfo.packageName,
3794 extras);
3795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 }
3797 Runtime.getRuntime().gc();
3798 }
3799 });
3800 }
3801
3802 class PackageInstalledInfo {
3803 String name;
3804 int uid;
3805 PackageParser.Package pkg;
3806 int returnCode;
3807 PackageRemovedInfo removedInfo;
3808 }
3809
3810 /*
3811 * Install a non-existing package.
3812 */
3813 private void installNewPackageLI(String pkgName,
3814 File tmpPackageFile,
3815 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003816 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003817 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818 // Remember this for later, in case we need to rollback this install
3819 boolean dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3820 res.name = pkgName;
3821 synchronized(mPackages) {
3822 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(destFilePath)) {
3823 // Don't allow installation over an existing package with the same name.
3824 Log.w(TAG, "Attempt to re-install " + pkgName
3825 + " without first uninstalling.");
3826 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3827 return;
3828 }
3829 }
3830 if (destPackageFile.exists()) {
3831 // It's safe to do this because we know (from the above check) that the file
3832 // isn't currently used for an installed package.
3833 destPackageFile.delete();
3834 }
3835 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3836 PackageParser.Package newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3837 destResourceFile, pkg, 0,
3838 SCAN_MONITOR | SCAN_FORCE_DEX
3839 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003840 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3841 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 if (newPackage == null) {
3843 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3844 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3845 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3846 }
3847 } else {
3848 updateSettingsLI(pkgName, tmpPackageFile,
3849 destFilePath, destPackageFile,
3850 destResourceFile, pkg,
3851 newPackage,
3852 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02003853 forwardLocked,
3854 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 res);
3856 // delete the partially installed application. the data directory will have to be
3857 // restored if it was already existing
3858 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3859 // remove package from internal structures. Note that we want deletePackageX to
3860 // delete the package data and cache directories that it created in
3861 // scanPackageLocked, unless those directories existed before we even tried to
3862 // install.
3863 deletePackageLI(
3864 pkgName, true,
3865 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3866 res.removedInfo);
3867 }
3868 }
3869 }
3870
3871 private void replacePackageLI(String pkgName,
3872 File tmpPackageFile,
3873 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003874 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003875 String installerPackageName, PackageInstalledInfo res) {
3876
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003877 PackageParser.Package oldPackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 // First find the old package info and check signatures
3879 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003880 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003881 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
3882 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3884 return;
3885 }
3886 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003887 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 if(sysPkg) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003889 replaceSystemPackageLI(oldPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003891 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003892 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 } else {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003894 replaceNonSystemPackageLI(oldPackage, tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003895 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003896 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
3898 }
3899
3900 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
3901 File tmpPackageFile,
3902 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003903 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003904 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 PackageParser.Package newPackage = null;
3906 String pkgName = deletedPackage.packageName;
3907 boolean deletedPkg = true;
3908 boolean updatedSettings = false;
Jacek Surazski65e13172009-04-28 15:26:38 +02003909
3910 String oldInstallerPackageName = null;
3911 synchronized (mPackages) {
3912 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3913 }
3914
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003915 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 // First delete the existing package while retaining the data directory
3917 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3918 res.removedInfo)) {
3919 // If the existing package was'nt successfully deleted
3920 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3921 deletedPkg = false;
3922 } else {
3923 // Successfully deleted the old package. Now proceed with re-installation
3924 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3925 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3926 destResourceFile, pkg, parseFlags,
3927 SCAN_MONITOR | SCAN_FORCE_DEX
3928 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003929 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3930 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 if (newPackage == null) {
3932 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3933 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3934 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3935 }
3936 } else {
3937 updateSettingsLI(pkgName, tmpPackageFile,
3938 destFilePath, destPackageFile,
3939 destResourceFile, pkg,
3940 newPackage,
3941 true,
3942 forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003943 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 res);
3945 updatedSettings = true;
3946 }
3947 }
3948
3949 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3950 // If we deleted an exisiting package, the old source and resource files that we
3951 // were keeping around in case we needed them (see below) can now be deleted
3952 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
3953 final ApplicationInfo installedPackageAppInfo =
3954 newPackage.applicationInfo;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003955 deletePackageResourcesLI(pkgName,
3956 !deletedPackageAppInfo.sourceDir
3957 .equals(installedPackageAppInfo.sourceDir)
3958 ? deletedPackageAppInfo.sourceDir : null,
3959 !deletedPackageAppInfo.publicSourceDir
3960 .equals(installedPackageAppInfo.publicSourceDir)
3961 ? deletedPackageAppInfo.publicSourceDir : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 //update signature on the new package setting
3963 //this should always succeed, since we checked the
3964 //signature earlier.
3965 synchronized(mPackages) {
3966 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
3967 parseFlags, true);
3968 }
3969 } else {
3970 // remove package from internal structures. Note that we want deletePackageX to
3971 // delete the package data and cache directories that it created in
3972 // scanPackageLocked, unless those directories existed before we even tried to
3973 // install.
3974 if(updatedSettings) {
3975 deletePackageLI(
3976 pkgName, true,
3977 PackageManager.DONT_DELETE_DATA,
3978 res.removedInfo);
3979 }
3980 // Since we failed to install the new package we need to restore the old
3981 // package that we deleted.
3982 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003983 File restoreFile = new File(deletedPackage.mPath);
3984 if (restoreFile == null) {
3985 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
3986 return;
3987 }
3988 File restoreTmpFile = createTempPackageFile();
3989 if (restoreTmpFile == null) {
3990 Log.e(TAG, "Failed creating temp file when restoring pkg : " + pkgName);
3991 return;
3992 }
3993 if (!FileUtils.copyFile(restoreFile, restoreTmpFile)) {
3994 Log.e(TAG, "Failed copying temp file when restoring pkg : " + pkgName);
3995 return;
3996 }
3997 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
3998 restoreRes.removedInfo = new PackageRemovedInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 installPackageLI(
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004000 Uri.fromFile(restoreFile),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004002 ? PackageManager.INSTALL_FORWARD_LOCK
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004003 : 0, false, oldInstallerPackageName, restoreTmpFile, restoreRes);
4004 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4005 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 }
4008 }
4009 }
4010
4011 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
4012 File tmpPackageFile,
4013 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07004014 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02004015 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 PackageParser.Package newPackage = null;
4017 boolean updatedSettings = false;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004018 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 PackageParser.PARSE_IS_SYSTEM;
4020 String packageName = deletedPackage.packageName;
4021 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4022 if (packageName == null) {
4023 Log.w(TAG, "Attempt to delete null packageName.");
4024 return;
4025 }
4026 PackageParser.Package oldPkg;
4027 PackageSetting oldPkgSetting;
4028 synchronized (mPackages) {
4029 oldPkg = mPackages.get(packageName);
4030 oldPkgSetting = mSettings.mPackages.get(packageName);
4031 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4032 (oldPkgSetting == null)) {
4033 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4034 return;
4035 }
4036 }
4037 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4038 res.removedInfo.removedPackage = packageName;
4039 // Remove existing system package
4040 removePackageLI(oldPkg, true);
4041 synchronized (mPackages) {
4042 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4043 }
4044
4045 // Successfully disabled the old package. Now proceed with re-installation
4046 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4047 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
4048 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
4049 destResourceFile, pkg, parseFlags,
4050 SCAN_MONITOR | SCAN_FORCE_DEX
4051 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07004052 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
4053 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 if (newPackage == null) {
4055 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
4056 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4057 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4058 }
4059 } else {
4060 updateSettingsLI(packageName, tmpPackageFile,
4061 destFilePath, destPackageFile,
4062 destResourceFile, pkg,
4063 newPackage,
4064 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02004065 forwardLocked,
4066 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 res);
4068 updatedSettings = true;
4069 }
4070
4071 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4072 //update signature on the new package setting
4073 //this should always succeed, since we checked the
4074 //signature earlier.
4075 synchronized(mPackages) {
4076 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4077 parseFlags, true);
4078 }
4079 } else {
4080 // Re installation failed. Restore old information
4081 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004082 if (newPackage != null) {
4083 removePackageLI(newPackage, true);
4084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 // Add back the old system package
4086 scanPackageLI(oldPkgSetting.codePath, oldPkgSetting.codePath,
4087 oldPkgSetting.resourcePath,
4088 oldPkg, parseFlags,
4089 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004090 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 // Restore the old system information in Settings
4092 synchronized(mPackages) {
4093 if(updatedSettings) {
4094 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004095 mSettings.setInstallerPackageName(packageName,
4096 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 }
4098 mSettings.writeLP();
4099 }
4100 }
4101 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 private void updateSettingsLI(String pkgName, File tmpPackageFile,
4104 String destFilePath, File destPackageFile,
4105 File destResourceFile,
4106 PackageParser.Package pkg,
4107 PackageParser.Package newPackage,
4108 boolean replacingExistingPackage,
4109 boolean forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02004110 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 synchronized (mPackages) {
4112 //write settings. the installStatus will be incomplete at this stage.
4113 //note that the new package setting would have already been
4114 //added to mPackages. It hasn't been persisted yet.
4115 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4116 mSettings.writeLP();
4117 }
4118
4119 int retCode = 0;
4120 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4121 retCode = mInstaller.movedex(tmpPackageFile.toString(),
4122 destPackageFile.toString());
4123 if (retCode != 0) {
4124 Log.e(TAG, "Couldn't rename dex file: " + destPackageFile);
4125 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4126 return;
4127 }
4128 }
4129 // XXX There are probably some big issues here: upon doing
4130 // the rename, we have reached the point of no return (the
4131 // original .apk is gone!), so we can't fail. Yet... we can.
4132 if (!tmpPackageFile.renameTo(destPackageFile)) {
4133 Log.e(TAG, "Couldn't move package file to: " + destPackageFile);
4134 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4135 } else {
4136 res.returnCode = setPermissionsLI(pkgName, newPackage, destFilePath,
4137 destResourceFile,
4138 forwardLocked);
4139 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4140 return;
4141 } else {
4142 Log.d(TAG, "New package installed in " + destPackageFile);
4143 }
4144 }
4145 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4146 if (mInstaller != null) {
4147 mInstaller.rmdex(tmpPackageFile.getPath());
4148 }
4149 }
4150
4151 synchronized (mPackages) {
4152 grantPermissionsLP(newPackage, true);
4153 res.name = pkgName;
4154 res.uid = newPackage.applicationInfo.uid;
4155 res.pkg = newPackage;
4156 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004157 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004158 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4159 //to update install status
4160 mSettings.writeLP();
4161 }
4162 }
4163
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07004164 private File getFwdLockedResource(String pkgName) {
4165 final String publicZipFileName = pkgName + ".zip";
4166 return new File(mAppInstallDir, publicZipFileName);
4167 }
4168
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004169 private File copyTempInstallFile(Uri pPackageURI,
4170 PackageInstalledInfo res) {
4171 File tmpPackageFile = createTempPackageFile();
4172 int retCode = PackageManager.INSTALL_SUCCEEDED;
4173 if (tmpPackageFile == null) {
4174 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4175 return null;
4176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004178 if (pPackageURI.getScheme().equals("file")) {
4179 final File srcPackageFile = new File(pPackageURI.getPath());
4180 // We copy the source package file to a temp file and then rename it to the
4181 // destination file in order to eliminate a window where the package directory
4182 // scanner notices the new package file but it's not completely copied yet.
4183 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
4184 Log.e(TAG, "Couldn't copy package file to temp file.");
4185 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004187 } else if (pPackageURI.getScheme().equals("content")) {
4188 ParcelFileDescriptor fd = null;
4189 try {
4190 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
4191 } catch (FileNotFoundException e) {
4192 Log.e(TAG, "Couldn't open file descriptor from download service. Failed with exception " + e);
4193 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4194 }
4195 if (fd == null) {
4196 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
4197 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4198 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 if (Config.LOGV) {
4200 Log.v(TAG, "Opened file descriptor from download service.");
4201 }
4202 ParcelFileDescriptor.AutoCloseInputStream
4203 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
4204 // We copy the source package file to a temp file and then rename it to the
4205 // destination file in order to eliminate a window where the package directory
4206 // scanner notices the new package file but it's not completely copied yet.
4207 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
4208 Log.e(TAG, "Couldn't copy package stream to temp file.");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004209 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004212 } else {
4213 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
4214 retCode = PackageManager.INSTALL_FAILED_INVALID_URI;
4215 }
4216
4217 res.returnCode = retCode;
4218 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
4219 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4220 tmpPackageFile.delete();
4221 }
4222 return null;
4223 }
4224 return tmpPackageFile;
4225 }
4226
4227 private void installPackageLI(Uri pPackageURI,
4228 int pFlags, boolean newInstall, String installerPackageName,
4229 File tmpPackageFile, PackageInstalledInfo res) {
4230 String pkgName = null;
4231 boolean forwardLocked = false;
4232 boolean replacingExistingPackage = false;
4233 // Result object to be returned
4234 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4235
4236 main_flow: try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 pkgName = PackageParser.parsePackageName(
4238 tmpPackageFile.getAbsolutePath(), 0);
4239 if (pkgName == null) {
4240 Log.e(TAG, "Couldn't find a package name in : " + tmpPackageFile);
4241 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4242 break main_flow;
4243 }
4244 res.name = pkgName;
4245 //initialize some variables before installing pkg
4246 final String pkgFileName = pkgName + ".apk";
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004247 final File destDir = ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 ? mDrmAppPrivateInstallDir
4249 : mAppInstallDir;
4250 final File destPackageFile = new File(destDir, pkgFileName);
4251 final String destFilePath = destPackageFile.getAbsolutePath();
4252 File destResourceFile;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004253 if ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0) {
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07004254 destResourceFile = getFwdLockedResource(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255 forwardLocked = true;
4256 } else {
4257 destResourceFile = destPackageFile;
4258 }
4259 // Retrieve PackageSettings and parse package
4260 int parseFlags = PackageParser.PARSE_CHATTY;
4261 parseFlags |= mDefParseFlags;
4262 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4263 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
4265 destPackageFile.getAbsolutePath(), mMetrics, parseFlags);
4266 if (pkg == null) {
4267 res.returnCode = pp.getParseError();
4268 break main_flow;
4269 }
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004270 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4271 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4272 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4273 break main_flow;
4274 }
4275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4277 res.returnCode = pp.getParseError();
4278 break main_flow;
4279 }
4280
4281 synchronized (mPackages) {
4282 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004283 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 && mPackages.containsKey(pkgName)) {
4285 replacingExistingPackage = true;
4286 }
4287 }
4288
4289 if(replacingExistingPackage) {
4290 replacePackageLI(pkgName,
4291 tmpPackageFile,
4292 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02004293 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 res);
4295 } else {
4296 installNewPackageLI(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 }
4302 } finally {
4303 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4304 tmpPackageFile.delete();
4305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 }
4307 }
4308
4309 private int setPermissionsLI(String pkgName,
4310 PackageParser.Package newPackage,
4311 String destFilePath,
4312 File destResourceFile,
4313 boolean forwardLocked) {
4314 int retCode;
4315 if (forwardLocked) {
4316 try {
4317 extractPublicFiles(newPackage, destResourceFile);
4318 } catch (IOException e) {
4319 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
4320 " forward-locked app.");
4321 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4322 } finally {
4323 //TODO clean up the extracted public files
4324 }
4325 if (mInstaller != null) {
4326 retCode = mInstaller.setForwardLockPerm(pkgName,
4327 newPackage.applicationInfo.uid);
4328 } else {
4329 final int filePermissions =
4330 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
4331 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1,
4332 newPackage.applicationInfo.uid);
4333 }
4334 } else {
4335 final int filePermissions =
4336 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4337 |FileUtils.S_IROTH;
4338 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1, -1);
4339 }
4340 if (retCode != 0) {
4341 Log.e(TAG, "Couldn't set new package file permissions for " + destFilePath
4342 + ". The return code was: " + retCode);
4343 }
4344 return PackageManager.INSTALL_SUCCEEDED;
4345 }
4346
4347 private boolean isForwardLocked(PackageParser.Package deletedPackage) {
4348 final ApplicationInfo applicationInfo = deletedPackage.applicationInfo;
4349 return applicationInfo.sourceDir.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath());
4350 }
4351
4352 private void extractPublicFiles(PackageParser.Package newPackage,
4353 File publicZipFile) throws IOException {
4354 final ZipOutputStream publicZipOutStream =
4355 new ZipOutputStream(new FileOutputStream(publicZipFile));
4356 final ZipFile privateZip = new ZipFile(newPackage.mPath);
4357
4358 // Copy manifest, resources.arsc and res directory to public zip
4359
4360 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
4361 while (privateZipEntries.hasMoreElements()) {
4362 final ZipEntry zipEntry = privateZipEntries.nextElement();
4363 final String zipEntryName = zipEntry.getName();
4364 if ("AndroidManifest.xml".equals(zipEntryName)
4365 || "resources.arsc".equals(zipEntryName)
4366 || zipEntryName.startsWith("res/")) {
4367 try {
4368 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
4369 } catch (IOException e) {
4370 try {
4371 publicZipOutStream.close();
4372 throw e;
4373 } finally {
4374 publicZipFile.delete();
4375 }
4376 }
4377 }
4378 }
4379
4380 publicZipOutStream.close();
4381 FileUtils.setPermissions(
4382 publicZipFile.getAbsolutePath(),
4383 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4384 -1, -1);
4385 }
4386
4387 private static void copyZipEntry(ZipEntry zipEntry,
4388 ZipFile inZipFile,
4389 ZipOutputStream outZipStream) throws IOException {
4390 byte[] buffer = new byte[4096];
4391 int num;
4392
4393 ZipEntry newEntry;
4394 if (zipEntry.getMethod() == ZipEntry.STORED) {
4395 // Preserve the STORED method of the input entry.
4396 newEntry = new ZipEntry(zipEntry);
4397 } else {
4398 // Create a new entry so that the compressed len is recomputed.
4399 newEntry = new ZipEntry(zipEntry.getName());
4400 }
4401 outZipStream.putNextEntry(newEntry);
4402
4403 InputStream data = inZipFile.getInputStream(zipEntry);
4404 while ((num = data.read(buffer)) > 0) {
4405 outZipStream.write(buffer, 0, num);
4406 }
4407 outZipStream.flush();
4408 }
4409
4410 private void deleteTempPackageFiles() {
4411 FilenameFilter filter = new FilenameFilter() {
4412 public boolean accept(File dir, String name) {
4413 return name.startsWith("vmdl") && name.endsWith(".tmp");
4414 }
4415 };
4416 String tmpFilesList[] = mAppInstallDir.list(filter);
4417 if(tmpFilesList == null) {
4418 return;
4419 }
4420 for(int i = 0; i < tmpFilesList.length; i++) {
4421 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4422 tmpFile.delete();
4423 }
4424 }
4425
4426 private File createTempPackageFile() {
4427 File tmpPackageFile;
4428 try {
4429 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
4430 } catch (IOException e) {
4431 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4432 return null;
4433 }
4434 try {
4435 FileUtils.setPermissions(
4436 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4437 -1, -1);
4438 } catch (IOException e) {
4439 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4440 return null;
4441 }
4442 return tmpPackageFile;
4443 }
4444
4445 public void deletePackage(final String packageName,
4446 final IPackageDeleteObserver observer,
4447 final int flags) {
4448 mContext.enforceCallingOrSelfPermission(
4449 android.Manifest.permission.DELETE_PACKAGES, null);
4450 // Queue up an async operation since the package deletion may take a little while.
4451 mHandler.post(new Runnable() {
4452 public void run() {
4453 mHandler.removeCallbacks(this);
4454 final boolean succeded = deletePackageX(packageName, true, true, flags);
4455 if (observer != null) {
4456 try {
4457 observer.packageDeleted(succeded);
4458 } catch (RemoteException e) {
4459 Log.i(TAG, "Observer no longer exists.");
4460 } //end catch
4461 } //end if
4462 } //end run
4463 });
4464 }
4465
4466 /**
4467 * This method is an internal method that could be get invoked either
4468 * to delete an installed package or to clean up a failed installation.
4469 * After deleting an installed package, a broadcast is sent to notify any
4470 * listeners that the package has been installed. For cleaning up a failed
4471 * installation, the broadcast is not necessary since the package's
4472 * installation wouldn't have sent the initial broadcast either
4473 * The key steps in deleting a package are
4474 * deleting the package information in internal structures like mPackages,
4475 * deleting the packages base directories through installd
4476 * updating mSettings to reflect current status
4477 * persisting settings for later use
4478 * sending a broadcast if necessary
4479 */
4480
4481 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4482 boolean deleteCodeAndResources, int flags) {
4483 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004484 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485
4486 synchronized (mInstallLock) {
4487 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4488 }
4489
4490 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004491 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4492 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4493
4494 // If the removed package was a system update, the old system packaged
4495 // was re-enabled; we need to broadcast this information
4496 if (systemUpdate) {
4497 Bundle extras = new Bundle(1);
4498 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4499 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4500
4501 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4502 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 }
4505 return res;
4506 }
4507
4508 static class PackageRemovedInfo {
4509 String removedPackage;
4510 int uid = -1;
4511 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004512 boolean isRemovedPackageSystemUpdate = false;
4513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 void sendBroadcast(boolean fullRemove, boolean replacing) {
4515 Bundle extras = new Bundle(1);
4516 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4517 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4518 if (replacing) {
4519 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4520 }
4521 if (removedPackage != null) {
4522 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4523 }
4524 if (removedUid >= 0) {
4525 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4526 }
4527 }
4528 }
4529
4530 /*
4531 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4532 * flag is not set, the data directory is removed as well.
4533 * make sure this flag is set for partially installed apps. If not its meaningless to
4534 * delete a partially installed application.
4535 */
4536 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
4537 int flags) {
4538 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004539 if (outInfo != null) {
4540 outInfo.removedPackage = packageName;
4541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004542 removePackageLI(p, true);
4543 // Retrieve object to delete permissions for shared user later on
4544 PackageSetting deletedPs;
4545 synchronized (mPackages) {
4546 deletedPs = mSettings.mPackages.get(packageName);
4547 }
4548 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
4549 if (mInstaller != null) {
4550 int retCode = mInstaller.remove(packageName);
4551 if (retCode < 0) {
4552 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4553 + packageName + ", retcode=" + retCode);
4554 // we don't consider this to be a failure of the core package deletion
4555 }
4556 } else {
4557 //for emulator
4558 PackageParser.Package pkg = mPackages.get(packageName);
4559 File dataDir = new File(pkg.applicationInfo.dataDir);
4560 dataDir.delete();
4561 }
4562 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004563 if (outInfo != null) {
4564 outInfo.removedUid = mSettings.removePackageLP(packageName);
4565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 }
4567 }
4568 synchronized (mPackages) {
4569 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4570 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004571 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 }
4573 // Save settings now
4574 mSettings.writeLP ();
4575 }
4576 }
4577
4578 /*
4579 * Tries to delete system package.
4580 */
4581 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004582 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 ApplicationInfo applicationInfo = p.applicationInfo;
4584 //applicable for non-partially installed applications only
4585 if (applicationInfo == null) {
4586 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4587 return false;
4588 }
4589 PackageSetting ps = null;
4590 // Confirm if the system package has been updated
4591 // An updated system app can be deleted. This will also have to restore
4592 // the system pkg from system partition
4593 synchronized (mPackages) {
4594 ps = mSettings.getDisabledSystemPkg(p.packageName);
4595 }
4596 if (ps == null) {
4597 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4598 return false;
4599 } else {
4600 Log.i(TAG, "Deleting system pkg from data partition");
4601 }
4602 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004603 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004604 boolean deleteCodeAndResources = false;
4605 if (ps.versionCode < p.mVersionCode) {
4606 // Delete code and resources for downgrades
4607 deleteCodeAndResources = true;
4608 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4609 flags &= ~PackageManager.DONT_DELETE_DATA;
4610 }
4611 } else {
4612 // Preserve data by setting flag
4613 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4614 flags |= PackageManager.DONT_DELETE_DATA;
4615 }
4616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4618 if (!ret) {
4619 return false;
4620 }
4621 synchronized (mPackages) {
4622 // Reinstate the old system package
4623 mSettings.enableSystemPackageLP(p.packageName);
4624 }
4625 // Install the system package
4626 PackageParser.Package newPkg = scanPackageLI(ps.codePath, ps.codePath, ps.resourcePath,
4627 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
4628 SCAN_MONITOR);
4629
4630 if (newPkg == null) {
4631 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4632 return false;
4633 }
4634 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07004635 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004636 mSettings.writeLP();
4637 }
4638 return true;
4639 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004640
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004641 private void deletePackageResourcesLI(String packageName,
4642 String sourceDir, String publicSourceDir) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004643 if (sourceDir != null) {
4644 File sourceFile = new File(sourceDir);
4645 if (!sourceFile.exists()) {
4646 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4647 }
4648 // Delete application's code and resources
4649 sourceFile.delete();
4650 if (mInstaller != null) {
4651 int retCode = mInstaller.rmdex(sourceFile.toString());
4652 if (retCode < 0) {
4653 Log.w(TAG, "Couldn't remove dex file for package: "
4654 + packageName + " at location "
4655 + sourceFile.toString() + ", retcode=" + retCode);
4656 // we don't consider this to be a failure of the core package deletion
4657 }
4658 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004659 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004660 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4661 final File publicSourceFile = new File(publicSourceDir);
4662 if (!publicSourceFile.exists()) {
4663 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4664 }
4665 if (publicSourceFile.exists()) {
4666 publicSourceFile.delete();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004667 }
4668 }
4669 }
4670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4672 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4673 ApplicationInfo applicationInfo = p.applicationInfo;
4674 if (applicationInfo == null) {
4675 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4676 return false;
4677 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004678 if (outInfo != null) {
4679 outInfo.uid = applicationInfo.uid;
4680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681
4682 // Delete package data from internal structures and also remove data if flag is set
4683 removePackageDataLI(p, outInfo, flags);
4684
4685 // Delete application code and resources
4686 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004687 deletePackageResourcesLI(applicationInfo.packageName,
4688 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 }
4690 return true;
4691 }
4692
4693 /*
4694 * This method handles package deletion in general
4695 */
4696 private boolean deletePackageLI(String packageName,
4697 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4698 if (packageName == null) {
4699 Log.w(TAG, "Attempt to delete null packageName.");
4700 return false;
4701 }
4702 PackageParser.Package p;
4703 boolean dataOnly = false;
4704 synchronized (mPackages) {
4705 p = mPackages.get(packageName);
4706 if (p == null) {
4707 //this retrieves partially installed apps
4708 dataOnly = true;
4709 PackageSetting ps = mSettings.mPackages.get(packageName);
4710 if (ps == null) {
4711 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4712 return false;
4713 }
4714 p = ps.pkg;
4715 }
4716 }
4717 if (p == null) {
4718 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4719 return false;
4720 }
4721
4722 if (dataOnly) {
4723 // Delete application data first
4724 removePackageDataLI(p, outInfo, flags);
4725 return true;
4726 }
4727 // At this point the package should have ApplicationInfo associated with it
4728 if (p.applicationInfo == null) {
4729 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4730 return false;
4731 }
4732 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4733 Log.i(TAG, "Removing system package:"+p.packageName);
4734 // When an updated system application is deleted we delete the existing resources as well and
4735 // fall back to existing code in system partition
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004736 return deleteSystemPackageLI(p, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 }
4738 Log.i(TAG, "Removing non-system package:"+p.packageName);
4739 return deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
4740 }
4741
4742 public void clearApplicationUserData(final String packageName,
4743 final IPackageDataObserver observer) {
4744 mContext.enforceCallingOrSelfPermission(
4745 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4746 // Queue up an async operation since the package deletion may take a little while.
4747 mHandler.post(new Runnable() {
4748 public void run() {
4749 mHandler.removeCallbacks(this);
4750 final boolean succeeded;
4751 synchronized (mInstallLock) {
4752 succeeded = clearApplicationUserDataLI(packageName);
4753 }
4754 if (succeeded) {
4755 // invoke DeviceStorageMonitor's update method to clear any notifications
4756 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4757 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4758 if (dsm != null) {
4759 dsm.updateMemory();
4760 }
4761 }
4762 if(observer != null) {
4763 try {
4764 observer.onRemoveCompleted(packageName, succeeded);
4765 } catch (RemoteException e) {
4766 Log.i(TAG, "Observer no longer exists.");
4767 }
4768 } //end if observer
4769 } //end run
4770 });
4771 }
4772
4773 private boolean clearApplicationUserDataLI(String packageName) {
4774 if (packageName == null) {
4775 Log.w(TAG, "Attempt to delete null packageName.");
4776 return false;
4777 }
4778 PackageParser.Package p;
4779 boolean dataOnly = false;
4780 synchronized (mPackages) {
4781 p = mPackages.get(packageName);
4782 if(p == null) {
4783 dataOnly = true;
4784 PackageSetting ps = mSettings.mPackages.get(packageName);
4785 if((ps == null) || (ps.pkg == null)) {
4786 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4787 return false;
4788 }
4789 p = ps.pkg;
4790 }
4791 }
4792 if(!dataOnly) {
4793 //need to check this only for fully installed applications
4794 if (p == null) {
4795 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4796 return false;
4797 }
4798 final ApplicationInfo applicationInfo = p.applicationInfo;
4799 if (applicationInfo == null) {
4800 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4801 return false;
4802 }
4803 }
4804 if (mInstaller != null) {
4805 int retCode = mInstaller.clearUserData(packageName);
4806 if (retCode < 0) {
4807 Log.w(TAG, "Couldn't remove cache files for package: "
4808 + packageName);
4809 return false;
4810 }
4811 }
4812 return true;
4813 }
4814
4815 public void deleteApplicationCacheFiles(final String packageName,
4816 final IPackageDataObserver observer) {
4817 mContext.enforceCallingOrSelfPermission(
4818 android.Manifest.permission.DELETE_CACHE_FILES, null);
4819 // Queue up an async operation since the package deletion may take a little while.
4820 mHandler.post(new Runnable() {
4821 public void run() {
4822 mHandler.removeCallbacks(this);
4823 final boolean succeded;
4824 synchronized (mInstallLock) {
4825 succeded = deleteApplicationCacheFilesLI(packageName);
4826 }
4827 if(observer != null) {
4828 try {
4829 observer.onRemoveCompleted(packageName, succeded);
4830 } catch (RemoteException e) {
4831 Log.i(TAG, "Observer no longer exists.");
4832 }
4833 } //end if observer
4834 } //end run
4835 });
4836 }
4837
4838 private boolean deleteApplicationCacheFilesLI(String packageName) {
4839 if (packageName == null) {
4840 Log.w(TAG, "Attempt to delete null packageName.");
4841 return false;
4842 }
4843 PackageParser.Package p;
4844 synchronized (mPackages) {
4845 p = mPackages.get(packageName);
4846 }
4847 if (p == null) {
4848 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4849 return false;
4850 }
4851 final ApplicationInfo applicationInfo = p.applicationInfo;
4852 if (applicationInfo == null) {
4853 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4854 return false;
4855 }
4856 if (mInstaller != null) {
4857 int retCode = mInstaller.deleteCacheFiles(packageName);
4858 if (retCode < 0) {
4859 Log.w(TAG, "Couldn't remove cache files for package: "
4860 + packageName);
4861 return false;
4862 }
4863 }
4864 return true;
4865 }
4866
4867 public void getPackageSizeInfo(final String packageName,
4868 final IPackageStatsObserver observer) {
4869 mContext.enforceCallingOrSelfPermission(
4870 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4871 // Queue up an async operation since the package deletion may take a little while.
4872 mHandler.post(new Runnable() {
4873 public void run() {
4874 mHandler.removeCallbacks(this);
4875 PackageStats lStats = new PackageStats(packageName);
4876 final boolean succeded;
4877 synchronized (mInstallLock) {
4878 succeded = getPackageSizeInfoLI(packageName, lStats);
4879 }
4880 if(observer != null) {
4881 try {
4882 observer.onGetStatsCompleted(lStats, succeded);
4883 } catch (RemoteException e) {
4884 Log.i(TAG, "Observer no longer exists.");
4885 }
4886 } //end if observer
4887 } //end run
4888 });
4889 }
4890
4891 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4892 if (packageName == null) {
4893 Log.w(TAG, "Attempt to get size of null packageName.");
4894 return false;
4895 }
4896 PackageParser.Package p;
4897 boolean dataOnly = false;
4898 synchronized (mPackages) {
4899 p = mPackages.get(packageName);
4900 if(p == null) {
4901 dataOnly = true;
4902 PackageSetting ps = mSettings.mPackages.get(packageName);
4903 if((ps == null) || (ps.pkg == null)) {
4904 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4905 return false;
4906 }
4907 p = ps.pkg;
4908 }
4909 }
4910 String publicSrcDir = null;
4911 if(!dataOnly) {
4912 final ApplicationInfo applicationInfo = p.applicationInfo;
4913 if (applicationInfo == null) {
4914 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4915 return false;
4916 }
4917 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4918 }
4919 if (mInstaller != null) {
4920 int res = mInstaller.getSizeInfo(packageName, p.mPath,
4921 publicSrcDir, pStats);
4922 if (res < 0) {
4923 return false;
4924 } else {
4925 return true;
4926 }
4927 }
4928 return true;
4929 }
4930
4931
4932 public void addPackageToPreferred(String packageName) {
4933 mContext.enforceCallingOrSelfPermission(
4934 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004935 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004936 }
4937
4938 public void removePackageFromPreferred(String packageName) {
4939 mContext.enforceCallingOrSelfPermission(
4940 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004941 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 }
4943
4944 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004945 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946 }
4947
4948 public void addPreferredActivity(IntentFilter filter, int match,
4949 ComponentName[] set, ComponentName activity) {
4950 mContext.enforceCallingOrSelfPermission(
4951 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4952
4953 synchronized (mPackages) {
4954 Log.i(TAG, "Adding preferred activity " + activity + ":");
4955 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4956 mSettings.mPreferredActivities.addFilter(
4957 new PreferredActivity(filter, match, set, activity));
4958 mSettings.writeLP();
4959 }
4960 }
4961
Satish Sampath8dbe6122009-06-02 23:35:54 +01004962 public void replacePreferredActivity(IntentFilter filter, int match,
4963 ComponentName[] set, ComponentName activity) {
4964 mContext.enforceCallingOrSelfPermission(
4965 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4966 if (filter.countActions() != 1) {
4967 throw new IllegalArgumentException(
4968 "replacePreferredActivity expects filter to have only 1 action.");
4969 }
4970 if (filter.countCategories() != 1) {
4971 throw new IllegalArgumentException(
4972 "replacePreferredActivity expects filter to have only 1 category.");
4973 }
4974 if (filter.countDataAuthorities() != 0
4975 || filter.countDataPaths() != 0
4976 || filter.countDataSchemes() != 0
4977 || filter.countDataTypes() != 0) {
4978 throw new IllegalArgumentException(
4979 "replacePreferredActivity expects filter to have no data authorities, " +
4980 "paths, schemes or types.");
4981 }
4982 synchronized (mPackages) {
4983 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4984 String action = filter.getAction(0);
4985 String category = filter.getCategory(0);
4986 while (it.hasNext()) {
4987 PreferredActivity pa = it.next();
4988 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
4989 it.remove();
4990 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
4991 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4992 }
4993 }
4994 addPreferredActivity(filter, match, set, activity);
4995 }
4996 }
4997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 public void clearPackagePreferredActivities(String packageName) {
4999 mContext.enforceCallingOrSelfPermission(
5000 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5001
5002 synchronized (mPackages) {
5003 if (clearPackagePreferredActivitiesLP(packageName)) {
5004 mSettings.writeLP();
5005 }
5006 }
5007 }
5008
5009 boolean clearPackagePreferredActivitiesLP(String packageName) {
5010 boolean changed = false;
5011 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5012 while (it.hasNext()) {
5013 PreferredActivity pa = it.next();
5014 if (pa.mActivity.getPackageName().equals(packageName)) {
5015 it.remove();
5016 changed = true;
5017 }
5018 }
5019 return changed;
5020 }
5021
5022 public int getPreferredActivities(List<IntentFilter> outFilters,
5023 List<ComponentName> outActivities, String packageName) {
5024
5025 int num = 0;
5026 synchronized (mPackages) {
5027 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5028 while (it.hasNext()) {
5029 PreferredActivity pa = it.next();
5030 if (packageName == null
5031 || pa.mActivity.getPackageName().equals(packageName)) {
5032 if (outFilters != null) {
5033 outFilters.add(new IntentFilter(pa));
5034 }
5035 if (outActivities != null) {
5036 outActivities.add(pa.mActivity);
5037 }
5038 }
5039 }
5040 }
5041
5042 return num;
5043 }
5044
5045 public void setApplicationEnabledSetting(String appPackageName,
5046 int newState, int flags) {
5047 setEnabledSetting(appPackageName, null, newState, flags);
5048 }
5049
5050 public void setComponentEnabledSetting(ComponentName componentName,
5051 int newState, int flags) {
5052 setEnabledSetting(componentName.getPackageName(),
5053 componentName.getClassName(), newState, flags);
5054 }
5055
5056 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005057 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005058 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5059 || newState == COMPONENT_ENABLED_STATE_ENABLED
5060 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5061 throw new IllegalArgumentException("Invalid new component state: "
5062 + newState);
5063 }
5064 PackageSetting pkgSetting;
5065 final int uid = Binder.getCallingUid();
5066 final int permission = mContext.checkCallingPermission(
5067 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5068 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005069 boolean sendNow = false;
5070 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005071 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005073 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005075 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005076 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005077 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005079 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 }
5081 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005082 "Unknown component: " + packageName
5083 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 }
5085 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5086 throw new SecurityException(
5087 "Permission Denial: attempt to change component state from pid="
5088 + Binder.getCallingPid()
5089 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5090 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005091 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 // We're dealing with an application/package level state change
5093 pkgSetting.enabled = newState;
5094 } else {
5095 // We're dealing with a component level state change
5096 switch (newState) {
5097 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005098 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 break;
5100 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005101 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102 break;
5103 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005104 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 break;
5106 default:
5107 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005108 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 }
5110 }
5111 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005112 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005113 components = mPendingBroadcasts.get(packageName);
5114 boolean newPackage = components == null;
5115 if (newPackage) {
5116 components = new ArrayList<String>();
5117 }
5118 if (!components.contains(componentName)) {
5119 components.add(componentName);
5120 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005121 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5122 sendNow = true;
5123 // Purge entry from pending broadcast list if another one exists already
5124 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005125 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005126 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005127 if (newPackage) {
5128 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005129 }
5130 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5131 // Schedule a message
5132 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5133 }
5134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 long callingId = Binder.clearCallingIdentity();
5138 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005139 if (sendNow) {
5140 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005141 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005143 } finally {
5144 Binder.restoreCallingIdentity(callingId);
5145 }
5146 }
5147
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005148 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005149 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5150 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5151 + " components=" + componentNames);
5152 Bundle extras = new Bundle(4);
5153 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5154 String nameList[] = new String[componentNames.size()];
5155 componentNames.toArray(nameList);
5156 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005157 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5158 extras.putInt(Intent.EXTRA_UID, packageUid);
5159 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
5160 }
5161
Jacek Surazski65e13172009-04-28 15:26:38 +02005162 public String getInstallerPackageName(String packageName) {
5163 synchronized (mPackages) {
5164 PackageSetting pkg = mSettings.mPackages.get(packageName);
5165 if (pkg == null) {
5166 throw new IllegalArgumentException("Unknown package: " + packageName);
5167 }
5168 return pkg.installerPackageName;
5169 }
5170 }
5171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005172 public int getApplicationEnabledSetting(String appPackageName) {
5173 synchronized (mPackages) {
5174 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5175 if (pkg == null) {
5176 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5177 }
5178 return pkg.enabled;
5179 }
5180 }
5181
5182 public int getComponentEnabledSetting(ComponentName componentName) {
5183 synchronized (mPackages) {
5184 final String packageNameStr = componentName.getPackageName();
5185 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5186 if (pkg == null) {
5187 throw new IllegalArgumentException("Unknown component: " + componentName);
5188 }
5189 final String classNameStr = componentName.getClassName();
5190 return pkg.currentEnabledStateLP(classNameStr);
5191 }
5192 }
5193
5194 public void enterSafeMode() {
5195 if (!mSystemReady) {
5196 mSafeMode = true;
5197 }
5198 }
5199
5200 public void systemReady() {
5201 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005202
5203 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005204 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005205 mContext.getContentResolver(),
5206 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005207 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005208 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005209 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 }
5212
5213 public boolean isSafeMode() {
5214 return mSafeMode;
5215 }
5216
5217 public boolean hasSystemUidErrors() {
5218 return mHasSystemUidErrors;
5219 }
5220
5221 static String arrayToString(int[] array) {
5222 StringBuffer buf = new StringBuffer(128);
5223 buf.append('[');
5224 if (array != null) {
5225 for (int i=0; i<array.length; i++) {
5226 if (i > 0) buf.append(", ");
5227 buf.append(array[i]);
5228 }
5229 }
5230 buf.append(']');
5231 return buf.toString();
5232 }
5233
5234 @Override
5235 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5236 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5237 != PackageManager.PERMISSION_GRANTED) {
5238 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5239 + Binder.getCallingPid()
5240 + ", uid=" + Binder.getCallingUid()
5241 + " without permission "
5242 + android.Manifest.permission.DUMP);
5243 return;
5244 }
5245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 synchronized (mPackages) {
5247 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005248 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249 pw.println(" ");
5250 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005251 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005252 pw.println(" ");
5253 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005254 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 pw.println(" ");
5256 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005257 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005259 pw.println("Permissions:");
5260 {
5261 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005262 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5263 pw.print(Integer.toHexString(System.identityHashCode(p)));
5264 pw.println("):");
5265 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5266 pw.print(" uid="); pw.print(p.uid);
5267 pw.print(" gids="); pw.print(arrayToString(p.gids));
5268 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 }
5270 }
5271 pw.println(" ");
5272 pw.println("Packages:");
5273 {
5274 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005275 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5276 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5277 pw.println("):");
5278 pw.print(" userId="); pw.print(ps.userId);
5279 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5280 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5281 pw.print(" pkg="); pw.println(ps.pkg);
5282 pw.print(" codePath="); pw.println(ps.codePathString);
5283 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005284 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005285 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005286 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005287 pw.print(" supportsScreens=[");
5288 boolean first = true;
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005289 if ((ps.pkg.applicationInfo.flags &
5290 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005291 if (!first) pw.print(", ");
5292 first = false;
5293 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005294 }
5295 if ((ps.pkg.applicationInfo.flags &
5296 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005297 if (!first) pw.print(", ");
5298 first = false;
5299 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005300 }
5301 if ((ps.pkg.applicationInfo.flags &
5302 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005303 if (!first) pw.print(", ");
5304 first = false;
5305 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005306 }
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005307 if ((ps.pkg.applicationInfo.flags &
5308 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005309 if (!first) pw.print(", ");
5310 first = false;
5311 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005312 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005313 if ((ps.pkg.applicationInfo.flags &
5314 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
5315 if (!first) pw.print(", ");
5316 first = false;
5317 pw.print("anyDensity");
5318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005319 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005320 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005321 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
5322 pw.print(" signatures="); pw.println(ps.signatures);
5323 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
5324 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
5325 pw.print(" installStatus="); pw.print(ps.installStatus);
5326 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 if (ps.disabledComponents.size() > 0) {
5328 pw.println(" disabledComponents:");
5329 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005330 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 }
5332 }
5333 if (ps.enabledComponents.size() > 0) {
5334 pw.println(" enabledComponents:");
5335 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005336 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005337 }
5338 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005339 if (ps.grantedPermissions.size() > 0) {
5340 pw.println(" grantedPermissions:");
5341 for (String s : ps.grantedPermissions) {
5342 pw.print(" "); pw.println(s);
5343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005344 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005345 if (ps.loadedPermissions.size() > 0) {
5346 pw.println(" loadedPermissions:");
5347 for (String s : ps.loadedPermissions) {
5348 pw.print(" "); pw.println(s);
5349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005350 }
5351 }
5352 }
5353 pw.println(" ");
5354 pw.println("Shared Users:");
5355 {
5356 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005357 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5358 pw.print(Integer.toHexString(System.identityHashCode(su)));
5359 pw.println("):");
5360 pw.print(" userId="); pw.print(su.userId);
5361 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 pw.println(" grantedPermissions:");
5363 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005364 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005365 }
5366 pw.println(" loadedPermissions:");
5367 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005368 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 }
5370 }
5371 }
5372 pw.println(" ");
5373 pw.println("Settings parse messages:");
5374 pw.println(mSettings.mReadMessages.toString());
5375 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05005376
5377 synchronized (mProviders) {
5378 pw.println(" ");
5379 pw.println("Registered ContentProviders:");
5380 for (PackageParser.Provider p : mProviders.values()) {
5381 pw.println(" ["); pw.println(p.info.authority); pw.println("]: ");
5382 pw.println(p.toString());
5383 }
5384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 }
5386
5387 static final class BasePermission {
5388 final static int TYPE_NORMAL = 0;
5389 final static int TYPE_BUILTIN = 1;
5390 final static int TYPE_DYNAMIC = 2;
5391
5392 final String name;
5393 final String sourcePackage;
5394 final int type;
5395 PackageParser.Permission perm;
5396 PermissionInfo pendingInfo;
5397 int uid;
5398 int[] gids;
5399
5400 BasePermission(String _name, String _sourcePackage, int _type) {
5401 name = _name;
5402 sourcePackage = _sourcePackage;
5403 type = _type;
5404 }
5405 }
5406
5407 static class PackageSignatures {
5408 private Signature[] mSignatures;
5409
5410 PackageSignatures(Signature[] sigs) {
5411 assignSignatures(sigs);
5412 }
5413
5414 PackageSignatures() {
5415 }
5416
5417 void writeXml(XmlSerializer serializer, String tagName,
5418 ArrayList<Signature> pastSignatures) throws IOException {
5419 if (mSignatures == null) {
5420 return;
5421 }
5422 serializer.startTag(null, tagName);
5423 serializer.attribute(null, "count",
5424 Integer.toString(mSignatures.length));
5425 for (int i=0; i<mSignatures.length; i++) {
5426 serializer.startTag(null, "cert");
5427 final Signature sig = mSignatures[i];
5428 final int sigHash = sig.hashCode();
5429 final int numPast = pastSignatures.size();
5430 int j;
5431 for (j=0; j<numPast; j++) {
5432 Signature pastSig = pastSignatures.get(j);
5433 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5434 serializer.attribute(null, "index", Integer.toString(j));
5435 break;
5436 }
5437 }
5438 if (j >= numPast) {
5439 pastSignatures.add(sig);
5440 serializer.attribute(null, "index", Integer.toString(numPast));
5441 serializer.attribute(null, "key", sig.toCharsString());
5442 }
5443 serializer.endTag(null, "cert");
5444 }
5445 serializer.endTag(null, tagName);
5446 }
5447
5448 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5449 throws IOException, XmlPullParserException {
5450 String countStr = parser.getAttributeValue(null, "count");
5451 if (countStr == null) {
5452 reportSettingsProblem(Log.WARN,
5453 "Error in package manager settings: <signatures> has"
5454 + " no count at " + parser.getPositionDescription());
5455 XmlUtils.skipCurrentTag(parser);
5456 }
5457 final int count = Integer.parseInt(countStr);
5458 mSignatures = new Signature[count];
5459 int pos = 0;
5460
5461 int outerDepth = parser.getDepth();
5462 int type;
5463 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5464 && (type != XmlPullParser.END_TAG
5465 || parser.getDepth() > outerDepth)) {
5466 if (type == XmlPullParser.END_TAG
5467 || type == XmlPullParser.TEXT) {
5468 continue;
5469 }
5470
5471 String tagName = parser.getName();
5472 if (tagName.equals("cert")) {
5473 if (pos < count) {
5474 String index = parser.getAttributeValue(null, "index");
5475 if (index != null) {
5476 try {
5477 int idx = Integer.parseInt(index);
5478 String key = parser.getAttributeValue(null, "key");
5479 if (key == null) {
5480 if (idx >= 0 && idx < pastSignatures.size()) {
5481 Signature sig = pastSignatures.get(idx);
5482 if (sig != null) {
5483 mSignatures[pos] = pastSignatures.get(idx);
5484 pos++;
5485 } else {
5486 reportSettingsProblem(Log.WARN,
5487 "Error in package manager settings: <cert> "
5488 + "index " + index + " is not defined at "
5489 + parser.getPositionDescription());
5490 }
5491 } else {
5492 reportSettingsProblem(Log.WARN,
5493 "Error in package manager settings: <cert> "
5494 + "index " + index + " is out of bounds at "
5495 + parser.getPositionDescription());
5496 }
5497 } else {
5498 while (pastSignatures.size() <= idx) {
5499 pastSignatures.add(null);
5500 }
5501 Signature sig = new Signature(key);
5502 pastSignatures.set(idx, sig);
5503 mSignatures[pos] = sig;
5504 pos++;
5505 }
5506 } catch (NumberFormatException e) {
5507 reportSettingsProblem(Log.WARN,
5508 "Error in package manager settings: <cert> "
5509 + "index " + index + " is not a number at "
5510 + parser.getPositionDescription());
5511 }
5512 } else {
5513 reportSettingsProblem(Log.WARN,
5514 "Error in package manager settings: <cert> has"
5515 + " no index at " + parser.getPositionDescription());
5516 }
5517 } else {
5518 reportSettingsProblem(Log.WARN,
5519 "Error in package manager settings: too "
5520 + "many <cert> tags, expected " + count
5521 + " at " + parser.getPositionDescription());
5522 }
5523 } else {
5524 reportSettingsProblem(Log.WARN,
5525 "Unknown element under <cert>: "
5526 + parser.getName());
5527 }
5528 XmlUtils.skipCurrentTag(parser);
5529 }
5530
5531 if (pos < count) {
5532 // Should never happen -- there is an error in the written
5533 // settings -- but if it does we don't want to generate
5534 // a bad array.
5535 Signature[] newSigs = new Signature[pos];
5536 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5537 mSignatures = newSigs;
5538 }
5539 }
5540
5541 /**
5542 * If any of the given 'sigs' is contained in the existing signatures,
5543 * then completely replace the current signatures with the ones in
5544 * 'sigs'. This is used for updating an existing package to a newly
5545 * installed version.
5546 */
5547 boolean updateSignatures(Signature[] sigs, boolean update) {
5548 if (mSignatures == null) {
5549 if (update) {
5550 assignSignatures(sigs);
5551 }
5552 return true;
5553 }
5554 if (sigs == null) {
5555 return false;
5556 }
5557
5558 for (int i=0; i<sigs.length; i++) {
5559 Signature sig = sigs[i];
5560 for (int j=0; j<mSignatures.length; j++) {
5561 if (mSignatures[j].equals(sig)) {
5562 if (update) {
5563 assignSignatures(sigs);
5564 }
5565 return true;
5566 }
5567 }
5568 }
5569 return false;
5570 }
5571
5572 /**
5573 * If any of the given 'sigs' is contained in the existing signatures,
5574 * then add in any new signatures found in 'sigs'. This is used for
5575 * including a new package into an existing shared user id.
5576 */
5577 boolean mergeSignatures(Signature[] sigs, boolean update) {
5578 if (mSignatures == null) {
5579 if (update) {
5580 assignSignatures(sigs);
5581 }
5582 return true;
5583 }
5584 if (sigs == null) {
5585 return false;
5586 }
5587
5588 Signature[] added = null;
5589 int addedCount = 0;
5590 boolean haveMatch = false;
5591 for (int i=0; i<sigs.length; i++) {
5592 Signature sig = sigs[i];
5593 boolean found = false;
5594 for (int j=0; j<mSignatures.length; j++) {
5595 if (mSignatures[j].equals(sig)) {
5596 found = true;
5597 haveMatch = true;
5598 break;
5599 }
5600 }
5601
5602 if (!found) {
5603 if (added == null) {
5604 added = new Signature[sigs.length];
5605 }
5606 added[i] = sig;
5607 addedCount++;
5608 }
5609 }
5610
5611 if (!haveMatch) {
5612 // Nothing matched -- reject the new signatures.
5613 return false;
5614 }
5615 if (added == null) {
5616 // Completely matched -- nothing else to do.
5617 return true;
5618 }
5619
5620 // Add additional signatures in.
5621 if (update) {
5622 Signature[] total = new Signature[addedCount+mSignatures.length];
5623 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5624 int j = mSignatures.length;
5625 for (int i=0; i<added.length; i++) {
5626 if (added[i] != null) {
5627 total[j] = added[i];
5628 j++;
5629 }
5630 }
5631 mSignatures = total;
5632 }
5633 return true;
5634 }
5635
5636 private void assignSignatures(Signature[] sigs) {
5637 if (sigs == null) {
5638 mSignatures = null;
5639 return;
5640 }
5641 mSignatures = new Signature[sigs.length];
5642 for (int i=0; i<sigs.length; i++) {
5643 mSignatures[i] = sigs[i];
5644 }
5645 }
5646
5647 @Override
5648 public String toString() {
5649 StringBuffer buf = new StringBuffer(128);
5650 buf.append("PackageSignatures{");
5651 buf.append(Integer.toHexString(System.identityHashCode(this)));
5652 buf.append(" [");
5653 if (mSignatures != null) {
5654 for (int i=0; i<mSignatures.length; i++) {
5655 if (i > 0) buf.append(", ");
5656 buf.append(Integer.toHexString(
5657 System.identityHashCode(mSignatures[i])));
5658 }
5659 }
5660 buf.append("]}");
5661 return buf.toString();
5662 }
5663 }
5664
5665 static class PreferredActivity extends IntentFilter {
5666 final int mMatch;
5667 final String[] mSetPackages;
5668 final String[] mSetClasses;
5669 final String[] mSetComponents;
5670 final ComponentName mActivity;
5671 final String mShortActivity;
5672 String mParseError;
5673
5674 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5675 ComponentName activity) {
5676 super(filter);
5677 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5678 mActivity = activity;
5679 mShortActivity = activity.flattenToShortString();
5680 mParseError = null;
5681 if (set != null) {
5682 final int N = set.length;
5683 String[] myPackages = new String[N];
5684 String[] myClasses = new String[N];
5685 String[] myComponents = new String[N];
5686 for (int i=0; i<N; i++) {
5687 ComponentName cn = set[i];
5688 if (cn == null) {
5689 mSetPackages = null;
5690 mSetClasses = null;
5691 mSetComponents = null;
5692 return;
5693 }
5694 myPackages[i] = cn.getPackageName().intern();
5695 myClasses[i] = cn.getClassName().intern();
5696 myComponents[i] = cn.flattenToShortString().intern();
5697 }
5698 mSetPackages = myPackages;
5699 mSetClasses = myClasses;
5700 mSetComponents = myComponents;
5701 } else {
5702 mSetPackages = null;
5703 mSetClasses = null;
5704 mSetComponents = null;
5705 }
5706 }
5707
5708 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5709 IOException {
5710 mShortActivity = parser.getAttributeValue(null, "name");
5711 mActivity = ComponentName.unflattenFromString(mShortActivity);
5712 if (mActivity == null) {
5713 mParseError = "Bad activity name " + mShortActivity;
5714 }
5715 String matchStr = parser.getAttributeValue(null, "match");
5716 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5717 String setCountStr = parser.getAttributeValue(null, "set");
5718 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5719
5720 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5721 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5722 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5723
5724 int setPos = 0;
5725
5726 int outerDepth = parser.getDepth();
5727 int type;
5728 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5729 && (type != XmlPullParser.END_TAG
5730 || parser.getDepth() > outerDepth)) {
5731 if (type == XmlPullParser.END_TAG
5732 || type == XmlPullParser.TEXT) {
5733 continue;
5734 }
5735
5736 String tagName = parser.getName();
5737 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5738 // + parser.getDepth() + " tag=" + tagName);
5739 if (tagName.equals("set")) {
5740 String name = parser.getAttributeValue(null, "name");
5741 if (name == null) {
5742 if (mParseError == null) {
5743 mParseError = "No name in set tag in preferred activity "
5744 + mShortActivity;
5745 }
5746 } else if (setPos >= setCount) {
5747 if (mParseError == null) {
5748 mParseError = "Too many set tags in preferred activity "
5749 + mShortActivity;
5750 }
5751 } else {
5752 ComponentName cn = ComponentName.unflattenFromString(name);
5753 if (cn == null) {
5754 if (mParseError == null) {
5755 mParseError = "Bad set name " + name + " in preferred activity "
5756 + mShortActivity;
5757 }
5758 } else {
5759 myPackages[setPos] = cn.getPackageName();
5760 myClasses[setPos] = cn.getClassName();
5761 myComponents[setPos] = name;
5762 setPos++;
5763 }
5764 }
5765 XmlUtils.skipCurrentTag(parser);
5766 } else if (tagName.equals("filter")) {
5767 //Log.i(TAG, "Starting to parse filter...");
5768 readFromXml(parser);
5769 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5770 // + parser.getDepth() + " tag=" + parser.getName());
5771 } else {
5772 reportSettingsProblem(Log.WARN,
5773 "Unknown element under <preferred-activities>: "
5774 + parser.getName());
5775 XmlUtils.skipCurrentTag(parser);
5776 }
5777 }
5778
5779 if (setPos != setCount) {
5780 if (mParseError == null) {
5781 mParseError = "Not enough set tags (expected " + setCount
5782 + " but found " + setPos + ") in " + mShortActivity;
5783 }
5784 }
5785
5786 mSetPackages = myPackages;
5787 mSetClasses = myClasses;
5788 mSetComponents = myComponents;
5789 }
5790
5791 public void writeToXml(XmlSerializer serializer) throws IOException {
5792 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5793 serializer.attribute(null, "name", mShortActivity);
5794 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5795 serializer.attribute(null, "set", Integer.toString(NS));
5796 for (int s=0; s<NS; s++) {
5797 serializer.startTag(null, "set");
5798 serializer.attribute(null, "name", mSetComponents[s]);
5799 serializer.endTag(null, "set");
5800 }
5801 serializer.startTag(null, "filter");
5802 super.writeToXml(serializer);
5803 serializer.endTag(null, "filter");
5804 }
5805
5806 boolean sameSet(List<ResolveInfo> query, int priority) {
5807 if (mSetPackages == null) return false;
5808 final int NQ = query.size();
5809 final int NS = mSetPackages.length;
5810 int numMatch = 0;
5811 for (int i=0; i<NQ; i++) {
5812 ResolveInfo ri = query.get(i);
5813 if (ri.priority != priority) continue;
5814 ActivityInfo ai = ri.activityInfo;
5815 boolean good = false;
5816 for (int j=0; j<NS; j++) {
5817 if (mSetPackages[j].equals(ai.packageName)
5818 && mSetClasses[j].equals(ai.name)) {
5819 numMatch++;
5820 good = true;
5821 break;
5822 }
5823 }
5824 if (!good) return false;
5825 }
5826 return numMatch == NS;
5827 }
5828 }
5829
5830 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07005831 int pkgFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832
5833 HashSet<String> grantedPermissions = new HashSet<String>();
5834 int[] gids;
5835
5836 HashSet<String> loadedPermissions = new HashSet<String>();
5837
5838 GrantedPermissions(int pkgFlags) {
5839 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5840 }
5841 }
5842
5843 /**
5844 * Settings base class for pending and resolved classes.
5845 */
5846 static class PackageSettingBase extends GrantedPermissions {
5847 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005848 File codePath;
5849 String codePathString;
5850 File resourcePath;
5851 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 private long timeStamp;
5853 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005854 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855
5856 PackageSignatures signatures = new PackageSignatures();
5857
5858 boolean permissionsFixed;
5859
5860 /* Explicitly disabled components */
5861 HashSet<String> disabledComponents = new HashSet<String>(0);
5862 /* Explicitly enabled components */
5863 HashSet<String> enabledComponents = new HashSet<String>(0);
5864 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5865 int installStatus = PKG_INSTALL_COMPLETE;
Jacek Surazski65e13172009-04-28 15:26:38 +02005866
5867 /* package name of the app that installed this package */
5868 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869
5870 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005871 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 super(pkgFlags);
5873 this.name = name;
5874 this.codePath = codePath;
5875 this.codePathString = codePath.toString();
5876 this.resourcePath = resourcePath;
5877 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005878 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 }
5880
Jacek Surazski65e13172009-04-28 15:26:38 +02005881 public void setInstallerPackageName(String packageName) {
5882 installerPackageName = packageName;
5883 }
5884
5885 String getInstallerPackageName() {
5886 return installerPackageName;
5887 }
5888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 public void setInstallStatus(int newStatus) {
5890 installStatus = newStatus;
5891 }
5892
5893 public int getInstallStatus() {
5894 return installStatus;
5895 }
5896
5897 public void setTimeStamp(long newStamp) {
5898 if (newStamp != timeStamp) {
5899 timeStamp = newStamp;
5900 timeStampString = Long.toString(newStamp);
5901 }
5902 }
5903
5904 public void setTimeStamp(long newStamp, String newStampStr) {
5905 timeStamp = newStamp;
5906 timeStampString = newStampStr;
5907 }
5908
5909 public long getTimeStamp() {
5910 return timeStamp;
5911 }
5912
5913 public String getTimeStampStr() {
5914 return timeStampString;
5915 }
5916
5917 public void copyFrom(PackageSettingBase base) {
5918 grantedPermissions = base.grantedPermissions;
5919 gids = base.gids;
5920 loadedPermissions = base.loadedPermissions;
5921
5922 timeStamp = base.timeStamp;
5923 timeStampString = base.timeStampString;
5924 signatures = base.signatures;
5925 permissionsFixed = base.permissionsFixed;
5926 disabledComponents = base.disabledComponents;
5927 enabledComponents = base.enabledComponents;
5928 enabled = base.enabled;
5929 installStatus = base.installStatus;
5930 }
5931
5932 void enableComponentLP(String componentClassName) {
5933 disabledComponents.remove(componentClassName);
5934 enabledComponents.add(componentClassName);
5935 }
5936
5937 void disableComponentLP(String componentClassName) {
5938 enabledComponents.remove(componentClassName);
5939 disabledComponents.add(componentClassName);
5940 }
5941
5942 void restoreComponentLP(String componentClassName) {
5943 enabledComponents.remove(componentClassName);
5944 disabledComponents.remove(componentClassName);
5945 }
5946
5947 int currentEnabledStateLP(String componentName) {
5948 if (enabledComponents.contains(componentName)) {
5949 return COMPONENT_ENABLED_STATE_ENABLED;
5950 } else if (disabledComponents.contains(componentName)) {
5951 return COMPONENT_ENABLED_STATE_DISABLED;
5952 } else {
5953 return COMPONENT_ENABLED_STATE_DEFAULT;
5954 }
5955 }
5956 }
5957
5958 /**
5959 * Settings data for a particular package we know about.
5960 */
5961 static final class PackageSetting extends PackageSettingBase {
5962 int userId;
5963 PackageParser.Package pkg;
5964 SharedUserSetting sharedUser;
5965
5966 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005967 int pVersionCode, int pkgFlags) {
5968 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 }
5970
5971 @Override
5972 public String toString() {
5973 return "PackageSetting{"
5974 + Integer.toHexString(System.identityHashCode(this))
5975 + " " + name + "/" + userId + "}";
5976 }
5977 }
5978
5979 /**
5980 * Settings data for a particular shared user ID we know about.
5981 */
5982 static final class SharedUserSetting extends GrantedPermissions {
5983 final String name;
5984 int userId;
5985 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
5986 final PackageSignatures signatures = new PackageSignatures();
5987
5988 SharedUserSetting(String _name, int _pkgFlags) {
5989 super(_pkgFlags);
5990 name = _name;
5991 }
5992
5993 @Override
5994 public String toString() {
5995 return "SharedUserSetting{"
5996 + Integer.toHexString(System.identityHashCode(this))
5997 + " " + name + "/" + userId + "}";
5998 }
5999 }
6000
6001 /**
6002 * Holds information about dynamic settings.
6003 */
6004 private static final class Settings {
6005 private final File mSettingsFilename;
6006 private final File mBackupSettingsFilename;
6007 private final HashMap<String, PackageSetting> mPackages =
6008 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 // List of replaced system applications
6010 final HashMap<String, PackageSetting> mDisabledSysPackages =
6011 new HashMap<String, PackageSetting>();
6012
6013 // The user's preferred activities associated with particular intent
6014 // filters.
6015 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6016 new IntentResolver<PreferredActivity, PreferredActivity>() {
6017 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006018 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006020 out.print(prefix); out.print(
6021 Integer.toHexString(System.identityHashCode(filter)));
6022 out.print(' ');
6023 out.print(filter.mActivity.flattenToShortString());
6024 out.print(" match=0x");
6025 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006027 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006029 out.print(prefix); out.print(" ");
6030 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 }
6032 }
6033 }
6034 };
6035 private final HashMap<String, SharedUserSetting> mSharedUsers =
6036 new HashMap<String, SharedUserSetting>();
6037 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6038 private final SparseArray<Object> mOtherUserIds =
6039 new SparseArray<Object>();
6040
6041 // For reading/writing settings file.
6042 private final ArrayList<Signature> mPastSignatures =
6043 new ArrayList<Signature>();
6044
6045 // Mapping from permission names to info about them.
6046 final HashMap<String, BasePermission> mPermissions =
6047 new HashMap<String, BasePermission>();
6048
6049 // Mapping from permission tree names to info about them.
6050 final HashMap<String, BasePermission> mPermissionTrees =
6051 new HashMap<String, BasePermission>();
6052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 private final StringBuilder mReadMessages = new StringBuilder();
6054
6055 private static final class PendingPackage extends PackageSettingBase {
6056 final int sharedId;
6057
6058 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006059 int sharedId, int pVersionCode, int pkgFlags) {
6060 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 this.sharedId = sharedId;
6062 }
6063 }
6064 private final ArrayList<PendingPackage> mPendingPackages
6065 = new ArrayList<PendingPackage>();
6066
6067 Settings() {
6068 File dataDir = Environment.getDataDirectory();
6069 File systemDir = new File(dataDir, "system");
6070 systemDir.mkdirs();
6071 FileUtils.setPermissions(systemDir.toString(),
6072 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6073 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6074 -1, -1);
6075 mSettingsFilename = new File(systemDir, "packages.xml");
6076 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6077 }
6078
6079 PackageSetting getPackageLP(PackageParser.Package pkg,
6080 SharedUserSetting sharedUser, File codePath, File resourcePath,
6081 int pkgFlags, boolean create, boolean add) {
6082 final String name = pkg.packageName;
6083 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006084 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 return p;
6086 }
6087
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006088 PackageSetting peekPackageLP(String name) {
6089 return mPackages.get(name);
6090 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 PackageSetting p = mPackages.get(name);
6092 if (p != null && p.codePath.getPath().equals(codePath)) {
6093 return p;
6094 }
6095 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006096 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 }
6098
6099 void setInstallStatus(String pkgName, int status) {
6100 PackageSetting p = mPackages.get(pkgName);
6101 if(p != null) {
6102 if(p.getInstallStatus() != status) {
6103 p.setInstallStatus(status);
6104 }
6105 }
6106 }
6107
Jacek Surazski65e13172009-04-28 15:26:38 +02006108 void setInstallerPackageName(String pkgName,
6109 String installerPkgName) {
6110 PackageSetting p = mPackages.get(pkgName);
6111 if(p != null) {
6112 p.setInstallerPackageName(installerPkgName);
6113 }
6114 }
6115
6116 String getInstallerPackageName(String pkgName) {
6117 PackageSetting p = mPackages.get(pkgName);
6118 return (p == null) ? null : p.getInstallerPackageName();
6119 }
6120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 int getInstallStatus(String pkgName) {
6122 PackageSetting p = mPackages.get(pkgName);
6123 if(p != null) {
6124 return p.getInstallStatus();
6125 }
6126 return -1;
6127 }
6128
6129 SharedUserSetting getSharedUserLP(String name,
6130 int pkgFlags, boolean create) {
6131 SharedUserSetting s = mSharedUsers.get(name);
6132 if (s == null) {
6133 if (!create) {
6134 return null;
6135 }
6136 s = new SharedUserSetting(name, pkgFlags);
6137 if (MULTIPLE_APPLICATION_UIDS) {
6138 s.userId = newUserIdLP(s);
6139 } else {
6140 s.userId = FIRST_APPLICATION_UID;
6141 }
6142 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6143 // < 0 means we couldn't assign a userid; fall out and return
6144 // s, which is currently null
6145 if (s.userId >= 0) {
6146 mSharedUsers.put(name, s);
6147 }
6148 }
6149
6150 return s;
6151 }
6152
6153 int disableSystemPackageLP(String name) {
6154 PackageSetting p = mPackages.get(name);
6155 if(p == null) {
6156 Log.w(TAG, "Package:"+name+" is not an installed package");
6157 return -1;
6158 }
6159 PackageSetting dp = mDisabledSysPackages.get(name);
6160 // always make sure the system package code and resource paths dont change
6161 if(dp == null) {
6162 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6163 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6164 }
6165 mDisabledSysPackages.put(name, p);
6166 }
6167 return removePackageLP(name);
6168 }
6169
6170 PackageSetting enableSystemPackageLP(String name) {
6171 PackageSetting p = mDisabledSysPackages.get(name);
6172 if(p == null) {
6173 Log.w(TAG, "Package:"+name+" is not disabled");
6174 return null;
6175 }
6176 // Reset flag in ApplicationInfo object
6177 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6178 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6179 }
6180 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006181 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 mDisabledSysPackages.remove(name);
6183 return ret;
6184 }
6185
6186 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006187 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 PackageSetting p = mPackages.get(name);
6189 if (p != null) {
6190 if (p.userId == uid) {
6191 return p;
6192 }
6193 reportSettingsProblem(Log.ERROR,
6194 "Adding duplicate package, keeping first: " + name);
6195 return null;
6196 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006197 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 p.userId = uid;
6199 if (addUserIdLP(uid, p, name)) {
6200 mPackages.put(name, p);
6201 return p;
6202 }
6203 return null;
6204 }
6205
6206 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6207 SharedUserSetting s = mSharedUsers.get(name);
6208 if (s != null) {
6209 if (s.userId == uid) {
6210 return s;
6211 }
6212 reportSettingsProblem(Log.ERROR,
6213 "Adding duplicate shared user, keeping first: " + name);
6214 return null;
6215 }
6216 s = new SharedUserSetting(name, pkgFlags);
6217 s.userId = uid;
6218 if (addUserIdLP(uid, s, name)) {
6219 mSharedUsers.put(name, s);
6220 return s;
6221 }
6222 return null;
6223 }
6224
6225 private PackageSetting getPackageLP(String name,
6226 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006227 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006228 PackageSetting p = mPackages.get(name);
6229 if (p != null) {
6230 if (!p.codePath.equals(codePath)) {
6231 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006232 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006233 // This is an updated system app with versions in both system
6234 // and data partition. Just let the most recent version
6235 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006236 Log.w(TAG, "Trying to update system app code path from " +
6237 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006238 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006239 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07006240 reportSettingsProblem(Log.WARN,
6241 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006242 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006244 }
6245 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 reportSettingsProblem(Log.WARN,
6247 "Package " + name + " shared user changed from "
6248 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
6249 + " to "
6250 + (sharedUser != null ? sharedUser.name : "<nothing>")
6251 + "; replacing with new");
6252 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006253 } else {
6254 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6255 // If what we are scanning is a system package, then
6256 // make it so, regardless of whether it was previously
6257 // installed only in the data partition.
6258 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 }
6261 }
6262 if (p == null) {
6263 // Create a new PackageSettings entry. this can end up here because
6264 // of code path mismatch or user id mismatch of an updated system partition
6265 if (!create) {
6266 return null;
6267 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006268 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07006270 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 if (sharedUser != null) {
6272 p.userId = sharedUser.userId;
6273 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006274 // Clone the setting here for disabled system packages
6275 PackageSetting dis = mDisabledSysPackages.get(name);
6276 if (dis != null) {
6277 // For disabled packages a new setting is created
6278 // from the existing user id. This still has to be
6279 // added to list of user id's
6280 // Copy signatures from previous setting
6281 if (dis.signatures.mSignatures != null) {
6282 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
6283 }
6284 p.userId = dis.userId;
6285 // Clone permissions
6286 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
6287 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
6288 // Clone component info
6289 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
6290 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
6291 // Add new setting to list of user ids
6292 addUserIdLP(p.userId, p, name);
6293 } else {
6294 // Assign new user id
6295 p.userId = newUserIdLP(p);
6296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 } else {
6298 p.userId = FIRST_APPLICATION_UID;
6299 }
6300 if (p.userId < 0) {
6301 reportSettingsProblem(Log.WARN,
6302 "Package " + name + " could not be assigned a valid uid");
6303 return null;
6304 }
6305 if (add) {
6306 // Finish adding new package by adding it and updating shared
6307 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006308 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 }
6310 }
6311 return p;
6312 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006313
6314 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg,
6315 File codePath, File resourcePath) {
6316 p.pkg = pkg;
6317 // Update code path if needed
6318 if (!codePath.toString().equalsIgnoreCase(p.codePathString)) {
6319 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006320 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006321 p.codePath = codePath;
6322 p.codePathString = codePath.toString();
6323 }
6324 //Update resource path if needed
6325 if (!resourcePath.toString().equalsIgnoreCase(p.resourcePathString)) {
6326 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006327 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006328 p.resourcePath = resourcePath;
6329 p.resourcePathString = resourcePath.toString();
6330 }
6331 // Update version code if needed
6332 if (pkg.mVersionCode != p.versionCode) {
6333 p.versionCode = pkg.mVersionCode;
6334 }
6335 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
6336 }
6337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 // Utility method that adds a PackageSetting to mPackages and
6339 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006340 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 SharedUserSetting sharedUser) {
6342 mPackages.put(name, p);
6343 if (sharedUser != null) {
6344 if (p.sharedUser != null && p.sharedUser != sharedUser) {
6345 reportSettingsProblem(Log.ERROR,
6346 "Package " + p.name + " was user "
6347 + p.sharedUser + " but is now " + sharedUser
6348 + "; I am not changing its files so it will probably fail!");
6349 p.sharedUser.packages.remove(p);
6350 } else if (p.userId != sharedUser.userId) {
6351 reportSettingsProblem(Log.ERROR,
6352 "Package " + p.name + " was user id " + p.userId
6353 + " but is now user " + sharedUser
6354 + " with id " + sharedUser.userId
6355 + "; I am not changing its files so it will probably fail!");
6356 }
6357
6358 sharedUser.packages.add(p);
6359 p.sharedUser = sharedUser;
6360 p.userId = sharedUser.userId;
6361 }
6362 }
6363
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006364 /*
6365 * Update the shared user setting when a package using
6366 * specifying the shared user id is removed. The gids
6367 * associated with each permission of the deleted package
6368 * are removed from the shared user's gid list only if its
6369 * not in use by other permissions of packages in the
6370 * shared user setting.
6371 */
6372 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6374 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6375 return;
6376 }
6377 // No sharedUserId
6378 if (deletedPs.sharedUser == null) {
6379 return;
6380 }
6381 SharedUserSetting sus = deletedPs.sharedUser;
6382 // Update permissions
6383 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6384 boolean used = false;
6385 if (!sus.grantedPermissions.contains (eachPerm)) {
6386 continue;
6387 }
6388 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006389 if (pkg.pkg != null &&
6390 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
6391 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 used = true;
6393 break;
6394 }
6395 }
6396 if (!used) {
6397 // can safely delete this permission from list
6398 sus.grantedPermissions.remove(eachPerm);
6399 sus.loadedPermissions.remove(eachPerm);
6400 }
6401 }
6402 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006403 int newGids[] = globalGids;
6404 for (String eachPerm : sus.grantedPermissions) {
6405 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006406 if (bp != null) {
6407 newGids = appendInts(newGids, bp.gids);
6408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 }
6410 sus.gids = newGids;
6411 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 private int removePackageLP(String name) {
6414 PackageSetting p = mPackages.get(name);
6415 if (p != null) {
6416 mPackages.remove(name);
6417 if (p.sharedUser != null) {
6418 p.sharedUser.packages.remove(p);
6419 if (p.sharedUser.packages.size() == 0) {
6420 mSharedUsers.remove(p.sharedUser.name);
6421 removeUserIdLP(p.sharedUser.userId);
6422 return p.sharedUser.userId;
6423 }
6424 } else {
6425 removeUserIdLP(p.userId);
6426 return p.userId;
6427 }
6428 }
6429 return -1;
6430 }
6431
6432 private boolean addUserIdLP(int uid, Object obj, Object name) {
6433 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6434 return false;
6435 }
6436
6437 if (uid >= FIRST_APPLICATION_UID) {
6438 int N = mUserIds.size();
6439 final int index = uid - FIRST_APPLICATION_UID;
6440 while (index >= N) {
6441 mUserIds.add(null);
6442 N++;
6443 }
6444 if (mUserIds.get(index) != null) {
6445 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006446 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 + " name=" + name);
6448 return false;
6449 }
6450 mUserIds.set(index, obj);
6451 } else {
6452 if (mOtherUserIds.get(uid) != null) {
6453 reportSettingsProblem(Log.ERROR,
6454 "Adding duplicate shared id: " + uid
6455 + " name=" + name);
6456 return false;
6457 }
6458 mOtherUserIds.put(uid, obj);
6459 }
6460 return true;
6461 }
6462
6463 public Object getUserIdLP(int uid) {
6464 if (uid >= FIRST_APPLICATION_UID) {
6465 int N = mUserIds.size();
6466 final int index = uid - FIRST_APPLICATION_UID;
6467 return index < N ? mUserIds.get(index) : null;
6468 } else {
6469 return mOtherUserIds.get(uid);
6470 }
6471 }
6472
6473 private void removeUserIdLP(int uid) {
6474 if (uid >= FIRST_APPLICATION_UID) {
6475 int N = mUserIds.size();
6476 final int index = uid - FIRST_APPLICATION_UID;
6477 if (index < N) mUserIds.set(index, null);
6478 } else {
6479 mOtherUserIds.remove(uid);
6480 }
6481 }
6482
6483 void writeLP() {
6484 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6485
6486 // Keep the old settings around until we know the new ones have
6487 // been successfully written.
6488 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006489 // Presence of backup settings file indicates that we failed
6490 // to persist settings earlier. So preserve the older
6491 // backup for future reference since the current settings
6492 // might have been corrupted.
6493 if (!mBackupSettingsFilename.exists()) {
6494 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
6495 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
6496 return;
6497 }
6498 } else {
6499 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07006500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 }
6502
6503 mPastSignatures.clear();
6504
6505 try {
6506 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6507
6508 //XmlSerializer serializer = XmlUtils.serializerInstance();
6509 XmlSerializer serializer = new FastXmlSerializer();
6510 serializer.setOutput(str, "utf-8");
6511 serializer.startDocument(null, true);
6512 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6513
6514 serializer.startTag(null, "packages");
6515
6516 serializer.startTag(null, "permission-trees");
6517 for (BasePermission bp : mPermissionTrees.values()) {
6518 writePermission(serializer, bp);
6519 }
6520 serializer.endTag(null, "permission-trees");
6521
6522 serializer.startTag(null, "permissions");
6523 for (BasePermission bp : mPermissions.values()) {
6524 writePermission(serializer, bp);
6525 }
6526 serializer.endTag(null, "permissions");
6527
6528 for (PackageSetting pkg : mPackages.values()) {
6529 writePackage(serializer, pkg);
6530 }
6531
6532 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6533 writeDisabledSysPackage(serializer, pkg);
6534 }
6535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 serializer.startTag(null, "preferred-activities");
6537 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6538 serializer.startTag(null, "item");
6539 pa.writeToXml(serializer);
6540 serializer.endTag(null, "item");
6541 }
6542 serializer.endTag(null, "preferred-activities");
6543
6544 for (SharedUserSetting usr : mSharedUsers.values()) {
6545 serializer.startTag(null, "shared-user");
6546 serializer.attribute(null, "name", usr.name);
6547 serializer.attribute(null, "userId",
6548 Integer.toString(usr.userId));
6549 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6550 serializer.startTag(null, "perms");
6551 for (String name : usr.grantedPermissions) {
6552 serializer.startTag(null, "item");
6553 serializer.attribute(null, "name", name);
6554 serializer.endTag(null, "item");
6555 }
6556 serializer.endTag(null, "perms");
6557 serializer.endTag(null, "shared-user");
6558 }
6559
6560 serializer.endTag(null, "packages");
6561
6562 serializer.endDocument();
6563
6564 str.flush();
6565 str.close();
6566
6567 // New settings successfully written, old ones are no longer
6568 // needed.
6569 mBackupSettingsFilename.delete();
6570 FileUtils.setPermissions(mSettingsFilename.toString(),
6571 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6572 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6573 |FileUtils.S_IROTH,
6574 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006575 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576
6577 } catch(XmlPullParserException e) {
6578 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 -08006579 } catch(java.io.IOException e) {
6580 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 -08006581 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006582 // Clean up partially written file
6583 if (mSettingsFilename.exists()) {
6584 if (!mSettingsFilename.delete()) {
6585 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
6586 }
6587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 //Debug.stopMethodTracing();
6589 }
6590
6591 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
6592 throws java.io.IOException {
6593 serializer.startTag(null, "updated-package");
6594 serializer.attribute(null, "name", pkg.name);
6595 serializer.attribute(null, "codePath", pkg.codePathString);
6596 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006597 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6599 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6600 }
6601 if (pkg.sharedUser == null) {
6602 serializer.attribute(null, "userId",
6603 Integer.toString(pkg.userId));
6604 } else {
6605 serializer.attribute(null, "sharedUserId",
6606 Integer.toString(pkg.userId));
6607 }
6608 serializer.startTag(null, "perms");
6609 if (pkg.sharedUser == null) {
6610 // If this is a shared user, the permissions will
6611 // be written there. We still need to write an
6612 // empty permissions list so permissionsFixed will
6613 // be set.
6614 for (final String name : pkg.grantedPermissions) {
6615 BasePermission bp = mPermissions.get(name);
6616 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6617 // We only need to write signature or system permissions but this wont
6618 // match the semantics of grantedPermissions. So write all permissions.
6619 serializer.startTag(null, "item");
6620 serializer.attribute(null, "name", name);
6621 serializer.endTag(null, "item");
6622 }
6623 }
6624 }
6625 serializer.endTag(null, "perms");
6626 serializer.endTag(null, "updated-package");
6627 }
6628
6629 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
6630 throws java.io.IOException {
6631 serializer.startTag(null, "package");
6632 serializer.attribute(null, "name", pkg.name);
6633 serializer.attribute(null, "codePath", pkg.codePathString);
6634 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6635 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6636 }
6637 serializer.attribute(null, "system",
6638 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6639 ? "true" : "false");
6640 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006641 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 if (pkg.sharedUser == null) {
6643 serializer.attribute(null, "userId",
6644 Integer.toString(pkg.userId));
6645 } else {
6646 serializer.attribute(null, "sharedUserId",
6647 Integer.toString(pkg.userId));
6648 }
6649 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6650 serializer.attribute(null, "enabled",
6651 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6652 ? "true" : "false");
6653 }
6654 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6655 serializer.attribute(null, "installStatus", "false");
6656 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006657 if (pkg.installerPackageName != null) {
6658 serializer.attribute(null, "installer", pkg.installerPackageName);
6659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6661 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6662 serializer.startTag(null, "perms");
6663 if (pkg.sharedUser == null) {
6664 // If this is a shared user, the permissions will
6665 // be written there. We still need to write an
6666 // empty permissions list so permissionsFixed will
6667 // be set.
6668 for (final String name : pkg.grantedPermissions) {
6669 serializer.startTag(null, "item");
6670 serializer.attribute(null, "name", name);
6671 serializer.endTag(null, "item");
6672 }
6673 }
6674 serializer.endTag(null, "perms");
6675 }
6676 if (pkg.disabledComponents.size() > 0) {
6677 serializer.startTag(null, "disabled-components");
6678 for (final String name : pkg.disabledComponents) {
6679 serializer.startTag(null, "item");
6680 serializer.attribute(null, "name", name);
6681 serializer.endTag(null, "item");
6682 }
6683 serializer.endTag(null, "disabled-components");
6684 }
6685 if (pkg.enabledComponents.size() > 0) {
6686 serializer.startTag(null, "enabled-components");
6687 for (final String name : pkg.enabledComponents) {
6688 serializer.startTag(null, "item");
6689 serializer.attribute(null, "name", name);
6690 serializer.endTag(null, "item");
6691 }
6692 serializer.endTag(null, "enabled-components");
6693 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 serializer.endTag(null, "package");
6696 }
6697
6698 void writePermission(XmlSerializer serializer, BasePermission bp)
6699 throws XmlPullParserException, java.io.IOException {
6700 if (bp.type != BasePermission.TYPE_BUILTIN
6701 && bp.sourcePackage != null) {
6702 serializer.startTag(null, "item");
6703 serializer.attribute(null, "name", bp.name);
6704 serializer.attribute(null, "package", bp.sourcePackage);
6705 if (DEBUG_SETTINGS) Log.v(TAG,
6706 "Writing perm: name=" + bp.name + " type=" + bp.type);
6707 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6708 PermissionInfo pi = bp.perm != null ? bp.perm.info
6709 : bp.pendingInfo;
6710 if (pi != null) {
6711 serializer.attribute(null, "type", "dynamic");
6712 if (pi.icon != 0) {
6713 serializer.attribute(null, "icon",
6714 Integer.toString(pi.icon));
6715 }
6716 if (pi.nonLocalizedLabel != null) {
6717 serializer.attribute(null, "label",
6718 pi.nonLocalizedLabel.toString());
6719 }
6720 if (pi.protectionLevel !=
6721 PermissionInfo.PROTECTION_NORMAL) {
6722 serializer.attribute(null, "protection",
6723 Integer.toString(pi.protectionLevel));
6724 }
6725 }
6726 }
6727 serializer.endTag(null, "item");
6728 }
6729 }
6730
6731 String getReadMessagesLP() {
6732 return mReadMessages.toString();
6733 }
6734
6735 ArrayList<String> getListOfIncompleteInstallPackages() {
6736 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6737 Iterator<String> its = kList.iterator();
6738 ArrayList<String> ret = new ArrayList<String>();
6739 while(its.hasNext()) {
6740 String key = its.next();
6741 PackageSetting ps = mPackages.get(key);
6742 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
6743 ret.add(key);
6744 }
6745 }
6746 return ret;
6747 }
6748
6749 boolean readLP() {
6750 FileInputStream str = null;
6751 if (mBackupSettingsFilename.exists()) {
6752 try {
6753 str = new FileInputStream(mBackupSettingsFilename);
6754 mReadMessages.append("Reading from backup settings file\n");
6755 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006756 if (mSettingsFilename.exists()) {
6757 // If both the backup and settings file exist, we
6758 // ignore the settings since it might have been
6759 // corrupted.
6760 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
6761 mSettingsFilename.delete();
6762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 } catch (java.io.IOException e) {
6764 // We'll try for the normal settings file.
6765 }
6766 }
6767
6768 mPastSignatures.clear();
6769
6770 try {
6771 if (str == null) {
6772 if (!mSettingsFilename.exists()) {
6773 mReadMessages.append("No settings file found\n");
6774 Log.i(TAG, "No current settings file!");
6775 return false;
6776 }
6777 str = new FileInputStream(mSettingsFilename);
6778 }
6779 XmlPullParser parser = Xml.newPullParser();
6780 parser.setInput(str, null);
6781
6782 int type;
6783 while ((type=parser.next()) != XmlPullParser.START_TAG
6784 && type != XmlPullParser.END_DOCUMENT) {
6785 ;
6786 }
6787
6788 if (type != XmlPullParser.START_TAG) {
6789 mReadMessages.append("No start tag found in settings file\n");
6790 Log.e(TAG, "No start tag found in package manager settings");
6791 return false;
6792 }
6793
6794 int outerDepth = parser.getDepth();
6795 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6796 && (type != XmlPullParser.END_TAG
6797 || parser.getDepth() > outerDepth)) {
6798 if (type == XmlPullParser.END_TAG
6799 || type == XmlPullParser.TEXT) {
6800 continue;
6801 }
6802
6803 String tagName = parser.getName();
6804 if (tagName.equals("package")) {
6805 readPackageLP(parser);
6806 } else if (tagName.equals("permissions")) {
6807 readPermissionsLP(mPermissions, parser);
6808 } else if (tagName.equals("permission-trees")) {
6809 readPermissionsLP(mPermissionTrees, parser);
6810 } else if (tagName.equals("shared-user")) {
6811 readSharedUserLP(parser);
6812 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006813 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006814 } else if (tagName.equals("preferred-activities")) {
6815 readPreferredActivitiesLP(parser);
6816 } else if(tagName.equals("updated-package")) {
6817 readDisabledSysPackageLP(parser);
6818 } else {
6819 Log.w(TAG, "Unknown element under <packages>: "
6820 + parser.getName());
6821 XmlUtils.skipCurrentTag(parser);
6822 }
6823 }
6824
6825 str.close();
6826
6827 } catch(XmlPullParserException e) {
6828 mReadMessages.append("Error reading: " + e.toString());
6829 Log.e(TAG, "Error reading package manager settings", e);
6830
6831 } catch(java.io.IOException e) {
6832 mReadMessages.append("Error reading: " + e.toString());
6833 Log.e(TAG, "Error reading package manager settings", e);
6834
6835 }
6836
6837 int N = mPendingPackages.size();
6838 for (int i=0; i<N; i++) {
6839 final PendingPackage pp = mPendingPackages.get(i);
6840 Object idObj = getUserIdLP(pp.sharedId);
6841 if (idObj != null && idObj instanceof SharedUserSetting) {
6842 PackageSetting p = getPackageLP(pp.name,
6843 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006844 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 if (p == null) {
6846 Log.w(TAG, "Unable to create application package for "
6847 + pp.name);
6848 continue;
6849 }
6850 p.copyFrom(pp);
6851 } else if (idObj != null) {
6852 String msg = "Bad package setting: package " + pp.name
6853 + " has shared uid " + pp.sharedId
6854 + " that is not a shared uid\n";
6855 mReadMessages.append(msg);
6856 Log.e(TAG, msg);
6857 } else {
6858 String msg = "Bad package setting: package " + pp.name
6859 + " has shared uid " + pp.sharedId
6860 + " that is not defined\n";
6861 mReadMessages.append(msg);
6862 Log.e(TAG, msg);
6863 }
6864 }
6865 mPendingPackages.clear();
6866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867 mReadMessages.append("Read completed successfully: "
6868 + mPackages.size() + " packages, "
6869 + mSharedUsers.size() + " shared uids\n");
6870
6871 return true;
6872 }
6873
6874 private int readInt(XmlPullParser parser, String ns, String name,
6875 int defValue) {
6876 String v = parser.getAttributeValue(ns, name);
6877 try {
6878 if (v == null) {
6879 return defValue;
6880 }
6881 return Integer.parseInt(v);
6882 } catch (NumberFormatException e) {
6883 reportSettingsProblem(Log.WARN,
6884 "Error in package manager settings: attribute " +
6885 name + " has bad integer value " + v + " at "
6886 + parser.getPositionDescription());
6887 }
6888 return defValue;
6889 }
6890
6891 private void readPermissionsLP(HashMap<String, BasePermission> out,
6892 XmlPullParser parser)
6893 throws IOException, XmlPullParserException {
6894 int outerDepth = parser.getDepth();
6895 int type;
6896 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6897 && (type != XmlPullParser.END_TAG
6898 || parser.getDepth() > outerDepth)) {
6899 if (type == XmlPullParser.END_TAG
6900 || type == XmlPullParser.TEXT) {
6901 continue;
6902 }
6903
6904 String tagName = parser.getName();
6905 if (tagName.equals("item")) {
6906 String name = parser.getAttributeValue(null, "name");
6907 String sourcePackage = parser.getAttributeValue(null, "package");
6908 String ptype = parser.getAttributeValue(null, "type");
6909 if (name != null && sourcePackage != null) {
6910 boolean dynamic = "dynamic".equals(ptype);
6911 BasePermission bp = new BasePermission(name, sourcePackage,
6912 dynamic
6913 ? BasePermission.TYPE_DYNAMIC
6914 : BasePermission.TYPE_NORMAL);
6915 if (dynamic) {
6916 PermissionInfo pi = new PermissionInfo();
6917 pi.packageName = sourcePackage.intern();
6918 pi.name = name.intern();
6919 pi.icon = readInt(parser, null, "icon", 0);
6920 pi.nonLocalizedLabel = parser.getAttributeValue(
6921 null, "label");
6922 pi.protectionLevel = readInt(parser, null, "protection",
6923 PermissionInfo.PROTECTION_NORMAL);
6924 bp.pendingInfo = pi;
6925 }
6926 out.put(bp.name, bp);
6927 } else {
6928 reportSettingsProblem(Log.WARN,
6929 "Error in package manager settings: permissions has"
6930 + " no name at " + parser.getPositionDescription());
6931 }
6932 } else {
6933 reportSettingsProblem(Log.WARN,
6934 "Unknown element reading permissions: "
6935 + parser.getName() + " at "
6936 + parser.getPositionDescription());
6937 }
6938 XmlUtils.skipCurrentTag(parser);
6939 }
6940 }
6941
6942 private void readDisabledSysPackageLP(XmlPullParser parser)
6943 throws XmlPullParserException, IOException {
6944 String name = parser.getAttributeValue(null, "name");
6945 String codePathStr = parser.getAttributeValue(null, "codePath");
6946 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6947 if(resourcePathStr == null) {
6948 resourcePathStr = codePathStr;
6949 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006950 String version = parser.getAttributeValue(null, "version");
6951 int versionCode = 0;
6952 if (version != null) {
6953 try {
6954 versionCode = Integer.parseInt(version);
6955 } catch (NumberFormatException e) {
6956 }
6957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958
6959 int pkgFlags = 0;
6960 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6961 PackageSetting ps = new PackageSetting(name,
6962 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006963 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006964 String timeStampStr = parser.getAttributeValue(null, "ts");
6965 if (timeStampStr != null) {
6966 try {
6967 long timeStamp = Long.parseLong(timeStampStr);
6968 ps.setTimeStamp(timeStamp, timeStampStr);
6969 } catch (NumberFormatException e) {
6970 }
6971 }
6972 String idStr = parser.getAttributeValue(null, "userId");
6973 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
6974 if(ps.userId <= 0) {
6975 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6976 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
6977 }
6978 int outerDepth = parser.getDepth();
6979 int type;
6980 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6981 && (type != XmlPullParser.END_TAG
6982 || parser.getDepth() > outerDepth)) {
6983 if (type == XmlPullParser.END_TAG
6984 || type == XmlPullParser.TEXT) {
6985 continue;
6986 }
6987
6988 String tagName = parser.getName();
6989 if (tagName.equals("perms")) {
6990 readGrantedPermissionsLP(parser,
6991 ps.grantedPermissions);
6992 } else {
6993 reportSettingsProblem(Log.WARN,
6994 "Unknown element under <updated-package>: "
6995 + parser.getName());
6996 XmlUtils.skipCurrentTag(parser);
6997 }
6998 }
6999 mDisabledSysPackages.put(name, ps);
7000 }
7001
7002 private void readPackageLP(XmlPullParser parser)
7003 throws XmlPullParserException, IOException {
7004 String name = null;
7005 String idStr = null;
7006 String sharedIdStr = null;
7007 String codePathStr = null;
7008 String resourcePathStr = null;
7009 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007010 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 int pkgFlags = 0;
7012 String timeStampStr;
7013 long timeStamp = 0;
7014 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007015 String version = null;
7016 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 try {
7018 name = parser.getAttributeValue(null, "name");
7019 idStr = parser.getAttributeValue(null, "userId");
7020 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7021 codePathStr = parser.getAttributeValue(null, "codePath");
7022 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007023 version = parser.getAttributeValue(null, "version");
7024 if (version != null) {
7025 try {
7026 versionCode = Integer.parseInt(version);
7027 } catch (NumberFormatException e) {
7028 }
7029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazski65e13172009-04-28 15:26:38 +02007031 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032 if (systemStr != null) {
7033 if ("true".equals(systemStr)) {
7034 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7035 }
7036 } else {
7037 // Old settings that don't specify system... just treat
7038 // them as system, good enough.
7039 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7040 }
7041 timeStampStr = parser.getAttributeValue(null, "ts");
7042 if (timeStampStr != null) {
7043 try {
7044 timeStamp = Long.parseLong(timeStampStr);
7045 } catch (NumberFormatException e) {
7046 }
7047 }
7048 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7049 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7050 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7051 if (resourcePathStr == null) {
7052 resourcePathStr = codePathStr;
7053 }
7054 if (name == null) {
7055 reportSettingsProblem(Log.WARN,
7056 "Error in package manager settings: <package> has no name at "
7057 + parser.getPositionDescription());
7058 } else if (codePathStr == null) {
7059 reportSettingsProblem(Log.WARN,
7060 "Error in package manager settings: <package> has no codePath at "
7061 + parser.getPositionDescription());
7062 } else if (userId > 0) {
7063 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007064 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007065 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7066 + ": userId=" + userId + " pkg=" + packageSetting);
7067 if (packageSetting == null) {
7068 reportSettingsProblem(Log.ERROR,
7069 "Failure adding uid " + userId
7070 + " while parsing settings at "
7071 + parser.getPositionDescription());
7072 } else {
7073 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7074 }
7075 } else if (sharedIdStr != null) {
7076 userId = sharedIdStr != null
7077 ? Integer.parseInt(sharedIdStr) : 0;
7078 if (userId > 0) {
7079 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007080 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7082 mPendingPackages.add((PendingPackage) packageSetting);
7083 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7084 + ": sharedUserId=" + userId + " pkg="
7085 + packageSetting);
7086 } else {
7087 reportSettingsProblem(Log.WARN,
7088 "Error in package manager settings: package "
7089 + name + " has bad sharedId " + sharedIdStr
7090 + " at " + parser.getPositionDescription());
7091 }
7092 } else {
7093 reportSettingsProblem(Log.WARN,
7094 "Error in package manager settings: package "
7095 + name + " has bad userId " + idStr + " at "
7096 + parser.getPositionDescription());
7097 }
7098 } catch (NumberFormatException e) {
7099 reportSettingsProblem(Log.WARN,
7100 "Error in package manager settings: package "
7101 + name + " has bad userId " + idStr + " at "
7102 + parser.getPositionDescription());
7103 }
7104 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02007105 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106 final String enabledStr = parser.getAttributeValue(null, "enabled");
7107 if (enabledStr != null) {
7108 if (enabledStr.equalsIgnoreCase("true")) {
7109 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7110 } else if (enabledStr.equalsIgnoreCase("false")) {
7111 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7112 } else if (enabledStr.equalsIgnoreCase("default")) {
7113 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7114 } else {
7115 reportSettingsProblem(Log.WARN,
7116 "Error in package manager settings: package "
7117 + name + " has bad enabled value: " + idStr
7118 + " at " + parser.getPositionDescription());
7119 }
7120 } else {
7121 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7122 }
7123 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7124 if (installStatusStr != null) {
7125 if (installStatusStr.equalsIgnoreCase("false")) {
7126 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7127 } else {
7128 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7129 }
7130 }
7131
7132 int outerDepth = parser.getDepth();
7133 int type;
7134 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7135 && (type != XmlPullParser.END_TAG
7136 || parser.getDepth() > outerDepth)) {
7137 if (type == XmlPullParser.END_TAG
7138 || type == XmlPullParser.TEXT) {
7139 continue;
7140 }
7141
7142 String tagName = parser.getName();
7143 if (tagName.equals("disabled-components")) {
7144 readDisabledComponentsLP(packageSetting, parser);
7145 } else if (tagName.equals("enabled-components")) {
7146 readEnabledComponentsLP(packageSetting, parser);
7147 } else if (tagName.equals("sigs")) {
7148 packageSetting.signatures.readXml(parser, mPastSignatures);
7149 } else if (tagName.equals("perms")) {
7150 readGrantedPermissionsLP(parser,
7151 packageSetting.loadedPermissions);
7152 packageSetting.permissionsFixed = true;
7153 } else {
7154 reportSettingsProblem(Log.WARN,
7155 "Unknown element under <package>: "
7156 + parser.getName());
7157 XmlUtils.skipCurrentTag(parser);
7158 }
7159 }
7160 } else {
7161 XmlUtils.skipCurrentTag(parser);
7162 }
7163 }
7164
7165 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7166 XmlPullParser parser)
7167 throws IOException, XmlPullParserException {
7168 int outerDepth = parser.getDepth();
7169 int type;
7170 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7171 && (type != XmlPullParser.END_TAG
7172 || parser.getDepth() > outerDepth)) {
7173 if (type == XmlPullParser.END_TAG
7174 || type == XmlPullParser.TEXT) {
7175 continue;
7176 }
7177
7178 String tagName = parser.getName();
7179 if (tagName.equals("item")) {
7180 String name = parser.getAttributeValue(null, "name");
7181 if (name != null) {
7182 packageSetting.disabledComponents.add(name.intern());
7183 } else {
7184 reportSettingsProblem(Log.WARN,
7185 "Error in package manager settings: <disabled-components> has"
7186 + " no name at " + parser.getPositionDescription());
7187 }
7188 } else {
7189 reportSettingsProblem(Log.WARN,
7190 "Unknown element under <disabled-components>: "
7191 + parser.getName());
7192 }
7193 XmlUtils.skipCurrentTag(parser);
7194 }
7195 }
7196
7197 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
7198 XmlPullParser parser)
7199 throws IOException, XmlPullParserException {
7200 int outerDepth = parser.getDepth();
7201 int type;
7202 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7203 && (type != XmlPullParser.END_TAG
7204 || parser.getDepth() > outerDepth)) {
7205 if (type == XmlPullParser.END_TAG
7206 || type == XmlPullParser.TEXT) {
7207 continue;
7208 }
7209
7210 String tagName = parser.getName();
7211 if (tagName.equals("item")) {
7212 String name = parser.getAttributeValue(null, "name");
7213 if (name != null) {
7214 packageSetting.enabledComponents.add(name.intern());
7215 } else {
7216 reportSettingsProblem(Log.WARN,
7217 "Error in package manager settings: <enabled-components> has"
7218 + " no name at " + parser.getPositionDescription());
7219 }
7220 } else {
7221 reportSettingsProblem(Log.WARN,
7222 "Unknown element under <enabled-components>: "
7223 + parser.getName());
7224 }
7225 XmlUtils.skipCurrentTag(parser);
7226 }
7227 }
7228
7229 private void readSharedUserLP(XmlPullParser parser)
7230 throws XmlPullParserException, IOException {
7231 String name = null;
7232 String idStr = null;
7233 int pkgFlags = 0;
7234 SharedUserSetting su = null;
7235 try {
7236 name = parser.getAttributeValue(null, "name");
7237 idStr = parser.getAttributeValue(null, "userId");
7238 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7239 if ("true".equals(parser.getAttributeValue(null, "system"))) {
7240 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7241 }
7242 if (name == null) {
7243 reportSettingsProblem(Log.WARN,
7244 "Error in package manager settings: <shared-user> has no name at "
7245 + parser.getPositionDescription());
7246 } else if (userId == 0) {
7247 reportSettingsProblem(Log.WARN,
7248 "Error in package manager settings: shared-user "
7249 + name + " has bad userId " + idStr + " at "
7250 + parser.getPositionDescription());
7251 } else {
7252 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
7253 reportSettingsProblem(Log.ERROR,
7254 "Occurred while parsing settings at "
7255 + parser.getPositionDescription());
7256 }
7257 }
7258 } catch (NumberFormatException e) {
7259 reportSettingsProblem(Log.WARN,
7260 "Error in package manager settings: package "
7261 + name + " has bad userId " + idStr + " at "
7262 + parser.getPositionDescription());
7263 };
7264
7265 if (su != null) {
7266 int outerDepth = parser.getDepth();
7267 int type;
7268 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7269 && (type != XmlPullParser.END_TAG
7270 || parser.getDepth() > outerDepth)) {
7271 if (type == XmlPullParser.END_TAG
7272 || type == XmlPullParser.TEXT) {
7273 continue;
7274 }
7275
7276 String tagName = parser.getName();
7277 if (tagName.equals("sigs")) {
7278 su.signatures.readXml(parser, mPastSignatures);
7279 } else if (tagName.equals("perms")) {
7280 readGrantedPermissionsLP(parser, su.loadedPermissions);
7281 } else {
7282 reportSettingsProblem(Log.WARN,
7283 "Unknown element under <shared-user>: "
7284 + parser.getName());
7285 XmlUtils.skipCurrentTag(parser);
7286 }
7287 }
7288
7289 } else {
7290 XmlUtils.skipCurrentTag(parser);
7291 }
7292 }
7293
7294 private void readGrantedPermissionsLP(XmlPullParser parser,
7295 HashSet<String> outPerms) throws IOException, XmlPullParserException {
7296 int outerDepth = parser.getDepth();
7297 int type;
7298 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7299 && (type != XmlPullParser.END_TAG
7300 || parser.getDepth() > outerDepth)) {
7301 if (type == XmlPullParser.END_TAG
7302 || type == XmlPullParser.TEXT) {
7303 continue;
7304 }
7305
7306 String tagName = parser.getName();
7307 if (tagName.equals("item")) {
7308 String name = parser.getAttributeValue(null, "name");
7309 if (name != null) {
7310 outPerms.add(name.intern());
7311 } else {
7312 reportSettingsProblem(Log.WARN,
7313 "Error in package manager settings: <perms> has"
7314 + " no name at " + parser.getPositionDescription());
7315 }
7316 } else {
7317 reportSettingsProblem(Log.WARN,
7318 "Unknown element under <perms>: "
7319 + parser.getName());
7320 }
7321 XmlUtils.skipCurrentTag(parser);
7322 }
7323 }
7324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007325 private void readPreferredActivitiesLP(XmlPullParser parser)
7326 throws XmlPullParserException, IOException {
7327 int outerDepth = parser.getDepth();
7328 int type;
7329 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7330 && (type != XmlPullParser.END_TAG
7331 || parser.getDepth() > outerDepth)) {
7332 if (type == XmlPullParser.END_TAG
7333 || type == XmlPullParser.TEXT) {
7334 continue;
7335 }
7336
7337 String tagName = parser.getName();
7338 if (tagName.equals("item")) {
7339 PreferredActivity pa = new PreferredActivity(parser);
7340 if (pa.mParseError == null) {
7341 mPreferredActivities.addFilter(pa);
7342 } else {
7343 reportSettingsProblem(Log.WARN,
7344 "Error in package manager settings: <preferred-activity> "
7345 + pa.mParseError + " at "
7346 + parser.getPositionDescription());
7347 }
7348 } else {
7349 reportSettingsProblem(Log.WARN,
7350 "Unknown element under <preferred-activities>: "
7351 + parser.getName());
7352 XmlUtils.skipCurrentTag(parser);
7353 }
7354 }
7355 }
7356
7357 // Returns -1 if we could not find an available UserId to assign
7358 private int newUserIdLP(Object obj) {
7359 // Let's be stupidly inefficient for now...
7360 final int N = mUserIds.size();
7361 for (int i=0; i<N; i++) {
7362 if (mUserIds.get(i) == null) {
7363 mUserIds.set(i, obj);
7364 return FIRST_APPLICATION_UID + i;
7365 }
7366 }
7367
7368 // None left?
7369 if (N >= MAX_APPLICATION_UIDS) {
7370 return -1;
7371 }
7372
7373 mUserIds.add(obj);
7374 return FIRST_APPLICATION_UID + N;
7375 }
7376
7377 public PackageSetting getDisabledSystemPkg(String name) {
7378 synchronized(mPackages) {
7379 PackageSetting ps = mDisabledSysPackages.get(name);
7380 return ps;
7381 }
7382 }
7383
7384 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7385 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7386 if (Config.LOGV) {
7387 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7388 + " componentName = " + componentInfo.name);
7389 Log.v(TAG, "enabledComponents: "
7390 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7391 Log.v(TAG, "disabledComponents: "
7392 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7393 }
7394 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7395 || ((componentInfo.enabled
7396 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7397 || (componentInfo.applicationInfo.enabled
7398 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7399 && !packageSettings.disabledComponents.contains(componentInfo.name))
7400 || packageSettings.enabledComponents.contains(componentInfo.name));
7401 }
7402 }
7403}