blob: e9387dadbf7ae813ad25f70a7d69100e0d4a9d50 [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;
Tom Taylord4a47292009-12-21 13:59:18 -080020import com.android.common.FastXmlSerializer;
21import com.android.common.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022
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
Oscar Montemayora8529f62009-11-18 10:14:20 -0800125 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private static final int REMOVE_EVENTS =
128 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
129 private static final int ADD_EVENTS =
130 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
131
132 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
133
134 static final int SCAN_MONITOR = 1<<0;
135 static final int SCAN_NO_DEX = 1<<1;
136 static final int SCAN_FORCE_DEX = 1<<2;
137 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800138 static final int SCAN_NEW_INSTALL = 1<<4;
139 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
141 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
142 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700143 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
Dianne Hackborn851a5412009-05-08 12:06:44 -0700145 final int mSdkVersion = Build.VERSION.SDK_INT;
146 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
147 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 final Context mContext;
150 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700151 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 final DisplayMetrics mMetrics;
153 final int mDefParseFlags;
154 final String[] mSeparateProcesses;
155
156 // This is where all application persistent data goes.
157 final File mAppDataDir;
158
Oscar Montemayora8529f62009-11-18 10:14:20 -0800159 // If Encrypted File System feature is enabled, all application persistent data
160 // should go here instead.
161 final File mSecureAppDataDir;
162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 // 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;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 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;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 // 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();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 // 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 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 // 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>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 // 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>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800230
Dianne Hackborn49237342009-08-27 20:08:01 -0700231 // Temporary for building the final shared libraries for an .apk.
232 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800233
Dianne Hackborn49237342009-08-27 20:08:01 -0700234 // 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>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800238
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>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800269
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;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800284 static final int DESTROY_SD_CONTAINER = 2;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700285 // Delay time in millisecs
286 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800287 static final int DESTROY_SD_CONTAINER_DELAY = 30 * 1000;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700288
289 class PackageHandler extends Handler {
290 PackageHandler(Looper looper) {
291 super(looper);
292 }
293 public void handleMessage(Message msg) {
294 switch (msg.what) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800295 case DESTROY_SD_CONTAINER:
296 String pkgName = (String) msg.obj;
297 if (pkgName != null) {
298 // Too bad we cannot handle the errors from destroying the containers.
299 if (!destroySdDir(pkgName)) {
300 Log.e(TAG, "Failed to destroy container for pkg : " + pkgName);
301 }
302 }
303 break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700304 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800305 String packages[];
306 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700307 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700308 int uids[];
309 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800310 if (mPendingBroadcasts == null) {
311 return;
312 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700313 size = mPendingBroadcasts.size();
314 if (size <= 0) {
315 // Nothing to be done. Just return
316 return;
317 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800318 packages = new String[size];
319 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700320 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800321 Iterator<HashMap.Entry<String, ArrayList<String>>>
322 it = mPendingBroadcasts.entrySet().iterator();
323 int i = 0;
324 while (it.hasNext() && i < size) {
325 HashMap.Entry<String, ArrayList<String>> ent = it.next();
326 packages[i] = ent.getKey();
327 components[i] = ent.getValue();
328 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700329 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800330 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700331 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800332 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700333 mPendingBroadcasts.clear();
334 }
335 // Send broadcasts
336 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800337 sendPackageChangedBroadcast(packages[i], true,
338 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700339 }
340 break;
341 }
342 }
343 }
344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 public static final IPackageManager main(Context context, boolean factoryTest) {
346 PackageManagerService m = new PackageManagerService(context, factoryTest);
347 ServiceManager.addService("package", m);
348 return m;
349 }
350
351 static String[] splitString(String str, char sep) {
352 int count = 1;
353 int i = 0;
354 while ((i=str.indexOf(sep, i)) >= 0) {
355 count++;
356 i++;
357 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 String[] res = new String[count];
360 i=0;
361 count = 0;
362 int lastI=0;
363 while ((i=str.indexOf(sep, i)) >= 0) {
364 res[count] = str.substring(lastI, i);
365 count++;
366 i++;
367 lastI = i;
368 }
369 res[count] = str.substring(lastI, str.length());
370 return res;
371 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800374 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 if (mSdkVersion <= 0) {
378 Log.w(TAG, "**** ro.build.version.sdk not set!");
379 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 mContext = context;
382 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700383 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 mMetrics = new DisplayMetrics();
385 mSettings = new Settings();
386 mSettings.addSharedUserLP("android.uid.system",
387 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
388 mSettings.addSharedUserLP("android.uid.phone",
389 MULTIPLE_APPLICATION_UIDS
390 ? RADIO_UID : FIRST_APPLICATION_UID,
391 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400392 mSettings.addSharedUserLP("android.uid.log",
393 MULTIPLE_APPLICATION_UIDS
394 ? LOG_UID : FIRST_APPLICATION_UID,
395 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396
397 String separateProcesses = SystemProperties.get("debug.separate_processes");
398 if (separateProcesses != null && separateProcesses.length() > 0) {
399 if ("*".equals(separateProcesses)) {
400 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
401 mSeparateProcesses = null;
402 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
403 } else {
404 mDefParseFlags = 0;
405 mSeparateProcesses = separateProcesses.split(",");
406 Log.w(TAG, "Running with debug.separate_processes: "
407 + separateProcesses);
408 }
409 } else {
410 mDefParseFlags = 0;
411 mSeparateProcesses = null;
412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 Installer installer = new Installer();
415 // Little hacky thing to check if installd is here, to determine
416 // whether we are running on the simulator and thus need to take
417 // care of building the /data file structure ourself.
418 // (apparently the sim now has a working installer)
419 if (installer.ping() && Process.supportsProcesses()) {
420 mInstaller = installer;
421 } else {
422 mInstaller = null;
423 }
424
425 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
426 Display d = wm.getDefaultDisplay();
427 d.getMetrics(mMetrics);
428
429 synchronized (mInstallLock) {
430 synchronized (mPackages) {
431 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700432 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 File dataDir = Environment.getDataDirectory();
435 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800436 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
438
439 if (mInstaller == null) {
440 // Make sure these dirs exist, when we are running in
441 // the simulator.
442 // Make a wide-open directory for random misc stuff.
443 File miscDir = new File(dataDir, "misc");
444 miscDir.mkdirs();
445 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800446 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 mDrmAppPrivateInstallDir.mkdirs();
448 }
449
450 readPermissions();
451
452 mRestoredSettings = mSettings.readLP();
453 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800454
455 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800457
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800458 // Set flag to monitor and not change apk file paths when
459 // scanning install directories.
460 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700461 if (mNoDexOpt) {
462 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800463 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700464 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700469 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700472 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 /**
475 * Out of paranoia, ensure that everything in the boot class
476 * path has been dexed.
477 */
478 String bootClassPath = System.getProperty("java.boot.class.path");
479 if (bootClassPath != null) {
480 String[] paths = splitString(bootClassPath, ':');
481 for (int i=0; i<paths.length; i++) {
482 try {
483 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
484 libFiles.add(paths[i]);
485 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700486 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 }
488 } catch (FileNotFoundException e) {
489 Log.w(TAG, "Boot class path not found: " + paths[i]);
490 } catch (IOException e) {
491 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
492 }
493 }
494 } else {
495 Log.w(TAG, "No BOOTCLASSPATH found!");
496 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 /**
499 * Also ensure all external libraries have had dexopt run on them.
500 */
501 if (mSharedLibraries.size() > 0) {
502 Iterator<String> libs = mSharedLibraries.values().iterator();
503 while (libs.hasNext()) {
504 String lib = libs.next();
505 try {
506 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
507 libFiles.add(lib);
508 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700509 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 }
511 } catch (FileNotFoundException e) {
512 Log.w(TAG, "Library not found: " + lib);
513 } catch (IOException e) {
514 Log.w(TAG, "Exception reading library: " + lib, e);
515 }
516 }
517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 // Gross hack for now: we know this file doesn't contain any
520 // code, so don't dexopt it to avoid the resulting log spew.
521 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 /**
524 * And there are a number of commands implemented in Java, which
525 * we currently need to do the dexopt on so that they can be
526 * run from a non-root shell.
527 */
528 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700529 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 for (int i=0; i<frameworkFiles.length; i++) {
531 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
532 String path = libPath.getPath();
533 // Skip the file if we alrady did it.
534 if (libFiles.contains(path)) {
535 continue;
536 }
537 // Skip the file if it is not a type we want to dexopt.
538 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
539 continue;
540 }
541 try {
542 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
543 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700544 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
546 } catch (FileNotFoundException e) {
547 Log.w(TAG, "Jar not found: " + path);
548 } catch (IOException e) {
549 Log.w(TAG, "Exception reading jar: " + path, e);
550 }
551 }
552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800553
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700554 if (didDexOpt) {
555 // If we had to do a dexopt of one of the previous
556 // things, then something on the system has changed.
557 // Consider this significant, and wipe away all other
558 // existing dexopt files to ensure we don't leave any
559 // dangling around.
560 String[] files = mDalvikCacheDir.list();
561 if (files != null) {
562 for (int i=0; i<files.length; i++) {
563 String fn = files[i];
564 if (fn.startsWith("data@app@")
565 || fn.startsWith("data@app-private@")) {
566 Log.i(TAG, "Pruning dalvik file: " + fn);
567 (new File(mDalvikCacheDir, fn)).delete();
568 }
569 }
570 }
571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 mFrameworkInstallObserver = new AppDirObserver(
575 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
576 mFrameworkInstallObserver.startWatching();
577 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800578 scanMode | SCAN_NO_DEX);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
580 mSystemInstallObserver = new AppDirObserver(
581 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
582 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800583 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 mAppInstallDir = new File(dataDir, "app");
585 if (mInstaller == null) {
586 // Make sure these dirs exist, when we are running in
587 // the simulator.
588 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
589 }
590 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800591 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 //clean up list
593 for(int i = 0; i < deletePkgsList.size(); i++) {
594 //clean up here
595 cleanupInstallFailedPackage(deletePkgsList.get(i));
596 }
597 //delete tmp files
598 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800599
600 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 SystemClock.uptimeMillis());
602 mAppInstallObserver = new AppDirObserver(
603 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
604 mAppInstallObserver.startWatching();
605 scanDirLI(mAppInstallDir, 0, scanMode);
606
607 mDrmAppInstallObserver = new AppDirObserver(
608 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
609 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800610 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800612 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 SystemClock.uptimeMillis());
614 Log.i(TAG, "Time to scan packages: "
615 + ((SystemClock.uptimeMillis()-startTime)/1000f)
616 + " seconds");
617
618 updatePermissionsLP();
619
620 mSettings.writeLP();
621
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800622 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 // Now after opening every single application zip, make sure they
626 // are all flushed. Not really needed, but keeps things nice and
627 // tidy.
628 Runtime.getRuntime().gc();
629 } // synchronized (mPackages)
630 } // synchronized (mInstallLock)
631 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 @Override
634 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
635 throws RemoteException {
636 try {
637 return super.onTransact(code, data, reply, flags);
638 } catch (RuntimeException e) {
639 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
640 Log.e(TAG, "Package Manager Crash", e);
641 }
642 throw e;
643 }
644 }
645
Oscar Montemayora8529f62009-11-18 10:14:20 -0800646 void cleanupInstallFailedPackage(PackageSetting pkgSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -0800648 boolean useSecureFS = useEncryptedFilesystemForPackage(pkgSettings.pkg);
649 int retCode = mInstaller.remove(pkgSettings.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 if (retCode < 0) {
651 Log.w(TAG, "Couldn't remove app data directory for package: "
Oscar Montemayora8529f62009-11-18 10:14:20 -0800652 + pkgSettings.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 }
654 } else {
655 //for emulator
Oscar Montemayora8529f62009-11-18 10:14:20 -0800656 File dataDir = new File(pkgSettings.pkg.applicationInfo.dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 dataDir.delete();
658 }
Oscar Montemayora8529f62009-11-18 10:14:20 -0800659 mSettings.removePackageLP(pkgSettings.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 }
661
662 void readPermissions() {
663 // Read permissions from .../etc/permission directory.
664 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
665 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
666 Log.w(TAG, "No directory " + libraryDir + ", skipping");
667 return;
668 }
669 if (!libraryDir.canRead()) {
670 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
671 return;
672 }
673
674 // Iterate over the files in the directory and scan .xml files
675 for (File f : libraryDir.listFiles()) {
676 // We'll read platform.xml last
677 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
678 continue;
679 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 if (!f.getPath().endsWith(".xml")) {
682 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
683 continue;
684 }
685 if (!f.canRead()) {
686 Log.w(TAG, "Permissions library file " + f + " cannot be read");
687 continue;
688 }
689
690 readPermissionsFromXml(f);
691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
694 final File permFile = new File(Environment.getRootDirectory(),
695 "etc/permissions/platform.xml");
696 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800697
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700698 StringBuilder sb = new StringBuilder(128);
699 sb.append("Libs:");
700 Iterator<String> it = mSharedLibraries.keySet().iterator();
701 while (it.hasNext()) {
702 sb.append(' ');
703 String name = it.next();
704 sb.append(name);
705 sb.append(':');
706 sb.append(mSharedLibraries.get(name));
707 }
708 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800709
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700710 sb.setLength(0);
711 sb.append("Features:");
712 it = mAvailableFeatures.keySet().iterator();
713 while (it.hasNext()) {
714 sb.append(' ');
715 sb.append(it.next());
716 }
717 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800719
720 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 FileReader permReader = null;
722 try {
723 permReader = new FileReader(permFile);
724 } catch (FileNotFoundException e) {
725 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
726 return;
727 }
728
729 try {
730 XmlPullParser parser = Xml.newPullParser();
731 parser.setInput(permReader);
732
733 XmlUtils.beginDocument(parser, "permissions");
734
735 while (true) {
736 XmlUtils.nextElement(parser);
737 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
738 break;
739 }
740
741 String name = parser.getName();
742 if ("group".equals(name)) {
743 String gidStr = parser.getAttributeValue(null, "gid");
744 if (gidStr != null) {
745 int gid = Integer.parseInt(gidStr);
746 mGlobalGids = appendInt(mGlobalGids, gid);
747 } else {
748 Log.w(TAG, "<group> without gid at "
749 + parser.getPositionDescription());
750 }
751
752 XmlUtils.skipCurrentTag(parser);
753 continue;
754 } else if ("permission".equals(name)) {
755 String perm = parser.getAttributeValue(null, "name");
756 if (perm == null) {
757 Log.w(TAG, "<permission> without name at "
758 + parser.getPositionDescription());
759 XmlUtils.skipCurrentTag(parser);
760 continue;
761 }
762 perm = perm.intern();
763 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 } else if ("assign-permission".equals(name)) {
766 String perm = parser.getAttributeValue(null, "name");
767 if (perm == null) {
768 Log.w(TAG, "<assign-permission> without name at "
769 + parser.getPositionDescription());
770 XmlUtils.skipCurrentTag(parser);
771 continue;
772 }
773 String uidStr = parser.getAttributeValue(null, "uid");
774 if (uidStr == null) {
775 Log.w(TAG, "<assign-permission> without uid at "
776 + parser.getPositionDescription());
777 XmlUtils.skipCurrentTag(parser);
778 continue;
779 }
780 int uid = Process.getUidForName(uidStr);
781 if (uid < 0) {
782 Log.w(TAG, "<assign-permission> with unknown uid \""
783 + uidStr + "\" at "
784 + parser.getPositionDescription());
785 XmlUtils.skipCurrentTag(parser);
786 continue;
787 }
788 perm = perm.intern();
789 HashSet<String> perms = mSystemPermissions.get(uid);
790 if (perms == null) {
791 perms = new HashSet<String>();
792 mSystemPermissions.put(uid, perms);
793 }
794 perms.add(perm);
795 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 } else if ("library".equals(name)) {
798 String lname = parser.getAttributeValue(null, "name");
799 String lfile = parser.getAttributeValue(null, "file");
800 if (lname == null) {
801 Log.w(TAG, "<library> without name at "
802 + parser.getPositionDescription());
803 } else if (lfile == null) {
804 Log.w(TAG, "<library> without file at "
805 + parser.getPositionDescription());
806 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700807 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700808 mSharedLibraries.put(lname, lfile);
809 }
810 XmlUtils.skipCurrentTag(parser);
811 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800812
Dianne Hackborn49237342009-08-27 20:08:01 -0700813 } else if ("feature".equals(name)) {
814 String fname = parser.getAttributeValue(null, "name");
815 if (fname == null) {
816 Log.w(TAG, "<feature> without name at "
817 + parser.getPositionDescription());
818 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700819 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700820 FeatureInfo fi = new FeatureInfo();
821 fi.name = fname;
822 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 }
824 XmlUtils.skipCurrentTag(parser);
825 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 } else {
828 XmlUtils.skipCurrentTag(parser);
829 continue;
830 }
831
832 }
833 } catch (XmlPullParserException e) {
834 Log.w(TAG, "Got execption parsing permissions.", e);
835 } catch (IOException e) {
836 Log.w(TAG, "Got execption parsing permissions.", e);
837 }
838 }
839
840 void readPermission(XmlPullParser parser, String name)
841 throws IOException, XmlPullParserException {
842
843 name = name.intern();
844
845 BasePermission bp = mSettings.mPermissions.get(name);
846 if (bp == null) {
847 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
848 mSettings.mPermissions.put(name, bp);
849 }
850 int outerDepth = parser.getDepth();
851 int type;
852 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
853 && (type != XmlPullParser.END_TAG
854 || parser.getDepth() > outerDepth)) {
855 if (type == XmlPullParser.END_TAG
856 || type == XmlPullParser.TEXT) {
857 continue;
858 }
859
860 String tagName = parser.getName();
861 if ("group".equals(tagName)) {
862 String gidStr = parser.getAttributeValue(null, "gid");
863 if (gidStr != null) {
864 int gid = Process.getGidForName(gidStr);
865 bp.gids = appendInt(bp.gids, gid);
866 } else {
867 Log.w(TAG, "<group> without gid at "
868 + parser.getPositionDescription());
869 }
870 }
871 XmlUtils.skipCurrentTag(parser);
872 }
873 }
874
875 static int[] appendInt(int[] cur, int val) {
876 if (cur == null) {
877 return new int[] { val };
878 }
879 final int N = cur.length;
880 for (int i=0; i<N; i++) {
881 if (cur[i] == val) {
882 return cur;
883 }
884 }
885 int[] ret = new int[N+1];
886 System.arraycopy(cur, 0, ret, 0, N);
887 ret[N] = val;
888 return ret;
889 }
890
891 static int[] appendInts(int[] cur, int[] add) {
892 if (add == null) return cur;
893 if (cur == null) return add;
894 final int N = add.length;
895 for (int i=0; i<N; i++) {
896 cur = appendInt(cur, add[i]);
897 }
898 return cur;
899 }
900
901 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -0700902 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
903 // The package has been uninstalled but has retained data and resources.
904 return PackageParser.generatePackageInfo(p, null, flags);
905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 final PackageSetting ps = (PackageSetting)p.mExtras;
907 if (ps == null) {
908 return null;
909 }
910 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
911 return PackageParser.generatePackageInfo(p, gp.gids, flags);
912 }
913
914 public PackageInfo getPackageInfo(String packageName, int flags) {
915 synchronized (mPackages) {
916 PackageParser.Package p = mPackages.get(packageName);
917 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700918 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 + ": " + p);
920 if (p != null) {
921 return generatePackageInfo(p, flags);
922 }
923 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
924 return generatePackageInfoFromSettingsLP(packageName, flags);
925 }
926 }
927 return null;
928 }
929
930 public int getPackageUid(String packageName) {
931 synchronized (mPackages) {
932 PackageParser.Package p = mPackages.get(packageName);
933 if(p != null) {
934 return p.applicationInfo.uid;
935 }
936 PackageSetting ps = mSettings.mPackages.get(packageName);
937 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
938 return -1;
939 }
940 p = ps.pkg;
941 return p != null ? p.applicationInfo.uid : -1;
942 }
943 }
944
945 public int[] getPackageGids(String packageName) {
946 synchronized (mPackages) {
947 PackageParser.Package p = mPackages.get(packageName);
948 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700949 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 + ": " + p);
951 if (p != null) {
952 final PackageSetting ps = (PackageSetting)p.mExtras;
953 final SharedUserSetting suid = ps.sharedUser;
954 return suid != null ? suid.gids : ps.gids;
955 }
956 }
957 // stupid thing to indicate an error.
958 return new int[0];
959 }
960
961 public PermissionInfo getPermissionInfo(String name, int flags) {
962 synchronized (mPackages) {
963 final BasePermission p = mSettings.mPermissions.get(name);
964 if (p != null && p.perm != null) {
965 return PackageParser.generatePermissionInfo(p.perm, flags);
966 }
967 return null;
968 }
969 }
970
971 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
972 synchronized (mPackages) {
973 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
974 for (BasePermission p : mSettings.mPermissions.values()) {
975 if (group == null) {
976 if (p.perm.info.group == null) {
977 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
978 }
979 } else {
980 if (group.equals(p.perm.info.group)) {
981 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
982 }
983 }
984 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 if (out.size() > 0) {
987 return out;
988 }
989 return mPermissionGroups.containsKey(group) ? out : null;
990 }
991 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
994 synchronized (mPackages) {
995 return PackageParser.generatePermissionGroupInfo(
996 mPermissionGroups.get(name), flags);
997 }
998 }
999
1000 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1001 synchronized (mPackages) {
1002 final int N = mPermissionGroups.size();
1003 ArrayList<PermissionGroupInfo> out
1004 = new ArrayList<PermissionGroupInfo>(N);
1005 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1006 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1007 }
1008 return out;
1009 }
1010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1013 PackageSetting ps = mSettings.mPackages.get(packageName);
1014 if(ps != null) {
1015 if(ps.pkg == null) {
1016 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1017 if(pInfo != null) {
1018 return pInfo.applicationInfo;
1019 }
1020 return null;
1021 }
1022 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1023 }
1024 return null;
1025 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1028 PackageSetting ps = mSettings.mPackages.get(packageName);
1029 if(ps != null) {
1030 if(ps.pkg == null) {
1031 ps.pkg = new PackageParser.Package(packageName);
1032 ps.pkg.applicationInfo.packageName = packageName;
1033 }
1034 return generatePackageInfo(ps.pkg, flags);
1035 }
1036 return null;
1037 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1040 synchronized (mPackages) {
1041 PackageParser.Package p = mPackages.get(packageName);
1042 if (Config.LOGV) Log.v(
1043 TAG, "getApplicationInfo " + packageName
1044 + ": " + p);
1045 if (p != null) {
1046 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001047 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 }
1049 if ("android".equals(packageName)||"system".equals(packageName)) {
1050 return mAndroidApplication;
1051 }
1052 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1053 return generateApplicationInfoFromSettingsLP(packageName, flags);
1054 }
1055 }
1056 return null;
1057 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001058
1059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1061 mContext.enforceCallingOrSelfPermission(
1062 android.Manifest.permission.CLEAR_APP_CACHE, null);
1063 // Queue up an async operation since clearing cache may take a little while.
1064 mHandler.post(new Runnable() {
1065 public void run() {
1066 mHandler.removeCallbacks(this);
1067 int retCode = -1;
1068 if (mInstaller != null) {
1069 retCode = mInstaller.freeCache(freeStorageSize);
1070 if (retCode < 0) {
1071 Log.w(TAG, "Couldn't clear application caches");
1072 }
1073 } //end if mInstaller
1074 if (observer != null) {
1075 try {
1076 observer.onRemoveCompleted(null, (retCode >= 0));
1077 } catch (RemoteException e) {
1078 Log.w(TAG, "RemoveException when invoking call back");
1079 }
1080 }
1081 }
1082 });
1083 }
1084
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001085 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001086 mContext.enforceCallingOrSelfPermission(
1087 android.Manifest.permission.CLEAR_APP_CACHE, null);
1088 // Queue up an async operation since clearing cache may take a little while.
1089 mHandler.post(new Runnable() {
1090 public void run() {
1091 mHandler.removeCallbacks(this);
1092 int retCode = -1;
1093 if (mInstaller != null) {
1094 retCode = mInstaller.freeCache(freeStorageSize);
1095 if (retCode < 0) {
1096 Log.w(TAG, "Couldn't clear application caches");
1097 }
1098 }
1099 if(pi != null) {
1100 try {
1101 // Callback via pending intent
1102 int code = (retCode >= 0) ? 1 : 0;
1103 pi.sendIntent(null, code, null,
1104 null, null);
1105 } catch (SendIntentException e1) {
1106 Log.i(TAG, "Failed to send pending intent");
1107 }
1108 }
1109 }
1110 });
1111 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1114 synchronized (mPackages) {
1115 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001116
1117 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001119 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 }
1121 if (mResolveComponentName.equals(component)) {
1122 return mResolveActivity;
1123 }
1124 }
1125 return null;
1126 }
1127
1128 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1129 synchronized (mPackages) {
1130 PackageParser.Activity a = mReceivers.mActivities.get(component);
1131 if (Config.LOGV) Log.v(
1132 TAG, "getReceiverInfo " + component + ": " + a);
1133 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1134 return PackageParser.generateActivityInfo(a, flags);
1135 }
1136 }
1137 return null;
1138 }
1139
1140 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1141 synchronized (mPackages) {
1142 PackageParser.Service s = mServices.mServices.get(component);
1143 if (Config.LOGV) Log.v(
1144 TAG, "getServiceInfo " + component + ": " + s);
1145 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1146 return PackageParser.generateServiceInfo(s, flags);
1147 }
1148 }
1149 return null;
1150 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 public String[] getSystemSharedLibraryNames() {
1153 Set<String> libSet;
1154 synchronized (mPackages) {
1155 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001156 int size = libSet.size();
1157 if (size > 0) {
1158 String[] libs = new String[size];
1159 libSet.toArray(libs);
1160 return libs;
1161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001163 return null;
1164 }
1165
1166 public FeatureInfo[] getSystemAvailableFeatures() {
1167 Collection<FeatureInfo> featSet;
1168 synchronized (mPackages) {
1169 featSet = mAvailableFeatures.values();
1170 int size = featSet.size();
1171 if (size > 0) {
1172 FeatureInfo[] features = new FeatureInfo[size+1];
1173 featSet.toArray(features);
1174 FeatureInfo fi = new FeatureInfo();
1175 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1176 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1177 features[size] = fi;
1178 return features;
1179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 }
1181 return null;
1182 }
1183
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001184 public boolean hasSystemFeature(String name) {
1185 synchronized (mPackages) {
1186 return mAvailableFeatures.containsKey(name);
1187 }
1188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 public int checkPermission(String permName, String pkgName) {
1191 synchronized (mPackages) {
1192 PackageParser.Package p = mPackages.get(pkgName);
1193 if (p != null && p.mExtras != null) {
1194 PackageSetting ps = (PackageSetting)p.mExtras;
1195 if (ps.sharedUser != null) {
1196 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1197 return PackageManager.PERMISSION_GRANTED;
1198 }
1199 } else if (ps.grantedPermissions.contains(permName)) {
1200 return PackageManager.PERMISSION_GRANTED;
1201 }
1202 }
1203 }
1204 return PackageManager.PERMISSION_DENIED;
1205 }
1206
1207 public int checkUidPermission(String permName, int uid) {
1208 synchronized (mPackages) {
1209 Object obj = mSettings.getUserIdLP(uid);
1210 if (obj != null) {
1211 if (obj instanceof SharedUserSetting) {
1212 SharedUserSetting sus = (SharedUserSetting)obj;
1213 if (sus.grantedPermissions.contains(permName)) {
1214 return PackageManager.PERMISSION_GRANTED;
1215 }
1216 } else if (obj instanceof PackageSetting) {
1217 PackageSetting ps = (PackageSetting)obj;
1218 if (ps.grantedPermissions.contains(permName)) {
1219 return PackageManager.PERMISSION_GRANTED;
1220 }
1221 }
1222 } else {
1223 HashSet<String> perms = mSystemPermissions.get(uid);
1224 if (perms != null && perms.contains(permName)) {
1225 return PackageManager.PERMISSION_GRANTED;
1226 }
1227 }
1228 }
1229 return PackageManager.PERMISSION_DENIED;
1230 }
1231
1232 private BasePermission findPermissionTreeLP(String permName) {
1233 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1234 if (permName.startsWith(bp.name) &&
1235 permName.length() > bp.name.length() &&
1236 permName.charAt(bp.name.length()) == '.') {
1237 return bp;
1238 }
1239 }
1240 return null;
1241 }
1242
1243 private BasePermission checkPermissionTreeLP(String permName) {
1244 if (permName != null) {
1245 BasePermission bp = findPermissionTreeLP(permName);
1246 if (bp != null) {
1247 if (bp.uid == Binder.getCallingUid()) {
1248 return bp;
1249 }
1250 throw new SecurityException("Calling uid "
1251 + Binder.getCallingUid()
1252 + " is not allowed to add to permission tree "
1253 + bp.name + " owned by uid " + bp.uid);
1254 }
1255 }
1256 throw new SecurityException("No permission tree found for " + permName);
1257 }
1258
1259 public boolean addPermission(PermissionInfo info) {
1260 synchronized (mPackages) {
1261 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1262 throw new SecurityException("Label must be specified in permission");
1263 }
1264 BasePermission tree = checkPermissionTreeLP(info.name);
1265 BasePermission bp = mSettings.mPermissions.get(info.name);
1266 boolean added = bp == null;
1267 if (added) {
1268 bp = new BasePermission(info.name, tree.sourcePackage,
1269 BasePermission.TYPE_DYNAMIC);
1270 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1271 throw new SecurityException(
1272 "Not allowed to modify non-dynamic permission "
1273 + info.name);
1274 }
1275 bp.perm = new PackageParser.Permission(tree.perm.owner,
1276 new PermissionInfo(info));
1277 bp.perm.info.packageName = tree.perm.info.packageName;
1278 bp.uid = tree.uid;
1279 if (added) {
1280 mSettings.mPermissions.put(info.name, bp);
1281 }
1282 mSettings.writeLP();
1283 return added;
1284 }
1285 }
1286
1287 public void removePermission(String name) {
1288 synchronized (mPackages) {
1289 checkPermissionTreeLP(name);
1290 BasePermission bp = mSettings.mPermissions.get(name);
1291 if (bp != null) {
1292 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1293 throw new SecurityException(
1294 "Not allowed to modify non-dynamic permission "
1295 + name);
1296 }
1297 mSettings.mPermissions.remove(name);
1298 mSettings.writeLP();
1299 }
1300 }
1301 }
1302
Dianne Hackborn854060af2009-07-09 18:14:31 -07001303 public boolean isProtectedBroadcast(String actionName) {
1304 synchronized (mPackages) {
1305 return mProtectedBroadcasts.contains(actionName);
1306 }
1307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 public int checkSignatures(String pkg1, String pkg2) {
1310 synchronized (mPackages) {
1311 PackageParser.Package p1 = mPackages.get(pkg1);
1312 PackageParser.Package p2 = mPackages.get(pkg2);
1313 if (p1 == null || p1.mExtras == null
1314 || p2 == null || p2.mExtras == null) {
1315 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1316 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001317 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
1319 }
1320
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001321 public int checkUidSignatures(int uid1, int uid2) {
1322 synchronized (mPackages) {
1323 Signature[] s1;
1324 Signature[] s2;
1325 Object obj = mSettings.getUserIdLP(uid1);
1326 if (obj != null) {
1327 if (obj instanceof SharedUserSetting) {
1328 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1329 } else if (obj instanceof PackageSetting) {
1330 s1 = ((PackageSetting)obj).signatures.mSignatures;
1331 } else {
1332 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1333 }
1334 } else {
1335 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1336 }
1337 obj = mSettings.getUserIdLP(uid2);
1338 if (obj != null) {
1339 if (obj instanceof SharedUserSetting) {
1340 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1341 } else if (obj instanceof PackageSetting) {
1342 s2 = ((PackageSetting)obj).signatures.mSignatures;
1343 } else {
1344 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1345 }
1346 } else {
1347 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1348 }
1349 return checkSignaturesLP(s1, s2);
1350 }
1351 }
1352
1353 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1354 if (s1 == null) {
1355 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1357 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1358 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001359 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1361 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001362 final int N1 = s1.length;
1363 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 for (int i=0; i<N1; i++) {
1365 boolean match = false;
1366 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001367 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 match = true;
1369 break;
1370 }
1371 }
1372 if (!match) {
1373 return PackageManager.SIGNATURE_NO_MATCH;
1374 }
1375 }
1376 return PackageManager.SIGNATURE_MATCH;
1377 }
1378
1379 public String[] getPackagesForUid(int uid) {
1380 synchronized (mPackages) {
1381 Object obj = mSettings.getUserIdLP(uid);
1382 if (obj instanceof SharedUserSetting) {
1383 SharedUserSetting sus = (SharedUserSetting)obj;
1384 final int N = sus.packages.size();
1385 String[] res = new String[N];
1386 Iterator<PackageSetting> it = sus.packages.iterator();
1387 int i=0;
1388 while (it.hasNext()) {
1389 res[i++] = it.next().name;
1390 }
1391 return res;
1392 } else if (obj instanceof PackageSetting) {
1393 PackageSetting ps = (PackageSetting)obj;
1394 return new String[] { ps.name };
1395 }
1396 }
1397 return null;
1398 }
1399
1400 public String getNameForUid(int uid) {
1401 synchronized (mPackages) {
1402 Object obj = mSettings.getUserIdLP(uid);
1403 if (obj instanceof SharedUserSetting) {
1404 SharedUserSetting sus = (SharedUserSetting)obj;
1405 return sus.name + ":" + sus.userId;
1406 } else if (obj instanceof PackageSetting) {
1407 PackageSetting ps = (PackageSetting)obj;
1408 return ps.name;
1409 }
1410 }
1411 return null;
1412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 public int getUidForSharedUser(String sharedUserName) {
1415 if(sharedUserName == null) {
1416 return -1;
1417 }
1418 synchronized (mPackages) {
1419 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1420 if(suid == null) {
1421 return -1;
1422 }
1423 return suid.userId;
1424 }
1425 }
1426
1427 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1428 int flags) {
1429 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001430 return chooseBestActivity(intent, resolvedType, flags, query);
1431 }
1432
Mihai Predaeae850c2009-05-13 10:13:48 +02001433 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1434 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 if (query != null) {
1436 final int N = query.size();
1437 if (N == 1) {
1438 return query.get(0);
1439 } else if (N > 1) {
1440 // If there is more than one activity with the same priority,
1441 // then let the user decide between them.
1442 ResolveInfo r0 = query.get(0);
1443 ResolveInfo r1 = query.get(1);
1444 if (false) {
1445 System.out.println(r0.activityInfo.name +
1446 "=" + r0.priority + " vs " +
1447 r1.activityInfo.name +
1448 "=" + r1.priority);
1449 }
1450 // If the first activity has a higher priority, or a different
1451 // default, then it is always desireable to pick it.
1452 if (r0.priority != r1.priority
1453 || r0.preferredOrder != r1.preferredOrder
1454 || r0.isDefault != r1.isDefault) {
1455 return query.get(0);
1456 }
1457 // If we have saved a preference for a preferred activity for
1458 // this Intent, use that.
1459 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1460 flags, query, r0.priority);
1461 if (ri != null) {
1462 return ri;
1463 }
1464 return mResolveInfo;
1465 }
1466 }
1467 return null;
1468 }
1469
1470 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1471 int flags, List<ResolveInfo> query, int priority) {
1472 synchronized (mPackages) {
1473 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1474 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001475 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1477 if (prefs != null && prefs.size() > 0) {
1478 // First figure out how good the original match set is.
1479 // We will only allow preferred activities that came
1480 // from the same match quality.
1481 int match = 0;
1482 final int N = query.size();
1483 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1484 for (int j=0; j<N; j++) {
1485 ResolveInfo ri = query.get(j);
1486 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1487 + ": 0x" + Integer.toHexString(match));
1488 if (ri.match > match) match = ri.match;
1489 }
1490 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1491 + Integer.toHexString(match));
1492 match &= IntentFilter.MATCH_CATEGORY_MASK;
1493 final int M = prefs.size();
1494 for (int i=0; i<M; i++) {
1495 PreferredActivity pa = prefs.get(i);
1496 if (pa.mMatch != match) {
1497 continue;
1498 }
1499 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1500 if (DEBUG_PREFERRED) {
1501 Log.v(TAG, "Got preferred activity:");
1502 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1503 }
1504 if (ai != null) {
1505 for (int j=0; j<N; j++) {
1506 ResolveInfo ri = query.get(j);
1507 if (!ri.activityInfo.applicationInfo.packageName
1508 .equals(ai.applicationInfo.packageName)) {
1509 continue;
1510 }
1511 if (!ri.activityInfo.name.equals(ai.name)) {
1512 continue;
1513 }
1514
1515 // Okay we found a previously set preferred app.
1516 // If the result set is different from when this
1517 // was created, we need to clear it and re-ask the
1518 // user their preference.
1519 if (!pa.sameSet(query, priority)) {
1520 Log.i(TAG, "Result set changed, dropping preferred activity for "
1521 + intent + " type " + resolvedType);
1522 mSettings.mPreferredActivities.removeFilter(pa);
1523 return null;
1524 }
1525
1526 // Yay!
1527 return ri;
1528 }
1529 }
1530 }
1531 }
1532 }
1533 return null;
1534 }
1535
1536 public List<ResolveInfo> queryIntentActivities(Intent intent,
1537 String resolvedType, int flags) {
1538 ComponentName comp = intent.getComponent();
1539 if (comp != null) {
1540 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1541 ActivityInfo ai = getActivityInfo(comp, flags);
1542 if (ai != null) {
1543 ResolveInfo ri = new ResolveInfo();
1544 ri.activityInfo = ai;
1545 list.add(ri);
1546 }
1547 return list;
1548 }
1549
1550 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001551 String pkgName = intent.getPackage();
1552 if (pkgName == null) {
1553 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1554 resolvedType, flags);
1555 }
1556 PackageParser.Package pkg = mPackages.get(pkgName);
1557 if (pkg != null) {
1558 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1559 resolvedType, flags, pkg.activities);
1560 }
1561 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 }
1563 }
1564
1565 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1566 Intent[] specifics, String[] specificTypes, Intent intent,
1567 String resolvedType, int flags) {
1568 final String resultsAction = intent.getAction();
1569
1570 List<ResolveInfo> results = queryIntentActivities(
1571 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1572 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1573
1574 int specificsPos = 0;
1575 int N;
1576
1577 // todo: note that the algorithm used here is O(N^2). This
1578 // isn't a problem in our current environment, but if we start running
1579 // into situations where we have more than 5 or 10 matches then this
1580 // should probably be changed to something smarter...
1581
1582 // First we go through and resolve each of the specific items
1583 // that were supplied, taking care of removing any corresponding
1584 // duplicate items in the generic resolve list.
1585 if (specifics != null) {
1586 for (int i=0; i<specifics.length; i++) {
1587 final Intent sintent = specifics[i];
1588 if (sintent == null) {
1589 continue;
1590 }
1591
1592 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1593 String action = sintent.getAction();
1594 if (resultsAction != null && resultsAction.equals(action)) {
1595 // If this action was explicitly requested, then don't
1596 // remove things that have it.
1597 action = null;
1598 }
1599 ComponentName comp = sintent.getComponent();
1600 ResolveInfo ri = null;
1601 ActivityInfo ai = null;
1602 if (comp == null) {
1603 ri = resolveIntent(
1604 sintent,
1605 specificTypes != null ? specificTypes[i] : null,
1606 flags);
1607 if (ri == null) {
1608 continue;
1609 }
1610 if (ri == mResolveInfo) {
1611 // ACK! Must do something better with this.
1612 }
1613 ai = ri.activityInfo;
1614 comp = new ComponentName(ai.applicationInfo.packageName,
1615 ai.name);
1616 } else {
1617 ai = getActivityInfo(comp, flags);
1618 if (ai == null) {
1619 continue;
1620 }
1621 }
1622
1623 // Look for any generic query activities that are duplicates
1624 // of this specific one, and remove them from the results.
1625 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1626 N = results.size();
1627 int j;
1628 for (j=specificsPos; j<N; j++) {
1629 ResolveInfo sri = results.get(j);
1630 if ((sri.activityInfo.name.equals(comp.getClassName())
1631 && sri.activityInfo.applicationInfo.packageName.equals(
1632 comp.getPackageName()))
1633 || (action != null && sri.filter.matchAction(action))) {
1634 results.remove(j);
1635 if (Config.LOGV) Log.v(
1636 TAG, "Removing duplicate item from " + j
1637 + " due to specific " + specificsPos);
1638 if (ri == null) {
1639 ri = sri;
1640 }
1641 j--;
1642 N--;
1643 }
1644 }
1645
1646 // Add this specific item to its proper place.
1647 if (ri == null) {
1648 ri = new ResolveInfo();
1649 ri.activityInfo = ai;
1650 }
1651 results.add(specificsPos, ri);
1652 ri.specificIndex = i;
1653 specificsPos++;
1654 }
1655 }
1656
1657 // Now we go through the remaining generic results and remove any
1658 // duplicate actions that are found here.
1659 N = results.size();
1660 for (int i=specificsPos; i<N-1; i++) {
1661 final ResolveInfo rii = results.get(i);
1662 if (rii.filter == null) {
1663 continue;
1664 }
1665
1666 // Iterate over all of the actions of this result's intent
1667 // filter... typically this should be just one.
1668 final Iterator<String> it = rii.filter.actionsIterator();
1669 if (it == null) {
1670 continue;
1671 }
1672 while (it.hasNext()) {
1673 final String action = it.next();
1674 if (resultsAction != null && resultsAction.equals(action)) {
1675 // If this action was explicitly requested, then don't
1676 // remove things that have it.
1677 continue;
1678 }
1679 for (int j=i+1; j<N; j++) {
1680 final ResolveInfo rij = results.get(j);
1681 if (rij.filter != null && rij.filter.hasAction(action)) {
1682 results.remove(j);
1683 if (Config.LOGV) Log.v(
1684 TAG, "Removing duplicate item from " + j
1685 + " due to action " + action + " at " + i);
1686 j--;
1687 N--;
1688 }
1689 }
1690 }
1691
1692 // If the caller didn't request filter information, drop it now
1693 // so we don't have to marshall/unmarshall it.
1694 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1695 rii.filter = null;
1696 }
1697 }
1698
1699 // Filter out the caller activity if so requested.
1700 if (caller != null) {
1701 N = results.size();
1702 for (int i=0; i<N; i++) {
1703 ActivityInfo ainfo = results.get(i).activityInfo;
1704 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1705 && caller.getClassName().equals(ainfo.name)) {
1706 results.remove(i);
1707 break;
1708 }
1709 }
1710 }
1711
1712 // If the caller didn't request filter information,
1713 // drop them now so we don't have to
1714 // marshall/unmarshall it.
1715 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1716 N = results.size();
1717 for (int i=0; i<N; i++) {
1718 results.get(i).filter = null;
1719 }
1720 }
1721
1722 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1723 return results;
1724 }
1725
1726 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1727 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001728 ComponentName comp = intent.getComponent();
1729 if (comp != null) {
1730 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1731 ActivityInfo ai = getReceiverInfo(comp, flags);
1732 if (ai != null) {
1733 ResolveInfo ri = new ResolveInfo();
1734 ri.activityInfo = ai;
1735 list.add(ri);
1736 }
1737 return list;
1738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001741 String pkgName = intent.getPackage();
1742 if (pkgName == null) {
1743 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1744 resolvedType, flags);
1745 }
1746 PackageParser.Package pkg = mPackages.get(pkgName);
1747 if (pkg != null) {
1748 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1749 resolvedType, flags, pkg.receivers);
1750 }
1751 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
1753 }
1754
1755 public ResolveInfo resolveService(Intent intent, String resolvedType,
1756 int flags) {
1757 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1758 flags);
1759 if (query != null) {
1760 if (query.size() >= 1) {
1761 // If there is more than one service with the same priority,
1762 // just arbitrarily pick the first one.
1763 return query.get(0);
1764 }
1765 }
1766 return null;
1767 }
1768
1769 public List<ResolveInfo> queryIntentServices(Intent intent,
1770 String resolvedType, int flags) {
1771 ComponentName comp = intent.getComponent();
1772 if (comp != null) {
1773 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1774 ServiceInfo si = getServiceInfo(comp, flags);
1775 if (si != null) {
1776 ResolveInfo ri = new ResolveInfo();
1777 ri.serviceInfo = si;
1778 list.add(ri);
1779 }
1780 return list;
1781 }
1782
1783 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001784 String pkgName = intent.getPackage();
1785 if (pkgName == null) {
1786 return (List<ResolveInfo>)mServices.queryIntent(intent,
1787 resolvedType, flags);
1788 }
1789 PackageParser.Package pkg = mPackages.get(pkgName);
1790 if (pkg != null) {
1791 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1792 resolvedType, flags, pkg.services);
1793 }
1794 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 }
1796 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 public List<PackageInfo> getInstalledPackages(int flags) {
1799 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1800
1801 synchronized (mPackages) {
1802 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1803 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1804 while (i.hasNext()) {
1805 final PackageSetting ps = i.next();
1806 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1807 if(psPkg != null) {
1808 finalList.add(psPkg);
1809 }
1810 }
1811 }
1812 else {
1813 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1814 while (i.hasNext()) {
1815 final PackageParser.Package p = i.next();
1816 if (p.applicationInfo != null) {
1817 PackageInfo pi = generatePackageInfo(p, flags);
1818 if(pi != null) {
1819 finalList.add(pi);
1820 }
1821 }
1822 }
1823 }
1824 }
1825 return finalList;
1826 }
1827
1828 public List<ApplicationInfo> getInstalledApplications(int flags) {
1829 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1830 synchronized(mPackages) {
1831 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1832 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1833 while (i.hasNext()) {
1834 final PackageSetting ps = i.next();
1835 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1836 if(ai != null) {
1837 finalList.add(ai);
1838 }
1839 }
1840 }
1841 else {
1842 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1843 while (i.hasNext()) {
1844 final PackageParser.Package p = i.next();
1845 if (p.applicationInfo != null) {
1846 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1847 if(ai != null) {
1848 finalList.add(ai);
1849 }
1850 }
1851 }
1852 }
1853 }
1854 return finalList;
1855 }
1856
1857 public List<ApplicationInfo> getPersistentApplications(int flags) {
1858 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1859
1860 synchronized (mPackages) {
1861 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1862 while (i.hasNext()) {
1863 PackageParser.Package p = i.next();
1864 if (p.applicationInfo != null
1865 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
1866 && (!mSafeMode || (p.applicationInfo.flags
1867 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1868 finalList.add(p.applicationInfo);
1869 }
1870 }
1871 }
1872
1873 return finalList;
1874 }
1875
1876 public ProviderInfo resolveContentProvider(String name, int flags) {
1877 synchronized (mPackages) {
1878 final PackageParser.Provider provider = mProviders.get(name);
1879 return provider != null
1880 && mSettings.isEnabledLP(provider.info, flags)
1881 && (!mSafeMode || (provider.info.applicationInfo.flags
1882 &ApplicationInfo.FLAG_SYSTEM) != 0)
1883 ? PackageParser.generateProviderInfo(provider, flags)
1884 : null;
1885 }
1886 }
1887
Fred Quintana718d8a22009-04-29 17:53:20 -07001888 /**
1889 * @deprecated
1890 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 public void querySyncProviders(List outNames, List outInfo) {
1892 synchronized (mPackages) {
1893 Iterator<Map.Entry<String, PackageParser.Provider>> i
1894 = mProviders.entrySet().iterator();
1895
1896 while (i.hasNext()) {
1897 Map.Entry<String, PackageParser.Provider> entry = i.next();
1898 PackageParser.Provider p = entry.getValue();
1899
1900 if (p.syncable
1901 && (!mSafeMode || (p.info.applicationInfo.flags
1902 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1903 outNames.add(entry.getKey());
1904 outInfo.add(PackageParser.generateProviderInfo(p, 0));
1905 }
1906 }
1907 }
1908 }
1909
1910 public List<ProviderInfo> queryContentProviders(String processName,
1911 int uid, int flags) {
1912 ArrayList<ProviderInfo> finalList = null;
1913
1914 synchronized (mPackages) {
1915 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
1916 while (i.hasNext()) {
1917 PackageParser.Provider p = i.next();
1918 if (p.info.authority != null
1919 && (processName == null ||
1920 (p.info.processName.equals(processName)
1921 && p.info.applicationInfo.uid == uid))
1922 && mSettings.isEnabledLP(p.info, flags)
1923 && (!mSafeMode || (p.info.applicationInfo.flags
1924 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1925 if (finalList == null) {
1926 finalList = new ArrayList<ProviderInfo>(3);
1927 }
1928 finalList.add(PackageParser.generateProviderInfo(p,
1929 flags));
1930 }
1931 }
1932 }
1933
1934 if (finalList != null) {
1935 Collections.sort(finalList, mProviderInitOrderSorter);
1936 }
1937
1938 return finalList;
1939 }
1940
1941 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
1942 int flags) {
1943 synchronized (mPackages) {
1944 final PackageParser.Instrumentation i = mInstrumentation.get(name);
1945 return PackageParser.generateInstrumentationInfo(i, flags);
1946 }
1947 }
1948
1949 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
1950 int flags) {
1951 ArrayList<InstrumentationInfo> finalList =
1952 new ArrayList<InstrumentationInfo>();
1953
1954 synchronized (mPackages) {
1955 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
1956 while (i.hasNext()) {
1957 PackageParser.Instrumentation p = i.next();
1958 if (targetPackage == null
1959 || targetPackage.equals(p.info.targetPackage)) {
1960 finalList.add(PackageParser.generateInstrumentationInfo(p,
1961 flags));
1962 }
1963 }
1964 }
1965
1966 return finalList;
1967 }
1968
1969 private void scanDirLI(File dir, int flags, int scanMode) {
1970 Log.d(TAG, "Scanning app dir " + dir);
1971
1972 String[] files = dir.list();
1973
1974 int i;
1975 for (i=0; i<files.length; i++) {
1976 File file = new File(dir, files[i]);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08001977 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
1979 }
1980 }
1981
1982 private static void reportSettingsProblem(int priority, String msg) {
1983 try {
1984 File dataDir = Environment.getDataDirectory();
1985 File systemDir = new File(dataDir, "system");
1986 File fname = new File(systemDir, "uiderrors.txt");
1987 FileOutputStream out = new FileOutputStream(fname, true);
1988 PrintWriter pw = new PrintWriter(out);
1989 pw.println(msg);
1990 pw.close();
1991 FileUtils.setPermissions(
1992 fname.toString(),
1993 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
1994 -1, -1);
1995 } catch (java.io.IOException e) {
1996 }
1997 Log.println(priority, TAG, msg);
1998 }
1999
2000 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2001 PackageParser.Package pkg, File srcFile, int parseFlags) {
2002 if (GET_CERTIFICATES) {
2003 if (ps == null || !ps.codePath.equals(srcFile)
2004 || ps.getTimeStamp() != srcFile.lastModified()) {
2005 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2006 if (!pp.collectCertificates(pkg, parseFlags)) {
2007 mLastScanError = pp.getParseError();
2008 return false;
2009 }
2010 }
2011 }
2012 return true;
2013 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 /*
2016 * Scan a package and return the newly parsed package.
2017 * Returns null in case of errors and the error code is stored in mLastScanError
2018 */
2019 private PackageParser.Package scanPackageLI(File scanFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002020 int parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 int scanMode) {
2022 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2023 parseFlags |= mDefParseFlags;
2024 PackageParser pp = new PackageParser(scanFile.getPath());
2025 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002027 scanFile.getPath(),
2028 mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 if (pkg == null) {
2030 mLastScanError = pp.getParseError();
2031 return null;
2032 }
2033 PackageSetting ps;
2034 PackageSetting updatedPkg;
2035 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002036 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2038 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002039 // Verify certificates first
2040 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2041 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2042 return null;
2043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 if (updatedPkg != null) {
2045 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2046 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2047 }
2048 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2049 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002050 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2051 if (pkg.mVersionCode < ps.versionCode) {
2052 // The system package has been updated and the code path does not match
2053 // Ignore entry. Just return
2054 Log.w(TAG, "Package:" + pkg.packageName +
2055 " has been updated. Ignoring the one from path:"+scanFile);
2056 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2057 return null;
2058 } else {
2059 // Delete the older apk pointed to by ps
2060 // At this point, its safely assumed that package installation for
2061 // apps in system partition will go through. If not there won't be a working
2062 // version of the app
2063 synchronized (mPackages) {
2064 // Just remove the loaded entries from package lists.
2065 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002066 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002067 deletePackageResourcesLI(ps.name, ps.codePathString, ps.resourcePathString);
2068 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
2071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 // The apk is forward locked (not public) if its code and resources
2073 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002074 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002076 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002079 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
2081
2082 private static String fixProcessName(String defProcessName,
2083 String processName, int uid) {
2084 if (processName == null) {
2085 return defProcessName;
2086 }
2087 return processName;
2088 }
2089
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002090 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2092 if (pkg.mSignatures != null) {
2093 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2094 updateSignature)) {
2095 Log.e(TAG, "Package " + pkg.packageName
2096 + " signatures do not match the previously installed version; ignoring!");
2097 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2098 return false;
2099 }
2100
2101 if (pkgSetting.sharedUser != null) {
2102 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2103 pkg.mSignatures, updateSignature)) {
2104 Log.e(TAG, "Package " + pkg.packageName
2105 + " has no signatures that match those in shared user "
2106 + pkgSetting.sharedUser.name + "; ignoring!");
2107 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2108 return false;
2109 }
2110 }
2111 } else {
2112 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2113 }
2114 return true;
2115 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002116
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002117 public boolean performDexOpt(String packageName) {
2118 if (!mNoDexOpt) {
2119 return false;
2120 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002121
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002122 PackageParser.Package p;
2123 synchronized (mPackages) {
2124 p = mPackages.get(packageName);
2125 if (p == null || p.mDidDexOpt) {
2126 return false;
2127 }
2128 }
2129 synchronized (mInstallLock) {
2130 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2131 }
2132 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002133
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002134 static final int DEX_OPT_SKIPPED = 0;
2135 static final int DEX_OPT_PERFORMED = 1;
2136 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002137
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002138 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2139 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002140 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002141 String path = pkg.mScanPath;
2142 int ret = 0;
2143 try {
2144 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002145 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002146 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002147 pkg.mDidDexOpt = true;
2148 performed = true;
2149 }
2150 } catch (FileNotFoundException e) {
2151 Log.w(TAG, "Apk not found for dexopt: " + path);
2152 ret = -1;
2153 } catch (IOException e) {
2154 Log.w(TAG, "Exception reading apk: " + path, e);
2155 ret = -1;
2156 }
2157 if (ret < 0) {
2158 //error from installer
2159 return DEX_OPT_FAILED;
2160 }
2161 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002162
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002163 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2164 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002165
2166 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2167 return Environment.isEncryptedFilesystemEnabled() &&
2168 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2169 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 private PackageParser.Package scanPackageLI(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 PackageParser.Package pkg, int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002173 File scanFile = new File(pkg.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 mScanningPath = scanFile;
2175 if (pkg == null) {
2176 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2177 return null;
2178 }
2179
2180 final String pkgName = pkg.applicationInfo.packageName;
2181 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2182 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2183 }
2184
2185 if (pkgName.equals("android")) {
2186 synchronized (mPackages) {
2187 if (mAndroidApplication != null) {
2188 Log.w(TAG, "*************************************************");
2189 Log.w(TAG, "Core android package being redefined. Skipping.");
2190 Log.w(TAG, " file=" + mScanningPath);
2191 Log.w(TAG, "*************************************************");
2192 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2193 return null;
2194 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 // Set up information for our fall-back user intent resolution
2197 // activity.
2198 mPlatformPackage = pkg;
2199 pkg.mVersionCode = mSdkVersion;
2200 mAndroidApplication = pkg.applicationInfo;
2201 mResolveActivity.applicationInfo = mAndroidApplication;
2202 mResolveActivity.name = ResolverActivity.class.getName();
2203 mResolveActivity.packageName = mAndroidApplication.packageName;
2204 mResolveActivity.processName = mAndroidApplication.processName;
2205 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2206 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2207 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2208 mResolveActivity.exported = true;
2209 mResolveActivity.enabled = true;
2210 mResolveInfo.activityInfo = mResolveActivity;
2211 mResolveInfo.priority = 0;
2212 mResolveInfo.preferredOrder = 0;
2213 mResolveInfo.match = 0;
2214 mResolveComponentName = new ComponentName(
2215 mAndroidApplication.packageName, mResolveActivity.name);
2216 }
2217 }
2218
2219 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2220 TAG, "Scanning package " + pkgName);
2221 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2222 Log.w(TAG, "*************************************************");
2223 Log.w(TAG, "Application package " + pkgName
2224 + " already installed. Skipping duplicate.");
2225 Log.w(TAG, "*************************************************");
2226 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2227 return null;
2228 }
2229
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002230 // Initialize package source and resource directories
2231 File destResourceFile = null;
2232 File destCodeFile = null;
2233 if ((scanMode & SCAN_NO_PATHS) == 0) {
2234 boolean fwdLocked = (parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0;
2235 final String pkgFileName = pkgName + ".apk";
2236 File destDir = null;
2237
2238 if (fwdLocked) {
2239 destDir = mDrmAppPrivateInstallDir;
2240 destResourceFile = new File(mAppInstallDir, pkgName + ".zip");
2241 } else {
2242 boolean onSd = (parseFlags & PackageParser.PARSE_ON_SDCARD) != 0;
2243 if (!onSd) {
2244 destDir = mAppInstallDir;
2245 } else {
2246 String cachePath = getSdDir(pkgName);
2247 if (cachePath == null) {
2248 Log.e(TAG, "Secure container path for pkg: " + pkgName + " at location: " + cachePath +
2249 " not found");
2250 mLastScanError = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
2251 return null;
2252 }
2253 destDir = new File(cachePath);
2254 }
2255 destResourceFile = new File(destDir, pkgFileName);
2256 }
2257 destCodeFile = new File(destDir, pkgFileName);
2258 pkg.mPath = destCodeFile.getAbsolutePath();
2259 } else {
2260 pkg.mPath = pkg.mScanPath;
2261 destCodeFile = new File(pkg.mScanPath);
2262 destResourceFile = new File(pkg.mScanPath);
2263 }
2264 pkg.applicationInfo.sourceDir = destCodeFile.getAbsolutePath();
2265 pkg.applicationInfo.publicSourceDir = destResourceFile.getAbsolutePath();
2266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 SharedUserSetting suid = null;
2268 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 synchronized (mPackages) {
2273 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002274 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2275 if (mTmpSharedLibraries == null ||
2276 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2277 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2278 }
2279 int num = 0;
2280 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2281 for (int i=0; i<N; i++) {
2282 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 if (file == null) {
2284 Log.e(TAG, "Package " + pkg.packageName
2285 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002286 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2288 return null;
2289 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002290 mTmpSharedLibraries[num] = file;
2291 num++;
2292 }
2293 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2294 for (int i=0; i<N; i++) {
2295 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2296 if (file == null) {
2297 Log.w(TAG, "Package " + pkg.packageName
2298 + " desires unavailable shared library "
2299 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2300 } else {
2301 mTmpSharedLibraries[num] = file;
2302 num++;
2303 }
2304 }
2305 if (num > 0) {
2306 pkg.usesLibraryFiles = new String[num];
2307 System.arraycopy(mTmpSharedLibraries, 0,
2308 pkg.usesLibraryFiles, 0, num);
2309 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002310
Dianne Hackborn49237342009-08-27 20:08:01 -07002311 if (pkg.reqFeatures != null) {
2312 N = pkg.reqFeatures.size();
2313 for (int i=0; i<N; i++) {
2314 FeatureInfo fi = pkg.reqFeatures.get(i);
2315 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2316 // Don't care.
2317 continue;
2318 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002319
Dianne Hackborn49237342009-08-27 20:08:01 -07002320 if (fi.name != null) {
2321 if (mAvailableFeatures.get(fi.name) == null) {
2322 Log.e(TAG, "Package " + pkg.packageName
2323 + " requires unavailable feature "
2324 + fi.name + "; failing!");
2325 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2326 return null;
2327 }
2328 }
2329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 }
2331 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 if (pkg.mSharedUserId != null) {
2334 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2335 pkg.applicationInfo.flags, true);
2336 if (suid == null) {
2337 Log.w(TAG, "Creating application package " + pkgName
2338 + " for shared user failed");
2339 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2340 return null;
2341 }
2342 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2343 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2344 + suid.userId + "): packages=" + suid.packages);
2345 }
2346 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002347
2348 // Just create the setting, don't add it yet. For already existing packages
2349 // the PkgSetting exists already and doesn't have to be created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
2351 destResourceFile, pkg.applicationInfo.flags, true, false);
2352 if (pkgSetting == null) {
2353 Log.w(TAG, "Creating application package " + pkgName + " failed");
2354 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2355 return null;
2356 }
2357 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
2358 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2359 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 pkg.applicationInfo.uid = pkgSetting.userId;
2362 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002363
2364 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2366 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2367 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2368 return null;
2369 }
2370 // The signature has changed, but this package is in the system
2371 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002372 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 // However... if this package is part of a shared user, but it
2374 // doesn't match the signature of the shared user, let's fail.
2375 // What this means is that you can't change the signatures
2376 // associated with an overall shared user, which doesn't seem all
2377 // that unreasonable.
2378 if (pkgSetting.sharedUser != null) {
2379 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2380 pkg.mSignatures, false)) {
2381 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2382 return null;
2383 }
2384 }
2385 removeExisting = true;
2386 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002387
The Android Open Source Project10592532009-03-18 17:39:46 -07002388 // Verify that this new package doesn't have any content providers
2389 // that conflict with existing packages. Only do this if the
2390 // package isn't already installed, since we don't want to break
2391 // things that are installed.
2392 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2393 int N = pkg.providers.size();
2394 int i;
2395 for (i=0; i<N; i++) {
2396 PackageParser.Provider p = pkg.providers.get(i);
2397 String names[] = p.info.authority.split(";");
2398 for (int j = 0; j < names.length; j++) {
2399 if (mProviders.containsKey(names[j])) {
2400 PackageParser.Provider other = mProviders.get(names[j]);
2401 Log.w(TAG, "Can't install because provider name " + names[j] +
2402 " (in package " + pkg.applicationInfo.packageName +
2403 ") is already used by "
2404 + ((other != null && other.component != null)
2405 ? other.component.getPackageName() : "?"));
2406 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2407 return null;
2408 }
2409 }
2410 }
2411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 }
2413
2414 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002415 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002417 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 if (ret != 0) {
2419 String msg = "System package " + pkg.packageName
2420 + " could not have data directory erased after signature change.";
2421 reportSettingsProblem(Log.WARN, msg);
2422 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2423 return null;
2424 }
2425 }
2426 Log.w(TAG, "System package " + pkg.packageName
2427 + " signature changed: existing data removed.");
2428 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2429 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 long scanFileTime = scanFile.lastModified();
2432 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2433 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2434 pkg.applicationInfo.processName = fixProcessName(
2435 pkg.applicationInfo.packageName,
2436 pkg.applicationInfo.processName,
2437 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438
2439 File dataPath;
2440 if (mPlatformPackage == pkg) {
2441 // The system package is special.
2442 dataPath = new File (Environment.getDataDirectory(), "system");
2443 pkg.applicationInfo.dataDir = dataPath.getPath();
2444 } else {
2445 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002446 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2447 if (useEncryptedFSDir) {
2448 dataPath = new File(mSecureAppDataDir, pkgName);
2449 } else {
2450 dataPath = new File(mAppDataDir, pkgName);
2451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 if (dataPath.exists()) {
2453 mOutPermissions[1] = 0;
2454 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2455 if (mOutPermissions[1] == pkg.applicationInfo.uid
2456 || !Process.supportsProcesses()) {
2457 pkg.applicationInfo.dataDir = dataPath.getPath();
2458 } else {
2459 boolean recovered = false;
2460 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2461 // If this is a system app, we can at least delete its
2462 // current data so the application will still work.
2463 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002464 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 if(ret >= 0) {
2466 // Old data gone!
2467 String msg = "System package " + pkg.packageName
2468 + " has changed from uid: "
2469 + mOutPermissions[1] + " to "
2470 + pkg.applicationInfo.uid + "; old data erased";
2471 reportSettingsProblem(Log.WARN, msg);
2472 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002475 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 pkg.applicationInfo.uid);
2477 if (ret == -1) {
2478 // Ack should not happen!
2479 msg = "System package " + pkg.packageName
2480 + " could not have data directory re-created after delete.";
2481 reportSettingsProblem(Log.WARN, msg);
2482 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2483 return null;
2484 }
2485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 if (!recovered) {
2488 mHasSystemUidErrors = true;
2489 }
2490 }
2491 if (!recovered) {
2492 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2493 + pkg.applicationInfo.uid + "/fs_"
2494 + mOutPermissions[1];
2495 String msg = "Package " + pkg.packageName
2496 + " has mismatched uid: "
2497 + mOutPermissions[1] + " on disk, "
2498 + pkg.applicationInfo.uid + " in settings";
2499 synchronized (mPackages) {
2500 if (!mReportedUidError) {
2501 mReportedUidError = true;
2502 msg = msg + "; read messages:\n"
2503 + mSettings.getReadMessagesLP();
2504 }
2505 reportSettingsProblem(Log.ERROR, msg);
2506 }
2507 }
2508 }
2509 pkg.applicationInfo.dataDir = dataPath.getPath();
2510 } else {
2511 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2512 Log.v(TAG, "Want this data dir: " + dataPath);
2513 //invoke installer to do the actual installation
2514 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002515 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 pkg.applicationInfo.uid);
2517 if(ret < 0) {
2518 // Error from installer
2519 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2520 return null;
2521 }
2522 } else {
2523 dataPath.mkdirs();
2524 if (dataPath.exists()) {
2525 FileUtils.setPermissions(
2526 dataPath.toString(),
2527 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2528 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2529 }
2530 }
2531 if (dataPath.exists()) {
2532 pkg.applicationInfo.dataDir = dataPath.getPath();
2533 } else {
2534 Log.w(TAG, "Unable to create data directory: " + dataPath);
2535 pkg.applicationInfo.dataDir = null;
2536 }
2537 }
2538 }
2539
2540 // Perform shared library installation and dex validation and
2541 // optimization, if this is not a system app.
2542 if (mInstaller != null) {
2543 String path = scanFile.getPath();
2544 if (scanFileNewer) {
2545 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002546 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2547 if (err != PackageManager.INSTALL_SUCCEEDED) {
2548 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 return null;
2550 }
2551 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002552 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002553
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002554 if ((scanMode&SCAN_NO_DEX) == 0) {
2555 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2557 return null;
2558 }
2559 }
2560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 if (mFactoryTest && pkg.requestedPermissions.contains(
2563 android.Manifest.permission.FACTORY_TEST)) {
2564 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2565 }
2566
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002567 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 if ((scanMode&SCAN_MONITOR) != 0) {
2569 pkg.mPath = destCodeFile.getAbsolutePath();
2570 mAppDirs.put(pkg.mPath, pkg);
2571 }
2572
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002573 // Request the ActivityManager to kill the process(only for existing packages)
2574 // so that we do not end up in a confused state while the user is still using the older
2575 // version of the application while the new one gets installed.
2576 IActivityManager am = ActivityManagerNative.getDefault();
2577 if ((am != null) && ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0)) {
2578 try {
2579 am.killApplicationWithUid(pkg.applicationInfo.packageName,
2580 pkg.applicationInfo.uid);
2581 } catch (RemoteException e) {
2582 }
2583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002586 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002588 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 int N = pkg.providers.size();
2590 StringBuilder r = null;
2591 int i;
2592 for (i=0; i<N; i++) {
2593 PackageParser.Provider p = pkg.providers.get(i);
2594 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2595 p.info.processName, pkg.applicationInfo.uid);
2596 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2597 p.info.name), p);
2598 p.syncable = p.info.isSyncable;
2599 String names[] = p.info.authority.split(";");
2600 p.info.authority = null;
2601 for (int j = 0; j < names.length; j++) {
2602 if (j == 1 && p.syncable) {
2603 // We only want the first authority for a provider to possibly be
2604 // syncable, so if we already added this provider using a different
2605 // authority clear the syncable flag. We copy the provider before
2606 // changing it because the mProviders object contains a reference
2607 // to a provider that we don't want to change.
2608 // Only do this for the second authority since the resulting provider
2609 // object can be the same for all future authorities for this provider.
2610 p = new PackageParser.Provider(p);
2611 p.syncable = false;
2612 }
2613 if (!mProviders.containsKey(names[j])) {
2614 mProviders.put(names[j], p);
2615 if (p.info.authority == null) {
2616 p.info.authority = names[j];
2617 } else {
2618 p.info.authority = p.info.authority + ";" + names[j];
2619 }
2620 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2621 Log.d(TAG, "Registered content provider: " + names[j] +
2622 ", className = " + p.info.name +
2623 ", isSyncable = " + p.info.isSyncable);
2624 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002625 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 Log.w(TAG, "Skipping provider name " + names[j] +
2627 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002628 "): name already used by "
2629 + ((other != null && other.component != null)
2630 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 }
2632 }
2633 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2634 if (r == null) {
2635 r = new StringBuilder(256);
2636 } else {
2637 r.append(' ');
2638 }
2639 r.append(p.info.name);
2640 }
2641 }
2642 if (r != null) {
2643 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2644 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 N = pkg.services.size();
2647 r = null;
2648 for (i=0; i<N; i++) {
2649 PackageParser.Service s = pkg.services.get(i);
2650 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2651 s.info.processName, pkg.applicationInfo.uid);
2652 mServices.addService(s);
2653 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2654 if (r == null) {
2655 r = new StringBuilder(256);
2656 } else {
2657 r.append(' ');
2658 }
2659 r.append(s.info.name);
2660 }
2661 }
2662 if (r != null) {
2663 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 N = pkg.receivers.size();
2667 r = null;
2668 for (i=0; i<N; i++) {
2669 PackageParser.Activity a = pkg.receivers.get(i);
2670 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2671 a.info.processName, pkg.applicationInfo.uid);
2672 mReceivers.addActivity(a, "receiver");
2673 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2674 if (r == null) {
2675 r = new StringBuilder(256);
2676 } else {
2677 r.append(' ');
2678 }
2679 r.append(a.info.name);
2680 }
2681 }
2682 if (r != null) {
2683 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2684 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 N = pkg.activities.size();
2687 r = null;
2688 for (i=0; i<N; i++) {
2689 PackageParser.Activity a = pkg.activities.get(i);
2690 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2691 a.info.processName, pkg.applicationInfo.uid);
2692 mActivities.addActivity(a, "activity");
2693 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2694 if (r == null) {
2695 r = new StringBuilder(256);
2696 } else {
2697 r.append(' ');
2698 }
2699 r.append(a.info.name);
2700 }
2701 }
2702 if (r != null) {
2703 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 N = pkg.permissionGroups.size();
2707 r = null;
2708 for (i=0; i<N; i++) {
2709 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2710 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2711 if (cur == null) {
2712 mPermissionGroups.put(pg.info.name, pg);
2713 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2714 if (r == null) {
2715 r = new StringBuilder(256);
2716 } else {
2717 r.append(' ');
2718 }
2719 r.append(pg.info.name);
2720 }
2721 } else {
2722 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2723 + pg.info.packageName + " ignored: original from "
2724 + cur.info.packageName);
2725 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2726 if (r == null) {
2727 r = new StringBuilder(256);
2728 } else {
2729 r.append(' ');
2730 }
2731 r.append("DUP:");
2732 r.append(pg.info.name);
2733 }
2734 }
2735 }
2736 if (r != null) {
2737 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 N = pkg.permissions.size();
2741 r = null;
2742 for (i=0; i<N; i++) {
2743 PackageParser.Permission p = pkg.permissions.get(i);
2744 HashMap<String, BasePermission> permissionMap =
2745 p.tree ? mSettings.mPermissionTrees
2746 : mSettings.mPermissions;
2747 p.group = mPermissionGroups.get(p.info.group);
2748 if (p.info.group == null || p.group != null) {
2749 BasePermission bp = permissionMap.get(p.info.name);
2750 if (bp == null) {
2751 bp = new BasePermission(p.info.name, p.info.packageName,
2752 BasePermission.TYPE_NORMAL);
2753 permissionMap.put(p.info.name, bp);
2754 }
2755 if (bp.perm == null) {
2756 if (bp.sourcePackage == null
2757 || bp.sourcePackage.equals(p.info.packageName)) {
2758 BasePermission tree = findPermissionTreeLP(p.info.name);
2759 if (tree == null
2760 || tree.sourcePackage.equals(p.info.packageName)) {
2761 bp.perm = p;
2762 bp.uid = pkg.applicationInfo.uid;
2763 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2764 if (r == null) {
2765 r = new StringBuilder(256);
2766 } else {
2767 r.append(' ');
2768 }
2769 r.append(p.info.name);
2770 }
2771 } else {
2772 Log.w(TAG, "Permission " + p.info.name + " from package "
2773 + p.info.packageName + " ignored: base tree "
2774 + tree.name + " is from package "
2775 + tree.sourcePackage);
2776 }
2777 } else {
2778 Log.w(TAG, "Permission " + p.info.name + " from package "
2779 + p.info.packageName + " ignored: original from "
2780 + bp.sourcePackage);
2781 }
2782 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2783 if (r == null) {
2784 r = new StringBuilder(256);
2785 } else {
2786 r.append(' ');
2787 }
2788 r.append("DUP:");
2789 r.append(p.info.name);
2790 }
2791 } else {
2792 Log.w(TAG, "Permission " + p.info.name + " from package "
2793 + p.info.packageName + " ignored: no group "
2794 + p.group);
2795 }
2796 }
2797 if (r != null) {
2798 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2799 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 N = pkg.instrumentation.size();
2802 r = null;
2803 for (i=0; i<N; i++) {
2804 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2805 a.info.packageName = pkg.applicationInfo.packageName;
2806 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2807 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2808 a.info.dataDir = pkg.applicationInfo.dataDir;
2809 mInstrumentation.put(a.component, a);
2810 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2811 if (r == null) {
2812 r = new StringBuilder(256);
2813 } else {
2814 r.append(' ');
2815 }
2816 r.append(a.info.name);
2817 }
2818 }
2819 if (r != null) {
2820 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2821 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002822
Dianne Hackborn854060af2009-07-09 18:14:31 -07002823 if (pkg.protectedBroadcasts != null) {
2824 N = pkg.protectedBroadcasts.size();
2825 for (i=0; i<N; i++) {
2826 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
2827 }
2828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 pkgSetting.setTimeStamp(scanFileTime);
2831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 return pkg;
2834 }
2835
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002836 // The following constants are returned by cachePackageSharedLibsForAbiLI
2837 // to indicate if native shared libraries were found in the package.
2838 // Values are:
2839 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
2840 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
2841 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
2842 // in package (and not installed)
2843 //
2844 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
2845 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
2846 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002848 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
2849 // and automatically copy them to /data/data/<appname>/lib if present.
2850 //
2851 // NOTE: this method may throw an IOException if the library cannot
2852 // be copied to its final destination, e.g. if there isn't enough
2853 // room left on the data partition, or a ZipException if the package
2854 // file is malformed.
2855 //
2856 private int cachePackageSharedLibsForAbiLI( PackageParser.Package pkg,
2857 File dataPath, File scanFile, String cpuAbi)
2858 throws IOException, ZipException {
2859 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
2860 final String apkLib = "lib/";
2861 final int apkLibLen = apkLib.length();
2862 final int cpuAbiLen = cpuAbi.length();
2863 final String libPrefix = "lib";
2864 final int libPrefixLen = libPrefix.length();
2865 final String libSuffix = ".so";
2866 final int libSuffixLen = libSuffix.length();
2867 boolean hasNativeLibraries = false;
2868 boolean installedNativeLibraries = false;
2869
2870 // the minimum length of a valid native shared library of the form
2871 // lib/<something>/lib<name>.so.
2872 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
2873
2874 ZipFile zipFile = new ZipFile(scanFile);
2875 Enumeration<ZipEntry> entries =
2876 (Enumeration<ZipEntry>) zipFile.entries();
2877
2878 while (entries.hasMoreElements()) {
2879 ZipEntry entry = entries.nextElement();
2880 // skip directories
2881 if (entry.isDirectory()) {
2882 continue;
2883 }
2884 String entryName = entry.getName();
2885
2886 // check that the entry looks like lib/<something>/lib<name>.so
2887 // here, but don't check the ABI just yet.
2888 //
2889 // - must be sufficiently long
2890 // - must end with libSuffix, i.e. ".so"
2891 // - must start with apkLib, i.e. "lib/"
2892 if (entryName.length() < minEntryLen ||
2893 !entryName.endsWith(libSuffix) ||
2894 !entryName.startsWith(apkLib) ) {
2895 continue;
2896 }
2897
2898 // file name must start with libPrefix, i.e. "lib"
2899 int lastSlash = entryName.lastIndexOf('/');
2900
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002901 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002902 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
2903 continue;
2904 }
2905
2906 hasNativeLibraries = true;
2907
2908 // check the cpuAbi now, between lib/ and /lib<name>.so
2909 //
2910 if (lastSlash != apkLibLen + cpuAbiLen ||
2911 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
2912 continue;
2913
2914 // extract the library file name, ensure it doesn't contain
2915 // weird characters. we're guaranteed here that it doesn't contain
2916 // a directory separator though.
2917 String libFileName = entryName.substring(lastSlash+1);
2918 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
2919 continue;
2920 }
2921
2922 installedNativeLibraries = true;
2923
2924 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
2925 File.separator + libFileName;
2926 File sharedLibraryFile = new File(sharedLibraryFilePath);
2927 if (! sharedLibraryFile.exists() ||
2928 sharedLibraryFile.length() != entry.getSize() ||
2929 sharedLibraryFile.lastModified() != entry.getTime()) {
2930 if (Config.LOGD) {
2931 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002933 if (mInstaller == null) {
2934 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07002935 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002936 cacheSharedLibLI(pkg, zipFile, entry, sharedLibraryDir,
2937 sharedLibraryFile);
2938 }
2939 }
2940 if (!hasNativeLibraries)
2941 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
2942
2943 if (!installedNativeLibraries)
2944 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
2945
2946 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
2947 }
2948
2949 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
2950 // and copy them to /data/data/<appname>/lib.
2951 //
2952 // This function will first try the main CPU ABI defined by Build.CPU_ABI
2953 // (which corresponds to ro.product.cpu.abi), and also try an alternate
2954 // one if ro.product.cpu.abi2 is defined.
2955 //
2956 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
2957 File dataPath, File scanFile) {
2958 final String cpuAbi = Build.CPU_ABI;
2959 try {
2960 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
2961
2962 // some architectures are capable of supporting several CPU ABIs
2963 // for example, 'armeabi-v7a' also supports 'armeabi' native code
2964 // this is indicated by the definition of the ro.product.cpu.abi2
2965 // system property.
2966 //
2967 // only scan the package twice in case of ABI mismatch
2968 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
2969 String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
2970 if (cpuAbi2 != null) {
2971 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002972 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002973
2974 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
2975 Log.w(TAG,"Native ABI mismatch from package file");
2976 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 }
2978 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002979 } catch (ZipException e) {
2980 Log.w(TAG, "Failed to extract data from package file", e);
2981 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002983 Log.w(TAG, "Failed to cache package shared libs", e);
2984 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002986 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 }
2988
2989 private void cacheSharedLibLI(PackageParser.Package pkg,
2990 ZipFile zipFile, ZipEntry entry,
2991 File sharedLibraryDir,
2992 File sharedLibraryFile) throws IOException {
2993 InputStream inputStream = zipFile.getInputStream(entry);
2994 try {
2995 File tempFile = File.createTempFile("tmp", "tmp", sharedLibraryDir);
2996 String tempFilePath = tempFile.getPath();
2997 // XXX package manager can't change owner, so the lib files for
2998 // now need to be left as world readable and owned by the system.
2999 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3000 ! tempFile.setLastModified(entry.getTime()) ||
3001 FileUtils.setPermissions(tempFilePath,
3002 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
3003 |FileUtils.S_IROTH, -1, -1) != 0 ||
3004 ! tempFile.renameTo(sharedLibraryFile)) {
3005 // Failed to properly write file.
3006 tempFile.delete();
3007 throw new IOException("Couldn't create cached shared lib "
3008 + sharedLibraryFile + " in " + sharedLibraryDir);
3009 }
3010 } finally {
3011 inputStream.close();
3012 }
3013 }
3014
3015 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3016 if (chatty && Config.LOGD) Log.d(
3017 TAG, "Removing package " + pkg.applicationInfo.packageName );
3018
3019 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003022 mPackages.remove(pkg.applicationInfo.packageName);
3023 if (pkg.mPath != null) {
3024 mAppDirs.remove(pkg.mPath);
3025 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 PackageSetting ps = (PackageSetting)pkg.mExtras;
3028 if (ps != null && ps.sharedUser != null) {
3029 // XXX don't do this until the data is removed.
3030 if (false) {
3031 ps.sharedUser.packages.remove(ps);
3032 if (ps.sharedUser.packages.size() == 0) {
3033 // Remove.
3034 }
3035 }
3036 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 int N = pkg.providers.size();
3039 StringBuilder r = null;
3040 int i;
3041 for (i=0; i<N; i++) {
3042 PackageParser.Provider p = pkg.providers.get(i);
3043 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3044 p.info.name));
3045 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 /* The is another ContentProvider with this authority when
3048 * this app was installed so this authority is null,
3049 * Ignore it as we don't have to unregister the provider.
3050 */
3051 continue;
3052 }
3053 String names[] = p.info.authority.split(";");
3054 for (int j = 0; j < names.length; j++) {
3055 if (mProviders.get(names[j]) == p) {
3056 mProviders.remove(names[j]);
3057 if (chatty && Config.LOGD) Log.d(
3058 TAG, "Unregistered content provider: " + names[j] +
3059 ", className = " + p.info.name +
3060 ", isSyncable = " + p.info.isSyncable);
3061 }
3062 }
3063 if (chatty) {
3064 if (r == null) {
3065 r = new StringBuilder(256);
3066 } else {
3067 r.append(' ');
3068 }
3069 r.append(p.info.name);
3070 }
3071 }
3072 if (r != null) {
3073 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 N = pkg.services.size();
3077 r = null;
3078 for (i=0; i<N; i++) {
3079 PackageParser.Service s = pkg.services.get(i);
3080 mServices.removeService(s);
3081 if (chatty) {
3082 if (r == null) {
3083 r = new StringBuilder(256);
3084 } else {
3085 r.append(' ');
3086 }
3087 r.append(s.info.name);
3088 }
3089 }
3090 if (r != null) {
3091 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3092 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 N = pkg.receivers.size();
3095 r = null;
3096 for (i=0; i<N; i++) {
3097 PackageParser.Activity a = pkg.receivers.get(i);
3098 mReceivers.removeActivity(a, "receiver");
3099 if (chatty) {
3100 if (r == null) {
3101 r = new StringBuilder(256);
3102 } else {
3103 r.append(' ');
3104 }
3105 r.append(a.info.name);
3106 }
3107 }
3108 if (r != null) {
3109 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3110 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 N = pkg.activities.size();
3113 r = null;
3114 for (i=0; i<N; i++) {
3115 PackageParser.Activity a = pkg.activities.get(i);
3116 mActivities.removeActivity(a, "activity");
3117 if (chatty) {
3118 if (r == null) {
3119 r = new StringBuilder(256);
3120 } else {
3121 r.append(' ');
3122 }
3123 r.append(a.info.name);
3124 }
3125 }
3126 if (r != null) {
3127 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3128 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 N = pkg.permissions.size();
3131 r = null;
3132 for (i=0; i<N; i++) {
3133 PackageParser.Permission p = pkg.permissions.get(i);
3134 boolean tree = false;
3135 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3136 if (bp == null) {
3137 tree = true;
3138 bp = mSettings.mPermissionTrees.get(p.info.name);
3139 }
3140 if (bp != null && bp.perm == p) {
3141 if (bp.type != BasePermission.TYPE_BUILTIN) {
3142 if (tree) {
3143 mSettings.mPermissionTrees.remove(p.info.name);
3144 } else {
3145 mSettings.mPermissions.remove(p.info.name);
3146 }
3147 } else {
3148 bp.perm = null;
3149 }
3150 if (chatty) {
3151 if (r == null) {
3152 r = new StringBuilder(256);
3153 } else {
3154 r.append(' ');
3155 }
3156 r.append(p.info.name);
3157 }
3158 }
3159 }
3160 if (r != null) {
3161 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3162 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164 N = pkg.instrumentation.size();
3165 r = null;
3166 for (i=0; i<N; i++) {
3167 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3168 mInstrumentation.remove(a.component);
3169 if (chatty) {
3170 if (r == null) {
3171 r = new StringBuilder(256);
3172 } else {
3173 r.append(' ');
3174 }
3175 r.append(a.info.name);
3176 }
3177 }
3178 if (r != null) {
3179 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3180 }
3181 }
3182 }
3183
3184 private static final boolean isPackageFilename(String name) {
3185 return name != null && name.endsWith(".apk");
3186 }
3187
3188 private void updatePermissionsLP() {
3189 // Make sure there are no dangling permission trees.
3190 Iterator<BasePermission> it = mSettings.mPermissionTrees
3191 .values().iterator();
3192 while (it.hasNext()) {
3193 BasePermission bp = it.next();
3194 if (bp.perm == null) {
3195 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3196 + " from package " + bp.sourcePackage);
3197 it.remove();
3198 }
3199 }
3200
3201 // Make sure all dynamic permissions have been assigned to a package,
3202 // and make sure there are no dangling permissions.
3203 it = mSettings.mPermissions.values().iterator();
3204 while (it.hasNext()) {
3205 BasePermission bp = it.next();
3206 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3207 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3208 + bp.name + " pkg=" + bp.sourcePackage
3209 + " info=" + bp.pendingInfo);
3210 if (bp.perm == null && bp.pendingInfo != null) {
3211 BasePermission tree = findPermissionTreeLP(bp.name);
3212 if (tree != null) {
3213 bp.perm = new PackageParser.Permission(tree.perm.owner,
3214 new PermissionInfo(bp.pendingInfo));
3215 bp.perm.info.packageName = tree.perm.info.packageName;
3216 bp.perm.info.name = bp.name;
3217 bp.uid = tree.uid;
3218 }
3219 }
3220 }
3221 if (bp.perm == null) {
3222 Log.w(TAG, "Removing dangling permission: " + bp.name
3223 + " from package " + bp.sourcePackage);
3224 it.remove();
3225 }
3226 }
3227
3228 // Now update the permissions for all packages, in particular
3229 // replace the granted permissions of the system packages.
3230 for (PackageParser.Package pkg : mPackages.values()) {
3231 grantPermissionsLP(pkg, false);
3232 }
3233 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3236 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3237 if (ps == null) {
3238 return;
3239 }
3240 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3241 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003243 if (replace) {
3244 ps.permissionsFixed = false;
3245 if (gp == ps) {
3246 gp.grantedPermissions.clear();
3247 gp.gids = mGlobalGids;
3248 }
3249 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 if (gp.gids == null) {
3252 gp.gids = mGlobalGids;
3253 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 final int N = pkg.requestedPermissions.size();
3256 for (int i=0; i<N; i++) {
3257 String name = pkg.requestedPermissions.get(i);
3258 BasePermission bp = mSettings.mPermissions.get(name);
3259 PackageParser.Permission p = bp != null ? bp.perm : null;
3260 if (false) {
3261 if (gp != ps) {
3262 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3263 + ": " + p);
3264 }
3265 }
3266 if (p != null) {
3267 final String perm = p.info.name;
3268 boolean allowed;
3269 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3270 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3271 allowed = true;
3272 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3273 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003274 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003276 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 == PackageManager.SIGNATURE_MATCH);
3278 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3279 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3280 // For updated system applications, the signatureOrSystem permission
3281 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003282 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3284 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3285 if(sysPs.grantedPermissions.contains(perm)) {
3286 allowed = true;
3287 } else {
3288 allowed = false;
3289 }
3290 } else {
3291 allowed = true;
3292 }
3293 }
3294 }
3295 } else {
3296 allowed = false;
3297 }
3298 if (false) {
3299 if (gp != ps) {
3300 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3301 }
3302 }
3303 if (allowed) {
3304 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3305 && ps.permissionsFixed) {
3306 // If this is an existing, non-system package, then
3307 // we can't add any new permissions to it.
3308 if (!gp.loadedPermissions.contains(perm)) {
3309 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003310 // Except... if this is a permission that was added
3311 // to the platform (note: need to only do this when
3312 // updating the platform).
3313 final int NP = PackageParser.NEW_PERMISSIONS.length;
3314 for (int ip=0; ip<NP; ip++) {
3315 final PackageParser.NewPermissionInfo npi
3316 = PackageParser.NEW_PERMISSIONS[ip];
3317 if (npi.name.equals(perm)
3318 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3319 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003320 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003321 + pkg.packageName);
3322 break;
3323 }
3324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 }
3326 }
3327 if (allowed) {
3328 if (!gp.grantedPermissions.contains(perm)) {
3329 addedPermission = true;
3330 gp.grantedPermissions.add(perm);
3331 gp.gids = appendInts(gp.gids, bp.gids);
3332 }
3333 } else {
3334 Log.w(TAG, "Not granting permission " + perm
3335 + " to package " + pkg.packageName
3336 + " because it was previously installed without");
3337 }
3338 } else {
3339 Log.w(TAG, "Not granting permission " + perm
3340 + " to package " + pkg.packageName
3341 + " (protectionLevel=" + p.info.protectionLevel
3342 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3343 + ")");
3344 }
3345 } else {
3346 Log.w(TAG, "Unknown permission " + name
3347 + " in package " + pkg.packageName);
3348 }
3349 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003352 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3353 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 // This is the first that we have heard about this package, so the
3355 // permissions we have now selected are fixed until explicitly
3356 // changed.
3357 ps.permissionsFixed = true;
3358 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3359 }
3360 }
3361
3362 private final class ActivityIntentResolver
3363 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003364 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003366 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 }
3368
Mihai Preda074edef2009-05-18 17:13:31 +02003369 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003371 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3373 }
3374
Mihai Predaeae850c2009-05-13 10:13:48 +02003375 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3376 ArrayList<PackageParser.Activity> packageActivities) {
3377 if (packageActivities == null) {
3378 return null;
3379 }
3380 mFlags = flags;
3381 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3382 int N = packageActivities.size();
3383 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3384 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003385
3386 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003387 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003388 intentFilters = packageActivities.get(i).intents;
3389 if (intentFilters != null && intentFilters.size() > 0) {
3390 listCut.add(intentFilters);
3391 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003392 }
3393 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3394 }
3395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 public final void addActivity(PackageParser.Activity a, String type) {
3397 mActivities.put(a.component, a);
3398 if (SHOW_INFO || Config.LOGV) Log.v(
3399 TAG, " " + type + " " +
3400 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3401 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3402 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003403 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3405 if (SHOW_INFO || Config.LOGV) {
3406 Log.v(TAG, " IntentFilter:");
3407 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3408 }
3409 if (!intent.debugCheck()) {
3410 Log.w(TAG, "==> For Activity " + a.info.name);
3411 }
3412 addFilter(intent);
3413 }
3414 }
3415
3416 public final void removeActivity(PackageParser.Activity a, String type) {
3417 mActivities.remove(a.component);
3418 if (SHOW_INFO || Config.LOGV) Log.v(
3419 TAG, " " + type + " " +
3420 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3421 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3422 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003423 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3425 if (SHOW_INFO || Config.LOGV) {
3426 Log.v(TAG, " IntentFilter:");
3427 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3428 }
3429 removeFilter(intent);
3430 }
3431 }
3432
3433 @Override
3434 protected boolean allowFilterResult(
3435 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3436 ActivityInfo filterAi = filter.activity.info;
3437 for (int i=dest.size()-1; i>=0; i--) {
3438 ActivityInfo destAi = dest.get(i).activityInfo;
3439 if (destAi.name == filterAi.name
3440 && destAi.packageName == filterAi.packageName) {
3441 return false;
3442 }
3443 }
3444 return true;
3445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 @Override
3448 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3449 int match) {
3450 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3451 return null;
3452 }
3453 final PackageParser.Activity activity = info.activity;
3454 if (mSafeMode && (activity.info.applicationInfo.flags
3455 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3456 return null;
3457 }
3458 final ResolveInfo res = new ResolveInfo();
3459 res.activityInfo = PackageParser.generateActivityInfo(activity,
3460 mFlags);
3461 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3462 res.filter = info;
3463 }
3464 res.priority = info.getPriority();
3465 res.preferredOrder = activity.owner.mPreferredOrder;
3466 //System.out.println("Result: " + res.activityInfo.className +
3467 // " = " + res.priority);
3468 res.match = match;
3469 res.isDefault = info.hasDefault;
3470 res.labelRes = info.labelRes;
3471 res.nonLocalizedLabel = info.nonLocalizedLabel;
3472 res.icon = info.icon;
3473 return res;
3474 }
3475
3476 @Override
3477 protected void sortResults(List<ResolveInfo> results) {
3478 Collections.sort(results, mResolvePrioritySorter);
3479 }
3480
3481 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003482 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003484 out.print(prefix); out.print(
3485 Integer.toHexString(System.identityHashCode(filter.activity)));
3486 out.print(' ');
3487 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 }
3489
3490// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3491// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3492// final List<ResolveInfo> retList = Lists.newArrayList();
3493// while (i.hasNext()) {
3494// final ResolveInfo resolveInfo = i.next();
3495// if (isEnabledLP(resolveInfo.activityInfo)) {
3496// retList.add(resolveInfo);
3497// }
3498// }
3499// return retList;
3500// }
3501
3502 // Keys are String (activity class name), values are Activity.
3503 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3504 = new HashMap<ComponentName, PackageParser.Activity>();
3505 private int mFlags;
3506 }
3507
3508 private final class ServiceIntentResolver
3509 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003510 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003512 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 }
3514
Mihai Preda074edef2009-05-18 17:13:31 +02003515 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003517 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3519 }
3520
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003521 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3522 ArrayList<PackageParser.Service> packageServices) {
3523 if (packageServices == null) {
3524 return null;
3525 }
3526 mFlags = flags;
3527 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3528 int N = packageServices.size();
3529 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3530 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3531
3532 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3533 for (int i = 0; i < N; ++i) {
3534 intentFilters = packageServices.get(i).intents;
3535 if (intentFilters != null && intentFilters.size() > 0) {
3536 listCut.add(intentFilters);
3537 }
3538 }
3539 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3540 }
3541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 public final void addService(PackageParser.Service s) {
3543 mServices.put(s.component, s);
3544 if (SHOW_INFO || Config.LOGV) Log.v(
3545 TAG, " " + (s.info.nonLocalizedLabel != null
3546 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3547 if (SHOW_INFO || Config.LOGV) Log.v(
3548 TAG, " Class=" + s.info.name);
3549 int NI = s.intents.size();
3550 int j;
3551 for (j=0; j<NI; j++) {
3552 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3553 if (SHOW_INFO || Config.LOGV) {
3554 Log.v(TAG, " IntentFilter:");
3555 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3556 }
3557 if (!intent.debugCheck()) {
3558 Log.w(TAG, "==> For Service " + s.info.name);
3559 }
3560 addFilter(intent);
3561 }
3562 }
3563
3564 public final void removeService(PackageParser.Service s) {
3565 mServices.remove(s.component);
3566 if (SHOW_INFO || Config.LOGV) Log.v(
3567 TAG, " " + (s.info.nonLocalizedLabel != null
3568 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3569 if (SHOW_INFO || Config.LOGV) Log.v(
3570 TAG, " Class=" + s.info.name);
3571 int NI = s.intents.size();
3572 int j;
3573 for (j=0; j<NI; j++) {
3574 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3575 if (SHOW_INFO || Config.LOGV) {
3576 Log.v(TAG, " IntentFilter:");
3577 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3578 }
3579 removeFilter(intent);
3580 }
3581 }
3582
3583 @Override
3584 protected boolean allowFilterResult(
3585 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3586 ServiceInfo filterSi = filter.service.info;
3587 for (int i=dest.size()-1; i>=0; i--) {
3588 ServiceInfo destAi = dest.get(i).serviceInfo;
3589 if (destAi.name == filterSi.name
3590 && destAi.packageName == filterSi.packageName) {
3591 return false;
3592 }
3593 }
3594 return true;
3595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 @Override
3598 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3599 int match) {
3600 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3601 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3602 return null;
3603 }
3604 final PackageParser.Service service = info.service;
3605 if (mSafeMode && (service.info.applicationInfo.flags
3606 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3607 return null;
3608 }
3609 final ResolveInfo res = new ResolveInfo();
3610 res.serviceInfo = PackageParser.generateServiceInfo(service,
3611 mFlags);
3612 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3613 res.filter = filter;
3614 }
3615 res.priority = info.getPriority();
3616 res.preferredOrder = service.owner.mPreferredOrder;
3617 //System.out.println("Result: " + res.activityInfo.className +
3618 // " = " + res.priority);
3619 res.match = match;
3620 res.isDefault = info.hasDefault;
3621 res.labelRes = info.labelRes;
3622 res.nonLocalizedLabel = info.nonLocalizedLabel;
3623 res.icon = info.icon;
3624 return res;
3625 }
3626
3627 @Override
3628 protected void sortResults(List<ResolveInfo> results) {
3629 Collections.sort(results, mResolvePrioritySorter);
3630 }
3631
3632 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003633 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003635 out.print(prefix); out.print(
3636 Integer.toHexString(System.identityHashCode(filter.service)));
3637 out.print(' ');
3638 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 }
3640
3641// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3642// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3643// final List<ResolveInfo> retList = Lists.newArrayList();
3644// while (i.hasNext()) {
3645// final ResolveInfo resolveInfo = (ResolveInfo) i;
3646// if (isEnabledLP(resolveInfo.serviceInfo)) {
3647// retList.add(resolveInfo);
3648// }
3649// }
3650// return retList;
3651// }
3652
3653 // Keys are String (activity class name), values are Activity.
3654 private final HashMap<ComponentName, PackageParser.Service> mServices
3655 = new HashMap<ComponentName, PackageParser.Service>();
3656 private int mFlags;
3657 };
3658
3659 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3660 new Comparator<ResolveInfo>() {
3661 public int compare(ResolveInfo r1, ResolveInfo r2) {
3662 int v1 = r1.priority;
3663 int v2 = r2.priority;
3664 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3665 if (v1 != v2) {
3666 return (v1 > v2) ? -1 : 1;
3667 }
3668 v1 = r1.preferredOrder;
3669 v2 = r2.preferredOrder;
3670 if (v1 != v2) {
3671 return (v1 > v2) ? -1 : 1;
3672 }
3673 if (r1.isDefault != r2.isDefault) {
3674 return r1.isDefault ? -1 : 1;
3675 }
3676 v1 = r1.match;
3677 v2 = r2.match;
3678 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3679 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3680 }
3681 };
3682
3683 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3684 new Comparator<ProviderInfo>() {
3685 public int compare(ProviderInfo p1, ProviderInfo p2) {
3686 final int v1 = p1.initOrder;
3687 final int v2 = p2.initOrder;
3688 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3689 }
3690 };
3691
3692 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3693 IActivityManager am = ActivityManagerNative.getDefault();
3694 if (am != null) {
3695 try {
3696 final Intent intent = new Intent(action,
3697 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3698 if (extras != null) {
3699 intent.putExtras(extras);
3700 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003701 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 am.broadcastIntent(
3703 null, intent,
3704 null, null, 0, null, null, null, false, false);
3705 } catch (RemoteException ex) {
3706 }
3707 }
3708 }
3709
3710 private final class AppDirObserver extends FileObserver {
3711 public AppDirObserver(String path, int mask, boolean isrom) {
3712 super(path, mask);
3713 mRootDir = path;
3714 mIsRom = isrom;
3715 }
3716
3717 public void onEvent(int event, String path) {
3718 String removedPackage = null;
3719 int removedUid = -1;
3720 String addedPackage = null;
3721 int addedUid = -1;
3722
3723 synchronized (mInstallLock) {
3724 String fullPathStr = null;
3725 File fullPath = null;
3726 if (path != null) {
3727 fullPath = new File(mRootDir, path);
3728 fullPathStr = fullPath.getPath();
3729 }
3730
3731 if (Config.LOGV) Log.v(
3732 TAG, "File " + fullPathStr + " changed: "
3733 + Integer.toHexString(event));
3734
3735 if (!isPackageFilename(path)) {
3736 if (Config.LOGV) Log.v(
3737 TAG, "Ignoring change of non-package file: " + fullPathStr);
3738 return;
3739 }
3740
3741 if ((event&REMOVE_EVENTS) != 0) {
3742 synchronized (mInstallLock) {
3743 PackageParser.Package p = mAppDirs.get(fullPathStr);
3744 if (p != null) {
3745 removePackageLI(p, true);
3746 removedPackage = p.applicationInfo.packageName;
3747 removedUid = p.applicationInfo.uid;
3748 }
3749 }
3750 }
3751
3752 if ((event&ADD_EVENTS) != 0) {
3753 PackageParser.Package p = mAppDirs.get(fullPathStr);
3754 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003755 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3757 PackageParser.PARSE_CHATTY |
3758 PackageParser.PARSE_MUST_BE_APK,
3759 SCAN_MONITOR);
3760 if (p != null) {
3761 synchronized (mPackages) {
3762 grantPermissionsLP(p, false);
3763 }
3764 addedPackage = p.applicationInfo.packageName;
3765 addedUid = p.applicationInfo.uid;
3766 }
3767 }
3768 }
3769
3770 synchronized (mPackages) {
3771 mSettings.writeLP();
3772 }
3773 }
3774
3775 if (removedPackage != null) {
3776 Bundle extras = new Bundle(1);
3777 extras.putInt(Intent.EXTRA_UID, removedUid);
3778 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3779 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3780 }
3781 if (addedPackage != null) {
3782 Bundle extras = new Bundle(1);
3783 extras.putInt(Intent.EXTRA_UID, addedUid);
3784 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3785 }
3786 }
3787
3788 private final String mRootDir;
3789 private final boolean mIsRom;
3790 }
Jacek Surazski65e13172009-04-28 15:26:38 +02003791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 /* Called when a downloaded package installation has been confirmed by the user */
3793 public void installPackage(
3794 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003795 installPackage(packageURI, observer, flags, null);
3796 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003797
Jacek Surazski65e13172009-04-28 15:26:38 +02003798 /* Called when a downloaded package installation has been confirmed by the user */
3799 public void installPackage(
3800 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3801 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 mContext.enforceCallingOrSelfPermission(
3803 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 // Queue up an async operation since the package installation may take a little while.
3806 mHandler.post(new Runnable() {
3807 public void run() {
3808 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003809 // Result object to be returned
3810 PackageInstalledInfo res = new PackageInstalledInfo();
3811 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3812 res.uid = -1;
3813 res.pkg = null;
3814 res.removedInfo = new PackageRemovedInfo();
3815 // Make a temporary copy of file from given packageURI
3816 File tmpPackageFile = copyTempInstallFile(packageURI, res);
3817 if (tmpPackageFile != null) {
3818 synchronized (mInstallLock) {
3819 installPackageLI(packageURI, flags, true, installerPackageName, tmpPackageFile, res);
3820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 }
3822 if (observer != null) {
3823 try {
3824 observer.packageInstalled(res.name, res.returnCode);
3825 } catch (RemoteException e) {
3826 Log.i(TAG, "Observer no longer exists.");
3827 }
3828 }
3829 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3830 // call appears in the synchronized block above.
3831 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3832 res.removedInfo.sendBroadcast(false, true);
3833 Bundle extras = new Bundle(1);
3834 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003835 final boolean update = res.removedInfo.removedPackage != null;
3836 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3838 }
3839 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3840 res.pkg.applicationInfo.packageName,
3841 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003842 if (update) {
3843 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3844 res.pkg.applicationInfo.packageName,
3845 extras);
3846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 }
3848 Runtime.getRuntime().gc();
3849 }
3850 });
3851 }
3852
3853 class PackageInstalledInfo {
3854 String name;
3855 int uid;
3856 PackageParser.Package pkg;
3857 int returnCode;
3858 PackageRemovedInfo removedInfo;
3859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 /*
3862 * Install a non-existing package.
3863 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003864 private void installNewPackageLI(PackageParser.Package pkg,
3865 int parseFlags,
3866 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02003867 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08003869 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003870 String pkgName = pkg.packageName;
3871 boolean onSd = (parseFlags & PackageParser.PARSE_ON_SDCARD) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -08003872
3873 if (useEncryptedFilesystemForPackage(pkg)) {
3874 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
3875 } else {
3876 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 res.name = pkgName;
3879 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003880 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003882 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 + " without first uninstalling.");
3884 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3885 return;
3886 }
3887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003889 if (onSd) {
3890 // Create secure container mount point for package
3891 String cPath = createSdDir(new File(pkg.mScanPath), pkgName);
3892 if (cPath == null) {
3893 mLastScanError = res.returnCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
3894 return;
3895 }
3896 }
3897 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003899 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3901 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3902 }
3903 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003904 File destPackageFile = new File(pkg.mPath);
3905 if (destPackageFile.exists()) {
3906 // It's safe to do this because we know (from the above check) that the file
3907 // isn't currently used for an installed package.
3908 destPackageFile.delete();
3909 }
3910 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02003911 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 res);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003913 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3914 // Check if container can be finalized
3915 if(onSd && !finalizeSdDir(pkgName)) {
3916 res.returnCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
3917 }
3918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 // delete the partially installed application. the data directory will have to be
3920 // restored if it was already existing
3921 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3922 // remove package from internal structures. Note that we want deletePackageX to
3923 // delete the package data and cache directories that it created in
3924 // scanPackageLocked, unless those directories existed before we even tried to
3925 // install.
3926 deletePackageLI(
3927 pkgName, true,
3928 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3929 res.removedInfo);
3930 }
3931 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003932 if (onSd && res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3933 // Destroy cache
3934 destroySdDir(pkgName);
3935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003937
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003938 private void replacePackageLI(PackageParser.Package pkg,
3939 int parseFlags,
3940 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02003941 String installerPackageName, PackageInstalledInfo res) {
3942
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003943 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003944 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 // First find the old package info and check signatures
3946 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003947 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003948 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
3949 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3951 return;
3952 }
3953 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003954 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 if(sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003956 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003958 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 }
3960 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003963 PackageParser.Package pkg,
3964 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02003965 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 PackageParser.Package newPackage = null;
3967 String pkgName = deletedPackage.packageName;
3968 boolean deletedPkg = true;
3969 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003970
Jacek Surazski65e13172009-04-28 15:26:38 +02003971 String oldInstallerPackageName = null;
3972 synchronized (mPackages) {
3973 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3974 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003975
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003976 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 // First delete the existing package while retaining the data directory
3978 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3979 res.removedInfo)) {
3980 // If the existing package was'nt successfully deleted
3981 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3982 deletedPkg = false;
3983 } else {
3984 // Successfully deleted the old package. Now proceed with re-installation
3985 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003986 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003988 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3990 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08003991 }
3992 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003993 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02003994 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 res);
3996 updatedSettings = true;
3997 }
3998 }
3999
4000 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4001 // If we deleted an exisiting package, the old source and resource files that we
4002 // were keeping around in case we needed them (see below) can now be deleted
4003 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
4004 final ApplicationInfo installedPackageAppInfo =
4005 newPackage.applicationInfo;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004006 deletePackageResourcesLI(pkgName,
4007 !deletedPackageAppInfo.sourceDir
4008 .equals(installedPackageAppInfo.sourceDir)
4009 ? deletedPackageAppInfo.sourceDir : null,
4010 !deletedPackageAppInfo.publicSourceDir
4011 .equals(installedPackageAppInfo.publicSourceDir)
4012 ? deletedPackageAppInfo.publicSourceDir : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 //update signature on the new package setting
4014 //this should always succeed, since we checked the
4015 //signature earlier.
4016 synchronized(mPackages) {
4017 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
4018 parseFlags, true);
4019 }
4020 } else {
4021 // remove package from internal structures. Note that we want deletePackageX to
4022 // delete the package data and cache directories that it created in
4023 // scanPackageLocked, unless those directories existed before we even tried to
4024 // install.
4025 if(updatedSettings) {
4026 deletePackageLI(
4027 pkgName, true,
4028 PackageManager.DONT_DELETE_DATA,
4029 res.removedInfo);
4030 }
4031 // Since we failed to install the new package we need to restore the old
4032 // package that we deleted.
4033 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004034 File restoreFile = new File(deletedPackage.mPath);
4035 if (restoreFile == null) {
4036 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
4037 return;
4038 }
4039 File restoreTmpFile = createTempPackageFile();
4040 if (restoreTmpFile == null) {
4041 Log.e(TAG, "Failed creating temp file when restoring pkg : " + pkgName);
4042 return;
4043 }
4044 if (!FileUtils.copyFile(restoreFile, restoreTmpFile)) {
4045 Log.e(TAG, "Failed copying temp file when restoring pkg : " + pkgName);
4046 return;
4047 }
4048 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4049 restoreRes.removedInfo = new PackageRemovedInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004050 installPackageLI(
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004051 Uri.fromFile(restoreFile),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004053 ? PackageManager.INSTALL_FORWARD_LOCK
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004054 : 0, false, oldInstallerPackageName, restoreTmpFile, restoreRes);
4055 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4056 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 }
4059 }
4060 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004063 PackageParser.Package pkg,
4064 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004065 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 PackageParser.Package newPackage = null;
4067 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004068 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 PackageParser.PARSE_IS_SYSTEM;
4070 String packageName = deletedPackage.packageName;
4071 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4072 if (packageName == null) {
4073 Log.w(TAG, "Attempt to delete null packageName.");
4074 return;
4075 }
4076 PackageParser.Package oldPkg;
4077 PackageSetting oldPkgSetting;
4078 synchronized (mPackages) {
4079 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004080 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4082 (oldPkgSetting == null)) {
4083 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4084 return;
4085 }
4086 }
4087 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4088 res.removedInfo.removedPackage = packageName;
4089 // Remove existing system package
4090 removePackageLI(oldPkg, true);
4091 synchronized (mPackages) {
4092 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4093 }
4094
4095 // Successfully disabled the old package. Now proceed with re-installation
4096 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4097 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004098 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004100 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4102 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4103 }
4104 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004105 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 updatedSettings = true;
4107 }
4108
4109 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4110 //update signature on the new package setting
4111 //this should always succeed, since we checked the
4112 //signature earlier.
4113 synchronized(mPackages) {
4114 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4115 parseFlags, true);
4116 }
4117 } else {
4118 // Re installation failed. Restore old information
4119 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004120 if (newPackage != null) {
4121 removePackageLI(newPackage, true);
4122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004124 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004126 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 // Restore the old system information in Settings
4128 synchronized(mPackages) {
4129 if(updatedSettings) {
4130 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004131 mSettings.setInstallerPackageName(packageName,
4132 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 }
4134 mSettings.writeLP();
4135 }
4136 }
4137 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004138
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004139 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004140 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004141 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 synchronized (mPackages) {
4143 //write settings. the installStatus will be incomplete at this stage.
4144 //note that the new package setting would have already been
4145 //added to mPackages. It hasn't been persisted yet.
4146 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4147 mSettings.writeLP();
4148 }
4149
4150 int retCode = 0;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004151 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4152 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004154 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4156 return;
4157 }
4158 }
4159 // XXX There are probably some big issues here: upon doing
4160 // the rename, we have reached the point of no return (the
4161 // original .apk is gone!), so we can't fail. Yet... we can.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004162 File scanFile = new File(newPackage.mScanPath);
4163 if (!scanFile.renameTo(new File(newPackage.mPath))) {
4164 Log.e(TAG, "Couldn't move package file: " + newPackage.mScanPath + " to: " + newPackage.mPath);
4165 // TODO rename should work. Workaround
4166 if (!FileUtils.copyFile(scanFile, new File(newPackage.mPath))) {
4167 Log.e(TAG, "Couldn't move package file to: " + newPackage.mPath);
4168 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004171 res.returnCode = setPermissionsLI(newPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4173 return;
4174 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004175 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 }
4177 }
4178 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4179 if (mInstaller != null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004180 mInstaller.rmdex(newPackage.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 }
4182 }
4183
4184 synchronized (mPackages) {
4185 grantPermissionsLP(newPackage, true);
4186 res.name = pkgName;
4187 res.uid = newPackage.applicationInfo.uid;
4188 res.pkg = newPackage;
4189 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004190 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4192 //to update install status
4193 mSettings.writeLP();
4194 }
4195 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004196
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004197 private File copyTempInstallFile(Uri pPackageURI,
4198 PackageInstalledInfo res) {
4199 File tmpPackageFile = createTempPackageFile();
4200 int retCode = PackageManager.INSTALL_SUCCEEDED;
4201 if (tmpPackageFile == null) {
4202 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4203 return null;
4204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004206 if (pPackageURI.getScheme().equals("file")) {
4207 final File srcPackageFile = new File(pPackageURI.getPath());
4208 // We copy the source package file to a temp file and then rename it to the
4209 // destination file in order to eliminate a window where the package directory
4210 // scanner notices the new package file but it's not completely copied yet.
4211 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
4212 Log.e(TAG, "Couldn't copy package file to temp file.");
4213 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004215 } else if (pPackageURI.getScheme().equals("content")) {
4216 ParcelFileDescriptor fd = null;
4217 try {
4218 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
4219 } catch (FileNotFoundException e) {
4220 Log.e(TAG, "Couldn't open file descriptor from download service. Failed with exception " + e);
4221 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4222 }
4223 if (fd == null) {
4224 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
4225 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4226 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 if (Config.LOGV) {
4228 Log.v(TAG, "Opened file descriptor from download service.");
4229 }
4230 ParcelFileDescriptor.AutoCloseInputStream
4231 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
4232 // We copy the source package file to a temp file and then rename it to the
4233 // destination file in order to eliminate a window where the package directory
4234 // scanner notices the new package file but it's not completely copied yet.
4235 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
4236 Log.e(TAG, "Couldn't copy package stream to temp file.");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004237 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004240 } else {
4241 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
4242 retCode = PackageManager.INSTALL_FAILED_INVALID_URI;
4243 }
4244
4245 res.returnCode = retCode;
4246 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
4247 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4248 tmpPackageFile.delete();
4249 }
4250 return null;
4251 }
4252 return tmpPackageFile;
4253 }
4254
4255 private void installPackageLI(Uri pPackageURI,
4256 int pFlags, boolean newInstall, String installerPackageName,
4257 File tmpPackageFile, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004258 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
4259 boolean onSd = ((pFlags & PackageManager.INSTALL_ON_SDCARD) != 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004260 boolean replacingExistingPackage = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004261 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
4262 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004263 // Result object to be returned
4264 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4265
4266 main_flow: try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 // Retrieve PackageSettings and parse package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004268 int parseFlags = PackageParser.PARSE_CHATTY |
4269 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
4270 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 parseFlags |= mDefParseFlags;
4272 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4273 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004274 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004275 null, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 if (pkg == null) {
4277 res.returnCode = pp.getParseError();
4278 break main_flow;
4279 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004280 String pkgName = res.name = pkg.packageName;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004281 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4282 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4283 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4284 break main_flow;
4285 }
4286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4288 res.returnCode = pp.getParseError();
4289 break main_flow;
4290 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 synchronized (mPackages) {
4293 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004294 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 && mPackages.containsKey(pkgName)) {
4296 replacingExistingPackage = true;
4297 }
4298 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 if(replacingExistingPackage) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004301 replacePackageLI(pkg, parseFlags, scanMode,
4302 installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004304 installNewPackageLI(pkg, parseFlags, scanMode,
4305 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 }
4307 } finally {
4308 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4309 tmpPackageFile.delete();
4310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 }
4312 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004313
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004314 private int setPermissionsLI(PackageParser.Package newPackage) {
4315 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 int retCode;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004317 if ((newPackage.applicationInfo.flags
4318 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
4319 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 try {
4321 extractPublicFiles(newPackage, destResourceFile);
4322 } catch (IOException e) {
4323 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
4324 " forward-locked app.");
4325 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4326 } finally {
4327 //TODO clean up the extracted public files
4328 }
4329 if (mInstaller != null) {
4330 retCode = mInstaller.setForwardLockPerm(pkgName,
4331 newPackage.applicationInfo.uid);
4332 } else {
4333 final int filePermissions =
4334 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004335 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 newPackage.applicationInfo.uid);
4337 }
4338 } else {
4339 final int filePermissions =
4340 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4341 |FileUtils.S_IROTH;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004342 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 }
4344 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004345 Log.e(TAG, "Couldn't set new package file permissions for " +
4346 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 + ". The return code was: " + retCode);
4348 }
4349 return PackageManager.INSTALL_SUCCEEDED;
4350 }
4351
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004352 private boolean isForwardLocked(PackageParser.Package pkg) {
4353 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354 }
4355
4356 private void extractPublicFiles(PackageParser.Package newPackage,
4357 File publicZipFile) throws IOException {
4358 final ZipOutputStream publicZipOutStream =
4359 new ZipOutputStream(new FileOutputStream(publicZipFile));
4360 final ZipFile privateZip = new ZipFile(newPackage.mPath);
4361
4362 // Copy manifest, resources.arsc and res directory to public zip
4363
4364 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
4365 while (privateZipEntries.hasMoreElements()) {
4366 final ZipEntry zipEntry = privateZipEntries.nextElement();
4367 final String zipEntryName = zipEntry.getName();
4368 if ("AndroidManifest.xml".equals(zipEntryName)
4369 || "resources.arsc".equals(zipEntryName)
4370 || zipEntryName.startsWith("res/")) {
4371 try {
4372 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
4373 } catch (IOException e) {
4374 try {
4375 publicZipOutStream.close();
4376 throw e;
4377 } finally {
4378 publicZipFile.delete();
4379 }
4380 }
4381 }
4382 }
4383
4384 publicZipOutStream.close();
4385 FileUtils.setPermissions(
4386 publicZipFile.getAbsolutePath(),
4387 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4388 -1, -1);
4389 }
4390
4391 private static void copyZipEntry(ZipEntry zipEntry,
4392 ZipFile inZipFile,
4393 ZipOutputStream outZipStream) throws IOException {
4394 byte[] buffer = new byte[4096];
4395 int num;
4396
4397 ZipEntry newEntry;
4398 if (zipEntry.getMethod() == ZipEntry.STORED) {
4399 // Preserve the STORED method of the input entry.
4400 newEntry = new ZipEntry(zipEntry);
4401 } else {
4402 // Create a new entry so that the compressed len is recomputed.
4403 newEntry = new ZipEntry(zipEntry.getName());
4404 }
4405 outZipStream.putNextEntry(newEntry);
4406
4407 InputStream data = inZipFile.getInputStream(zipEntry);
4408 while ((num = data.read(buffer)) > 0) {
4409 outZipStream.write(buffer, 0, num);
4410 }
4411 outZipStream.flush();
4412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 private void deleteTempPackageFiles() {
4415 FilenameFilter filter = new FilenameFilter() {
4416 public boolean accept(File dir, String name) {
4417 return name.startsWith("vmdl") && name.endsWith(".tmp");
4418 }
4419 };
4420 String tmpFilesList[] = mAppInstallDir.list(filter);
4421 if(tmpFilesList == null) {
4422 return;
4423 }
4424 for(int i = 0; i < tmpFilesList.length; i++) {
4425 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4426 tmpFile.delete();
4427 }
4428 }
4429
4430 private File createTempPackageFile() {
4431 File tmpPackageFile;
4432 try {
4433 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
4434 } catch (IOException e) {
4435 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4436 return null;
4437 }
4438 try {
4439 FileUtils.setPermissions(
4440 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4441 -1, -1);
4442 } catch (IOException e) {
4443 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4444 return null;
4445 }
4446 return tmpPackageFile;
4447 }
4448
4449 public void deletePackage(final String packageName,
4450 final IPackageDeleteObserver observer,
4451 final int flags) {
4452 mContext.enforceCallingOrSelfPermission(
4453 android.Manifest.permission.DELETE_PACKAGES, null);
4454 // Queue up an async operation since the package deletion may take a little while.
4455 mHandler.post(new Runnable() {
4456 public void run() {
4457 mHandler.removeCallbacks(this);
4458 final boolean succeded = deletePackageX(packageName, true, true, flags);
4459 if (observer != null) {
4460 try {
4461 observer.packageDeleted(succeded);
4462 } catch (RemoteException e) {
4463 Log.i(TAG, "Observer no longer exists.");
4464 } //end catch
4465 } //end if
4466 } //end run
4467 });
4468 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 /**
4471 * This method is an internal method that could be get invoked either
4472 * to delete an installed package or to clean up a failed installation.
4473 * After deleting an installed package, a broadcast is sent to notify any
4474 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004475 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 * installation wouldn't have sent the initial broadcast either
4477 * The key steps in deleting a package are
4478 * deleting the package information in internal structures like mPackages,
4479 * deleting the packages base directories through installd
4480 * updating mSettings to reflect current status
4481 * persisting settings for later use
4482 * sending a broadcast if necessary
4483 */
4484
4485 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4486 boolean deleteCodeAndResources, int flags) {
4487 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004488 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489
4490 synchronized (mInstallLock) {
4491 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004495 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4496 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4497
4498 // If the removed package was a system update, the old system packaged
4499 // was re-enabled; we need to broadcast this information
4500 if (systemUpdate) {
4501 Bundle extras = new Bundle(1);
4502 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4503 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4504
4505 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4506 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 }
4509 return res;
4510 }
4511
4512 static class PackageRemovedInfo {
4513 String removedPackage;
4514 int uid = -1;
4515 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004516 boolean isRemovedPackageSystemUpdate = false;
4517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518 void sendBroadcast(boolean fullRemove, boolean replacing) {
4519 Bundle extras = new Bundle(1);
4520 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4521 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4522 if (replacing) {
4523 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4524 }
4525 if (removedPackage != null) {
4526 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4527 }
4528 if (removedUid >= 0) {
4529 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4530 }
4531 }
4532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 /*
4535 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4536 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004537 * make sure this flag is set for partially installed apps. If not its meaningless to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 * delete a partially installed application.
4539 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004540 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004541 int flags) {
4542 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004543 if (outInfo != null) {
4544 outInfo.removedPackage = packageName;
4545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004546 removePackageLI(p, true);
4547 // Retrieve object to delete permissions for shared user later on
4548 PackageSetting deletedPs;
4549 synchronized (mPackages) {
4550 deletedPs = mSettings.mPackages.get(packageName);
4551 }
4552 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004553 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004554 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004555 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 if (retCode < 0) {
4557 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4558 + packageName + ", retcode=" + retCode);
4559 // we don't consider this to be a failure of the core package deletion
4560 }
4561 } else {
4562 //for emulator
4563 PackageParser.Package pkg = mPackages.get(packageName);
4564 File dataDir = new File(pkg.applicationInfo.dataDir);
4565 dataDir.delete();
4566 }
4567 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004568 if (outInfo != null) {
4569 outInfo.removedUid = mSettings.removePackageLP(packageName);
4570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004571 }
4572 }
4573 synchronized (mPackages) {
4574 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4575 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004576 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 }
4578 // Save settings now
4579 mSettings.writeLP ();
4580 }
4581 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 /*
4584 * Tries to delete system package.
4585 */
4586 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004587 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 ApplicationInfo applicationInfo = p.applicationInfo;
4589 //applicable for non-partially installed applications only
4590 if (applicationInfo == null) {
4591 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4592 return false;
4593 }
4594 PackageSetting ps = null;
4595 // Confirm if the system package has been updated
4596 // An updated system app can be deleted. This will also have to restore
4597 // the system pkg from system partition
4598 synchronized (mPackages) {
4599 ps = mSettings.getDisabledSystemPkg(p.packageName);
4600 }
4601 if (ps == null) {
4602 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4603 return false;
4604 } else {
4605 Log.i(TAG, "Deleting system pkg from data partition");
4606 }
4607 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004608 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004609 boolean deleteCodeAndResources = false;
4610 if (ps.versionCode < p.mVersionCode) {
4611 // Delete code and resources for downgrades
4612 deleteCodeAndResources = true;
4613 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4614 flags &= ~PackageManager.DONT_DELETE_DATA;
4615 }
4616 } else {
4617 // Preserve data by setting flag
4618 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4619 flags |= PackageManager.DONT_DELETE_DATA;
4620 }
4621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4623 if (!ret) {
4624 return false;
4625 }
4626 synchronized (mPackages) {
4627 // Reinstate the old system package
4628 mSettings.enableSystemPackageLP(p.packageName);
4629 }
4630 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004631 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004633 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 if (newPkg == null) {
4636 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4637 return false;
4638 }
4639 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07004640 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 mSettings.writeLP();
4642 }
4643 return true;
4644 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004645
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004646 private void deletePackageResourcesLI(String packageName,
4647 String sourceDir, String publicSourceDir) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004648 if (sourceDir != null) {
4649 File sourceFile = new File(sourceDir);
4650 if (!sourceFile.exists()) {
4651 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4652 }
4653 // Delete application's code and resources
4654 sourceFile.delete();
4655 if (mInstaller != null) {
4656 int retCode = mInstaller.rmdex(sourceFile.toString());
4657 if (retCode < 0) {
4658 Log.w(TAG, "Couldn't remove dex file for package: "
4659 + packageName + " at location "
4660 + sourceFile.toString() + ", retcode=" + retCode);
4661 // we don't consider this to be a failure of the core package deletion
4662 }
4663 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004664 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004665 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4666 final File publicSourceFile = new File(publicSourceDir);
4667 if (!publicSourceFile.exists()) {
4668 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4669 }
4670 if (publicSourceFile.exists()) {
4671 publicSourceFile.delete();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004672 }
4673 }
4674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4677 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4678 ApplicationInfo applicationInfo = p.applicationInfo;
4679 if (applicationInfo == null) {
4680 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4681 return false;
4682 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004683 if (outInfo != null) {
4684 outInfo.uid = applicationInfo.uid;
4685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686
4687 // Delete package data from internal structures and also remove data if flag is set
4688 removePackageDataLI(p, outInfo, flags);
4689
4690 // Delete application code and resources
4691 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004692 deletePackageResourcesLI(applicationInfo.packageName,
4693 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 }
4695 return true;
4696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 /*
4699 * This method handles package deletion in general
4700 */
4701 private boolean deletePackageLI(String packageName,
4702 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4703 if (packageName == null) {
4704 Log.w(TAG, "Attempt to delete null packageName.");
4705 return false;
4706 }
4707 PackageParser.Package p;
4708 boolean dataOnly = false;
4709 synchronized (mPackages) {
4710 p = mPackages.get(packageName);
4711 if (p == null) {
4712 //this retrieves partially installed apps
4713 dataOnly = true;
4714 PackageSetting ps = mSettings.mPackages.get(packageName);
4715 if (ps == null) {
4716 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4717 return false;
4718 }
4719 p = ps.pkg;
4720 }
4721 }
4722 if (p == null) {
4723 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4724 return false;
4725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 if (dataOnly) {
4728 // Delete application data first
4729 removePackageDataLI(p, outInfo, flags);
4730 return true;
4731 }
4732 // At this point the package should have ApplicationInfo associated with it
4733 if (p.applicationInfo == null) {
4734 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4735 return false;
4736 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004737 boolean onSd = (p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0;
4738 // Mount sd container if needed
4739 if (onSd) {
4740 // TODO Better error handling from MountService api later
4741 mountSdDir(p.packageName, Process.SYSTEM_UID) ;
4742 }
4743 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004744 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4745 Log.i(TAG, "Removing system package:"+p.packageName);
4746 // When an updated system application is deleted we delete the existing resources as well and
4747 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004748 ret = deleteSystemPackageLI(p, flags, outInfo);
4749 } else {
4750 Log.i(TAG, "Removing non-system package:"+p.packageName);
4751 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004752 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004753 if (ret && onSd) {
4754 // Post a delayed destroy on the container since there might
4755 // be active processes holding open file handles to package
4756 // resources which will get killed by the process killer when
4757 // destroying the container. This might even kill the current
4758 // process and crash the system. Delay the destroy a bit so
4759 // that the active processes get to handle the uninstall broadcasts.
4760 sendDelayedDestroySdDir(packageName);
4761 }
4762 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004763 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004765 public void clearApplicationUserData(final String packageName,
4766 final IPackageDataObserver observer) {
4767 mContext.enforceCallingOrSelfPermission(
4768 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4769 // Queue up an async operation since the package deletion may take a little while.
4770 mHandler.post(new Runnable() {
4771 public void run() {
4772 mHandler.removeCallbacks(this);
4773 final boolean succeeded;
4774 synchronized (mInstallLock) {
4775 succeeded = clearApplicationUserDataLI(packageName);
4776 }
4777 if (succeeded) {
4778 // invoke DeviceStorageMonitor's update method to clear any notifications
4779 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4780 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4781 if (dsm != null) {
4782 dsm.updateMemory();
4783 }
4784 }
4785 if(observer != null) {
4786 try {
4787 observer.onRemoveCompleted(packageName, succeeded);
4788 } catch (RemoteException e) {
4789 Log.i(TAG, "Observer no longer exists.");
4790 }
4791 } //end if observer
4792 } //end run
4793 });
4794 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004796 private boolean clearApplicationUserDataLI(String packageName) {
4797 if (packageName == null) {
4798 Log.w(TAG, "Attempt to delete null packageName.");
4799 return false;
4800 }
4801 PackageParser.Package p;
4802 boolean dataOnly = false;
4803 synchronized (mPackages) {
4804 p = mPackages.get(packageName);
4805 if(p == null) {
4806 dataOnly = true;
4807 PackageSetting ps = mSettings.mPackages.get(packageName);
4808 if((ps == null) || (ps.pkg == null)) {
4809 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4810 return false;
4811 }
4812 p = ps.pkg;
4813 }
4814 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004815 boolean useEncryptedFSDir = false;
4816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004817 if(!dataOnly) {
4818 //need to check this only for fully installed applications
4819 if (p == null) {
4820 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4821 return false;
4822 }
4823 final ApplicationInfo applicationInfo = p.applicationInfo;
4824 if (applicationInfo == null) {
4825 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4826 return false;
4827 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004828 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004829 }
4830 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004831 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004832 if (retCode < 0) {
4833 Log.w(TAG, "Couldn't remove cache files for package: "
4834 + packageName);
4835 return false;
4836 }
4837 }
4838 return true;
4839 }
4840
4841 public void deleteApplicationCacheFiles(final String packageName,
4842 final IPackageDataObserver observer) {
4843 mContext.enforceCallingOrSelfPermission(
4844 android.Manifest.permission.DELETE_CACHE_FILES, null);
4845 // Queue up an async operation since the package deletion may take a little while.
4846 mHandler.post(new Runnable() {
4847 public void run() {
4848 mHandler.removeCallbacks(this);
4849 final boolean succeded;
4850 synchronized (mInstallLock) {
4851 succeded = deleteApplicationCacheFilesLI(packageName);
4852 }
4853 if(observer != null) {
4854 try {
4855 observer.onRemoveCompleted(packageName, succeded);
4856 } catch (RemoteException e) {
4857 Log.i(TAG, "Observer no longer exists.");
4858 }
4859 } //end if observer
4860 } //end run
4861 });
4862 }
4863
4864 private boolean deleteApplicationCacheFilesLI(String packageName) {
4865 if (packageName == null) {
4866 Log.w(TAG, "Attempt to delete null packageName.");
4867 return false;
4868 }
4869 PackageParser.Package p;
4870 synchronized (mPackages) {
4871 p = mPackages.get(packageName);
4872 }
4873 if (p == null) {
4874 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4875 return false;
4876 }
4877 final ApplicationInfo applicationInfo = p.applicationInfo;
4878 if (applicationInfo == null) {
4879 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4880 return false;
4881 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004882 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004884 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004885 if (retCode < 0) {
4886 Log.w(TAG, "Couldn't remove cache files for package: "
4887 + packageName);
4888 return false;
4889 }
4890 }
4891 return true;
4892 }
4893
4894 public void getPackageSizeInfo(final String packageName,
4895 final IPackageStatsObserver observer) {
4896 mContext.enforceCallingOrSelfPermission(
4897 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4898 // Queue up an async operation since the package deletion may take a little while.
4899 mHandler.post(new Runnable() {
4900 public void run() {
4901 mHandler.removeCallbacks(this);
4902 PackageStats lStats = new PackageStats(packageName);
4903 final boolean succeded;
4904 synchronized (mInstallLock) {
4905 succeded = getPackageSizeInfoLI(packageName, lStats);
4906 }
4907 if(observer != null) {
4908 try {
4909 observer.onGetStatsCompleted(lStats, succeded);
4910 } catch (RemoteException e) {
4911 Log.i(TAG, "Observer no longer exists.");
4912 }
4913 } //end if observer
4914 } //end run
4915 });
4916 }
4917
4918 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4919 if (packageName == null) {
4920 Log.w(TAG, "Attempt to get size of null packageName.");
4921 return false;
4922 }
4923 PackageParser.Package p;
4924 boolean dataOnly = false;
4925 synchronized (mPackages) {
4926 p = mPackages.get(packageName);
4927 if(p == null) {
4928 dataOnly = true;
4929 PackageSetting ps = mSettings.mPackages.get(packageName);
4930 if((ps == null) || (ps.pkg == null)) {
4931 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4932 return false;
4933 }
4934 p = ps.pkg;
4935 }
4936 }
4937 String publicSrcDir = null;
4938 if(!dataOnly) {
4939 final ApplicationInfo applicationInfo = p.applicationInfo;
4940 if (applicationInfo == null) {
4941 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4942 return false;
4943 }
4944 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4945 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004946 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004947 if (mInstaller != null) {
4948 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08004949 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004950 if (res < 0) {
4951 return false;
4952 } else {
4953 return true;
4954 }
4955 }
4956 return true;
4957 }
4958
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 public void addPackageToPreferred(String packageName) {
4961 mContext.enforceCallingOrSelfPermission(
4962 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004963 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 }
4965
4966 public void removePackageFromPreferred(String packageName) {
4967 mContext.enforceCallingOrSelfPermission(
4968 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004969 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004970 }
4971
4972 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004973 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004974 }
4975
4976 public void addPreferredActivity(IntentFilter filter, int match,
4977 ComponentName[] set, ComponentName activity) {
4978 mContext.enforceCallingOrSelfPermission(
4979 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4980
4981 synchronized (mPackages) {
4982 Log.i(TAG, "Adding preferred activity " + activity + ":");
4983 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4984 mSettings.mPreferredActivities.addFilter(
4985 new PreferredActivity(filter, match, set, activity));
4986 mSettings.writeLP();
4987 }
4988 }
4989
Satish Sampath8dbe6122009-06-02 23:35:54 +01004990 public void replacePreferredActivity(IntentFilter filter, int match,
4991 ComponentName[] set, ComponentName activity) {
4992 mContext.enforceCallingOrSelfPermission(
4993 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4994 if (filter.countActions() != 1) {
4995 throw new IllegalArgumentException(
4996 "replacePreferredActivity expects filter to have only 1 action.");
4997 }
4998 if (filter.countCategories() != 1) {
4999 throw new IllegalArgumentException(
5000 "replacePreferredActivity expects filter to have only 1 category.");
5001 }
5002 if (filter.countDataAuthorities() != 0
5003 || filter.countDataPaths() != 0
5004 || filter.countDataSchemes() != 0
5005 || filter.countDataTypes() != 0) {
5006 throw new IllegalArgumentException(
5007 "replacePreferredActivity expects filter to have no data authorities, " +
5008 "paths, schemes or types.");
5009 }
5010 synchronized (mPackages) {
5011 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5012 String action = filter.getAction(0);
5013 String category = filter.getCategory(0);
5014 while (it.hasNext()) {
5015 PreferredActivity pa = it.next();
5016 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5017 it.remove();
5018 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5019 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5020 }
5021 }
5022 addPreferredActivity(filter, match, set, activity);
5023 }
5024 }
5025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026 public void clearPackagePreferredActivities(String packageName) {
5027 mContext.enforceCallingOrSelfPermission(
5028 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5029
5030 synchronized (mPackages) {
5031 if (clearPackagePreferredActivitiesLP(packageName)) {
5032 mSettings.writeLP();
5033 }
5034 }
5035 }
5036
5037 boolean clearPackagePreferredActivitiesLP(String packageName) {
5038 boolean changed = false;
5039 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5040 while (it.hasNext()) {
5041 PreferredActivity pa = it.next();
5042 if (pa.mActivity.getPackageName().equals(packageName)) {
5043 it.remove();
5044 changed = true;
5045 }
5046 }
5047 return changed;
5048 }
5049
5050 public int getPreferredActivities(List<IntentFilter> outFilters,
5051 List<ComponentName> outActivities, String packageName) {
5052
5053 int num = 0;
5054 synchronized (mPackages) {
5055 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5056 while (it.hasNext()) {
5057 PreferredActivity pa = it.next();
5058 if (packageName == null
5059 || pa.mActivity.getPackageName().equals(packageName)) {
5060 if (outFilters != null) {
5061 outFilters.add(new IntentFilter(pa));
5062 }
5063 if (outActivities != null) {
5064 outActivities.add(pa.mActivity);
5065 }
5066 }
5067 }
5068 }
5069
5070 return num;
5071 }
5072
5073 public void setApplicationEnabledSetting(String appPackageName,
5074 int newState, int flags) {
5075 setEnabledSetting(appPackageName, null, newState, flags);
5076 }
5077
5078 public void setComponentEnabledSetting(ComponentName componentName,
5079 int newState, int flags) {
5080 setEnabledSetting(componentName.getPackageName(),
5081 componentName.getClassName(), newState, flags);
5082 }
5083
5084 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005085 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5087 || newState == COMPONENT_ENABLED_STATE_ENABLED
5088 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5089 throw new IllegalArgumentException("Invalid new component state: "
5090 + newState);
5091 }
5092 PackageSetting pkgSetting;
5093 final int uid = Binder.getCallingUid();
5094 final int permission = mContext.checkCallingPermission(
5095 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5096 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005097 boolean sendNow = false;
5098 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005099 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005100 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005101 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005103 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005105 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005107 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005108 }
5109 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005110 "Unknown component: " + packageName
5111 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 }
5113 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5114 throw new SecurityException(
5115 "Permission Denial: attempt to change component state from pid="
5116 + Binder.getCallingPid()
5117 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5118 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005119 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005120 // We're dealing with an application/package level state change
5121 pkgSetting.enabled = newState;
5122 } else {
5123 // We're dealing with a component level state change
5124 switch (newState) {
5125 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005126 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005127 break;
5128 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005129 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005130 break;
5131 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005132 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005133 break;
5134 default:
5135 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005136 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 }
5138 }
5139 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005140 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005141 components = mPendingBroadcasts.get(packageName);
5142 boolean newPackage = components == null;
5143 if (newPackage) {
5144 components = new ArrayList<String>();
5145 }
5146 if (!components.contains(componentName)) {
5147 components.add(componentName);
5148 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005149 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5150 sendNow = true;
5151 // Purge entry from pending broadcast list if another one exists already
5152 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005153 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005154 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005155 if (newPackage) {
5156 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005157 }
5158 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5159 // Schedule a message
5160 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5161 }
5162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005163 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005165 long callingId = Binder.clearCallingIdentity();
5166 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005167 if (sendNow) {
5168 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005169 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005171 } finally {
5172 Binder.restoreCallingIdentity(callingId);
5173 }
5174 }
5175
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005176 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005177 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5178 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5179 + " components=" + componentNames);
5180 Bundle extras = new Bundle(4);
5181 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5182 String nameList[] = new String[componentNames.size()];
5183 componentNames.toArray(nameList);
5184 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005185 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5186 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005187 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005188 }
5189
Jacek Surazski65e13172009-04-28 15:26:38 +02005190 public String getInstallerPackageName(String packageName) {
5191 synchronized (mPackages) {
5192 PackageSetting pkg = mSettings.mPackages.get(packageName);
5193 if (pkg == null) {
5194 throw new IllegalArgumentException("Unknown package: " + packageName);
5195 }
5196 return pkg.installerPackageName;
5197 }
5198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 public int getApplicationEnabledSetting(String appPackageName) {
5201 synchronized (mPackages) {
5202 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5203 if (pkg == null) {
5204 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5205 }
5206 return pkg.enabled;
5207 }
5208 }
5209
5210 public int getComponentEnabledSetting(ComponentName componentName) {
5211 synchronized (mPackages) {
5212 final String packageNameStr = componentName.getPackageName();
5213 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5214 if (pkg == null) {
5215 throw new IllegalArgumentException("Unknown component: " + componentName);
5216 }
5217 final String classNameStr = componentName.getClassName();
5218 return pkg.currentEnabledStateLP(classNameStr);
5219 }
5220 }
5221
5222 public void enterSafeMode() {
5223 if (!mSystemReady) {
5224 mSafeMode = true;
5225 }
5226 }
5227
5228 public void systemReady() {
5229 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005230
5231 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005232 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005233 mContext.getContentResolver(),
5234 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005235 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005236 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005237 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005239 }
5240
5241 public boolean isSafeMode() {
5242 return mSafeMode;
5243 }
5244
5245 public boolean hasSystemUidErrors() {
5246 return mHasSystemUidErrors;
5247 }
5248
5249 static String arrayToString(int[] array) {
5250 StringBuffer buf = new StringBuffer(128);
5251 buf.append('[');
5252 if (array != null) {
5253 for (int i=0; i<array.length; i++) {
5254 if (i > 0) buf.append(", ");
5255 buf.append(array[i]);
5256 }
5257 }
5258 buf.append(']');
5259 return buf.toString();
5260 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005262 @Override
5263 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5264 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5265 != PackageManager.PERMISSION_GRANTED) {
5266 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5267 + Binder.getCallingPid()
5268 + ", uid=" + Binder.getCallingUid()
5269 + " without permission "
5270 + android.Manifest.permission.DUMP);
5271 return;
5272 }
5273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274 synchronized (mPackages) {
5275 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005276 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 pw.println(" ");
5278 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005279 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005280 pw.println(" ");
5281 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005282 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005283 pw.println(" ");
5284 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005285 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 pw.println("Permissions:");
5288 {
5289 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005290 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5291 pw.print(Integer.toHexString(System.identityHashCode(p)));
5292 pw.println("):");
5293 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5294 pw.print(" uid="); pw.print(p.uid);
5295 pw.print(" gids="); pw.print(arrayToString(p.gids));
5296 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 }
5298 }
5299 pw.println(" ");
5300 pw.println("Packages:");
5301 {
5302 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005303 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5304 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5305 pw.println("):");
5306 pw.print(" userId="); pw.print(ps.userId);
5307 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5308 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5309 pw.print(" pkg="); pw.println(ps.pkg);
5310 pw.print(" codePath="); pw.println(ps.codePathString);
5311 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005313 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005314 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005315 pw.print(" supportsScreens=[");
5316 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005317 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005318 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005319 if (!first) pw.print(", ");
5320 first = false;
5321 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005323 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005324 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005325 if (!first) pw.print(", ");
5326 first = false;
5327 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005329 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005330 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005331 if (!first) pw.print(", ");
5332 first = false;
5333 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005334 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005335 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005336 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005337 if (!first) pw.print(", ");
5338 first = false;
5339 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005341 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005342 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
5343 if (!first) pw.print(", ");
5344 first = false;
5345 pw.print("anyDensity");
5346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005347 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005348 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005349 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
5350 pw.print(" signatures="); pw.println(ps.signatures);
5351 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
5352 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
5353 pw.print(" installStatus="); pw.print(ps.installStatus);
5354 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005355 if (ps.disabledComponents.size() > 0) {
5356 pw.println(" disabledComponents:");
5357 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005358 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005359 }
5360 }
5361 if (ps.enabledComponents.size() > 0) {
5362 pw.println(" enabledComponents:");
5363 for (String s : ps.enabledComponents) {
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 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005367 if (ps.grantedPermissions.size() > 0) {
5368 pw.println(" grantedPermissions:");
5369 for (String s : ps.grantedPermissions) {
5370 pw.print(" "); pw.println(s);
5371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005373 if (ps.loadedPermissions.size() > 0) {
5374 pw.println(" loadedPermissions:");
5375 for (String s : ps.loadedPermissions) {
5376 pw.print(" "); pw.println(s);
5377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 }
5379 }
5380 }
5381 pw.println(" ");
5382 pw.println("Shared Users:");
5383 {
5384 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005385 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5386 pw.print(Integer.toHexString(System.identityHashCode(su)));
5387 pw.println("):");
5388 pw.print(" userId="); pw.print(su.userId);
5389 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005390 pw.println(" grantedPermissions:");
5391 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005392 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 }
5394 pw.println(" loadedPermissions:");
5395 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005396 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 }
5398 }
5399 }
5400 pw.println(" ");
5401 pw.println("Settings parse messages:");
5402 pw.println(mSettings.mReadMessages.toString());
5403 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05005404
5405 synchronized (mProviders) {
5406 pw.println(" ");
5407 pw.println("Registered ContentProviders:");
5408 for (PackageParser.Provider p : mProviders.values()) {
5409 pw.println(" ["); pw.println(p.info.authority); pw.println("]: ");
5410 pw.println(p.toString());
5411 }
5412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005413 }
5414
5415 static final class BasePermission {
5416 final static int TYPE_NORMAL = 0;
5417 final static int TYPE_BUILTIN = 1;
5418 final static int TYPE_DYNAMIC = 2;
5419
5420 final String name;
5421 final String sourcePackage;
5422 final int type;
5423 PackageParser.Permission perm;
5424 PermissionInfo pendingInfo;
5425 int uid;
5426 int[] gids;
5427
5428 BasePermission(String _name, String _sourcePackage, int _type) {
5429 name = _name;
5430 sourcePackage = _sourcePackage;
5431 type = _type;
5432 }
5433 }
5434
5435 static class PackageSignatures {
5436 private Signature[] mSignatures;
5437
5438 PackageSignatures(Signature[] sigs) {
5439 assignSignatures(sigs);
5440 }
5441
5442 PackageSignatures() {
5443 }
5444
5445 void writeXml(XmlSerializer serializer, String tagName,
5446 ArrayList<Signature> pastSignatures) throws IOException {
5447 if (mSignatures == null) {
5448 return;
5449 }
5450 serializer.startTag(null, tagName);
5451 serializer.attribute(null, "count",
5452 Integer.toString(mSignatures.length));
5453 for (int i=0; i<mSignatures.length; i++) {
5454 serializer.startTag(null, "cert");
5455 final Signature sig = mSignatures[i];
5456 final int sigHash = sig.hashCode();
5457 final int numPast = pastSignatures.size();
5458 int j;
5459 for (j=0; j<numPast; j++) {
5460 Signature pastSig = pastSignatures.get(j);
5461 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5462 serializer.attribute(null, "index", Integer.toString(j));
5463 break;
5464 }
5465 }
5466 if (j >= numPast) {
5467 pastSignatures.add(sig);
5468 serializer.attribute(null, "index", Integer.toString(numPast));
5469 serializer.attribute(null, "key", sig.toCharsString());
5470 }
5471 serializer.endTag(null, "cert");
5472 }
5473 serializer.endTag(null, tagName);
5474 }
5475
5476 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5477 throws IOException, XmlPullParserException {
5478 String countStr = parser.getAttributeValue(null, "count");
5479 if (countStr == null) {
5480 reportSettingsProblem(Log.WARN,
5481 "Error in package manager settings: <signatures> has"
5482 + " no count at " + parser.getPositionDescription());
5483 XmlUtils.skipCurrentTag(parser);
5484 }
5485 final int count = Integer.parseInt(countStr);
5486 mSignatures = new Signature[count];
5487 int pos = 0;
5488
5489 int outerDepth = parser.getDepth();
5490 int type;
5491 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5492 && (type != XmlPullParser.END_TAG
5493 || parser.getDepth() > outerDepth)) {
5494 if (type == XmlPullParser.END_TAG
5495 || type == XmlPullParser.TEXT) {
5496 continue;
5497 }
5498
5499 String tagName = parser.getName();
5500 if (tagName.equals("cert")) {
5501 if (pos < count) {
5502 String index = parser.getAttributeValue(null, "index");
5503 if (index != null) {
5504 try {
5505 int idx = Integer.parseInt(index);
5506 String key = parser.getAttributeValue(null, "key");
5507 if (key == null) {
5508 if (idx >= 0 && idx < pastSignatures.size()) {
5509 Signature sig = pastSignatures.get(idx);
5510 if (sig != null) {
5511 mSignatures[pos] = pastSignatures.get(idx);
5512 pos++;
5513 } else {
5514 reportSettingsProblem(Log.WARN,
5515 "Error in package manager settings: <cert> "
5516 + "index " + index + " is not defined at "
5517 + parser.getPositionDescription());
5518 }
5519 } else {
5520 reportSettingsProblem(Log.WARN,
5521 "Error in package manager settings: <cert> "
5522 + "index " + index + " is out of bounds at "
5523 + parser.getPositionDescription());
5524 }
5525 } else {
5526 while (pastSignatures.size() <= idx) {
5527 pastSignatures.add(null);
5528 }
5529 Signature sig = new Signature(key);
5530 pastSignatures.set(idx, sig);
5531 mSignatures[pos] = sig;
5532 pos++;
5533 }
5534 } catch (NumberFormatException e) {
5535 reportSettingsProblem(Log.WARN,
5536 "Error in package manager settings: <cert> "
5537 + "index " + index + " is not a number at "
5538 + parser.getPositionDescription());
5539 }
5540 } else {
5541 reportSettingsProblem(Log.WARN,
5542 "Error in package manager settings: <cert> has"
5543 + " no index at " + parser.getPositionDescription());
5544 }
5545 } else {
5546 reportSettingsProblem(Log.WARN,
5547 "Error in package manager settings: too "
5548 + "many <cert> tags, expected " + count
5549 + " at " + parser.getPositionDescription());
5550 }
5551 } else {
5552 reportSettingsProblem(Log.WARN,
5553 "Unknown element under <cert>: "
5554 + parser.getName());
5555 }
5556 XmlUtils.skipCurrentTag(parser);
5557 }
5558
5559 if (pos < count) {
5560 // Should never happen -- there is an error in the written
5561 // settings -- but if it does we don't want to generate
5562 // a bad array.
5563 Signature[] newSigs = new Signature[pos];
5564 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5565 mSignatures = newSigs;
5566 }
5567 }
5568
5569 /**
5570 * If any of the given 'sigs' is contained in the existing signatures,
5571 * then completely replace the current signatures with the ones in
5572 * 'sigs'. This is used for updating an existing package to a newly
5573 * installed version.
5574 */
5575 boolean updateSignatures(Signature[] sigs, boolean update) {
5576 if (mSignatures == null) {
5577 if (update) {
5578 assignSignatures(sigs);
5579 }
5580 return true;
5581 }
5582 if (sigs == null) {
5583 return false;
5584 }
5585
5586 for (int i=0; i<sigs.length; i++) {
5587 Signature sig = sigs[i];
5588 for (int j=0; j<mSignatures.length; j++) {
5589 if (mSignatures[j].equals(sig)) {
5590 if (update) {
5591 assignSignatures(sigs);
5592 }
5593 return true;
5594 }
5595 }
5596 }
5597 return false;
5598 }
5599
5600 /**
5601 * If any of the given 'sigs' is contained in the existing signatures,
5602 * then add in any new signatures found in 'sigs'. This is used for
5603 * including a new package into an existing shared user id.
5604 */
5605 boolean mergeSignatures(Signature[] sigs, boolean update) {
5606 if (mSignatures == null) {
5607 if (update) {
5608 assignSignatures(sigs);
5609 }
5610 return true;
5611 }
5612 if (sigs == null) {
5613 return false;
5614 }
5615
5616 Signature[] added = null;
5617 int addedCount = 0;
5618 boolean haveMatch = false;
5619 for (int i=0; i<sigs.length; i++) {
5620 Signature sig = sigs[i];
5621 boolean found = false;
5622 for (int j=0; j<mSignatures.length; j++) {
5623 if (mSignatures[j].equals(sig)) {
5624 found = true;
5625 haveMatch = true;
5626 break;
5627 }
5628 }
5629
5630 if (!found) {
5631 if (added == null) {
5632 added = new Signature[sigs.length];
5633 }
5634 added[i] = sig;
5635 addedCount++;
5636 }
5637 }
5638
5639 if (!haveMatch) {
5640 // Nothing matched -- reject the new signatures.
5641 return false;
5642 }
5643 if (added == null) {
5644 // Completely matched -- nothing else to do.
5645 return true;
5646 }
5647
5648 // Add additional signatures in.
5649 if (update) {
5650 Signature[] total = new Signature[addedCount+mSignatures.length];
5651 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5652 int j = mSignatures.length;
5653 for (int i=0; i<added.length; i++) {
5654 if (added[i] != null) {
5655 total[j] = added[i];
5656 j++;
5657 }
5658 }
5659 mSignatures = total;
5660 }
5661 return true;
5662 }
5663
5664 private void assignSignatures(Signature[] sigs) {
5665 if (sigs == null) {
5666 mSignatures = null;
5667 return;
5668 }
5669 mSignatures = new Signature[sigs.length];
5670 for (int i=0; i<sigs.length; i++) {
5671 mSignatures[i] = sigs[i];
5672 }
5673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 @Override
5676 public String toString() {
5677 StringBuffer buf = new StringBuffer(128);
5678 buf.append("PackageSignatures{");
5679 buf.append(Integer.toHexString(System.identityHashCode(this)));
5680 buf.append(" [");
5681 if (mSignatures != null) {
5682 for (int i=0; i<mSignatures.length; i++) {
5683 if (i > 0) buf.append(", ");
5684 buf.append(Integer.toHexString(
5685 System.identityHashCode(mSignatures[i])));
5686 }
5687 }
5688 buf.append("]}");
5689 return buf.toString();
5690 }
5691 }
5692
5693 static class PreferredActivity extends IntentFilter {
5694 final int mMatch;
5695 final String[] mSetPackages;
5696 final String[] mSetClasses;
5697 final String[] mSetComponents;
5698 final ComponentName mActivity;
5699 final String mShortActivity;
5700 String mParseError;
5701
5702 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5703 ComponentName activity) {
5704 super(filter);
5705 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5706 mActivity = activity;
5707 mShortActivity = activity.flattenToShortString();
5708 mParseError = null;
5709 if (set != null) {
5710 final int N = set.length;
5711 String[] myPackages = new String[N];
5712 String[] myClasses = new String[N];
5713 String[] myComponents = new String[N];
5714 for (int i=0; i<N; i++) {
5715 ComponentName cn = set[i];
5716 if (cn == null) {
5717 mSetPackages = null;
5718 mSetClasses = null;
5719 mSetComponents = null;
5720 return;
5721 }
5722 myPackages[i] = cn.getPackageName().intern();
5723 myClasses[i] = cn.getClassName().intern();
5724 myComponents[i] = cn.flattenToShortString().intern();
5725 }
5726 mSetPackages = myPackages;
5727 mSetClasses = myClasses;
5728 mSetComponents = myComponents;
5729 } else {
5730 mSetPackages = null;
5731 mSetClasses = null;
5732 mSetComponents = null;
5733 }
5734 }
5735
5736 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5737 IOException {
5738 mShortActivity = parser.getAttributeValue(null, "name");
5739 mActivity = ComponentName.unflattenFromString(mShortActivity);
5740 if (mActivity == null) {
5741 mParseError = "Bad activity name " + mShortActivity;
5742 }
5743 String matchStr = parser.getAttributeValue(null, "match");
5744 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5745 String setCountStr = parser.getAttributeValue(null, "set");
5746 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5747
5748 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5749 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5750 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5751
5752 int setPos = 0;
5753
5754 int outerDepth = parser.getDepth();
5755 int type;
5756 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5757 && (type != XmlPullParser.END_TAG
5758 || parser.getDepth() > outerDepth)) {
5759 if (type == XmlPullParser.END_TAG
5760 || type == XmlPullParser.TEXT) {
5761 continue;
5762 }
5763
5764 String tagName = parser.getName();
5765 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5766 // + parser.getDepth() + " tag=" + tagName);
5767 if (tagName.equals("set")) {
5768 String name = parser.getAttributeValue(null, "name");
5769 if (name == null) {
5770 if (mParseError == null) {
5771 mParseError = "No name in set tag in preferred activity "
5772 + mShortActivity;
5773 }
5774 } else if (setPos >= setCount) {
5775 if (mParseError == null) {
5776 mParseError = "Too many set tags in preferred activity "
5777 + mShortActivity;
5778 }
5779 } else {
5780 ComponentName cn = ComponentName.unflattenFromString(name);
5781 if (cn == null) {
5782 if (mParseError == null) {
5783 mParseError = "Bad set name " + name + " in preferred activity "
5784 + mShortActivity;
5785 }
5786 } else {
5787 myPackages[setPos] = cn.getPackageName();
5788 myClasses[setPos] = cn.getClassName();
5789 myComponents[setPos] = name;
5790 setPos++;
5791 }
5792 }
5793 XmlUtils.skipCurrentTag(parser);
5794 } else if (tagName.equals("filter")) {
5795 //Log.i(TAG, "Starting to parse filter...");
5796 readFromXml(parser);
5797 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5798 // + parser.getDepth() + " tag=" + parser.getName());
5799 } else {
5800 reportSettingsProblem(Log.WARN,
5801 "Unknown element under <preferred-activities>: "
5802 + parser.getName());
5803 XmlUtils.skipCurrentTag(parser);
5804 }
5805 }
5806
5807 if (setPos != setCount) {
5808 if (mParseError == null) {
5809 mParseError = "Not enough set tags (expected " + setCount
5810 + " but found " + setPos + ") in " + mShortActivity;
5811 }
5812 }
5813
5814 mSetPackages = myPackages;
5815 mSetClasses = myClasses;
5816 mSetComponents = myComponents;
5817 }
5818
5819 public void writeToXml(XmlSerializer serializer) throws IOException {
5820 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5821 serializer.attribute(null, "name", mShortActivity);
5822 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5823 serializer.attribute(null, "set", Integer.toString(NS));
5824 for (int s=0; s<NS; s++) {
5825 serializer.startTag(null, "set");
5826 serializer.attribute(null, "name", mSetComponents[s]);
5827 serializer.endTag(null, "set");
5828 }
5829 serializer.startTag(null, "filter");
5830 super.writeToXml(serializer);
5831 serializer.endTag(null, "filter");
5832 }
5833
5834 boolean sameSet(List<ResolveInfo> query, int priority) {
5835 if (mSetPackages == null) return false;
5836 final int NQ = query.size();
5837 final int NS = mSetPackages.length;
5838 int numMatch = 0;
5839 for (int i=0; i<NQ; i++) {
5840 ResolveInfo ri = query.get(i);
5841 if (ri.priority != priority) continue;
5842 ActivityInfo ai = ri.activityInfo;
5843 boolean good = false;
5844 for (int j=0; j<NS; j++) {
5845 if (mSetPackages[j].equals(ai.packageName)
5846 && mSetClasses[j].equals(ai.name)) {
5847 numMatch++;
5848 good = true;
5849 break;
5850 }
5851 }
5852 if (!good) return false;
5853 }
5854 return numMatch == NS;
5855 }
5856 }
5857
5858 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07005859 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 HashSet<String> grantedPermissions = new HashSet<String>();
5862 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 GrantedPermissions(int pkgFlags) {
5867 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5868 }
5869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 /**
5872 * Settings base class for pending and resolved classes.
5873 */
5874 static class PackageSettingBase extends GrantedPermissions {
5875 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005876 File codePath;
5877 String codePathString;
5878 File resourcePath;
5879 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 private long timeStamp;
5881 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005882 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883
5884 PackageSignatures signatures = new PackageSignatures();
5885
5886 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 /* Explicitly disabled components */
5889 HashSet<String> disabledComponents = new HashSet<String>(0);
5890 /* Explicitly enabled components */
5891 HashSet<String> enabledComponents = new HashSet<String>(0);
5892 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5893 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005894
Jacek Surazski65e13172009-04-28 15:26:38 +02005895 /* package name of the app that installed this package */
5896 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897
5898 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005899 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 super(pkgFlags);
5901 this.name = name;
5902 this.codePath = codePath;
5903 this.codePathString = codePath.toString();
5904 this.resourcePath = resourcePath;
5905 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005906 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 }
5908
Jacek Surazski65e13172009-04-28 15:26:38 +02005909 public void setInstallerPackageName(String packageName) {
5910 installerPackageName = packageName;
5911 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005912
Jacek Surazski65e13172009-04-28 15:26:38 +02005913 String getInstallerPackageName() {
5914 return installerPackageName;
5915 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 public void setInstallStatus(int newStatus) {
5918 installStatus = newStatus;
5919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 public int getInstallStatus() {
5922 return installStatus;
5923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 public void setTimeStamp(long newStamp) {
5926 if (newStamp != timeStamp) {
5927 timeStamp = newStamp;
5928 timeStampString = Long.toString(newStamp);
5929 }
5930 }
5931
5932 public void setTimeStamp(long newStamp, String newStampStr) {
5933 timeStamp = newStamp;
5934 timeStampString = newStampStr;
5935 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 public long getTimeStamp() {
5938 return timeStamp;
5939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005941 public String getTimeStampStr() {
5942 return timeStampString;
5943 }
5944
5945 public void copyFrom(PackageSettingBase base) {
5946 grantedPermissions = base.grantedPermissions;
5947 gids = base.gids;
5948 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 timeStamp = base.timeStamp;
5951 timeStampString = base.timeStampString;
5952 signatures = base.signatures;
5953 permissionsFixed = base.permissionsFixed;
5954 disabledComponents = base.disabledComponents;
5955 enabledComponents = base.enabledComponents;
5956 enabled = base.enabled;
5957 installStatus = base.installStatus;
5958 }
5959
5960 void enableComponentLP(String componentClassName) {
5961 disabledComponents.remove(componentClassName);
5962 enabledComponents.add(componentClassName);
5963 }
5964
5965 void disableComponentLP(String componentClassName) {
5966 enabledComponents.remove(componentClassName);
5967 disabledComponents.add(componentClassName);
5968 }
5969
5970 void restoreComponentLP(String componentClassName) {
5971 enabledComponents.remove(componentClassName);
5972 disabledComponents.remove(componentClassName);
5973 }
5974
5975 int currentEnabledStateLP(String componentName) {
5976 if (enabledComponents.contains(componentName)) {
5977 return COMPONENT_ENABLED_STATE_ENABLED;
5978 } else if (disabledComponents.contains(componentName)) {
5979 return COMPONENT_ENABLED_STATE_DISABLED;
5980 } else {
5981 return COMPONENT_ENABLED_STATE_DEFAULT;
5982 }
5983 }
5984 }
5985
5986 /**
5987 * Settings data for a particular package we know about.
5988 */
5989 static final class PackageSetting extends PackageSettingBase {
5990 int userId;
5991 PackageParser.Package pkg;
5992 SharedUserSetting sharedUser;
5993
5994 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005995 int pVersionCode, int pkgFlags) {
5996 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 @Override
6000 public String toString() {
6001 return "PackageSetting{"
6002 + Integer.toHexString(System.identityHashCode(this))
6003 + " " + name + "/" + userId + "}";
6004 }
6005 }
6006
6007 /**
6008 * Settings data for a particular shared user ID we know about.
6009 */
6010 static final class SharedUserSetting extends GrantedPermissions {
6011 final String name;
6012 int userId;
6013 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6014 final PackageSignatures signatures = new PackageSignatures();
6015
6016 SharedUserSetting(String _name, int _pkgFlags) {
6017 super(_pkgFlags);
6018 name = _name;
6019 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 @Override
6022 public String toString() {
6023 return "SharedUserSetting{"
6024 + Integer.toHexString(System.identityHashCode(this))
6025 + " " + name + "/" + userId + "}";
6026 }
6027 }
6028
6029 /**
6030 * Holds information about dynamic settings.
6031 */
6032 private static final class Settings {
6033 private final File mSettingsFilename;
6034 private final File mBackupSettingsFilename;
6035 private final HashMap<String, PackageSetting> mPackages =
6036 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 // List of replaced system applications
6038 final HashMap<String, PackageSetting> mDisabledSysPackages =
6039 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 // The user's preferred activities associated with particular intent
6042 // filters.
6043 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6044 new IntentResolver<PreferredActivity, PreferredActivity>() {
6045 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006046 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006048 out.print(prefix); out.print(
6049 Integer.toHexString(System.identityHashCode(filter)));
6050 out.print(' ');
6051 out.print(filter.mActivity.flattenToShortString());
6052 out.print(" match=0x");
6053 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006055 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006057 out.print(prefix); out.print(" ");
6058 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 }
6060 }
6061 }
6062 };
6063 private final HashMap<String, SharedUserSetting> mSharedUsers =
6064 new HashMap<String, SharedUserSetting>();
6065 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6066 private final SparseArray<Object> mOtherUserIds =
6067 new SparseArray<Object>();
6068
6069 // For reading/writing settings file.
6070 private final ArrayList<Signature> mPastSignatures =
6071 new ArrayList<Signature>();
6072
6073 // Mapping from permission names to info about them.
6074 final HashMap<String, BasePermission> mPermissions =
6075 new HashMap<String, BasePermission>();
6076
6077 // Mapping from permission tree names to info about them.
6078 final HashMap<String, BasePermission> mPermissionTrees =
6079 new HashMap<String, BasePermission>();
6080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 private final StringBuilder mReadMessages = new StringBuilder();
6082
6083 private static final class PendingPackage extends PackageSettingBase {
6084 final int sharedId;
6085
6086 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006087 int sharedId, int pVersionCode, int pkgFlags) {
6088 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 this.sharedId = sharedId;
6090 }
6091 }
6092 private final ArrayList<PendingPackage> mPendingPackages
6093 = new ArrayList<PendingPackage>();
6094
6095 Settings() {
6096 File dataDir = Environment.getDataDirectory();
6097 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08006098 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
6099 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006101 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 FileUtils.setPermissions(systemDir.toString(),
6103 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6104 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6105 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08006106 FileUtils.setPermissions(systemSecureDir.toString(),
6107 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6108 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6109 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110 mSettingsFilename = new File(systemDir, "packages.xml");
6111 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6112 }
6113
6114 PackageSetting getPackageLP(PackageParser.Package pkg,
6115 SharedUserSetting sharedUser, File codePath, File resourcePath,
6116 int pkgFlags, boolean create, boolean add) {
6117 final String name = pkg.packageName;
6118 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006119 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 return p;
6121 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006122
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006123 PackageSetting peekPackageLP(String name) {
6124 return mPackages.get(name);
6125 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 PackageSetting p = mPackages.get(name);
6127 if (p != null && p.codePath.getPath().equals(codePath)) {
6128 return p;
6129 }
6130 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006131 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006134 void setInstallStatus(String pkgName, int status) {
6135 PackageSetting p = mPackages.get(pkgName);
6136 if(p != null) {
6137 if(p.getInstallStatus() != status) {
6138 p.setInstallStatus(status);
6139 }
6140 }
6141 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006142
Jacek Surazski65e13172009-04-28 15:26:38 +02006143 void setInstallerPackageName(String pkgName,
6144 String installerPkgName) {
6145 PackageSetting p = mPackages.get(pkgName);
6146 if(p != null) {
6147 p.setInstallerPackageName(installerPkgName);
6148 }
6149 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006150
Jacek Surazski65e13172009-04-28 15:26:38 +02006151 String getInstallerPackageName(String pkgName) {
6152 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006153 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02006154 }
6155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 int getInstallStatus(String pkgName) {
6157 PackageSetting p = mPackages.get(pkgName);
6158 if(p != null) {
6159 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 return -1;
6162 }
6163
6164 SharedUserSetting getSharedUserLP(String name,
6165 int pkgFlags, boolean create) {
6166 SharedUserSetting s = mSharedUsers.get(name);
6167 if (s == null) {
6168 if (!create) {
6169 return null;
6170 }
6171 s = new SharedUserSetting(name, pkgFlags);
6172 if (MULTIPLE_APPLICATION_UIDS) {
6173 s.userId = newUserIdLP(s);
6174 } else {
6175 s.userId = FIRST_APPLICATION_UID;
6176 }
6177 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6178 // < 0 means we couldn't assign a userid; fall out and return
6179 // s, which is currently null
6180 if (s.userId >= 0) {
6181 mSharedUsers.put(name, s);
6182 }
6183 }
6184
6185 return s;
6186 }
6187
6188 int disableSystemPackageLP(String name) {
6189 PackageSetting p = mPackages.get(name);
6190 if(p == null) {
6191 Log.w(TAG, "Package:"+name+" is not an installed package");
6192 return -1;
6193 }
6194 PackageSetting dp = mDisabledSysPackages.get(name);
6195 // always make sure the system package code and resource paths dont change
6196 if(dp == null) {
6197 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6198 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6199 }
6200 mDisabledSysPackages.put(name, p);
6201 }
6202 return removePackageLP(name);
6203 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 PackageSetting enableSystemPackageLP(String name) {
6206 PackageSetting p = mDisabledSysPackages.get(name);
6207 if(p == null) {
6208 Log.w(TAG, "Package:"+name+" is not disabled");
6209 return null;
6210 }
6211 // Reset flag in ApplicationInfo object
6212 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6213 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6214 }
6215 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006216 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 mDisabledSysPackages.remove(name);
6218 return ret;
6219 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006222 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 PackageSetting p = mPackages.get(name);
6224 if (p != null) {
6225 if (p.userId == uid) {
6226 return p;
6227 }
6228 reportSettingsProblem(Log.ERROR,
6229 "Adding duplicate package, keeping first: " + name);
6230 return null;
6231 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006232 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 p.userId = uid;
6234 if (addUserIdLP(uid, p, name)) {
6235 mPackages.put(name, p);
6236 return p;
6237 }
6238 return null;
6239 }
6240
6241 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6242 SharedUserSetting s = mSharedUsers.get(name);
6243 if (s != null) {
6244 if (s.userId == uid) {
6245 return s;
6246 }
6247 reportSettingsProblem(Log.ERROR,
6248 "Adding duplicate shared user, keeping first: " + name);
6249 return null;
6250 }
6251 s = new SharedUserSetting(name, pkgFlags);
6252 s.userId = uid;
6253 if (addUserIdLP(uid, s, name)) {
6254 mSharedUsers.put(name, s);
6255 return s;
6256 }
6257 return null;
6258 }
6259
6260 private PackageSetting getPackageLP(String name,
6261 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006262 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 PackageSetting p = mPackages.get(name);
6264 if (p != null) {
6265 if (!p.codePath.equals(codePath)) {
6266 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006267 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006268 // This is an updated system app with versions in both system
6269 // and data partition. Just let the most recent version
6270 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006271 Log.w(TAG, "Trying to update system app code path from " +
6272 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006273 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006274 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07006275 reportSettingsProblem(Log.WARN,
6276 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006277 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006279 }
6280 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 reportSettingsProblem(Log.WARN,
6282 "Package " + name + " shared user changed from "
6283 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
6284 + " to "
6285 + (sharedUser != null ? sharedUser.name : "<nothing>")
6286 + "; replacing with new");
6287 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006288 } else {
6289 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6290 // If what we are scanning is a system package, then
6291 // make it so, regardless of whether it was previously
6292 // installed only in the data partition.
6293 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 }
6296 }
6297 if (p == null) {
6298 // Create a new PackageSettings entry. this can end up here because
6299 // of code path mismatch or user id mismatch of an updated system partition
6300 if (!create) {
6301 return null;
6302 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006303 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07006305 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 if (sharedUser != null) {
6307 p.userId = sharedUser.userId;
6308 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006309 // Clone the setting here for disabled system packages
6310 PackageSetting dis = mDisabledSysPackages.get(name);
6311 if (dis != null) {
6312 // For disabled packages a new setting is created
6313 // from the existing user id. This still has to be
6314 // added to list of user id's
6315 // Copy signatures from previous setting
6316 if (dis.signatures.mSignatures != null) {
6317 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
6318 }
6319 p.userId = dis.userId;
6320 // Clone permissions
6321 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
6322 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
6323 // Clone component info
6324 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
6325 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
6326 // Add new setting to list of user ids
6327 addUserIdLP(p.userId, p, name);
6328 } else {
6329 // Assign new user id
6330 p.userId = newUserIdLP(p);
6331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 } else {
6333 p.userId = FIRST_APPLICATION_UID;
6334 }
6335 if (p.userId < 0) {
6336 reportSettingsProblem(Log.WARN,
6337 "Package " + name + " could not be assigned a valid uid");
6338 return null;
6339 }
6340 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006341 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006343 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 }
6345 }
6346 return p;
6347 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006348
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006349 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006350 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006351 String codePath = pkg.applicationInfo.sourceDir;
6352 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006353 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006354 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006355 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006356 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006357 p.codePath = new File(codePath);
6358 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006359 }
6360 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006361 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006362 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006363 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006364 p.resourcePath = new File(resourcePath);
6365 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006366 }
6367 // Update version code if needed
6368 if (pkg.mVersionCode != p.versionCode) {
6369 p.versionCode = pkg.mVersionCode;
6370 }
6371 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
6372 }
6373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 // Utility method that adds a PackageSetting to mPackages and
6375 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006376 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 SharedUserSetting sharedUser) {
6378 mPackages.put(name, p);
6379 if (sharedUser != null) {
6380 if (p.sharedUser != null && p.sharedUser != sharedUser) {
6381 reportSettingsProblem(Log.ERROR,
6382 "Package " + p.name + " was user "
6383 + p.sharedUser + " but is now " + sharedUser
6384 + "; I am not changing its files so it will probably fail!");
6385 p.sharedUser.packages.remove(p);
6386 } else if (p.userId != sharedUser.userId) {
6387 reportSettingsProblem(Log.ERROR,
6388 "Package " + p.name + " was user id " + p.userId
6389 + " but is now user " + sharedUser
6390 + " with id " + sharedUser.userId
6391 + "; I am not changing its files so it will probably fail!");
6392 }
6393
6394 sharedUser.packages.add(p);
6395 p.sharedUser = sharedUser;
6396 p.userId = sharedUser.userId;
6397 }
6398 }
6399
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006400 /*
6401 * Update the shared user setting when a package using
6402 * specifying the shared user id is removed. The gids
6403 * associated with each permission of the deleted package
6404 * are removed from the shared user's gid list only if its
6405 * not in use by other permissions of packages in the
6406 * shared user setting.
6407 */
6408 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6410 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6411 return;
6412 }
6413 // No sharedUserId
6414 if (deletedPs.sharedUser == null) {
6415 return;
6416 }
6417 SharedUserSetting sus = deletedPs.sharedUser;
6418 // Update permissions
6419 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6420 boolean used = false;
6421 if (!sus.grantedPermissions.contains (eachPerm)) {
6422 continue;
6423 }
6424 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006425 if (pkg.pkg != null &&
6426 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
6427 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 used = true;
6429 break;
6430 }
6431 }
6432 if (!used) {
6433 // can safely delete this permission from list
6434 sus.grantedPermissions.remove(eachPerm);
6435 sus.loadedPermissions.remove(eachPerm);
6436 }
6437 }
6438 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006439 int newGids[] = globalGids;
6440 for (String eachPerm : sus.grantedPermissions) {
6441 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006442 if (bp != null) {
6443 newGids = appendInts(newGids, bp.gids);
6444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 }
6446 sus.gids = newGids;
6447 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 private int removePackageLP(String name) {
6450 PackageSetting p = mPackages.get(name);
6451 if (p != null) {
6452 mPackages.remove(name);
6453 if (p.sharedUser != null) {
6454 p.sharedUser.packages.remove(p);
6455 if (p.sharedUser.packages.size() == 0) {
6456 mSharedUsers.remove(p.sharedUser.name);
6457 removeUserIdLP(p.sharedUser.userId);
6458 return p.sharedUser.userId;
6459 }
6460 } else {
6461 removeUserIdLP(p.userId);
6462 return p.userId;
6463 }
6464 }
6465 return -1;
6466 }
6467
6468 private boolean addUserIdLP(int uid, Object obj, Object name) {
6469 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6470 return false;
6471 }
6472
6473 if (uid >= FIRST_APPLICATION_UID) {
6474 int N = mUserIds.size();
6475 final int index = uid - FIRST_APPLICATION_UID;
6476 while (index >= N) {
6477 mUserIds.add(null);
6478 N++;
6479 }
6480 if (mUserIds.get(index) != null) {
6481 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006482 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 + " name=" + name);
6484 return false;
6485 }
6486 mUserIds.set(index, obj);
6487 } else {
6488 if (mOtherUserIds.get(uid) != null) {
6489 reportSettingsProblem(Log.ERROR,
6490 "Adding duplicate shared id: " + uid
6491 + " name=" + name);
6492 return false;
6493 }
6494 mOtherUserIds.put(uid, obj);
6495 }
6496 return true;
6497 }
6498
6499 public Object getUserIdLP(int uid) {
6500 if (uid >= FIRST_APPLICATION_UID) {
6501 int N = mUserIds.size();
6502 final int index = uid - FIRST_APPLICATION_UID;
6503 return index < N ? mUserIds.get(index) : null;
6504 } else {
6505 return mOtherUserIds.get(uid);
6506 }
6507 }
6508
6509 private void removeUserIdLP(int uid) {
6510 if (uid >= FIRST_APPLICATION_UID) {
6511 int N = mUserIds.size();
6512 final int index = uid - FIRST_APPLICATION_UID;
6513 if (index < N) mUserIds.set(index, null);
6514 } else {
6515 mOtherUserIds.remove(uid);
6516 }
6517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 void writeLP() {
6520 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6521
6522 // Keep the old settings around until we know the new ones have
6523 // been successfully written.
6524 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006525 // Presence of backup settings file indicates that we failed
6526 // to persist settings earlier. So preserve the older
6527 // backup for future reference since the current settings
6528 // might have been corrupted.
6529 if (!mBackupSettingsFilename.exists()) {
6530 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
6531 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
6532 return;
6533 }
6534 } else {
6535 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07006536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 }
6538
6539 mPastSignatures.clear();
6540
6541 try {
6542 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6543
6544 //XmlSerializer serializer = XmlUtils.serializerInstance();
6545 XmlSerializer serializer = new FastXmlSerializer();
6546 serializer.setOutput(str, "utf-8");
6547 serializer.startDocument(null, true);
6548 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6549
6550 serializer.startTag(null, "packages");
6551
6552 serializer.startTag(null, "permission-trees");
6553 for (BasePermission bp : mPermissionTrees.values()) {
6554 writePermission(serializer, bp);
6555 }
6556 serializer.endTag(null, "permission-trees");
6557
6558 serializer.startTag(null, "permissions");
6559 for (BasePermission bp : mPermissions.values()) {
6560 writePermission(serializer, bp);
6561 }
6562 serializer.endTag(null, "permissions");
6563
6564 for (PackageSetting pkg : mPackages.values()) {
6565 writePackage(serializer, pkg);
6566 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6569 writeDisabledSysPackage(serializer, pkg);
6570 }
6571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 serializer.startTag(null, "preferred-activities");
6573 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6574 serializer.startTag(null, "item");
6575 pa.writeToXml(serializer);
6576 serializer.endTag(null, "item");
6577 }
6578 serializer.endTag(null, "preferred-activities");
6579
6580 for (SharedUserSetting usr : mSharedUsers.values()) {
6581 serializer.startTag(null, "shared-user");
6582 serializer.attribute(null, "name", usr.name);
6583 serializer.attribute(null, "userId",
6584 Integer.toString(usr.userId));
6585 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6586 serializer.startTag(null, "perms");
6587 for (String name : usr.grantedPermissions) {
6588 serializer.startTag(null, "item");
6589 serializer.attribute(null, "name", name);
6590 serializer.endTag(null, "item");
6591 }
6592 serializer.endTag(null, "perms");
6593 serializer.endTag(null, "shared-user");
6594 }
6595
6596 serializer.endTag(null, "packages");
6597
6598 serializer.endDocument();
6599
6600 str.flush();
6601 str.close();
6602
6603 // New settings successfully written, old ones are no longer
6604 // needed.
6605 mBackupSettingsFilename.delete();
6606 FileUtils.setPermissions(mSettingsFilename.toString(),
6607 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6608 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6609 |FileUtils.S_IROTH,
6610 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006611 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612
6613 } catch(XmlPullParserException e) {
6614 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 -08006615 } catch(java.io.IOException e) {
6616 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 -08006617 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006618 // Clean up partially written file
6619 if (mSettingsFilename.exists()) {
6620 if (!mSettingsFilename.delete()) {
6621 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
6622 }
6623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 //Debug.stopMethodTracing();
6625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006626
6627 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 throws java.io.IOException {
6629 serializer.startTag(null, "updated-package");
6630 serializer.attribute(null, "name", pkg.name);
6631 serializer.attribute(null, "codePath", pkg.codePathString);
6632 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006633 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6635 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6636 }
6637 if (pkg.sharedUser == null) {
6638 serializer.attribute(null, "userId",
6639 Integer.toString(pkg.userId));
6640 } else {
6641 serializer.attribute(null, "sharedUserId",
6642 Integer.toString(pkg.userId));
6643 }
6644 serializer.startTag(null, "perms");
6645 if (pkg.sharedUser == null) {
6646 // If this is a shared user, the permissions will
6647 // be written there. We still need to write an
6648 // empty permissions list so permissionsFixed will
6649 // be set.
6650 for (final String name : pkg.grantedPermissions) {
6651 BasePermission bp = mPermissions.get(name);
6652 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6653 // We only need to write signature or system permissions but this wont
6654 // match the semantics of grantedPermissions. So write all permissions.
6655 serializer.startTag(null, "item");
6656 serializer.attribute(null, "name", name);
6657 serializer.endTag(null, "item");
6658 }
6659 }
6660 }
6661 serializer.endTag(null, "perms");
6662 serializer.endTag(null, "updated-package");
6663 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006664
6665 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 throws java.io.IOException {
6667 serializer.startTag(null, "package");
6668 serializer.attribute(null, "name", pkg.name);
6669 serializer.attribute(null, "codePath", pkg.codePathString);
6670 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6671 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6672 }
6673 serializer.attribute(null, "system",
6674 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6675 ? "true" : "false");
6676 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006677 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006678 if (pkg.sharedUser == null) {
6679 serializer.attribute(null, "userId",
6680 Integer.toString(pkg.userId));
6681 } else {
6682 serializer.attribute(null, "sharedUserId",
6683 Integer.toString(pkg.userId));
6684 }
6685 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6686 serializer.attribute(null, "enabled",
6687 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6688 ? "true" : "false");
6689 }
6690 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6691 serializer.attribute(null, "installStatus", "false");
6692 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006693 if (pkg.installerPackageName != null) {
6694 serializer.attribute(null, "installer", pkg.installerPackageName);
6695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6697 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6698 serializer.startTag(null, "perms");
6699 if (pkg.sharedUser == null) {
6700 // If this is a shared user, the permissions will
6701 // be written there. We still need to write an
6702 // empty permissions list so permissionsFixed will
6703 // be set.
6704 for (final String name : pkg.grantedPermissions) {
6705 serializer.startTag(null, "item");
6706 serializer.attribute(null, "name", name);
6707 serializer.endTag(null, "item");
6708 }
6709 }
6710 serializer.endTag(null, "perms");
6711 }
6712 if (pkg.disabledComponents.size() > 0) {
6713 serializer.startTag(null, "disabled-components");
6714 for (final String name : pkg.disabledComponents) {
6715 serializer.startTag(null, "item");
6716 serializer.attribute(null, "name", name);
6717 serializer.endTag(null, "item");
6718 }
6719 serializer.endTag(null, "disabled-components");
6720 }
6721 if (pkg.enabledComponents.size() > 0) {
6722 serializer.startTag(null, "enabled-components");
6723 for (final String name : pkg.enabledComponents) {
6724 serializer.startTag(null, "item");
6725 serializer.attribute(null, "name", name);
6726 serializer.endTag(null, "item");
6727 }
6728 serializer.endTag(null, "enabled-components");
6729 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 serializer.endTag(null, "package");
6732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 void writePermission(XmlSerializer serializer, BasePermission bp)
6735 throws XmlPullParserException, java.io.IOException {
6736 if (bp.type != BasePermission.TYPE_BUILTIN
6737 && bp.sourcePackage != null) {
6738 serializer.startTag(null, "item");
6739 serializer.attribute(null, "name", bp.name);
6740 serializer.attribute(null, "package", bp.sourcePackage);
6741 if (DEBUG_SETTINGS) Log.v(TAG,
6742 "Writing perm: name=" + bp.name + " type=" + bp.type);
6743 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6744 PermissionInfo pi = bp.perm != null ? bp.perm.info
6745 : bp.pendingInfo;
6746 if (pi != null) {
6747 serializer.attribute(null, "type", "dynamic");
6748 if (pi.icon != 0) {
6749 serializer.attribute(null, "icon",
6750 Integer.toString(pi.icon));
6751 }
6752 if (pi.nonLocalizedLabel != null) {
6753 serializer.attribute(null, "label",
6754 pi.nonLocalizedLabel.toString());
6755 }
6756 if (pi.protectionLevel !=
6757 PermissionInfo.PROTECTION_NORMAL) {
6758 serializer.attribute(null, "protection",
6759 Integer.toString(pi.protectionLevel));
6760 }
6761 }
6762 }
6763 serializer.endTag(null, "item");
6764 }
6765 }
6766
6767 String getReadMessagesLP() {
6768 return mReadMessages.toString();
6769 }
6770
Oscar Montemayora8529f62009-11-18 10:14:20 -08006771 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6773 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006774 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 while(its.hasNext()) {
6776 String key = its.next();
6777 PackageSetting ps = mPackages.get(key);
6778 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006779 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006780 }
6781 }
6782 return ret;
6783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006785 boolean readLP() {
6786 FileInputStream str = null;
6787 if (mBackupSettingsFilename.exists()) {
6788 try {
6789 str = new FileInputStream(mBackupSettingsFilename);
6790 mReadMessages.append("Reading from backup settings file\n");
6791 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006792 if (mSettingsFilename.exists()) {
6793 // If both the backup and settings file exist, we
6794 // ignore the settings since it might have been
6795 // corrupted.
6796 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
6797 mSettingsFilename.delete();
6798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 } catch (java.io.IOException e) {
6800 // We'll try for the normal settings file.
6801 }
6802 }
6803
6804 mPastSignatures.clear();
6805
6806 try {
6807 if (str == null) {
6808 if (!mSettingsFilename.exists()) {
6809 mReadMessages.append("No settings file found\n");
6810 Log.i(TAG, "No current settings file!");
6811 return false;
6812 }
6813 str = new FileInputStream(mSettingsFilename);
6814 }
6815 XmlPullParser parser = Xml.newPullParser();
6816 parser.setInput(str, null);
6817
6818 int type;
6819 while ((type=parser.next()) != XmlPullParser.START_TAG
6820 && type != XmlPullParser.END_DOCUMENT) {
6821 ;
6822 }
6823
6824 if (type != XmlPullParser.START_TAG) {
6825 mReadMessages.append("No start tag found in settings file\n");
6826 Log.e(TAG, "No start tag found in package manager settings");
6827 return false;
6828 }
6829
6830 int outerDepth = parser.getDepth();
6831 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6832 && (type != XmlPullParser.END_TAG
6833 || parser.getDepth() > outerDepth)) {
6834 if (type == XmlPullParser.END_TAG
6835 || type == XmlPullParser.TEXT) {
6836 continue;
6837 }
6838
6839 String tagName = parser.getName();
6840 if (tagName.equals("package")) {
6841 readPackageLP(parser);
6842 } else if (tagName.equals("permissions")) {
6843 readPermissionsLP(mPermissions, parser);
6844 } else if (tagName.equals("permission-trees")) {
6845 readPermissionsLP(mPermissionTrees, parser);
6846 } else if (tagName.equals("shared-user")) {
6847 readSharedUserLP(parser);
6848 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006849 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006850 } else if (tagName.equals("preferred-activities")) {
6851 readPreferredActivitiesLP(parser);
6852 } else if(tagName.equals("updated-package")) {
6853 readDisabledSysPackageLP(parser);
6854 } else {
6855 Log.w(TAG, "Unknown element under <packages>: "
6856 + parser.getName());
6857 XmlUtils.skipCurrentTag(parser);
6858 }
6859 }
6860
6861 str.close();
6862
6863 } catch(XmlPullParserException e) {
6864 mReadMessages.append("Error reading: " + e.toString());
6865 Log.e(TAG, "Error reading package manager settings", e);
6866
6867 } catch(java.io.IOException e) {
6868 mReadMessages.append("Error reading: " + e.toString());
6869 Log.e(TAG, "Error reading package manager settings", e);
6870
6871 }
6872
6873 int N = mPendingPackages.size();
6874 for (int i=0; i<N; i++) {
6875 final PendingPackage pp = mPendingPackages.get(i);
6876 Object idObj = getUserIdLP(pp.sharedId);
6877 if (idObj != null && idObj instanceof SharedUserSetting) {
6878 PackageSetting p = getPackageLP(pp.name,
6879 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006880 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006881 if (p == null) {
6882 Log.w(TAG, "Unable to create application package for "
6883 + pp.name);
6884 continue;
6885 }
6886 p.copyFrom(pp);
6887 } else if (idObj != null) {
6888 String msg = "Bad package setting: package " + pp.name
6889 + " has shared uid " + pp.sharedId
6890 + " that is not a shared uid\n";
6891 mReadMessages.append(msg);
6892 Log.e(TAG, msg);
6893 } else {
6894 String msg = "Bad package setting: package " + pp.name
6895 + " has shared uid " + pp.sharedId
6896 + " that is not defined\n";
6897 mReadMessages.append(msg);
6898 Log.e(TAG, msg);
6899 }
6900 }
6901 mPendingPackages.clear();
6902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 mReadMessages.append("Read completed successfully: "
6904 + mPackages.size() + " packages, "
6905 + mSharedUsers.size() + " shared uids\n");
6906
6907 return true;
6908 }
6909
6910 private int readInt(XmlPullParser parser, String ns, String name,
6911 int defValue) {
6912 String v = parser.getAttributeValue(ns, name);
6913 try {
6914 if (v == null) {
6915 return defValue;
6916 }
6917 return Integer.parseInt(v);
6918 } catch (NumberFormatException e) {
6919 reportSettingsProblem(Log.WARN,
6920 "Error in package manager settings: attribute " +
6921 name + " has bad integer value " + v + " at "
6922 + parser.getPositionDescription());
6923 }
6924 return defValue;
6925 }
6926
6927 private void readPermissionsLP(HashMap<String, BasePermission> out,
6928 XmlPullParser parser)
6929 throws IOException, XmlPullParserException {
6930 int outerDepth = parser.getDepth();
6931 int type;
6932 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6933 && (type != XmlPullParser.END_TAG
6934 || parser.getDepth() > outerDepth)) {
6935 if (type == XmlPullParser.END_TAG
6936 || type == XmlPullParser.TEXT) {
6937 continue;
6938 }
6939
6940 String tagName = parser.getName();
6941 if (tagName.equals("item")) {
6942 String name = parser.getAttributeValue(null, "name");
6943 String sourcePackage = parser.getAttributeValue(null, "package");
6944 String ptype = parser.getAttributeValue(null, "type");
6945 if (name != null && sourcePackage != null) {
6946 boolean dynamic = "dynamic".equals(ptype);
6947 BasePermission bp = new BasePermission(name, sourcePackage,
6948 dynamic
6949 ? BasePermission.TYPE_DYNAMIC
6950 : BasePermission.TYPE_NORMAL);
6951 if (dynamic) {
6952 PermissionInfo pi = new PermissionInfo();
6953 pi.packageName = sourcePackage.intern();
6954 pi.name = name.intern();
6955 pi.icon = readInt(parser, null, "icon", 0);
6956 pi.nonLocalizedLabel = parser.getAttributeValue(
6957 null, "label");
6958 pi.protectionLevel = readInt(parser, null, "protection",
6959 PermissionInfo.PROTECTION_NORMAL);
6960 bp.pendingInfo = pi;
6961 }
6962 out.put(bp.name, bp);
6963 } else {
6964 reportSettingsProblem(Log.WARN,
6965 "Error in package manager settings: permissions has"
6966 + " no name at " + parser.getPositionDescription());
6967 }
6968 } else {
6969 reportSettingsProblem(Log.WARN,
6970 "Unknown element reading permissions: "
6971 + parser.getName() + " at "
6972 + parser.getPositionDescription());
6973 }
6974 XmlUtils.skipCurrentTag(parser);
6975 }
6976 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 private void readDisabledSysPackageLP(XmlPullParser parser)
6979 throws XmlPullParserException, IOException {
6980 String name = parser.getAttributeValue(null, "name");
6981 String codePathStr = parser.getAttributeValue(null, "codePath");
6982 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6983 if(resourcePathStr == null) {
6984 resourcePathStr = codePathStr;
6985 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006986 String version = parser.getAttributeValue(null, "version");
6987 int versionCode = 0;
6988 if (version != null) {
6989 try {
6990 versionCode = Integer.parseInt(version);
6991 } catch (NumberFormatException e) {
6992 }
6993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006995 int pkgFlags = 0;
6996 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006997 PackageSetting ps = new PackageSetting(name,
6998 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006999 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007000 String timeStampStr = parser.getAttributeValue(null, "ts");
7001 if (timeStampStr != null) {
7002 try {
7003 long timeStamp = Long.parseLong(timeStampStr);
7004 ps.setTimeStamp(timeStamp, timeStampStr);
7005 } catch (NumberFormatException e) {
7006 }
7007 }
7008 String idStr = parser.getAttributeValue(null, "userId");
7009 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
7010 if(ps.userId <= 0) {
7011 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7012 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7013 }
7014 int outerDepth = parser.getDepth();
7015 int type;
7016 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7017 && (type != XmlPullParser.END_TAG
7018 || parser.getDepth() > outerDepth)) {
7019 if (type == XmlPullParser.END_TAG
7020 || type == XmlPullParser.TEXT) {
7021 continue;
7022 }
7023
7024 String tagName = parser.getName();
7025 if (tagName.equals("perms")) {
7026 readGrantedPermissionsLP(parser,
7027 ps.grantedPermissions);
7028 } else {
7029 reportSettingsProblem(Log.WARN,
7030 "Unknown element under <updated-package>: "
7031 + parser.getName());
7032 XmlUtils.skipCurrentTag(parser);
7033 }
7034 }
7035 mDisabledSysPackages.put(name, ps);
7036 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038 private void readPackageLP(XmlPullParser parser)
7039 throws XmlPullParserException, IOException {
7040 String name = null;
7041 String idStr = null;
7042 String sharedIdStr = null;
7043 String codePathStr = null;
7044 String resourcePathStr = null;
7045 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007046 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 int pkgFlags = 0;
7048 String timeStampStr;
7049 long timeStamp = 0;
7050 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007051 String version = null;
7052 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 try {
7054 name = parser.getAttributeValue(null, "name");
7055 idStr = parser.getAttributeValue(null, "userId");
7056 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7057 codePathStr = parser.getAttributeValue(null, "codePath");
7058 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007059 version = parser.getAttributeValue(null, "version");
7060 if (version != null) {
7061 try {
7062 versionCode = Integer.parseInt(version);
7063 } catch (NumberFormatException e) {
7064 }
7065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazski65e13172009-04-28 15:26:38 +02007067 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 if (systemStr != null) {
7069 if ("true".equals(systemStr)) {
7070 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7071 }
7072 } else {
7073 // Old settings that don't specify system... just treat
7074 // them as system, good enough.
7075 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7076 }
7077 timeStampStr = parser.getAttributeValue(null, "ts");
7078 if (timeStampStr != null) {
7079 try {
7080 timeStamp = Long.parseLong(timeStampStr);
7081 } catch (NumberFormatException e) {
7082 }
7083 }
7084 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7085 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7086 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7087 if (resourcePathStr == null) {
7088 resourcePathStr = codePathStr;
7089 }
7090 if (name == null) {
7091 reportSettingsProblem(Log.WARN,
7092 "Error in package manager settings: <package> has no name at "
7093 + parser.getPositionDescription());
7094 } else if (codePathStr == null) {
7095 reportSettingsProblem(Log.WARN,
7096 "Error in package manager settings: <package> has no codePath at "
7097 + parser.getPositionDescription());
7098 } else if (userId > 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007099 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007100 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007101 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7102 + ": userId=" + userId + " pkg=" + packageSetting);
7103 if (packageSetting == null) {
7104 reportSettingsProblem(Log.ERROR,
7105 "Failure adding uid " + userId
7106 + " while parsing settings at "
7107 + parser.getPositionDescription());
7108 } else {
7109 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7110 }
7111 } else if (sharedIdStr != null) {
7112 userId = sharedIdStr != null
7113 ? Integer.parseInt(sharedIdStr) : 0;
7114 if (userId > 0) {
7115 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007116 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7118 mPendingPackages.add((PendingPackage) packageSetting);
7119 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7120 + ": sharedUserId=" + userId + " pkg="
7121 + packageSetting);
7122 } else {
7123 reportSettingsProblem(Log.WARN,
7124 "Error in package manager settings: package "
7125 + name + " has bad sharedId " + sharedIdStr
7126 + " at " + parser.getPositionDescription());
7127 }
7128 } else {
7129 reportSettingsProblem(Log.WARN,
7130 "Error in package manager settings: package "
7131 + name + " has bad userId " + idStr + " at "
7132 + parser.getPositionDescription());
7133 }
7134 } catch (NumberFormatException e) {
7135 reportSettingsProblem(Log.WARN,
7136 "Error in package manager settings: package "
7137 + name + " has bad userId " + idStr + " at "
7138 + parser.getPositionDescription());
7139 }
7140 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02007141 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 final String enabledStr = parser.getAttributeValue(null, "enabled");
7143 if (enabledStr != null) {
7144 if (enabledStr.equalsIgnoreCase("true")) {
7145 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7146 } else if (enabledStr.equalsIgnoreCase("false")) {
7147 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7148 } else if (enabledStr.equalsIgnoreCase("default")) {
7149 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7150 } else {
7151 reportSettingsProblem(Log.WARN,
7152 "Error in package manager settings: package "
7153 + name + " has bad enabled value: " + idStr
7154 + " at " + parser.getPositionDescription());
7155 }
7156 } else {
7157 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7158 }
7159 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7160 if (installStatusStr != null) {
7161 if (installStatusStr.equalsIgnoreCase("false")) {
7162 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7163 } else {
7164 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7165 }
7166 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007168 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("disabled-components")) {
7180 readDisabledComponentsLP(packageSetting, parser);
7181 } else if (tagName.equals("enabled-components")) {
7182 readEnabledComponentsLP(packageSetting, parser);
7183 } else if (tagName.equals("sigs")) {
7184 packageSetting.signatures.readXml(parser, mPastSignatures);
7185 } else if (tagName.equals("perms")) {
7186 readGrantedPermissionsLP(parser,
7187 packageSetting.loadedPermissions);
7188 packageSetting.permissionsFixed = true;
7189 } else {
7190 reportSettingsProblem(Log.WARN,
7191 "Unknown element under <package>: "
7192 + parser.getName());
7193 XmlUtils.skipCurrentTag(parser);
7194 }
7195 }
7196 } else {
7197 XmlUtils.skipCurrentTag(parser);
7198 }
7199 }
7200
7201 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7202 XmlPullParser parser)
7203 throws IOException, XmlPullParserException {
7204 int outerDepth = parser.getDepth();
7205 int type;
7206 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7207 && (type != XmlPullParser.END_TAG
7208 || parser.getDepth() > outerDepth)) {
7209 if (type == XmlPullParser.END_TAG
7210 || type == XmlPullParser.TEXT) {
7211 continue;
7212 }
7213
7214 String tagName = parser.getName();
7215 if (tagName.equals("item")) {
7216 String name = parser.getAttributeValue(null, "name");
7217 if (name != null) {
7218 packageSetting.disabledComponents.add(name.intern());
7219 } else {
7220 reportSettingsProblem(Log.WARN,
7221 "Error in package manager settings: <disabled-components> has"
7222 + " no name at " + parser.getPositionDescription());
7223 }
7224 } else {
7225 reportSettingsProblem(Log.WARN,
7226 "Unknown element under <disabled-components>: "
7227 + parser.getName());
7228 }
7229 XmlUtils.skipCurrentTag(parser);
7230 }
7231 }
7232
7233 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
7234 XmlPullParser parser)
7235 throws IOException, XmlPullParserException {
7236 int outerDepth = parser.getDepth();
7237 int type;
7238 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7239 && (type != XmlPullParser.END_TAG
7240 || parser.getDepth() > outerDepth)) {
7241 if (type == XmlPullParser.END_TAG
7242 || type == XmlPullParser.TEXT) {
7243 continue;
7244 }
7245
7246 String tagName = parser.getName();
7247 if (tagName.equals("item")) {
7248 String name = parser.getAttributeValue(null, "name");
7249 if (name != null) {
7250 packageSetting.enabledComponents.add(name.intern());
7251 } else {
7252 reportSettingsProblem(Log.WARN,
7253 "Error in package manager settings: <enabled-components> has"
7254 + " no name at " + parser.getPositionDescription());
7255 }
7256 } else {
7257 reportSettingsProblem(Log.WARN,
7258 "Unknown element under <enabled-components>: "
7259 + parser.getName());
7260 }
7261 XmlUtils.skipCurrentTag(parser);
7262 }
7263 }
7264
7265 private void readSharedUserLP(XmlPullParser parser)
7266 throws XmlPullParserException, IOException {
7267 String name = null;
7268 String idStr = null;
7269 int pkgFlags = 0;
7270 SharedUserSetting su = null;
7271 try {
7272 name = parser.getAttributeValue(null, "name");
7273 idStr = parser.getAttributeValue(null, "userId");
7274 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7275 if ("true".equals(parser.getAttributeValue(null, "system"))) {
7276 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7277 }
7278 if (name == null) {
7279 reportSettingsProblem(Log.WARN,
7280 "Error in package manager settings: <shared-user> has no name at "
7281 + parser.getPositionDescription());
7282 } else if (userId == 0) {
7283 reportSettingsProblem(Log.WARN,
7284 "Error in package manager settings: shared-user "
7285 + name + " has bad userId " + idStr + " at "
7286 + parser.getPositionDescription());
7287 } else {
7288 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
7289 reportSettingsProblem(Log.ERROR,
7290 "Occurred while parsing settings at "
7291 + parser.getPositionDescription());
7292 }
7293 }
7294 } catch (NumberFormatException e) {
7295 reportSettingsProblem(Log.WARN,
7296 "Error in package manager settings: package "
7297 + name + " has bad userId " + idStr + " at "
7298 + parser.getPositionDescription());
7299 };
7300
7301 if (su != null) {
7302 int outerDepth = parser.getDepth();
7303 int type;
7304 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7305 && (type != XmlPullParser.END_TAG
7306 || parser.getDepth() > outerDepth)) {
7307 if (type == XmlPullParser.END_TAG
7308 || type == XmlPullParser.TEXT) {
7309 continue;
7310 }
7311
7312 String tagName = parser.getName();
7313 if (tagName.equals("sigs")) {
7314 su.signatures.readXml(parser, mPastSignatures);
7315 } else if (tagName.equals("perms")) {
7316 readGrantedPermissionsLP(parser, su.loadedPermissions);
7317 } else {
7318 reportSettingsProblem(Log.WARN,
7319 "Unknown element under <shared-user>: "
7320 + parser.getName());
7321 XmlUtils.skipCurrentTag(parser);
7322 }
7323 }
7324
7325 } else {
7326 XmlUtils.skipCurrentTag(parser);
7327 }
7328 }
7329
7330 private void readGrantedPermissionsLP(XmlPullParser parser,
7331 HashSet<String> outPerms) throws IOException, XmlPullParserException {
7332 int outerDepth = parser.getDepth();
7333 int type;
7334 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7335 && (type != XmlPullParser.END_TAG
7336 || parser.getDepth() > outerDepth)) {
7337 if (type == XmlPullParser.END_TAG
7338 || type == XmlPullParser.TEXT) {
7339 continue;
7340 }
7341
7342 String tagName = parser.getName();
7343 if (tagName.equals("item")) {
7344 String name = parser.getAttributeValue(null, "name");
7345 if (name != null) {
7346 outPerms.add(name.intern());
7347 } else {
7348 reportSettingsProblem(Log.WARN,
7349 "Error in package manager settings: <perms> has"
7350 + " no name at " + parser.getPositionDescription());
7351 }
7352 } else {
7353 reportSettingsProblem(Log.WARN,
7354 "Unknown element under <perms>: "
7355 + parser.getName());
7356 }
7357 XmlUtils.skipCurrentTag(parser);
7358 }
7359 }
7360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007361 private void readPreferredActivitiesLP(XmlPullParser parser)
7362 throws XmlPullParserException, IOException {
7363 int outerDepth = parser.getDepth();
7364 int type;
7365 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7366 && (type != XmlPullParser.END_TAG
7367 || parser.getDepth() > outerDepth)) {
7368 if (type == XmlPullParser.END_TAG
7369 || type == XmlPullParser.TEXT) {
7370 continue;
7371 }
7372
7373 String tagName = parser.getName();
7374 if (tagName.equals("item")) {
7375 PreferredActivity pa = new PreferredActivity(parser);
7376 if (pa.mParseError == null) {
7377 mPreferredActivities.addFilter(pa);
7378 } else {
7379 reportSettingsProblem(Log.WARN,
7380 "Error in package manager settings: <preferred-activity> "
7381 + pa.mParseError + " at "
7382 + parser.getPositionDescription());
7383 }
7384 } else {
7385 reportSettingsProblem(Log.WARN,
7386 "Unknown element under <preferred-activities>: "
7387 + parser.getName());
7388 XmlUtils.skipCurrentTag(parser);
7389 }
7390 }
7391 }
7392
7393 // Returns -1 if we could not find an available UserId to assign
7394 private int newUserIdLP(Object obj) {
7395 // Let's be stupidly inefficient for now...
7396 final int N = mUserIds.size();
7397 for (int i=0; i<N; i++) {
7398 if (mUserIds.get(i) == null) {
7399 mUserIds.set(i, obj);
7400 return FIRST_APPLICATION_UID + i;
7401 }
7402 }
7403
7404 // None left?
7405 if (N >= MAX_APPLICATION_UIDS) {
7406 return -1;
7407 }
7408
7409 mUserIds.add(obj);
7410 return FIRST_APPLICATION_UID + N;
7411 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 public PackageSetting getDisabledSystemPkg(String name) {
7414 synchronized(mPackages) {
7415 PackageSetting ps = mDisabledSysPackages.get(name);
7416 return ps;
7417 }
7418 }
7419
7420 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7421 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7422 if (Config.LOGV) {
7423 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7424 + " componentName = " + componentInfo.name);
7425 Log.v(TAG, "enabledComponents: "
7426 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7427 Log.v(TAG, "disabledComponents: "
7428 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7429 }
7430 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7431 || ((componentInfo.enabled
7432 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7433 || (componentInfo.applicationInfo.enabled
7434 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7435 && !packageSettings.disabledComponents.contains(componentInfo.name))
7436 || packageSettings.enabledComponents.contains(componentInfo.name));
7437 }
7438 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007439
7440 // ------- apps on sdcard specific code -------
7441 static final boolean DEBUG_SD_INSTALL = false;
7442 final private String mSdEncryptKey = "none";
7443
7444 private MountService getMountService() {
7445 return (MountService) ServiceManager.getService("mount");
7446 }
7447
7448 private String createSdDir(File tmpPackageFile, String pkgName) {
7449 // Create mount point via MountService
7450 MountService mountService = getMountService();
7451 long len = tmpPackageFile.length();
7452 int mbLen = (int) (len/(1024*1024));
7453 if ((len - (mbLen * 1024 * 1024)) > 0) {
7454 mbLen++;
7455 }
7456 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
7457 String cachePath = null;
7458 // Remove any pending destroy messages
7459 mHandler.removeMessages(DESTROY_SD_CONTAINER, pkgName);
7460 try {
7461 cachePath = mountService.createSecureContainer(pkgName,
7462 mbLen,
7463 "vfat", mSdEncryptKey, Process.SYSTEM_UID);
7464 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
7465 return cachePath;
7466 } catch(IllegalStateException e) {
7467 Log.e(TAG, "Failed to create storage on sdcard with exception: " + e);
7468 }
7469 // TODO just fail here and let the user delete later on.
7470 try {
7471 mountService.destroySecureContainer(pkgName);
7472 if (DEBUG_SD_INSTALL) Log.i(TAG, "Destroying cache for " + pkgName + ", cachePath =" + cachePath);
7473 } catch(IllegalStateException e) {
7474 Log.e(TAG, "Failed to destroy existing cache: " + e);
7475 return null;
7476 }
7477 try {
7478 cachePath = mountService.createSecureContainer(pkgName,
7479 mbLen,
7480 "vfat", mSdEncryptKey, Process.SYSTEM_UID);
7481 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install again " + pkgName + ", cachePath =" + cachePath);
7482 return cachePath;
7483 } catch(IllegalStateException e) {
7484 Log.e(TAG, "Failed to create storage on sdcard with exception: " + e);
7485 return null;
7486 }
7487 }
7488
7489 private String mountSdDir(String pkgName, int ownerUid) {
7490 try {
7491 return getMountService().mountSecureContainer(pkgName, mSdEncryptKey, ownerUid);
7492 } catch (IllegalStateException e) {
7493 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " exception : " + e);
7494 }
7495 return null;
7496 }
7497
7498 private String getSdDir(String pkgName) {
7499 String cachePath = null;
7500 try {
7501 cachePath = getMountService().getSecureContainerPath(pkgName);
7502 } catch (IllegalStateException e) {
7503 Log.e(TAG, "Failed to retrieve secure container path for pkg : " + pkgName + " with exception " + e);
7504 }
7505 return cachePath;
7506 }
7507
7508 private boolean finalizeSdDir(String pkgName) {
7509 try {
7510 getMountService().finalizeSecureContainer(pkgName);
7511 return true;
7512 } catch (IllegalStateException e) {
7513 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
7514 return false;
7515 }
7516 }
7517
7518 private boolean destroySdDir(String pkgName) {
7519 try {
7520 if (mHandler.hasMessages(DESTROY_SD_CONTAINER, pkgName)) {
7521 // Don't have to send message again
7522 mHandler.removeMessages(DESTROY_SD_CONTAINER, pkgName);
7523 }
7524 // We need to destroy right away
7525 getMountService().destroySecureContainer(pkgName);
7526 return true;
7527 } catch (IllegalStateException e) {
7528 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
7529 return false;
7530 }
7531 }
7532
7533 private void sendDelayedDestroySdDir(String pkgName) {
7534 if (mHandler.hasMessages(DESTROY_SD_CONTAINER, pkgName)) {
7535 // Don't have to send message again
7536 return;
7537 }
7538 Message msg = mHandler.obtainMessage(DESTROY_SD_CONTAINER, pkgName);
7539 mHandler.sendMessageDelayed(msg, DESTROY_SD_CONTAINER_DELAY);
7540 }
7541
7542 public void updateExternalMediaStatus(boolean mediaStatus) {
7543 // TODO
7544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545}