blob: cafc80462eee9080b2d72aa32b65baf2276f05a6 [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;
Oscar Montemayord02546b2010-01-14 16:38:40 -080078import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.util.*;
80import android.view.Display;
81import android.view.WindowManager;
82
83import java.io.File;
84import java.io.FileDescriptor;
85import java.io.FileInputStream;
86import java.io.FileNotFoundException;
87import java.io.FileOutputStream;
88import java.io.FileReader;
89import java.io.FilenameFilter;
90import java.io.IOException;
91import java.io.InputStream;
92import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -080093import java.security.NoSuchAlgorithmException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import java.util.ArrayList;
95import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -070096import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import java.util.Collections;
98import java.util.Comparator;
99import java.util.Enumeration;
100import java.util.HashMap;
101import java.util.HashSet;
102import java.util.Iterator;
103import java.util.List;
104import java.util.Map;
105import java.util.Set;
106import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800107import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.zip.ZipFile;
109import java.util.zip.ZipOutputStream;
110
111class PackageManagerService extends IPackageManager.Stub {
112 private static final String TAG = "PackageManager";
113 private static final boolean DEBUG_SETTINGS = false;
114 private static final boolean DEBUG_PREFERRED = false;
115
116 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
117 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400118 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private static final int FIRST_APPLICATION_UID =
120 Process.FIRST_APPLICATION_UID;
121 private static final int MAX_APPLICATION_UIDS = 1000;
122
123 private static final boolean SHOW_INFO = false;
124
125 private static final boolean GET_CERTIFICATES = true;
126
Oscar Montemayora8529f62009-11-18 10:14:20 -0800127 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 private static final int REMOVE_EVENTS =
130 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
131 private static final int ADD_EVENTS =
132 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
133
134 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
135
136 static final int SCAN_MONITOR = 1<<0;
137 static final int SCAN_NO_DEX = 1<<1;
138 static final int SCAN_FORCE_DEX = 1<<2;
139 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800140 static final int SCAN_NEW_INSTALL = 1<<4;
141 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
143 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
144 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700145 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146
Dianne Hackborn851a5412009-05-08 12:06:44 -0700147 final int mSdkVersion = Build.VERSION.SDK_INT;
148 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
149 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 final Context mContext;
152 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700153 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 final DisplayMetrics mMetrics;
155 final int mDefParseFlags;
156 final String[] mSeparateProcesses;
157
158 // This is where all application persistent data goes.
159 final File mAppDataDir;
160
Oscar Montemayora8529f62009-11-18 10:14:20 -0800161 // If Encrypted File System feature is enabled, all application persistent data
162 // should go here instead.
163 final File mSecureAppDataDir;
164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 // This is the object monitoring the framework dir.
166 final FileObserver mFrameworkInstallObserver;
167
168 // This is the object monitoring the system app dir.
169 final FileObserver mSystemInstallObserver;
170
171 // This is the object monitoring mAppInstallDir.
172 final FileObserver mAppInstallObserver;
173
174 // This is the object monitoring mDrmAppPrivateInstallDir.
175 final FileObserver mDrmAppInstallObserver;
176
177 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
178 // LOCK HELD. Can be called with mInstallLock held.
179 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 final File mFrameworkDir;
182 final File mSystemAppDir;
183 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700184 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
186 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
187 // apps.
188 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 // Lock for state used when installing and doing other long running
193 // operations. Methods that must be called with this lock held have
194 // the prefix "LI".
195 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 // These are the directories in the 3rd party applications installed dir
198 // that we have currently loaded packages from. Keys are the application's
199 // installed zip file (absolute codePath), and values are Package.
200 final HashMap<String, PackageParser.Package> mAppDirs =
201 new HashMap<String, PackageParser.Package>();
202
203 // Information for the parser to write more useful error messages.
204 File mScanningPath;
205 int mLastScanError;
206
207 final int[] mOutPermissions = new int[3];
208
209 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 // Keys are String (package name), values are Package. This also serves
212 // as the lock for the global state. Methods that must be called with
213 // this lock held have the prefix "LP".
214 final HashMap<String, PackageParser.Package> mPackages =
215 new HashMap<String, PackageParser.Package>();
216
217 final Settings mSettings;
218 boolean mRestoredSettings;
219 boolean mReportedUidError;
220
221 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
222 int[] mGlobalGids;
223
224 // These are the built-in uid -> permission mappings that were read from the
225 // etc/permissions.xml file.
226 final SparseArray<HashSet<String>> mSystemPermissions =
227 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // These are the built-in shared libraries that were read from the
230 // etc/permissions.xml file.
231 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800232
Dianne Hackborn49237342009-08-27 20:08:01 -0700233 // Temporary for building the final shared libraries for an .apk.
234 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800235
Dianne Hackborn49237342009-08-27 20:08:01 -0700236 // These are the features this devices supports that were read from the
237 // etc/permissions.xml file.
238 final HashMap<String, FeatureInfo> mAvailableFeatures =
239 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 // All available activities, for your resolving pleasure.
242 final ActivityIntentResolver mActivities =
243 new ActivityIntentResolver();
244
245 // All available receivers, for your resolving pleasure.
246 final ActivityIntentResolver mReceivers =
247 new ActivityIntentResolver();
248
249 // All available services, for your resolving pleasure.
250 final ServiceIntentResolver mServices = new ServiceIntentResolver();
251
252 // Keys are String (provider class name), values are Provider.
253 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
254 new HashMap<ComponentName, PackageParser.Provider>();
255
256 // Mapping from provider base names (first directory in content URI codePath)
257 // to the provider information.
258 final HashMap<String, PackageParser.Provider> mProviders =
259 new HashMap<String, PackageParser.Provider>();
260
261 // Mapping from instrumentation class names to info about them.
262 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
263 new HashMap<ComponentName, PackageParser.Instrumentation>();
264
265 // Mapping from permission names to info about them.
266 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
267 new HashMap<String, PackageParser.PermissionGroup>();
268
Dianne Hackborn854060af2009-07-09 18:14:31 -0700269 // Broadcast actions that are only available to the system.
270 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 boolean mSystemReady;
273 boolean mSafeMode;
274 boolean mHasSystemUidErrors;
275
276 ApplicationInfo mAndroidApplication;
277 final ActivityInfo mResolveActivity = new ActivityInfo();
278 final ResolveInfo mResolveInfo = new ResolveInfo();
279 ComponentName mResolveComponentName;
280 PackageParser.Package mPlatformPackage;
281
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700282 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800283 final HashMap<String, ArrayList<String>> mPendingBroadcasts
284 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700285 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800286 static final int DESTROY_SD_CONTAINER = 2;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700287 // Delay time in millisecs
288 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800289 static final int DESTROY_SD_CONTAINER_DELAY = 30 * 1000;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700290
291 class PackageHandler extends Handler {
292 PackageHandler(Looper looper) {
293 super(looper);
294 }
295 public void handleMessage(Message msg) {
296 switch (msg.what) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800297 case DESTROY_SD_CONTAINER:
298 String pkgName = (String) msg.obj;
299 if (pkgName != null) {
300 // Too bad we cannot handle the errors from destroying the containers.
301 if (!destroySdDir(pkgName)) {
302 Log.e(TAG, "Failed to destroy container for pkg : " + pkgName);
303 }
304 }
305 break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700306 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800307 String packages[];
308 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700309 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700310 int uids[];
311 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800312 if (mPendingBroadcasts == null) {
313 return;
314 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700315 size = mPendingBroadcasts.size();
316 if (size <= 0) {
317 // Nothing to be done. Just return
318 return;
319 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800320 packages = new String[size];
321 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700322 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800323 Iterator<HashMap.Entry<String, ArrayList<String>>>
324 it = mPendingBroadcasts.entrySet().iterator();
325 int i = 0;
326 while (it.hasNext() && i < size) {
327 HashMap.Entry<String, ArrayList<String>> ent = it.next();
328 packages[i] = ent.getKey();
329 components[i] = ent.getValue();
330 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700331 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800332 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700333 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800334 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700335 mPendingBroadcasts.clear();
336 }
337 // Send broadcasts
338 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800339 sendPackageChangedBroadcast(packages[i], true,
340 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700341 }
342 break;
343 }
344 }
345 }
346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 public static final IPackageManager main(Context context, boolean factoryTest) {
348 PackageManagerService m = new PackageManagerService(context, factoryTest);
349 ServiceManager.addService("package", m);
350 return m;
351 }
352
353 static String[] splitString(String str, char sep) {
354 int count = 1;
355 int i = 0;
356 while ((i=str.indexOf(sep, i)) >= 0) {
357 count++;
358 i++;
359 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 String[] res = new String[count];
362 i=0;
363 count = 0;
364 int lastI=0;
365 while ((i=str.indexOf(sep, i)) >= 0) {
366 res[count] = str.substring(lastI, i);
367 count++;
368 i++;
369 lastI = i;
370 }
371 res[count] = str.substring(lastI, str.length());
372 return res;
373 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800376 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 if (mSdkVersion <= 0) {
380 Log.w(TAG, "**** ro.build.version.sdk not set!");
381 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 mContext = context;
384 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700385 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 mMetrics = new DisplayMetrics();
387 mSettings = new Settings();
388 mSettings.addSharedUserLP("android.uid.system",
389 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
390 mSettings.addSharedUserLP("android.uid.phone",
391 MULTIPLE_APPLICATION_UIDS
392 ? RADIO_UID : FIRST_APPLICATION_UID,
393 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400394 mSettings.addSharedUserLP("android.uid.log",
395 MULTIPLE_APPLICATION_UIDS
396 ? LOG_UID : FIRST_APPLICATION_UID,
397 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398
399 String separateProcesses = SystemProperties.get("debug.separate_processes");
400 if (separateProcesses != null && separateProcesses.length() > 0) {
401 if ("*".equals(separateProcesses)) {
402 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
403 mSeparateProcesses = null;
404 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
405 } else {
406 mDefParseFlags = 0;
407 mSeparateProcesses = separateProcesses.split(",");
408 Log.w(TAG, "Running with debug.separate_processes: "
409 + separateProcesses);
410 }
411 } else {
412 mDefParseFlags = 0;
413 mSeparateProcesses = null;
414 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 Installer installer = new Installer();
417 // Little hacky thing to check if installd is here, to determine
418 // whether we are running on the simulator and thus need to take
419 // care of building the /data file structure ourself.
420 // (apparently the sim now has a working installer)
421 if (installer.ping() && Process.supportsProcesses()) {
422 mInstaller = installer;
423 } else {
424 mInstaller = null;
425 }
426
427 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
428 Display d = wm.getDefaultDisplay();
429 d.getMetrics(mMetrics);
430
431 synchronized (mInstallLock) {
432 synchronized (mPackages) {
433 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700434 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 File dataDir = Environment.getDataDirectory();
437 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800438 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
440
441 if (mInstaller == null) {
442 // Make sure these dirs exist, when we are running in
443 // the simulator.
444 // Make a wide-open directory for random misc stuff.
445 File miscDir = new File(dataDir, "misc");
446 miscDir.mkdirs();
447 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800448 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 mDrmAppPrivateInstallDir.mkdirs();
450 }
451
452 readPermissions();
453
454 mRestoredSettings = mSettings.readLP();
455 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800456
457 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800459
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800460 // Set flag to monitor and not change apk file paths when
461 // scanning install directories.
462 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700463 if (mNoDexOpt) {
464 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800465 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700466 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700471 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700474 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 /**
477 * Out of paranoia, ensure that everything in the boot class
478 * path has been dexed.
479 */
480 String bootClassPath = System.getProperty("java.boot.class.path");
481 if (bootClassPath != null) {
482 String[] paths = splitString(bootClassPath, ':');
483 for (int i=0; i<paths.length; i++) {
484 try {
485 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
486 libFiles.add(paths[i]);
487 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700488 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 }
490 } catch (FileNotFoundException e) {
491 Log.w(TAG, "Boot class path not found: " + paths[i]);
492 } catch (IOException e) {
493 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
494 }
495 }
496 } else {
497 Log.w(TAG, "No BOOTCLASSPATH found!");
498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 /**
501 * Also ensure all external libraries have had dexopt run on them.
502 */
503 if (mSharedLibraries.size() > 0) {
504 Iterator<String> libs = mSharedLibraries.values().iterator();
505 while (libs.hasNext()) {
506 String lib = libs.next();
507 try {
508 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
509 libFiles.add(lib);
510 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700511 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
513 } catch (FileNotFoundException e) {
514 Log.w(TAG, "Library not found: " + lib);
515 } catch (IOException e) {
516 Log.w(TAG, "Exception reading library: " + lib, e);
517 }
518 }
519 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 // Gross hack for now: we know this file doesn't contain any
522 // code, so don't dexopt it to avoid the resulting log spew.
523 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 /**
526 * And there are a number of commands implemented in Java, which
527 * we currently need to do the dexopt on so that they can be
528 * run from a non-root shell.
529 */
530 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700531 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 for (int i=0; i<frameworkFiles.length; i++) {
533 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
534 String path = libPath.getPath();
535 // Skip the file if we alrady did it.
536 if (libFiles.contains(path)) {
537 continue;
538 }
539 // Skip the file if it is not a type we want to dexopt.
540 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
541 continue;
542 }
543 try {
544 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
545 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700546 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 }
548 } catch (FileNotFoundException e) {
549 Log.w(TAG, "Jar not found: " + path);
550 } catch (IOException e) {
551 Log.w(TAG, "Exception reading jar: " + path, e);
552 }
553 }
554 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800555
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700556 if (didDexOpt) {
557 // If we had to do a dexopt of one of the previous
558 // things, then something on the system has changed.
559 // Consider this significant, and wipe away all other
560 // existing dexopt files to ensure we don't leave any
561 // dangling around.
562 String[] files = mDalvikCacheDir.list();
563 if (files != null) {
564 for (int i=0; i<files.length; i++) {
565 String fn = files[i];
566 if (fn.startsWith("data@app@")
567 || fn.startsWith("data@app-private@")) {
568 Log.i(TAG, "Pruning dalvik file: " + fn);
569 (new File(mDalvikCacheDir, fn)).delete();
570 }
571 }
572 }
573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 mFrameworkInstallObserver = new AppDirObserver(
577 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
578 mFrameworkInstallObserver.startWatching();
579 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800580 scanMode | SCAN_NO_DEX);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
582 mSystemInstallObserver = new AppDirObserver(
583 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
584 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800585 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 mAppInstallDir = new File(dataDir, "app");
587 if (mInstaller == null) {
588 // Make sure these dirs exist, when we are running in
589 // the simulator.
590 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
591 }
592 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800593 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 //clean up list
595 for(int i = 0; i < deletePkgsList.size(); i++) {
596 //clean up here
597 cleanupInstallFailedPackage(deletePkgsList.get(i));
598 }
599 //delete tmp files
600 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800601
602 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 SystemClock.uptimeMillis());
604 mAppInstallObserver = new AppDirObserver(
605 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
606 mAppInstallObserver.startWatching();
607 scanDirLI(mAppInstallDir, 0, scanMode);
608
609 mDrmAppInstallObserver = new AppDirObserver(
610 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
611 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800612 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800614 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 SystemClock.uptimeMillis());
616 Log.i(TAG, "Time to scan packages: "
617 + ((SystemClock.uptimeMillis()-startTime)/1000f)
618 + " seconds");
619
620 updatePermissionsLP();
621
622 mSettings.writeLP();
623
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800624 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 // Now after opening every single application zip, make sure they
628 // are all flushed. Not really needed, but keeps things nice and
629 // tidy.
630 Runtime.getRuntime().gc();
631 } // synchronized (mPackages)
632 } // synchronized (mInstallLock)
633 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 @Override
636 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
637 throws RemoteException {
638 try {
639 return super.onTransact(code, data, reply, flags);
640 } catch (RuntimeException e) {
641 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
642 Log.e(TAG, "Package Manager Crash", e);
643 }
644 throw e;
645 }
646 }
647
Oscar Montemayora8529f62009-11-18 10:14:20 -0800648 void cleanupInstallFailedPackage(PackageSetting pkgSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -0800650 boolean useSecureFS = useEncryptedFilesystemForPackage(pkgSettings.pkg);
651 int retCode = mInstaller.remove(pkgSettings.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 if (retCode < 0) {
653 Log.w(TAG, "Couldn't remove app data directory for package: "
Oscar Montemayora8529f62009-11-18 10:14:20 -0800654 + pkgSettings.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 }
656 } else {
657 //for emulator
Oscar Montemayora8529f62009-11-18 10:14:20 -0800658 File dataDir = new File(pkgSettings.pkg.applicationInfo.dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 dataDir.delete();
660 }
Oscar Montemayora8529f62009-11-18 10:14:20 -0800661 mSettings.removePackageLP(pkgSettings.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 }
663
664 void readPermissions() {
665 // Read permissions from .../etc/permission directory.
666 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
667 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
668 Log.w(TAG, "No directory " + libraryDir + ", skipping");
669 return;
670 }
671 if (!libraryDir.canRead()) {
672 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
673 return;
674 }
675
676 // Iterate over the files in the directory and scan .xml files
677 for (File f : libraryDir.listFiles()) {
678 // We'll read platform.xml last
679 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
680 continue;
681 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 if (!f.getPath().endsWith(".xml")) {
684 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
685 continue;
686 }
687 if (!f.canRead()) {
688 Log.w(TAG, "Permissions library file " + f + " cannot be read");
689 continue;
690 }
691
692 readPermissionsFromXml(f);
693 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
696 final File permFile = new File(Environment.getRootDirectory(),
697 "etc/permissions/platform.xml");
698 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800699
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700700 StringBuilder sb = new StringBuilder(128);
701 sb.append("Libs:");
702 Iterator<String> it = mSharedLibraries.keySet().iterator();
703 while (it.hasNext()) {
704 sb.append(' ');
705 String name = it.next();
706 sb.append(name);
707 sb.append(':');
708 sb.append(mSharedLibraries.get(name));
709 }
710 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800711
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700712 sb.setLength(0);
713 sb.append("Features:");
714 it = mAvailableFeatures.keySet().iterator();
715 while (it.hasNext()) {
716 sb.append(' ');
717 sb.append(it.next());
718 }
719 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721
722 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 FileReader permReader = null;
724 try {
725 permReader = new FileReader(permFile);
726 } catch (FileNotFoundException e) {
727 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
728 return;
729 }
730
731 try {
732 XmlPullParser parser = Xml.newPullParser();
733 parser.setInput(permReader);
734
735 XmlUtils.beginDocument(parser, "permissions");
736
737 while (true) {
738 XmlUtils.nextElement(parser);
739 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
740 break;
741 }
742
743 String name = parser.getName();
744 if ("group".equals(name)) {
745 String gidStr = parser.getAttributeValue(null, "gid");
746 if (gidStr != null) {
747 int gid = Integer.parseInt(gidStr);
748 mGlobalGids = appendInt(mGlobalGids, gid);
749 } else {
750 Log.w(TAG, "<group> without gid at "
751 + parser.getPositionDescription());
752 }
753
754 XmlUtils.skipCurrentTag(parser);
755 continue;
756 } else if ("permission".equals(name)) {
757 String perm = parser.getAttributeValue(null, "name");
758 if (perm == null) {
759 Log.w(TAG, "<permission> without name at "
760 + parser.getPositionDescription());
761 XmlUtils.skipCurrentTag(parser);
762 continue;
763 }
764 perm = perm.intern();
765 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 } else if ("assign-permission".equals(name)) {
768 String perm = parser.getAttributeValue(null, "name");
769 if (perm == null) {
770 Log.w(TAG, "<assign-permission> without name at "
771 + parser.getPositionDescription());
772 XmlUtils.skipCurrentTag(parser);
773 continue;
774 }
775 String uidStr = parser.getAttributeValue(null, "uid");
776 if (uidStr == null) {
777 Log.w(TAG, "<assign-permission> without uid at "
778 + parser.getPositionDescription());
779 XmlUtils.skipCurrentTag(parser);
780 continue;
781 }
782 int uid = Process.getUidForName(uidStr);
783 if (uid < 0) {
784 Log.w(TAG, "<assign-permission> with unknown uid \""
785 + uidStr + "\" at "
786 + parser.getPositionDescription());
787 XmlUtils.skipCurrentTag(parser);
788 continue;
789 }
790 perm = perm.intern();
791 HashSet<String> perms = mSystemPermissions.get(uid);
792 if (perms == null) {
793 perms = new HashSet<String>();
794 mSystemPermissions.put(uid, perms);
795 }
796 perms.add(perm);
797 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 } else if ("library".equals(name)) {
800 String lname = parser.getAttributeValue(null, "name");
801 String lfile = parser.getAttributeValue(null, "file");
802 if (lname == null) {
803 Log.w(TAG, "<library> without name at "
804 + parser.getPositionDescription());
805 } else if (lfile == null) {
806 Log.w(TAG, "<library> without file at "
807 + parser.getPositionDescription());
808 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700809 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700810 mSharedLibraries.put(lname, lfile);
811 }
812 XmlUtils.skipCurrentTag(parser);
813 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800814
Dianne Hackborn49237342009-08-27 20:08:01 -0700815 } else if ("feature".equals(name)) {
816 String fname = parser.getAttributeValue(null, "name");
817 if (fname == null) {
818 Log.w(TAG, "<feature> without name at "
819 + parser.getPositionDescription());
820 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700821 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700822 FeatureInfo fi = new FeatureInfo();
823 fi.name = fname;
824 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 }
826 XmlUtils.skipCurrentTag(parser);
827 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 } else {
830 XmlUtils.skipCurrentTag(parser);
831 continue;
832 }
833
834 }
835 } catch (XmlPullParserException e) {
836 Log.w(TAG, "Got execption parsing permissions.", e);
837 } catch (IOException e) {
838 Log.w(TAG, "Got execption parsing permissions.", e);
839 }
840 }
841
842 void readPermission(XmlPullParser parser, String name)
843 throws IOException, XmlPullParserException {
844
845 name = name.intern();
846
847 BasePermission bp = mSettings.mPermissions.get(name);
848 if (bp == null) {
849 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
850 mSettings.mPermissions.put(name, bp);
851 }
852 int outerDepth = parser.getDepth();
853 int type;
854 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
855 && (type != XmlPullParser.END_TAG
856 || parser.getDepth() > outerDepth)) {
857 if (type == XmlPullParser.END_TAG
858 || type == XmlPullParser.TEXT) {
859 continue;
860 }
861
862 String tagName = parser.getName();
863 if ("group".equals(tagName)) {
864 String gidStr = parser.getAttributeValue(null, "gid");
865 if (gidStr != null) {
866 int gid = Process.getGidForName(gidStr);
867 bp.gids = appendInt(bp.gids, gid);
868 } else {
869 Log.w(TAG, "<group> without gid at "
870 + parser.getPositionDescription());
871 }
872 }
873 XmlUtils.skipCurrentTag(parser);
874 }
875 }
876
877 static int[] appendInt(int[] cur, int val) {
878 if (cur == null) {
879 return new int[] { val };
880 }
881 final int N = cur.length;
882 for (int i=0; i<N; i++) {
883 if (cur[i] == val) {
884 return cur;
885 }
886 }
887 int[] ret = new int[N+1];
888 System.arraycopy(cur, 0, ret, 0, N);
889 ret[N] = val;
890 return ret;
891 }
892
893 static int[] appendInts(int[] cur, int[] add) {
894 if (add == null) return cur;
895 if (cur == null) return add;
896 final int N = add.length;
897 for (int i=0; i<N; i++) {
898 cur = appendInt(cur, add[i]);
899 }
900 return cur;
901 }
902
903 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -0700904 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
905 // The package has been uninstalled but has retained data and resources.
906 return PackageParser.generatePackageInfo(p, null, flags);
907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 final PackageSetting ps = (PackageSetting)p.mExtras;
909 if (ps == null) {
910 return null;
911 }
912 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
913 return PackageParser.generatePackageInfo(p, gp.gids, flags);
914 }
915
916 public PackageInfo getPackageInfo(String packageName, int flags) {
917 synchronized (mPackages) {
918 PackageParser.Package p = mPackages.get(packageName);
919 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700920 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 + ": " + p);
922 if (p != null) {
923 return generatePackageInfo(p, flags);
924 }
925 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
926 return generatePackageInfoFromSettingsLP(packageName, flags);
927 }
928 }
929 return null;
930 }
931
932 public int getPackageUid(String packageName) {
933 synchronized (mPackages) {
934 PackageParser.Package p = mPackages.get(packageName);
935 if(p != null) {
936 return p.applicationInfo.uid;
937 }
938 PackageSetting ps = mSettings.mPackages.get(packageName);
939 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
940 return -1;
941 }
942 p = ps.pkg;
943 return p != null ? p.applicationInfo.uid : -1;
944 }
945 }
946
947 public int[] getPackageGids(String packageName) {
948 synchronized (mPackages) {
949 PackageParser.Package p = mPackages.get(packageName);
950 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700951 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 + ": " + p);
953 if (p != null) {
954 final PackageSetting ps = (PackageSetting)p.mExtras;
955 final SharedUserSetting suid = ps.sharedUser;
956 return suid != null ? suid.gids : ps.gids;
957 }
958 }
959 // stupid thing to indicate an error.
960 return new int[0];
961 }
962
963 public PermissionInfo getPermissionInfo(String name, int flags) {
964 synchronized (mPackages) {
965 final BasePermission p = mSettings.mPermissions.get(name);
966 if (p != null && p.perm != null) {
967 return PackageParser.generatePermissionInfo(p.perm, flags);
968 }
969 return null;
970 }
971 }
972
973 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
974 synchronized (mPackages) {
975 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
976 for (BasePermission p : mSettings.mPermissions.values()) {
977 if (group == null) {
978 if (p.perm.info.group == null) {
979 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
980 }
981 } else {
982 if (group.equals(p.perm.info.group)) {
983 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
984 }
985 }
986 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 if (out.size() > 0) {
989 return out;
990 }
991 return mPermissionGroups.containsKey(group) ? out : null;
992 }
993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
996 synchronized (mPackages) {
997 return PackageParser.generatePermissionGroupInfo(
998 mPermissionGroups.get(name), flags);
999 }
1000 }
1001
1002 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1003 synchronized (mPackages) {
1004 final int N = mPermissionGroups.size();
1005 ArrayList<PermissionGroupInfo> out
1006 = new ArrayList<PermissionGroupInfo>(N);
1007 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1008 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1009 }
1010 return out;
1011 }
1012 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1015 PackageSetting ps = mSettings.mPackages.get(packageName);
1016 if(ps != null) {
1017 if(ps.pkg == null) {
1018 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1019 if(pInfo != null) {
1020 return pInfo.applicationInfo;
1021 }
1022 return null;
1023 }
1024 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1025 }
1026 return null;
1027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1030 PackageSetting ps = mSettings.mPackages.get(packageName);
1031 if(ps != null) {
1032 if(ps.pkg == null) {
1033 ps.pkg = new PackageParser.Package(packageName);
1034 ps.pkg.applicationInfo.packageName = packageName;
1035 }
1036 return generatePackageInfo(ps.pkg, flags);
1037 }
1038 return null;
1039 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1042 synchronized (mPackages) {
1043 PackageParser.Package p = mPackages.get(packageName);
1044 if (Config.LOGV) Log.v(
1045 TAG, "getApplicationInfo " + packageName
1046 + ": " + p);
1047 if (p != null) {
1048 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001049 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051 if ("android".equals(packageName)||"system".equals(packageName)) {
1052 return mAndroidApplication;
1053 }
1054 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1055 return generateApplicationInfoFromSettingsLP(packageName, flags);
1056 }
1057 }
1058 return null;
1059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001060
1061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1063 mContext.enforceCallingOrSelfPermission(
1064 android.Manifest.permission.CLEAR_APP_CACHE, null);
1065 // Queue up an async operation since clearing cache may take a little while.
1066 mHandler.post(new Runnable() {
1067 public void run() {
1068 mHandler.removeCallbacks(this);
1069 int retCode = -1;
1070 if (mInstaller != null) {
1071 retCode = mInstaller.freeCache(freeStorageSize);
1072 if (retCode < 0) {
1073 Log.w(TAG, "Couldn't clear application caches");
1074 }
1075 } //end if mInstaller
1076 if (observer != null) {
1077 try {
1078 observer.onRemoveCompleted(null, (retCode >= 0));
1079 } catch (RemoteException e) {
1080 Log.w(TAG, "RemoveException when invoking call back");
1081 }
1082 }
1083 }
1084 });
1085 }
1086
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001087 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001088 mContext.enforceCallingOrSelfPermission(
1089 android.Manifest.permission.CLEAR_APP_CACHE, null);
1090 // Queue up an async operation since clearing cache may take a little while.
1091 mHandler.post(new Runnable() {
1092 public void run() {
1093 mHandler.removeCallbacks(this);
1094 int retCode = -1;
1095 if (mInstaller != null) {
1096 retCode = mInstaller.freeCache(freeStorageSize);
1097 if (retCode < 0) {
1098 Log.w(TAG, "Couldn't clear application caches");
1099 }
1100 }
1101 if(pi != null) {
1102 try {
1103 // Callback via pending intent
1104 int code = (retCode >= 0) ? 1 : 0;
1105 pi.sendIntent(null, code, null,
1106 null, null);
1107 } catch (SendIntentException e1) {
1108 Log.i(TAG, "Failed to send pending intent");
1109 }
1110 }
1111 }
1112 });
1113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1116 synchronized (mPackages) {
1117 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001118
1119 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001121 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 }
1123 if (mResolveComponentName.equals(component)) {
1124 return mResolveActivity;
1125 }
1126 }
1127 return null;
1128 }
1129
1130 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1131 synchronized (mPackages) {
1132 PackageParser.Activity a = mReceivers.mActivities.get(component);
1133 if (Config.LOGV) Log.v(
1134 TAG, "getReceiverInfo " + component + ": " + a);
1135 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1136 return PackageParser.generateActivityInfo(a, flags);
1137 }
1138 }
1139 return null;
1140 }
1141
1142 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1143 synchronized (mPackages) {
1144 PackageParser.Service s = mServices.mServices.get(component);
1145 if (Config.LOGV) Log.v(
1146 TAG, "getServiceInfo " + component + ": " + s);
1147 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1148 return PackageParser.generateServiceInfo(s, flags);
1149 }
1150 }
1151 return null;
1152 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 public String[] getSystemSharedLibraryNames() {
1155 Set<String> libSet;
1156 synchronized (mPackages) {
1157 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001158 int size = libSet.size();
1159 if (size > 0) {
1160 String[] libs = new String[size];
1161 libSet.toArray(libs);
1162 return libs;
1163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001165 return null;
1166 }
1167
1168 public FeatureInfo[] getSystemAvailableFeatures() {
1169 Collection<FeatureInfo> featSet;
1170 synchronized (mPackages) {
1171 featSet = mAvailableFeatures.values();
1172 int size = featSet.size();
1173 if (size > 0) {
1174 FeatureInfo[] features = new FeatureInfo[size+1];
1175 featSet.toArray(features);
1176 FeatureInfo fi = new FeatureInfo();
1177 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1178 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1179 features[size] = fi;
1180 return features;
1181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 }
1183 return null;
1184 }
1185
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001186 public boolean hasSystemFeature(String name) {
1187 synchronized (mPackages) {
1188 return mAvailableFeatures.containsKey(name);
1189 }
1190 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 public int checkPermission(String permName, String pkgName) {
1193 synchronized (mPackages) {
1194 PackageParser.Package p = mPackages.get(pkgName);
1195 if (p != null && p.mExtras != null) {
1196 PackageSetting ps = (PackageSetting)p.mExtras;
1197 if (ps.sharedUser != null) {
1198 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1199 return PackageManager.PERMISSION_GRANTED;
1200 }
1201 } else if (ps.grantedPermissions.contains(permName)) {
1202 return PackageManager.PERMISSION_GRANTED;
1203 }
1204 }
1205 }
1206 return PackageManager.PERMISSION_DENIED;
1207 }
1208
1209 public int checkUidPermission(String permName, int uid) {
1210 synchronized (mPackages) {
1211 Object obj = mSettings.getUserIdLP(uid);
1212 if (obj != null) {
1213 if (obj instanceof SharedUserSetting) {
1214 SharedUserSetting sus = (SharedUserSetting)obj;
1215 if (sus.grantedPermissions.contains(permName)) {
1216 return PackageManager.PERMISSION_GRANTED;
1217 }
1218 } else if (obj instanceof PackageSetting) {
1219 PackageSetting ps = (PackageSetting)obj;
1220 if (ps.grantedPermissions.contains(permName)) {
1221 return PackageManager.PERMISSION_GRANTED;
1222 }
1223 }
1224 } else {
1225 HashSet<String> perms = mSystemPermissions.get(uid);
1226 if (perms != null && perms.contains(permName)) {
1227 return PackageManager.PERMISSION_GRANTED;
1228 }
1229 }
1230 }
1231 return PackageManager.PERMISSION_DENIED;
1232 }
1233
1234 private BasePermission findPermissionTreeLP(String permName) {
1235 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1236 if (permName.startsWith(bp.name) &&
1237 permName.length() > bp.name.length() &&
1238 permName.charAt(bp.name.length()) == '.') {
1239 return bp;
1240 }
1241 }
1242 return null;
1243 }
1244
1245 private BasePermission checkPermissionTreeLP(String permName) {
1246 if (permName != null) {
1247 BasePermission bp = findPermissionTreeLP(permName);
1248 if (bp != null) {
1249 if (bp.uid == Binder.getCallingUid()) {
1250 return bp;
1251 }
1252 throw new SecurityException("Calling uid "
1253 + Binder.getCallingUid()
1254 + " is not allowed to add to permission tree "
1255 + bp.name + " owned by uid " + bp.uid);
1256 }
1257 }
1258 throw new SecurityException("No permission tree found for " + permName);
1259 }
1260
1261 public boolean addPermission(PermissionInfo info) {
1262 synchronized (mPackages) {
1263 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1264 throw new SecurityException("Label must be specified in permission");
1265 }
1266 BasePermission tree = checkPermissionTreeLP(info.name);
1267 BasePermission bp = mSettings.mPermissions.get(info.name);
1268 boolean added = bp == null;
1269 if (added) {
1270 bp = new BasePermission(info.name, tree.sourcePackage,
1271 BasePermission.TYPE_DYNAMIC);
1272 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1273 throw new SecurityException(
1274 "Not allowed to modify non-dynamic permission "
1275 + info.name);
1276 }
1277 bp.perm = new PackageParser.Permission(tree.perm.owner,
1278 new PermissionInfo(info));
1279 bp.perm.info.packageName = tree.perm.info.packageName;
1280 bp.uid = tree.uid;
1281 if (added) {
1282 mSettings.mPermissions.put(info.name, bp);
1283 }
1284 mSettings.writeLP();
1285 return added;
1286 }
1287 }
1288
1289 public void removePermission(String name) {
1290 synchronized (mPackages) {
1291 checkPermissionTreeLP(name);
1292 BasePermission bp = mSettings.mPermissions.get(name);
1293 if (bp != null) {
1294 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1295 throw new SecurityException(
1296 "Not allowed to modify non-dynamic permission "
1297 + name);
1298 }
1299 mSettings.mPermissions.remove(name);
1300 mSettings.writeLP();
1301 }
1302 }
1303 }
1304
Dianne Hackborn854060af2009-07-09 18:14:31 -07001305 public boolean isProtectedBroadcast(String actionName) {
1306 synchronized (mPackages) {
1307 return mProtectedBroadcasts.contains(actionName);
1308 }
1309 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 public int checkSignatures(String pkg1, String pkg2) {
1312 synchronized (mPackages) {
1313 PackageParser.Package p1 = mPackages.get(pkg1);
1314 PackageParser.Package p2 = mPackages.get(pkg2);
1315 if (p1 == null || p1.mExtras == null
1316 || p2 == null || p2.mExtras == null) {
1317 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1318 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001319 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 }
1321 }
1322
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001323 public int checkUidSignatures(int uid1, int uid2) {
1324 synchronized (mPackages) {
1325 Signature[] s1;
1326 Signature[] s2;
1327 Object obj = mSettings.getUserIdLP(uid1);
1328 if (obj != null) {
1329 if (obj instanceof SharedUserSetting) {
1330 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1331 } else if (obj instanceof PackageSetting) {
1332 s1 = ((PackageSetting)obj).signatures.mSignatures;
1333 } else {
1334 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1335 }
1336 } else {
1337 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1338 }
1339 obj = mSettings.getUserIdLP(uid2);
1340 if (obj != null) {
1341 if (obj instanceof SharedUserSetting) {
1342 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1343 } else if (obj instanceof PackageSetting) {
1344 s2 = ((PackageSetting)obj).signatures.mSignatures;
1345 } else {
1346 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1347 }
1348 } else {
1349 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1350 }
1351 return checkSignaturesLP(s1, s2);
1352 }
1353 }
1354
1355 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1356 if (s1 == null) {
1357 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1359 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1360 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001361 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1363 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001364 final int N1 = s1.length;
1365 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 for (int i=0; i<N1; i++) {
1367 boolean match = false;
1368 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001369 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 match = true;
1371 break;
1372 }
1373 }
1374 if (!match) {
1375 return PackageManager.SIGNATURE_NO_MATCH;
1376 }
1377 }
1378 return PackageManager.SIGNATURE_MATCH;
1379 }
1380
1381 public String[] getPackagesForUid(int uid) {
1382 synchronized (mPackages) {
1383 Object obj = mSettings.getUserIdLP(uid);
1384 if (obj instanceof SharedUserSetting) {
1385 SharedUserSetting sus = (SharedUserSetting)obj;
1386 final int N = sus.packages.size();
1387 String[] res = new String[N];
1388 Iterator<PackageSetting> it = sus.packages.iterator();
1389 int i=0;
1390 while (it.hasNext()) {
1391 res[i++] = it.next().name;
1392 }
1393 return res;
1394 } else if (obj instanceof PackageSetting) {
1395 PackageSetting ps = (PackageSetting)obj;
1396 return new String[] { ps.name };
1397 }
1398 }
1399 return null;
1400 }
1401
1402 public String getNameForUid(int uid) {
1403 synchronized (mPackages) {
1404 Object obj = mSettings.getUserIdLP(uid);
1405 if (obj instanceof SharedUserSetting) {
1406 SharedUserSetting sus = (SharedUserSetting)obj;
1407 return sus.name + ":" + sus.userId;
1408 } else if (obj instanceof PackageSetting) {
1409 PackageSetting ps = (PackageSetting)obj;
1410 return ps.name;
1411 }
1412 }
1413 return null;
1414 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 public int getUidForSharedUser(String sharedUserName) {
1417 if(sharedUserName == null) {
1418 return -1;
1419 }
1420 synchronized (mPackages) {
1421 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1422 if(suid == null) {
1423 return -1;
1424 }
1425 return suid.userId;
1426 }
1427 }
1428
1429 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1430 int flags) {
1431 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001432 return chooseBestActivity(intent, resolvedType, flags, query);
1433 }
1434
Mihai Predaeae850c2009-05-13 10:13:48 +02001435 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1436 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 if (query != null) {
1438 final int N = query.size();
1439 if (N == 1) {
1440 return query.get(0);
1441 } else if (N > 1) {
1442 // If there is more than one activity with the same priority,
1443 // then let the user decide between them.
1444 ResolveInfo r0 = query.get(0);
1445 ResolveInfo r1 = query.get(1);
1446 if (false) {
1447 System.out.println(r0.activityInfo.name +
1448 "=" + r0.priority + " vs " +
1449 r1.activityInfo.name +
1450 "=" + r1.priority);
1451 }
1452 // If the first activity has a higher priority, or a different
1453 // default, then it is always desireable to pick it.
1454 if (r0.priority != r1.priority
1455 || r0.preferredOrder != r1.preferredOrder
1456 || r0.isDefault != r1.isDefault) {
1457 return query.get(0);
1458 }
1459 // If we have saved a preference for a preferred activity for
1460 // this Intent, use that.
1461 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1462 flags, query, r0.priority);
1463 if (ri != null) {
1464 return ri;
1465 }
1466 return mResolveInfo;
1467 }
1468 }
1469 return null;
1470 }
1471
1472 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1473 int flags, List<ResolveInfo> query, int priority) {
1474 synchronized (mPackages) {
1475 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1476 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001477 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1479 if (prefs != null && prefs.size() > 0) {
1480 // First figure out how good the original match set is.
1481 // We will only allow preferred activities that came
1482 // from the same match quality.
1483 int match = 0;
1484 final int N = query.size();
1485 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1486 for (int j=0; j<N; j++) {
1487 ResolveInfo ri = query.get(j);
1488 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1489 + ": 0x" + Integer.toHexString(match));
1490 if (ri.match > match) match = ri.match;
1491 }
1492 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1493 + Integer.toHexString(match));
1494 match &= IntentFilter.MATCH_CATEGORY_MASK;
1495 final int M = prefs.size();
1496 for (int i=0; i<M; i++) {
1497 PreferredActivity pa = prefs.get(i);
1498 if (pa.mMatch != match) {
1499 continue;
1500 }
1501 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1502 if (DEBUG_PREFERRED) {
1503 Log.v(TAG, "Got preferred activity:");
1504 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1505 }
1506 if (ai != null) {
1507 for (int j=0; j<N; j++) {
1508 ResolveInfo ri = query.get(j);
1509 if (!ri.activityInfo.applicationInfo.packageName
1510 .equals(ai.applicationInfo.packageName)) {
1511 continue;
1512 }
1513 if (!ri.activityInfo.name.equals(ai.name)) {
1514 continue;
1515 }
1516
1517 // Okay we found a previously set preferred app.
1518 // If the result set is different from when this
1519 // was created, we need to clear it and re-ask the
1520 // user their preference.
1521 if (!pa.sameSet(query, priority)) {
1522 Log.i(TAG, "Result set changed, dropping preferred activity for "
1523 + intent + " type " + resolvedType);
1524 mSettings.mPreferredActivities.removeFilter(pa);
1525 return null;
1526 }
1527
1528 // Yay!
1529 return ri;
1530 }
1531 }
1532 }
1533 }
1534 }
1535 return null;
1536 }
1537
1538 public List<ResolveInfo> queryIntentActivities(Intent intent,
1539 String resolvedType, int flags) {
1540 ComponentName comp = intent.getComponent();
1541 if (comp != null) {
1542 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1543 ActivityInfo ai = getActivityInfo(comp, flags);
1544 if (ai != null) {
1545 ResolveInfo ri = new ResolveInfo();
1546 ri.activityInfo = ai;
1547 list.add(ri);
1548 }
1549 return list;
1550 }
1551
1552 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001553 String pkgName = intent.getPackage();
1554 if (pkgName == null) {
1555 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1556 resolvedType, flags);
1557 }
1558 PackageParser.Package pkg = mPackages.get(pkgName);
1559 if (pkg != null) {
1560 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1561 resolvedType, flags, pkg.activities);
1562 }
1563 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565 }
1566
1567 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1568 Intent[] specifics, String[] specificTypes, Intent intent,
1569 String resolvedType, int flags) {
1570 final String resultsAction = intent.getAction();
1571
1572 List<ResolveInfo> results = queryIntentActivities(
1573 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1574 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1575
1576 int specificsPos = 0;
1577 int N;
1578
1579 // todo: note that the algorithm used here is O(N^2). This
1580 // isn't a problem in our current environment, but if we start running
1581 // into situations where we have more than 5 or 10 matches then this
1582 // should probably be changed to something smarter...
1583
1584 // First we go through and resolve each of the specific items
1585 // that were supplied, taking care of removing any corresponding
1586 // duplicate items in the generic resolve list.
1587 if (specifics != null) {
1588 for (int i=0; i<specifics.length; i++) {
1589 final Intent sintent = specifics[i];
1590 if (sintent == null) {
1591 continue;
1592 }
1593
1594 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1595 String action = sintent.getAction();
1596 if (resultsAction != null && resultsAction.equals(action)) {
1597 // If this action was explicitly requested, then don't
1598 // remove things that have it.
1599 action = null;
1600 }
1601 ComponentName comp = sintent.getComponent();
1602 ResolveInfo ri = null;
1603 ActivityInfo ai = null;
1604 if (comp == null) {
1605 ri = resolveIntent(
1606 sintent,
1607 specificTypes != null ? specificTypes[i] : null,
1608 flags);
1609 if (ri == null) {
1610 continue;
1611 }
1612 if (ri == mResolveInfo) {
1613 // ACK! Must do something better with this.
1614 }
1615 ai = ri.activityInfo;
1616 comp = new ComponentName(ai.applicationInfo.packageName,
1617 ai.name);
1618 } else {
1619 ai = getActivityInfo(comp, flags);
1620 if (ai == null) {
1621 continue;
1622 }
1623 }
1624
1625 // Look for any generic query activities that are duplicates
1626 // of this specific one, and remove them from the results.
1627 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1628 N = results.size();
1629 int j;
1630 for (j=specificsPos; j<N; j++) {
1631 ResolveInfo sri = results.get(j);
1632 if ((sri.activityInfo.name.equals(comp.getClassName())
1633 && sri.activityInfo.applicationInfo.packageName.equals(
1634 comp.getPackageName()))
1635 || (action != null && sri.filter.matchAction(action))) {
1636 results.remove(j);
1637 if (Config.LOGV) Log.v(
1638 TAG, "Removing duplicate item from " + j
1639 + " due to specific " + specificsPos);
1640 if (ri == null) {
1641 ri = sri;
1642 }
1643 j--;
1644 N--;
1645 }
1646 }
1647
1648 // Add this specific item to its proper place.
1649 if (ri == null) {
1650 ri = new ResolveInfo();
1651 ri.activityInfo = ai;
1652 }
1653 results.add(specificsPos, ri);
1654 ri.specificIndex = i;
1655 specificsPos++;
1656 }
1657 }
1658
1659 // Now we go through the remaining generic results and remove any
1660 // duplicate actions that are found here.
1661 N = results.size();
1662 for (int i=specificsPos; i<N-1; i++) {
1663 final ResolveInfo rii = results.get(i);
1664 if (rii.filter == null) {
1665 continue;
1666 }
1667
1668 // Iterate over all of the actions of this result's intent
1669 // filter... typically this should be just one.
1670 final Iterator<String> it = rii.filter.actionsIterator();
1671 if (it == null) {
1672 continue;
1673 }
1674 while (it.hasNext()) {
1675 final String action = it.next();
1676 if (resultsAction != null && resultsAction.equals(action)) {
1677 // If this action was explicitly requested, then don't
1678 // remove things that have it.
1679 continue;
1680 }
1681 for (int j=i+1; j<N; j++) {
1682 final ResolveInfo rij = results.get(j);
1683 if (rij.filter != null && rij.filter.hasAction(action)) {
1684 results.remove(j);
1685 if (Config.LOGV) Log.v(
1686 TAG, "Removing duplicate item from " + j
1687 + " due to action " + action + " at " + i);
1688 j--;
1689 N--;
1690 }
1691 }
1692 }
1693
1694 // If the caller didn't request filter information, drop it now
1695 // so we don't have to marshall/unmarshall it.
1696 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1697 rii.filter = null;
1698 }
1699 }
1700
1701 // Filter out the caller activity if so requested.
1702 if (caller != null) {
1703 N = results.size();
1704 for (int i=0; i<N; i++) {
1705 ActivityInfo ainfo = results.get(i).activityInfo;
1706 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1707 && caller.getClassName().equals(ainfo.name)) {
1708 results.remove(i);
1709 break;
1710 }
1711 }
1712 }
1713
1714 // If the caller didn't request filter information,
1715 // drop them now so we don't have to
1716 // marshall/unmarshall it.
1717 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1718 N = results.size();
1719 for (int i=0; i<N; i++) {
1720 results.get(i).filter = null;
1721 }
1722 }
1723
1724 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1725 return results;
1726 }
1727
1728 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1729 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001730 ComponentName comp = intent.getComponent();
1731 if (comp != null) {
1732 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1733 ActivityInfo ai = getReceiverInfo(comp, flags);
1734 if (ai != null) {
1735 ResolveInfo ri = new ResolveInfo();
1736 ri.activityInfo = ai;
1737 list.add(ri);
1738 }
1739 return list;
1740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001743 String pkgName = intent.getPackage();
1744 if (pkgName == null) {
1745 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1746 resolvedType, flags);
1747 }
1748 PackageParser.Package pkg = mPackages.get(pkgName);
1749 if (pkg != null) {
1750 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1751 resolvedType, flags, pkg.receivers);
1752 }
1753 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
1755 }
1756
1757 public ResolveInfo resolveService(Intent intent, String resolvedType,
1758 int flags) {
1759 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1760 flags);
1761 if (query != null) {
1762 if (query.size() >= 1) {
1763 // If there is more than one service with the same priority,
1764 // just arbitrarily pick the first one.
1765 return query.get(0);
1766 }
1767 }
1768 return null;
1769 }
1770
1771 public List<ResolveInfo> queryIntentServices(Intent intent,
1772 String resolvedType, int flags) {
1773 ComponentName comp = intent.getComponent();
1774 if (comp != null) {
1775 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1776 ServiceInfo si = getServiceInfo(comp, flags);
1777 if (si != null) {
1778 ResolveInfo ri = new ResolveInfo();
1779 ri.serviceInfo = si;
1780 list.add(ri);
1781 }
1782 return list;
1783 }
1784
1785 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001786 String pkgName = intent.getPackage();
1787 if (pkgName == null) {
1788 return (List<ResolveInfo>)mServices.queryIntent(intent,
1789 resolvedType, flags);
1790 }
1791 PackageParser.Package pkg = mPackages.get(pkgName);
1792 if (pkg != null) {
1793 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1794 resolvedType, flags, pkg.services);
1795 }
1796 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 public List<PackageInfo> getInstalledPackages(int flags) {
1801 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1802
1803 synchronized (mPackages) {
1804 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1805 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1806 while (i.hasNext()) {
1807 final PackageSetting ps = i.next();
1808 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1809 if(psPkg != null) {
1810 finalList.add(psPkg);
1811 }
1812 }
1813 }
1814 else {
1815 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1816 while (i.hasNext()) {
1817 final PackageParser.Package p = i.next();
1818 if (p.applicationInfo != null) {
1819 PackageInfo pi = generatePackageInfo(p, flags);
1820 if(pi != null) {
1821 finalList.add(pi);
1822 }
1823 }
1824 }
1825 }
1826 }
1827 return finalList;
1828 }
1829
1830 public List<ApplicationInfo> getInstalledApplications(int flags) {
1831 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1832 synchronized(mPackages) {
1833 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1834 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1835 while (i.hasNext()) {
1836 final PackageSetting ps = i.next();
1837 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1838 if(ai != null) {
1839 finalList.add(ai);
1840 }
1841 }
1842 }
1843 else {
1844 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1845 while (i.hasNext()) {
1846 final PackageParser.Package p = i.next();
1847 if (p.applicationInfo != null) {
1848 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1849 if(ai != null) {
1850 finalList.add(ai);
1851 }
1852 }
1853 }
1854 }
1855 }
1856 return finalList;
1857 }
1858
1859 public List<ApplicationInfo> getPersistentApplications(int flags) {
1860 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1861
1862 synchronized (mPackages) {
1863 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1864 while (i.hasNext()) {
1865 PackageParser.Package p = i.next();
1866 if (p.applicationInfo != null
1867 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
1868 && (!mSafeMode || (p.applicationInfo.flags
1869 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1870 finalList.add(p.applicationInfo);
1871 }
1872 }
1873 }
1874
1875 return finalList;
1876 }
1877
1878 public ProviderInfo resolveContentProvider(String name, int flags) {
1879 synchronized (mPackages) {
1880 final PackageParser.Provider provider = mProviders.get(name);
1881 return provider != null
1882 && mSettings.isEnabledLP(provider.info, flags)
1883 && (!mSafeMode || (provider.info.applicationInfo.flags
1884 &ApplicationInfo.FLAG_SYSTEM) != 0)
1885 ? PackageParser.generateProviderInfo(provider, flags)
1886 : null;
1887 }
1888 }
1889
Fred Quintana718d8a22009-04-29 17:53:20 -07001890 /**
1891 * @deprecated
1892 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 public void querySyncProviders(List outNames, List outInfo) {
1894 synchronized (mPackages) {
1895 Iterator<Map.Entry<String, PackageParser.Provider>> i
1896 = mProviders.entrySet().iterator();
1897
1898 while (i.hasNext()) {
1899 Map.Entry<String, PackageParser.Provider> entry = i.next();
1900 PackageParser.Provider p = entry.getValue();
1901
1902 if (p.syncable
1903 && (!mSafeMode || (p.info.applicationInfo.flags
1904 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1905 outNames.add(entry.getKey());
1906 outInfo.add(PackageParser.generateProviderInfo(p, 0));
1907 }
1908 }
1909 }
1910 }
1911
1912 public List<ProviderInfo> queryContentProviders(String processName,
1913 int uid, int flags) {
1914 ArrayList<ProviderInfo> finalList = null;
1915
1916 synchronized (mPackages) {
1917 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
1918 while (i.hasNext()) {
1919 PackageParser.Provider p = i.next();
1920 if (p.info.authority != null
1921 && (processName == null ||
1922 (p.info.processName.equals(processName)
1923 && p.info.applicationInfo.uid == uid))
1924 && mSettings.isEnabledLP(p.info, flags)
1925 && (!mSafeMode || (p.info.applicationInfo.flags
1926 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1927 if (finalList == null) {
1928 finalList = new ArrayList<ProviderInfo>(3);
1929 }
1930 finalList.add(PackageParser.generateProviderInfo(p,
1931 flags));
1932 }
1933 }
1934 }
1935
1936 if (finalList != null) {
1937 Collections.sort(finalList, mProviderInitOrderSorter);
1938 }
1939
1940 return finalList;
1941 }
1942
1943 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
1944 int flags) {
1945 synchronized (mPackages) {
1946 final PackageParser.Instrumentation i = mInstrumentation.get(name);
1947 return PackageParser.generateInstrumentationInfo(i, flags);
1948 }
1949 }
1950
1951 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
1952 int flags) {
1953 ArrayList<InstrumentationInfo> finalList =
1954 new ArrayList<InstrumentationInfo>();
1955
1956 synchronized (mPackages) {
1957 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
1958 while (i.hasNext()) {
1959 PackageParser.Instrumentation p = i.next();
1960 if (targetPackage == null
1961 || targetPackage.equals(p.info.targetPackage)) {
1962 finalList.add(PackageParser.generateInstrumentationInfo(p,
1963 flags));
1964 }
1965 }
1966 }
1967
1968 return finalList;
1969 }
1970
1971 private void scanDirLI(File dir, int flags, int scanMode) {
1972 Log.d(TAG, "Scanning app dir " + dir);
1973
1974 String[] files = dir.list();
1975
1976 int i;
1977 for (i=0; i<files.length; i++) {
1978 File file = new File(dir, files[i]);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08001979 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
1981 }
1982 }
1983
1984 private static void reportSettingsProblem(int priority, String msg) {
1985 try {
1986 File dataDir = Environment.getDataDirectory();
1987 File systemDir = new File(dataDir, "system");
1988 File fname = new File(systemDir, "uiderrors.txt");
1989 FileOutputStream out = new FileOutputStream(fname, true);
1990 PrintWriter pw = new PrintWriter(out);
1991 pw.println(msg);
1992 pw.close();
1993 FileUtils.setPermissions(
1994 fname.toString(),
1995 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
1996 -1, -1);
1997 } catch (java.io.IOException e) {
1998 }
1999 Log.println(priority, TAG, msg);
2000 }
2001
2002 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2003 PackageParser.Package pkg, File srcFile, int parseFlags) {
2004 if (GET_CERTIFICATES) {
2005 if (ps == null || !ps.codePath.equals(srcFile)
2006 || ps.getTimeStamp() != srcFile.lastModified()) {
2007 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2008 if (!pp.collectCertificates(pkg, parseFlags)) {
2009 mLastScanError = pp.getParseError();
2010 return false;
2011 }
2012 }
2013 }
2014 return true;
2015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 /*
2018 * Scan a package and return the newly parsed package.
2019 * Returns null in case of errors and the error code is stored in mLastScanError
2020 */
2021 private PackageParser.Package scanPackageLI(File scanFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002022 int parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 int scanMode) {
2024 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2025 parseFlags |= mDefParseFlags;
2026 PackageParser pp = new PackageParser(scanFile.getPath());
2027 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002029 scanFile.getPath(),
2030 mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 if (pkg == null) {
2032 mLastScanError = pp.getParseError();
2033 return null;
2034 }
2035 PackageSetting ps;
2036 PackageSetting updatedPkg;
2037 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002038 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2040 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002041 // Verify certificates first
2042 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2043 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2044 return null;
2045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 if (updatedPkg != null) {
2047 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2048 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2049 }
2050 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2051 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002052 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2053 if (pkg.mVersionCode < ps.versionCode) {
2054 // The system package has been updated and the code path does not match
2055 // Ignore entry. Just return
2056 Log.w(TAG, "Package:" + pkg.packageName +
2057 " has been updated. Ignoring the one from path:"+scanFile);
2058 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2059 return null;
2060 } else {
2061 // Delete the older apk pointed to by ps
2062 // At this point, its safely assumed that package installation for
2063 // apps in system partition will go through. If not there won't be a working
2064 // version of the app
2065 synchronized (mPackages) {
2066 // Just remove the loaded entries from package lists.
2067 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002068 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002069 deletePackageResourcesLI(ps.name, ps.codePathString, ps.resourcePathString);
2070 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 // The apk is forward locked (not public) if its code and resources
2075 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002076 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002078 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002081 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 }
2083
2084 private static String fixProcessName(String defProcessName,
2085 String processName, int uid) {
2086 if (processName == null) {
2087 return defProcessName;
2088 }
2089 return processName;
2090 }
2091
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002092 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2094 if (pkg.mSignatures != null) {
2095 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2096 updateSignature)) {
2097 Log.e(TAG, "Package " + pkg.packageName
2098 + " signatures do not match the previously installed version; ignoring!");
2099 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2100 return false;
2101 }
2102
2103 if (pkgSetting.sharedUser != null) {
2104 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2105 pkg.mSignatures, updateSignature)) {
2106 Log.e(TAG, "Package " + pkg.packageName
2107 + " has no signatures that match those in shared user "
2108 + pkgSetting.sharedUser.name + "; ignoring!");
2109 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2110 return false;
2111 }
2112 }
2113 } else {
2114 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2115 }
2116 return true;
2117 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002118
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002119 public boolean performDexOpt(String packageName) {
2120 if (!mNoDexOpt) {
2121 return false;
2122 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002123
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002124 PackageParser.Package p;
2125 synchronized (mPackages) {
2126 p = mPackages.get(packageName);
2127 if (p == null || p.mDidDexOpt) {
2128 return false;
2129 }
2130 }
2131 synchronized (mInstallLock) {
2132 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2133 }
2134 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002135
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002136 static final int DEX_OPT_SKIPPED = 0;
2137 static final int DEX_OPT_PERFORMED = 1;
2138 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002139
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002140 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2141 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002142 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002143 String path = pkg.mScanPath;
2144 int ret = 0;
2145 try {
2146 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002147 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002148 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002149 pkg.mDidDexOpt = true;
2150 performed = true;
2151 }
2152 } catch (FileNotFoundException e) {
2153 Log.w(TAG, "Apk not found for dexopt: " + path);
2154 ret = -1;
2155 } catch (IOException e) {
2156 Log.w(TAG, "Exception reading apk: " + path, e);
2157 ret = -1;
2158 }
2159 if (ret < 0) {
2160 //error from installer
2161 return DEX_OPT_FAILED;
2162 }
2163 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002164
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002165 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2166 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002167
2168 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2169 return Environment.isEncryptedFilesystemEnabled() &&
2170 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2171 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 private PackageParser.Package scanPackageLI(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 PackageParser.Package pkg, int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002175 File scanFile = new File(pkg.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 mScanningPath = scanFile;
2177 if (pkg == null) {
2178 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2179 return null;
2180 }
2181
2182 final String pkgName = pkg.applicationInfo.packageName;
2183 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2184 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2185 }
2186
2187 if (pkgName.equals("android")) {
2188 synchronized (mPackages) {
2189 if (mAndroidApplication != null) {
2190 Log.w(TAG, "*************************************************");
2191 Log.w(TAG, "Core android package being redefined. Skipping.");
2192 Log.w(TAG, " file=" + mScanningPath);
2193 Log.w(TAG, "*************************************************");
2194 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2195 return null;
2196 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 // Set up information for our fall-back user intent resolution
2199 // activity.
2200 mPlatformPackage = pkg;
2201 pkg.mVersionCode = mSdkVersion;
2202 mAndroidApplication = pkg.applicationInfo;
2203 mResolveActivity.applicationInfo = mAndroidApplication;
2204 mResolveActivity.name = ResolverActivity.class.getName();
2205 mResolveActivity.packageName = mAndroidApplication.packageName;
2206 mResolveActivity.processName = mAndroidApplication.processName;
2207 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2208 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2209 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2210 mResolveActivity.exported = true;
2211 mResolveActivity.enabled = true;
2212 mResolveInfo.activityInfo = mResolveActivity;
2213 mResolveInfo.priority = 0;
2214 mResolveInfo.preferredOrder = 0;
2215 mResolveInfo.match = 0;
2216 mResolveComponentName = new ComponentName(
2217 mAndroidApplication.packageName, mResolveActivity.name);
2218 }
2219 }
2220
2221 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2222 TAG, "Scanning package " + pkgName);
2223 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2224 Log.w(TAG, "*************************************************");
2225 Log.w(TAG, "Application package " + pkgName
2226 + " already installed. Skipping duplicate.");
2227 Log.w(TAG, "*************************************************");
2228 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2229 return null;
2230 }
2231
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002232 // Initialize package source and resource directories
2233 File destResourceFile = null;
2234 File destCodeFile = null;
2235 if ((scanMode & SCAN_NO_PATHS) == 0) {
2236 boolean fwdLocked = (parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0;
2237 final String pkgFileName = pkgName + ".apk";
2238 File destDir = null;
2239
2240 if (fwdLocked) {
2241 destDir = mDrmAppPrivateInstallDir;
2242 destResourceFile = new File(mAppInstallDir, pkgName + ".zip");
2243 } else {
2244 boolean onSd = (parseFlags & PackageParser.PARSE_ON_SDCARD) != 0;
2245 if (!onSd) {
2246 destDir = mAppInstallDir;
2247 } else {
2248 String cachePath = getSdDir(pkgName);
2249 if (cachePath == null) {
2250 Log.e(TAG, "Secure container path for pkg: " + pkgName + " at location: " + cachePath +
2251 " not found");
2252 mLastScanError = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
2253 return null;
2254 }
2255 destDir = new File(cachePath);
2256 }
2257 destResourceFile = new File(destDir, pkgFileName);
2258 }
2259 destCodeFile = new File(destDir, pkgFileName);
2260 pkg.mPath = destCodeFile.getAbsolutePath();
2261 } else {
2262 pkg.mPath = pkg.mScanPath;
2263 destCodeFile = new File(pkg.mScanPath);
2264 destResourceFile = new File(pkg.mScanPath);
2265 }
2266 pkg.applicationInfo.sourceDir = destCodeFile.getAbsolutePath();
2267 pkg.applicationInfo.publicSourceDir = destResourceFile.getAbsolutePath();
2268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 SharedUserSetting suid = null;
2270 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 synchronized (mPackages) {
2275 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002276 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2277 if (mTmpSharedLibraries == null ||
2278 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2279 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2280 }
2281 int num = 0;
2282 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2283 for (int i=0; i<N; i++) {
2284 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 if (file == null) {
2286 Log.e(TAG, "Package " + pkg.packageName
2287 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002288 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2290 return null;
2291 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002292 mTmpSharedLibraries[num] = file;
2293 num++;
2294 }
2295 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2296 for (int i=0; i<N; i++) {
2297 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2298 if (file == null) {
2299 Log.w(TAG, "Package " + pkg.packageName
2300 + " desires unavailable shared library "
2301 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2302 } else {
2303 mTmpSharedLibraries[num] = file;
2304 num++;
2305 }
2306 }
2307 if (num > 0) {
2308 pkg.usesLibraryFiles = new String[num];
2309 System.arraycopy(mTmpSharedLibraries, 0,
2310 pkg.usesLibraryFiles, 0, num);
2311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002312
Dianne Hackborn49237342009-08-27 20:08:01 -07002313 if (pkg.reqFeatures != null) {
2314 N = pkg.reqFeatures.size();
2315 for (int i=0; i<N; i++) {
2316 FeatureInfo fi = pkg.reqFeatures.get(i);
2317 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2318 // Don't care.
2319 continue;
2320 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002321
Dianne Hackborn49237342009-08-27 20:08:01 -07002322 if (fi.name != null) {
2323 if (mAvailableFeatures.get(fi.name) == null) {
2324 Log.e(TAG, "Package " + pkg.packageName
2325 + " requires unavailable feature "
2326 + fi.name + "; failing!");
2327 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2328 return null;
2329 }
2330 }
2331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 }
2333 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 if (pkg.mSharedUserId != null) {
2336 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2337 pkg.applicationInfo.flags, true);
2338 if (suid == null) {
2339 Log.w(TAG, "Creating application package " + pkgName
2340 + " for shared user failed");
2341 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2342 return null;
2343 }
2344 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2345 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2346 + suid.userId + "): packages=" + suid.packages);
2347 }
2348 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002349
2350 // Just create the setting, don't add it yet. For already existing packages
2351 // the PkgSetting exists already and doesn't have to be created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
2353 destResourceFile, pkg.applicationInfo.flags, true, false);
2354 if (pkgSetting == null) {
2355 Log.w(TAG, "Creating application package " + pkgName + " failed");
2356 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2357 return null;
2358 }
2359 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
2360 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2361 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 pkg.applicationInfo.uid = pkgSetting.userId;
2364 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002365
2366 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2368 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2369 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2370 return null;
2371 }
2372 // The signature has changed, but this package is in the system
2373 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002374 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 // However... if this package is part of a shared user, but it
2376 // doesn't match the signature of the shared user, let's fail.
2377 // What this means is that you can't change the signatures
2378 // associated with an overall shared user, which doesn't seem all
2379 // that unreasonable.
2380 if (pkgSetting.sharedUser != null) {
2381 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2382 pkg.mSignatures, false)) {
2383 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2384 return null;
2385 }
2386 }
2387 removeExisting = true;
2388 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002389
The Android Open Source Project10592532009-03-18 17:39:46 -07002390 // Verify that this new package doesn't have any content providers
2391 // that conflict with existing packages. Only do this if the
2392 // package isn't already installed, since we don't want to break
2393 // things that are installed.
2394 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2395 int N = pkg.providers.size();
2396 int i;
2397 for (i=0; i<N; i++) {
2398 PackageParser.Provider p = pkg.providers.get(i);
2399 String names[] = p.info.authority.split(";");
2400 for (int j = 0; j < names.length; j++) {
2401 if (mProviders.containsKey(names[j])) {
2402 PackageParser.Provider other = mProviders.get(names[j]);
2403 Log.w(TAG, "Can't install because provider name " + names[j] +
2404 " (in package " + pkg.applicationInfo.packageName +
2405 ") is already used by "
2406 + ((other != null && other.component != null)
2407 ? other.component.getPackageName() : "?"));
2408 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2409 return null;
2410 }
2411 }
2412 }
2413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 }
2415
2416 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002417 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002419 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 if (ret != 0) {
2421 String msg = "System package " + pkg.packageName
2422 + " could not have data directory erased after signature change.";
2423 reportSettingsProblem(Log.WARN, msg);
2424 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2425 return null;
2426 }
2427 }
2428 Log.w(TAG, "System package " + pkg.packageName
2429 + " signature changed: existing data removed.");
2430 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 long scanFileTime = scanFile.lastModified();
2434 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2435 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2436 pkg.applicationInfo.processName = fixProcessName(
2437 pkg.applicationInfo.packageName,
2438 pkg.applicationInfo.processName,
2439 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440
2441 File dataPath;
2442 if (mPlatformPackage == pkg) {
2443 // The system package is special.
2444 dataPath = new File (Environment.getDataDirectory(), "system");
2445 pkg.applicationInfo.dataDir = dataPath.getPath();
2446 } else {
2447 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002448 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2449 if (useEncryptedFSDir) {
2450 dataPath = new File(mSecureAppDataDir, pkgName);
2451 } else {
2452 dataPath = new File(mAppDataDir, pkgName);
2453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 if (dataPath.exists()) {
2455 mOutPermissions[1] = 0;
2456 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2457 if (mOutPermissions[1] == pkg.applicationInfo.uid
2458 || !Process.supportsProcesses()) {
2459 pkg.applicationInfo.dataDir = dataPath.getPath();
2460 } else {
2461 boolean recovered = false;
2462 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2463 // If this is a system app, we can at least delete its
2464 // current data so the application will still work.
2465 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002466 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 if(ret >= 0) {
2468 // Old data gone!
2469 String msg = "System package " + pkg.packageName
2470 + " has changed from uid: "
2471 + mOutPermissions[1] + " to "
2472 + pkg.applicationInfo.uid + "; old data erased";
2473 reportSettingsProblem(Log.WARN, msg);
2474 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002477 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 pkg.applicationInfo.uid);
2479 if (ret == -1) {
2480 // Ack should not happen!
2481 msg = "System package " + pkg.packageName
2482 + " could not have data directory re-created after delete.";
2483 reportSettingsProblem(Log.WARN, msg);
2484 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2485 return null;
2486 }
2487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 if (!recovered) {
2490 mHasSystemUidErrors = true;
2491 }
2492 }
2493 if (!recovered) {
2494 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2495 + pkg.applicationInfo.uid + "/fs_"
2496 + mOutPermissions[1];
2497 String msg = "Package " + pkg.packageName
2498 + " has mismatched uid: "
2499 + mOutPermissions[1] + " on disk, "
2500 + pkg.applicationInfo.uid + " in settings";
2501 synchronized (mPackages) {
2502 if (!mReportedUidError) {
2503 mReportedUidError = true;
2504 msg = msg + "; read messages:\n"
2505 + mSettings.getReadMessagesLP();
2506 }
2507 reportSettingsProblem(Log.ERROR, msg);
2508 }
2509 }
2510 }
2511 pkg.applicationInfo.dataDir = dataPath.getPath();
2512 } else {
2513 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2514 Log.v(TAG, "Want this data dir: " + dataPath);
2515 //invoke installer to do the actual installation
2516 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002517 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 pkg.applicationInfo.uid);
2519 if(ret < 0) {
2520 // Error from installer
2521 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2522 return null;
2523 }
2524 } else {
2525 dataPath.mkdirs();
2526 if (dataPath.exists()) {
2527 FileUtils.setPermissions(
2528 dataPath.toString(),
2529 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2530 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2531 }
2532 }
2533 if (dataPath.exists()) {
2534 pkg.applicationInfo.dataDir = dataPath.getPath();
2535 } else {
2536 Log.w(TAG, "Unable to create data directory: " + dataPath);
2537 pkg.applicationInfo.dataDir = null;
2538 }
2539 }
2540 }
2541
2542 // Perform shared library installation and dex validation and
2543 // optimization, if this is not a system app.
2544 if (mInstaller != null) {
2545 String path = scanFile.getPath();
2546 if (scanFileNewer) {
2547 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002548 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2549 if (err != PackageManager.INSTALL_SUCCEEDED) {
2550 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 return null;
2552 }
2553 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002554 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002555
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002556 if ((scanMode&SCAN_NO_DEX) == 0) {
2557 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2559 return null;
2560 }
2561 }
2562 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 if (mFactoryTest && pkg.requestedPermissions.contains(
2565 android.Manifest.permission.FACTORY_TEST)) {
2566 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2567 }
2568
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002569 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 if ((scanMode&SCAN_MONITOR) != 0) {
2571 pkg.mPath = destCodeFile.getAbsolutePath();
2572 mAppDirs.put(pkg.mPath, pkg);
2573 }
2574
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002575 // Request the ActivityManager to kill the process(only for existing packages)
2576 // so that we do not end up in a confused state while the user is still using the older
2577 // version of the application while the new one gets installed.
2578 IActivityManager am = ActivityManagerNative.getDefault();
2579 if ((am != null) && ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0)) {
2580 try {
2581 am.killApplicationWithUid(pkg.applicationInfo.packageName,
2582 pkg.applicationInfo.uid);
2583 } catch (RemoteException e) {
2584 }
2585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002588 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002590 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 int N = pkg.providers.size();
2592 StringBuilder r = null;
2593 int i;
2594 for (i=0; i<N; i++) {
2595 PackageParser.Provider p = pkg.providers.get(i);
2596 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2597 p.info.processName, pkg.applicationInfo.uid);
2598 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2599 p.info.name), p);
2600 p.syncable = p.info.isSyncable;
2601 String names[] = p.info.authority.split(";");
2602 p.info.authority = null;
2603 for (int j = 0; j < names.length; j++) {
2604 if (j == 1 && p.syncable) {
2605 // We only want the first authority for a provider to possibly be
2606 // syncable, so if we already added this provider using a different
2607 // authority clear the syncable flag. We copy the provider before
2608 // changing it because the mProviders object contains a reference
2609 // to a provider that we don't want to change.
2610 // Only do this for the second authority since the resulting provider
2611 // object can be the same for all future authorities for this provider.
2612 p = new PackageParser.Provider(p);
2613 p.syncable = false;
2614 }
2615 if (!mProviders.containsKey(names[j])) {
2616 mProviders.put(names[j], p);
2617 if (p.info.authority == null) {
2618 p.info.authority = names[j];
2619 } else {
2620 p.info.authority = p.info.authority + ";" + names[j];
2621 }
2622 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2623 Log.d(TAG, "Registered content provider: " + names[j] +
2624 ", className = " + p.info.name +
2625 ", isSyncable = " + p.info.isSyncable);
2626 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002627 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 Log.w(TAG, "Skipping provider name " + names[j] +
2629 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002630 "): name already used by "
2631 + ((other != null && other.component != null)
2632 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 }
2634 }
2635 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2636 if (r == null) {
2637 r = new StringBuilder(256);
2638 } else {
2639 r.append(' ');
2640 }
2641 r.append(p.info.name);
2642 }
2643 }
2644 if (r != null) {
2645 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 N = pkg.services.size();
2649 r = null;
2650 for (i=0; i<N; i++) {
2651 PackageParser.Service s = pkg.services.get(i);
2652 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2653 s.info.processName, pkg.applicationInfo.uid);
2654 mServices.addService(s);
2655 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2656 if (r == null) {
2657 r = new StringBuilder(256);
2658 } else {
2659 r.append(' ');
2660 }
2661 r.append(s.info.name);
2662 }
2663 }
2664 if (r != null) {
2665 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2666 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 N = pkg.receivers.size();
2669 r = null;
2670 for (i=0; i<N; i++) {
2671 PackageParser.Activity a = pkg.receivers.get(i);
2672 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2673 a.info.processName, pkg.applicationInfo.uid);
2674 mReceivers.addActivity(a, "receiver");
2675 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2676 if (r == null) {
2677 r = new StringBuilder(256);
2678 } else {
2679 r.append(' ');
2680 }
2681 r.append(a.info.name);
2682 }
2683 }
2684 if (r != null) {
2685 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2686 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 N = pkg.activities.size();
2689 r = null;
2690 for (i=0; i<N; i++) {
2691 PackageParser.Activity a = pkg.activities.get(i);
2692 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2693 a.info.processName, pkg.applicationInfo.uid);
2694 mActivities.addActivity(a, "activity");
2695 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2696 if (r == null) {
2697 r = new StringBuilder(256);
2698 } else {
2699 r.append(' ');
2700 }
2701 r.append(a.info.name);
2702 }
2703 }
2704 if (r != null) {
2705 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 N = pkg.permissionGroups.size();
2709 r = null;
2710 for (i=0; i<N; i++) {
2711 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2712 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2713 if (cur == null) {
2714 mPermissionGroups.put(pg.info.name, pg);
2715 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2716 if (r == null) {
2717 r = new StringBuilder(256);
2718 } else {
2719 r.append(' ');
2720 }
2721 r.append(pg.info.name);
2722 }
2723 } else {
2724 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2725 + pg.info.packageName + " ignored: original from "
2726 + cur.info.packageName);
2727 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2728 if (r == null) {
2729 r = new StringBuilder(256);
2730 } else {
2731 r.append(' ');
2732 }
2733 r.append("DUP:");
2734 r.append(pg.info.name);
2735 }
2736 }
2737 }
2738 if (r != null) {
2739 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 N = pkg.permissions.size();
2743 r = null;
2744 for (i=0; i<N; i++) {
2745 PackageParser.Permission p = pkg.permissions.get(i);
2746 HashMap<String, BasePermission> permissionMap =
2747 p.tree ? mSettings.mPermissionTrees
2748 : mSettings.mPermissions;
2749 p.group = mPermissionGroups.get(p.info.group);
2750 if (p.info.group == null || p.group != null) {
2751 BasePermission bp = permissionMap.get(p.info.name);
2752 if (bp == null) {
2753 bp = new BasePermission(p.info.name, p.info.packageName,
2754 BasePermission.TYPE_NORMAL);
2755 permissionMap.put(p.info.name, bp);
2756 }
2757 if (bp.perm == null) {
2758 if (bp.sourcePackage == null
2759 || bp.sourcePackage.equals(p.info.packageName)) {
2760 BasePermission tree = findPermissionTreeLP(p.info.name);
2761 if (tree == null
2762 || tree.sourcePackage.equals(p.info.packageName)) {
2763 bp.perm = p;
2764 bp.uid = pkg.applicationInfo.uid;
2765 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2766 if (r == null) {
2767 r = new StringBuilder(256);
2768 } else {
2769 r.append(' ');
2770 }
2771 r.append(p.info.name);
2772 }
2773 } else {
2774 Log.w(TAG, "Permission " + p.info.name + " from package "
2775 + p.info.packageName + " ignored: base tree "
2776 + tree.name + " is from package "
2777 + tree.sourcePackage);
2778 }
2779 } else {
2780 Log.w(TAG, "Permission " + p.info.name + " from package "
2781 + p.info.packageName + " ignored: original from "
2782 + bp.sourcePackage);
2783 }
2784 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2785 if (r == null) {
2786 r = new StringBuilder(256);
2787 } else {
2788 r.append(' ');
2789 }
2790 r.append("DUP:");
2791 r.append(p.info.name);
2792 }
2793 } else {
2794 Log.w(TAG, "Permission " + p.info.name + " from package "
2795 + p.info.packageName + " ignored: no group "
2796 + p.group);
2797 }
2798 }
2799 if (r != null) {
2800 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 N = pkg.instrumentation.size();
2804 r = null;
2805 for (i=0; i<N; i++) {
2806 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2807 a.info.packageName = pkg.applicationInfo.packageName;
2808 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2809 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2810 a.info.dataDir = pkg.applicationInfo.dataDir;
2811 mInstrumentation.put(a.component, a);
2812 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2813 if (r == null) {
2814 r = new StringBuilder(256);
2815 } else {
2816 r.append(' ');
2817 }
2818 r.append(a.info.name);
2819 }
2820 }
2821 if (r != null) {
2822 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2823 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002824
Dianne Hackborn854060af2009-07-09 18:14:31 -07002825 if (pkg.protectedBroadcasts != null) {
2826 N = pkg.protectedBroadcasts.size();
2827 for (i=0; i<N; i++) {
2828 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
2829 }
2830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 pkgSetting.setTimeStamp(scanFileTime);
2833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 return pkg;
2836 }
2837
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002838 // The following constants are returned by cachePackageSharedLibsForAbiLI
2839 // to indicate if native shared libraries were found in the package.
2840 // Values are:
2841 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
2842 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
2843 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
2844 // in package (and not installed)
2845 //
2846 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
2847 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
2848 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002850 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
2851 // and automatically copy them to /data/data/<appname>/lib if present.
2852 //
2853 // NOTE: this method may throw an IOException if the library cannot
2854 // be copied to its final destination, e.g. if there isn't enough
2855 // room left on the data partition, or a ZipException if the package
2856 // file is malformed.
2857 //
2858 private int cachePackageSharedLibsForAbiLI( PackageParser.Package pkg,
2859 File dataPath, File scanFile, String cpuAbi)
2860 throws IOException, ZipException {
2861 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
2862 final String apkLib = "lib/";
2863 final int apkLibLen = apkLib.length();
2864 final int cpuAbiLen = cpuAbi.length();
2865 final String libPrefix = "lib";
2866 final int libPrefixLen = libPrefix.length();
2867 final String libSuffix = ".so";
2868 final int libSuffixLen = libSuffix.length();
2869 boolean hasNativeLibraries = false;
2870 boolean installedNativeLibraries = false;
2871
2872 // the minimum length of a valid native shared library of the form
2873 // lib/<something>/lib<name>.so.
2874 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
2875
2876 ZipFile zipFile = new ZipFile(scanFile);
2877 Enumeration<ZipEntry> entries =
2878 (Enumeration<ZipEntry>) zipFile.entries();
2879
2880 while (entries.hasMoreElements()) {
2881 ZipEntry entry = entries.nextElement();
2882 // skip directories
2883 if (entry.isDirectory()) {
2884 continue;
2885 }
2886 String entryName = entry.getName();
2887
2888 // check that the entry looks like lib/<something>/lib<name>.so
2889 // here, but don't check the ABI just yet.
2890 //
2891 // - must be sufficiently long
2892 // - must end with libSuffix, i.e. ".so"
2893 // - must start with apkLib, i.e. "lib/"
2894 if (entryName.length() < minEntryLen ||
2895 !entryName.endsWith(libSuffix) ||
2896 !entryName.startsWith(apkLib) ) {
2897 continue;
2898 }
2899
2900 // file name must start with libPrefix, i.e. "lib"
2901 int lastSlash = entryName.lastIndexOf('/');
2902
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002903 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002904 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
2905 continue;
2906 }
2907
2908 hasNativeLibraries = true;
2909
2910 // check the cpuAbi now, between lib/ and /lib<name>.so
2911 //
2912 if (lastSlash != apkLibLen + cpuAbiLen ||
2913 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
2914 continue;
2915
2916 // extract the library file name, ensure it doesn't contain
2917 // weird characters. we're guaranteed here that it doesn't contain
2918 // a directory separator though.
2919 String libFileName = entryName.substring(lastSlash+1);
2920 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
2921 continue;
2922 }
2923
2924 installedNativeLibraries = true;
2925
2926 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
2927 File.separator + libFileName;
2928 File sharedLibraryFile = new File(sharedLibraryFilePath);
2929 if (! sharedLibraryFile.exists() ||
2930 sharedLibraryFile.length() != entry.getSize() ||
2931 sharedLibraryFile.lastModified() != entry.getTime()) {
2932 if (Config.LOGD) {
2933 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002935 if (mInstaller == null) {
2936 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07002937 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002938 cacheSharedLibLI(pkg, zipFile, entry, sharedLibraryDir,
2939 sharedLibraryFile);
2940 }
2941 }
2942 if (!hasNativeLibraries)
2943 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
2944
2945 if (!installedNativeLibraries)
2946 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
2947
2948 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
2949 }
2950
2951 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
2952 // and copy them to /data/data/<appname>/lib.
2953 //
2954 // This function will first try the main CPU ABI defined by Build.CPU_ABI
2955 // (which corresponds to ro.product.cpu.abi), and also try an alternate
2956 // one if ro.product.cpu.abi2 is defined.
2957 //
2958 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
2959 File dataPath, File scanFile) {
2960 final String cpuAbi = Build.CPU_ABI;
2961 try {
2962 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
2963
2964 // some architectures are capable of supporting several CPU ABIs
2965 // for example, 'armeabi-v7a' also supports 'armeabi' native code
2966 // this is indicated by the definition of the ro.product.cpu.abi2
2967 // system property.
2968 //
2969 // only scan the package twice in case of ABI mismatch
2970 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
2971 String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
2972 if (cpuAbi2 != null) {
2973 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002975
2976 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
2977 Log.w(TAG,"Native ABI mismatch from package file");
2978 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 }
2980 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002981 } catch (ZipException e) {
2982 Log.w(TAG, "Failed to extract data from package file", e);
2983 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002985 Log.w(TAG, "Failed to cache package shared libs", e);
2986 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002988 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 }
2990
2991 private void cacheSharedLibLI(PackageParser.Package pkg,
2992 ZipFile zipFile, ZipEntry entry,
2993 File sharedLibraryDir,
2994 File sharedLibraryFile) throws IOException {
2995 InputStream inputStream = zipFile.getInputStream(entry);
2996 try {
2997 File tempFile = File.createTempFile("tmp", "tmp", sharedLibraryDir);
2998 String tempFilePath = tempFile.getPath();
2999 // XXX package manager can't change owner, so the lib files for
3000 // now need to be left as world readable and owned by the system.
3001 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3002 ! tempFile.setLastModified(entry.getTime()) ||
3003 FileUtils.setPermissions(tempFilePath,
3004 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
3005 |FileUtils.S_IROTH, -1, -1) != 0 ||
3006 ! tempFile.renameTo(sharedLibraryFile)) {
3007 // Failed to properly write file.
3008 tempFile.delete();
3009 throw new IOException("Couldn't create cached shared lib "
3010 + sharedLibraryFile + " in " + sharedLibraryDir);
3011 }
3012 } finally {
3013 inputStream.close();
3014 }
3015 }
3016
3017 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3018 if (chatty && Config.LOGD) Log.d(
3019 TAG, "Removing package " + pkg.applicationInfo.packageName );
3020
3021 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003022 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 mPackages.remove(pkg.applicationInfo.packageName);
3025 if (pkg.mPath != null) {
3026 mAppDirs.remove(pkg.mPath);
3027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 PackageSetting ps = (PackageSetting)pkg.mExtras;
3030 if (ps != null && ps.sharedUser != null) {
3031 // XXX don't do this until the data is removed.
3032 if (false) {
3033 ps.sharedUser.packages.remove(ps);
3034 if (ps.sharedUser.packages.size() == 0) {
3035 // Remove.
3036 }
3037 }
3038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 int N = pkg.providers.size();
3041 StringBuilder r = null;
3042 int i;
3043 for (i=0; i<N; i++) {
3044 PackageParser.Provider p = pkg.providers.get(i);
3045 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3046 p.info.name));
3047 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 /* The is another ContentProvider with this authority when
3050 * this app was installed so this authority is null,
3051 * Ignore it as we don't have to unregister the provider.
3052 */
3053 continue;
3054 }
3055 String names[] = p.info.authority.split(";");
3056 for (int j = 0; j < names.length; j++) {
3057 if (mProviders.get(names[j]) == p) {
3058 mProviders.remove(names[j]);
3059 if (chatty && Config.LOGD) Log.d(
3060 TAG, "Unregistered content provider: " + names[j] +
3061 ", className = " + p.info.name +
3062 ", isSyncable = " + p.info.isSyncable);
3063 }
3064 }
3065 if (chatty) {
3066 if (r == null) {
3067 r = new StringBuilder(256);
3068 } else {
3069 r.append(' ');
3070 }
3071 r.append(p.info.name);
3072 }
3073 }
3074 if (r != null) {
3075 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3076 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 N = pkg.services.size();
3079 r = null;
3080 for (i=0; i<N; i++) {
3081 PackageParser.Service s = pkg.services.get(i);
3082 mServices.removeService(s);
3083 if (chatty) {
3084 if (r == null) {
3085 r = new StringBuilder(256);
3086 } else {
3087 r.append(' ');
3088 }
3089 r.append(s.info.name);
3090 }
3091 }
3092 if (r != null) {
3093 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3094 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 N = pkg.receivers.size();
3097 r = null;
3098 for (i=0; i<N; i++) {
3099 PackageParser.Activity a = pkg.receivers.get(i);
3100 mReceivers.removeActivity(a, "receiver");
3101 if (chatty) {
3102 if (r == null) {
3103 r = new StringBuilder(256);
3104 } else {
3105 r.append(' ');
3106 }
3107 r.append(a.info.name);
3108 }
3109 }
3110 if (r != null) {
3111 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3112 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 N = pkg.activities.size();
3115 r = null;
3116 for (i=0; i<N; i++) {
3117 PackageParser.Activity a = pkg.activities.get(i);
3118 mActivities.removeActivity(a, "activity");
3119 if (chatty) {
3120 if (r == null) {
3121 r = new StringBuilder(256);
3122 } else {
3123 r.append(' ');
3124 }
3125 r.append(a.info.name);
3126 }
3127 }
3128 if (r != null) {
3129 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3130 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 N = pkg.permissions.size();
3133 r = null;
3134 for (i=0; i<N; i++) {
3135 PackageParser.Permission p = pkg.permissions.get(i);
3136 boolean tree = false;
3137 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3138 if (bp == null) {
3139 tree = true;
3140 bp = mSettings.mPermissionTrees.get(p.info.name);
3141 }
3142 if (bp != null && bp.perm == p) {
3143 if (bp.type != BasePermission.TYPE_BUILTIN) {
3144 if (tree) {
3145 mSettings.mPermissionTrees.remove(p.info.name);
3146 } else {
3147 mSettings.mPermissions.remove(p.info.name);
3148 }
3149 } else {
3150 bp.perm = null;
3151 }
3152 if (chatty) {
3153 if (r == null) {
3154 r = new StringBuilder(256);
3155 } else {
3156 r.append(' ');
3157 }
3158 r.append(p.info.name);
3159 }
3160 }
3161 }
3162 if (r != null) {
3163 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3164 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 N = pkg.instrumentation.size();
3167 r = null;
3168 for (i=0; i<N; i++) {
3169 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3170 mInstrumentation.remove(a.component);
3171 if (chatty) {
3172 if (r == null) {
3173 r = new StringBuilder(256);
3174 } else {
3175 r.append(' ');
3176 }
3177 r.append(a.info.name);
3178 }
3179 }
3180 if (r != null) {
3181 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3182 }
3183 }
3184 }
3185
3186 private static final boolean isPackageFilename(String name) {
3187 return name != null && name.endsWith(".apk");
3188 }
3189
3190 private void updatePermissionsLP() {
3191 // Make sure there are no dangling permission trees.
3192 Iterator<BasePermission> it = mSettings.mPermissionTrees
3193 .values().iterator();
3194 while (it.hasNext()) {
3195 BasePermission bp = it.next();
3196 if (bp.perm == null) {
3197 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3198 + " from package " + bp.sourcePackage);
3199 it.remove();
3200 }
3201 }
3202
3203 // Make sure all dynamic permissions have been assigned to a package,
3204 // and make sure there are no dangling permissions.
3205 it = mSettings.mPermissions.values().iterator();
3206 while (it.hasNext()) {
3207 BasePermission bp = it.next();
3208 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3209 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3210 + bp.name + " pkg=" + bp.sourcePackage
3211 + " info=" + bp.pendingInfo);
3212 if (bp.perm == null && bp.pendingInfo != null) {
3213 BasePermission tree = findPermissionTreeLP(bp.name);
3214 if (tree != null) {
3215 bp.perm = new PackageParser.Permission(tree.perm.owner,
3216 new PermissionInfo(bp.pendingInfo));
3217 bp.perm.info.packageName = tree.perm.info.packageName;
3218 bp.perm.info.name = bp.name;
3219 bp.uid = tree.uid;
3220 }
3221 }
3222 }
3223 if (bp.perm == null) {
3224 Log.w(TAG, "Removing dangling permission: " + bp.name
3225 + " from package " + bp.sourcePackage);
3226 it.remove();
3227 }
3228 }
3229
3230 // Now update the permissions for all packages, in particular
3231 // replace the granted permissions of the system packages.
3232 for (PackageParser.Package pkg : mPackages.values()) {
3233 grantPermissionsLP(pkg, false);
3234 }
3235 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3238 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3239 if (ps == null) {
3240 return;
3241 }
3242 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3243 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 if (replace) {
3246 ps.permissionsFixed = false;
3247 if (gp == ps) {
3248 gp.grantedPermissions.clear();
3249 gp.gids = mGlobalGids;
3250 }
3251 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 if (gp.gids == null) {
3254 gp.gids = mGlobalGids;
3255 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 final int N = pkg.requestedPermissions.size();
3258 for (int i=0; i<N; i++) {
3259 String name = pkg.requestedPermissions.get(i);
3260 BasePermission bp = mSettings.mPermissions.get(name);
3261 PackageParser.Permission p = bp != null ? bp.perm : null;
3262 if (false) {
3263 if (gp != ps) {
3264 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3265 + ": " + p);
3266 }
3267 }
3268 if (p != null) {
3269 final String perm = p.info.name;
3270 boolean allowed;
3271 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3272 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3273 allowed = true;
3274 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3275 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003276 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003278 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 == PackageManager.SIGNATURE_MATCH);
3280 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3281 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3282 // For updated system applications, the signatureOrSystem permission
3283 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003284 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3286 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3287 if(sysPs.grantedPermissions.contains(perm)) {
3288 allowed = true;
3289 } else {
3290 allowed = false;
3291 }
3292 } else {
3293 allowed = true;
3294 }
3295 }
3296 }
3297 } else {
3298 allowed = false;
3299 }
3300 if (false) {
3301 if (gp != ps) {
3302 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3303 }
3304 }
3305 if (allowed) {
3306 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3307 && ps.permissionsFixed) {
3308 // If this is an existing, non-system package, then
3309 // we can't add any new permissions to it.
3310 if (!gp.loadedPermissions.contains(perm)) {
3311 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003312 // Except... if this is a permission that was added
3313 // to the platform (note: need to only do this when
3314 // updating the platform).
3315 final int NP = PackageParser.NEW_PERMISSIONS.length;
3316 for (int ip=0; ip<NP; ip++) {
3317 final PackageParser.NewPermissionInfo npi
3318 = PackageParser.NEW_PERMISSIONS[ip];
3319 if (npi.name.equals(perm)
3320 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3321 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003322 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003323 + pkg.packageName);
3324 break;
3325 }
3326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 }
3328 }
3329 if (allowed) {
3330 if (!gp.grantedPermissions.contains(perm)) {
3331 addedPermission = true;
3332 gp.grantedPermissions.add(perm);
3333 gp.gids = appendInts(gp.gids, bp.gids);
3334 }
3335 } else {
3336 Log.w(TAG, "Not granting permission " + perm
3337 + " to package " + pkg.packageName
3338 + " because it was previously installed without");
3339 }
3340 } else {
3341 Log.w(TAG, "Not granting permission " + perm
3342 + " to package " + pkg.packageName
3343 + " (protectionLevel=" + p.info.protectionLevel
3344 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3345 + ")");
3346 }
3347 } else {
3348 Log.w(TAG, "Unknown permission " + name
3349 + " in package " + pkg.packageName);
3350 }
3351 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003354 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3355 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 // This is the first that we have heard about this package, so the
3357 // permissions we have now selected are fixed until explicitly
3358 // changed.
3359 ps.permissionsFixed = true;
3360 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3361 }
3362 }
3363
3364 private final class ActivityIntentResolver
3365 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003366 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003368 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 }
3370
Mihai Preda074edef2009-05-18 17:13:31 +02003371 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003373 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3375 }
3376
Mihai Predaeae850c2009-05-13 10:13:48 +02003377 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3378 ArrayList<PackageParser.Activity> packageActivities) {
3379 if (packageActivities == null) {
3380 return null;
3381 }
3382 mFlags = flags;
3383 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3384 int N = packageActivities.size();
3385 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3386 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003387
3388 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003389 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003390 intentFilters = packageActivities.get(i).intents;
3391 if (intentFilters != null && intentFilters.size() > 0) {
3392 listCut.add(intentFilters);
3393 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003394 }
3395 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3396 }
3397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 public final void addActivity(PackageParser.Activity a, String type) {
3399 mActivities.put(a.component, a);
3400 if (SHOW_INFO || Config.LOGV) Log.v(
3401 TAG, " " + type + " " +
3402 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3403 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3404 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003405 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3407 if (SHOW_INFO || Config.LOGV) {
3408 Log.v(TAG, " IntentFilter:");
3409 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3410 }
3411 if (!intent.debugCheck()) {
3412 Log.w(TAG, "==> For Activity " + a.info.name);
3413 }
3414 addFilter(intent);
3415 }
3416 }
3417
3418 public final void removeActivity(PackageParser.Activity a, String type) {
3419 mActivities.remove(a.component);
3420 if (SHOW_INFO || Config.LOGV) Log.v(
3421 TAG, " " + type + " " +
3422 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3423 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3424 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003425 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3427 if (SHOW_INFO || Config.LOGV) {
3428 Log.v(TAG, " IntentFilter:");
3429 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3430 }
3431 removeFilter(intent);
3432 }
3433 }
3434
3435 @Override
3436 protected boolean allowFilterResult(
3437 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3438 ActivityInfo filterAi = filter.activity.info;
3439 for (int i=dest.size()-1; i>=0; i--) {
3440 ActivityInfo destAi = dest.get(i).activityInfo;
3441 if (destAi.name == filterAi.name
3442 && destAi.packageName == filterAi.packageName) {
3443 return false;
3444 }
3445 }
3446 return true;
3447 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 @Override
3450 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3451 int match) {
3452 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3453 return null;
3454 }
3455 final PackageParser.Activity activity = info.activity;
3456 if (mSafeMode && (activity.info.applicationInfo.flags
3457 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3458 return null;
3459 }
3460 final ResolveInfo res = new ResolveInfo();
3461 res.activityInfo = PackageParser.generateActivityInfo(activity,
3462 mFlags);
3463 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3464 res.filter = info;
3465 }
3466 res.priority = info.getPriority();
3467 res.preferredOrder = activity.owner.mPreferredOrder;
3468 //System.out.println("Result: " + res.activityInfo.className +
3469 // " = " + res.priority);
3470 res.match = match;
3471 res.isDefault = info.hasDefault;
3472 res.labelRes = info.labelRes;
3473 res.nonLocalizedLabel = info.nonLocalizedLabel;
3474 res.icon = info.icon;
3475 return res;
3476 }
3477
3478 @Override
3479 protected void sortResults(List<ResolveInfo> results) {
3480 Collections.sort(results, mResolvePrioritySorter);
3481 }
3482
3483 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003484 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003486 out.print(prefix); out.print(
3487 Integer.toHexString(System.identityHashCode(filter.activity)));
3488 out.print(' ');
3489 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 }
3491
3492// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3493// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3494// final List<ResolveInfo> retList = Lists.newArrayList();
3495// while (i.hasNext()) {
3496// final ResolveInfo resolveInfo = i.next();
3497// if (isEnabledLP(resolveInfo.activityInfo)) {
3498// retList.add(resolveInfo);
3499// }
3500// }
3501// return retList;
3502// }
3503
3504 // Keys are String (activity class name), values are Activity.
3505 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3506 = new HashMap<ComponentName, PackageParser.Activity>();
3507 private int mFlags;
3508 }
3509
3510 private final class ServiceIntentResolver
3511 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003512 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003514 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 }
3516
Mihai Preda074edef2009-05-18 17:13:31 +02003517 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003519 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3521 }
3522
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003523 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3524 ArrayList<PackageParser.Service> packageServices) {
3525 if (packageServices == null) {
3526 return null;
3527 }
3528 mFlags = flags;
3529 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3530 int N = packageServices.size();
3531 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3532 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3533
3534 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3535 for (int i = 0; i < N; ++i) {
3536 intentFilters = packageServices.get(i).intents;
3537 if (intentFilters != null && intentFilters.size() > 0) {
3538 listCut.add(intentFilters);
3539 }
3540 }
3541 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3542 }
3543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 public final void addService(PackageParser.Service s) {
3545 mServices.put(s.component, s);
3546 if (SHOW_INFO || Config.LOGV) Log.v(
3547 TAG, " " + (s.info.nonLocalizedLabel != null
3548 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3549 if (SHOW_INFO || Config.LOGV) Log.v(
3550 TAG, " Class=" + s.info.name);
3551 int NI = s.intents.size();
3552 int j;
3553 for (j=0; j<NI; j++) {
3554 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3555 if (SHOW_INFO || Config.LOGV) {
3556 Log.v(TAG, " IntentFilter:");
3557 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3558 }
3559 if (!intent.debugCheck()) {
3560 Log.w(TAG, "==> For Service " + s.info.name);
3561 }
3562 addFilter(intent);
3563 }
3564 }
3565
3566 public final void removeService(PackageParser.Service s) {
3567 mServices.remove(s.component);
3568 if (SHOW_INFO || Config.LOGV) Log.v(
3569 TAG, " " + (s.info.nonLocalizedLabel != null
3570 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3571 if (SHOW_INFO || Config.LOGV) Log.v(
3572 TAG, " Class=" + s.info.name);
3573 int NI = s.intents.size();
3574 int j;
3575 for (j=0; j<NI; j++) {
3576 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3577 if (SHOW_INFO || Config.LOGV) {
3578 Log.v(TAG, " IntentFilter:");
3579 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3580 }
3581 removeFilter(intent);
3582 }
3583 }
3584
3585 @Override
3586 protected boolean allowFilterResult(
3587 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3588 ServiceInfo filterSi = filter.service.info;
3589 for (int i=dest.size()-1; i>=0; i--) {
3590 ServiceInfo destAi = dest.get(i).serviceInfo;
3591 if (destAi.name == filterSi.name
3592 && destAi.packageName == filterSi.packageName) {
3593 return false;
3594 }
3595 }
3596 return true;
3597 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 @Override
3600 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3601 int match) {
3602 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3603 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3604 return null;
3605 }
3606 final PackageParser.Service service = info.service;
3607 if (mSafeMode && (service.info.applicationInfo.flags
3608 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3609 return null;
3610 }
3611 final ResolveInfo res = new ResolveInfo();
3612 res.serviceInfo = PackageParser.generateServiceInfo(service,
3613 mFlags);
3614 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3615 res.filter = filter;
3616 }
3617 res.priority = info.getPriority();
3618 res.preferredOrder = service.owner.mPreferredOrder;
3619 //System.out.println("Result: " + res.activityInfo.className +
3620 // " = " + res.priority);
3621 res.match = match;
3622 res.isDefault = info.hasDefault;
3623 res.labelRes = info.labelRes;
3624 res.nonLocalizedLabel = info.nonLocalizedLabel;
3625 res.icon = info.icon;
3626 return res;
3627 }
3628
3629 @Override
3630 protected void sortResults(List<ResolveInfo> results) {
3631 Collections.sort(results, mResolvePrioritySorter);
3632 }
3633
3634 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003635 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003637 out.print(prefix); out.print(
3638 Integer.toHexString(System.identityHashCode(filter.service)));
3639 out.print(' ');
3640 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
3642
3643// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3644// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3645// final List<ResolveInfo> retList = Lists.newArrayList();
3646// while (i.hasNext()) {
3647// final ResolveInfo resolveInfo = (ResolveInfo) i;
3648// if (isEnabledLP(resolveInfo.serviceInfo)) {
3649// retList.add(resolveInfo);
3650// }
3651// }
3652// return retList;
3653// }
3654
3655 // Keys are String (activity class name), values are Activity.
3656 private final HashMap<ComponentName, PackageParser.Service> mServices
3657 = new HashMap<ComponentName, PackageParser.Service>();
3658 private int mFlags;
3659 };
3660
3661 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3662 new Comparator<ResolveInfo>() {
3663 public int compare(ResolveInfo r1, ResolveInfo r2) {
3664 int v1 = r1.priority;
3665 int v2 = r2.priority;
3666 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3667 if (v1 != v2) {
3668 return (v1 > v2) ? -1 : 1;
3669 }
3670 v1 = r1.preferredOrder;
3671 v2 = r2.preferredOrder;
3672 if (v1 != v2) {
3673 return (v1 > v2) ? -1 : 1;
3674 }
3675 if (r1.isDefault != r2.isDefault) {
3676 return r1.isDefault ? -1 : 1;
3677 }
3678 v1 = r1.match;
3679 v2 = r2.match;
3680 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3681 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3682 }
3683 };
3684
3685 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3686 new Comparator<ProviderInfo>() {
3687 public int compare(ProviderInfo p1, ProviderInfo p2) {
3688 final int v1 = p1.initOrder;
3689 final int v2 = p2.initOrder;
3690 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3691 }
3692 };
3693
3694 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3695 IActivityManager am = ActivityManagerNative.getDefault();
3696 if (am != null) {
3697 try {
3698 final Intent intent = new Intent(action,
3699 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3700 if (extras != null) {
3701 intent.putExtras(extras);
3702 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003703 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 am.broadcastIntent(
3705 null, intent,
3706 null, null, 0, null, null, null, false, false);
3707 } catch (RemoteException ex) {
3708 }
3709 }
3710 }
3711
3712 private final class AppDirObserver extends FileObserver {
3713 public AppDirObserver(String path, int mask, boolean isrom) {
3714 super(path, mask);
3715 mRootDir = path;
3716 mIsRom = isrom;
3717 }
3718
3719 public void onEvent(int event, String path) {
3720 String removedPackage = null;
3721 int removedUid = -1;
3722 String addedPackage = null;
3723 int addedUid = -1;
3724
3725 synchronized (mInstallLock) {
3726 String fullPathStr = null;
3727 File fullPath = null;
3728 if (path != null) {
3729 fullPath = new File(mRootDir, path);
3730 fullPathStr = fullPath.getPath();
3731 }
3732
3733 if (Config.LOGV) Log.v(
3734 TAG, "File " + fullPathStr + " changed: "
3735 + Integer.toHexString(event));
3736
3737 if (!isPackageFilename(path)) {
3738 if (Config.LOGV) Log.v(
3739 TAG, "Ignoring change of non-package file: " + fullPathStr);
3740 return;
3741 }
3742
3743 if ((event&REMOVE_EVENTS) != 0) {
3744 synchronized (mInstallLock) {
3745 PackageParser.Package p = mAppDirs.get(fullPathStr);
3746 if (p != null) {
3747 removePackageLI(p, true);
3748 removedPackage = p.applicationInfo.packageName;
3749 removedUid = p.applicationInfo.uid;
3750 }
3751 }
3752 }
3753
3754 if ((event&ADD_EVENTS) != 0) {
3755 PackageParser.Package p = mAppDirs.get(fullPathStr);
3756 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003757 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3759 PackageParser.PARSE_CHATTY |
3760 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08003761 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 if (p != null) {
3763 synchronized (mPackages) {
3764 grantPermissionsLP(p, false);
3765 }
3766 addedPackage = p.applicationInfo.packageName;
3767 addedUid = p.applicationInfo.uid;
3768 }
3769 }
3770 }
3771
3772 synchronized (mPackages) {
3773 mSettings.writeLP();
3774 }
3775 }
3776
3777 if (removedPackage != null) {
3778 Bundle extras = new Bundle(1);
3779 extras.putInt(Intent.EXTRA_UID, removedUid);
3780 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3781 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3782 }
3783 if (addedPackage != null) {
3784 Bundle extras = new Bundle(1);
3785 extras.putInt(Intent.EXTRA_UID, addedUid);
3786 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3787 }
3788 }
3789
3790 private final String mRootDir;
3791 private final boolean mIsRom;
3792 }
Jacek Surazski65e13172009-04-28 15:26:38 +02003793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 /* Called when a downloaded package installation has been confirmed by the user */
3795 public void installPackage(
3796 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003797 installPackage(packageURI, observer, flags, null);
3798 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003799
Jacek Surazski65e13172009-04-28 15:26:38 +02003800 /* Called when a downloaded package installation has been confirmed by the user */
3801 public void installPackage(
3802 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3803 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 mContext.enforceCallingOrSelfPermission(
3805 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 // Queue up an async operation since the package installation may take a little while.
3808 mHandler.post(new Runnable() {
3809 public void run() {
3810 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003811 // Result object to be returned
3812 PackageInstalledInfo res = new PackageInstalledInfo();
3813 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3814 res.uid = -1;
3815 res.pkg = null;
3816 res.removedInfo = new PackageRemovedInfo();
3817 // Make a temporary copy of file from given packageURI
3818 File tmpPackageFile = copyTempInstallFile(packageURI, res);
3819 if (tmpPackageFile != null) {
3820 synchronized (mInstallLock) {
3821 installPackageLI(packageURI, flags, true, installerPackageName, tmpPackageFile, res);
3822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 }
3824 if (observer != null) {
3825 try {
3826 observer.packageInstalled(res.name, res.returnCode);
3827 } catch (RemoteException e) {
3828 Log.i(TAG, "Observer no longer exists.");
3829 }
3830 }
3831 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3832 // call appears in the synchronized block above.
3833 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3834 res.removedInfo.sendBroadcast(false, true);
3835 Bundle extras = new Bundle(1);
3836 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003837 final boolean update = res.removedInfo.removedPackage != null;
3838 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3840 }
3841 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3842 res.pkg.applicationInfo.packageName,
3843 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003844 if (update) {
3845 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3846 res.pkg.applicationInfo.packageName,
3847 extras);
3848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 }
3850 Runtime.getRuntime().gc();
3851 }
3852 });
3853 }
3854
3855 class PackageInstalledInfo {
3856 String name;
3857 int uid;
3858 PackageParser.Package pkg;
3859 int returnCode;
3860 PackageRemovedInfo removedInfo;
3861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 /*
3864 * Install a non-existing package.
3865 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003866 private void installNewPackageLI(PackageParser.Package pkg,
3867 int parseFlags,
3868 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02003869 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08003871 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003872 String pkgName = pkg.packageName;
3873 boolean onSd = (parseFlags & PackageParser.PARSE_ON_SDCARD) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -08003874
3875 if (useEncryptedFilesystemForPackage(pkg)) {
3876 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
3877 } else {
3878 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 res.name = pkgName;
3881 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003882 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003884 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 + " without first uninstalling.");
3886 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3887 return;
3888 }
3889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003891 if (onSd) {
3892 // Create secure container mount point for package
3893 String cPath = createSdDir(new File(pkg.mScanPath), pkgName);
3894 if (cPath == null) {
3895 mLastScanError = res.returnCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
3896 return;
3897 }
3898 }
3899 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003901 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3903 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3904 }
3905 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003906 File destPackageFile = new File(pkg.mPath);
3907 if (destPackageFile.exists()) {
3908 // It's safe to do this because we know (from the above check) that the file
3909 // isn't currently used for an installed package.
3910 destPackageFile.delete();
3911 }
3912 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02003913 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 res);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003915 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3916 // Check if container can be finalized
3917 if(onSd && !finalizeSdDir(pkgName)) {
3918 res.returnCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
3919 }
3920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 // delete the partially installed application. the data directory will have to be
3922 // restored if it was already existing
3923 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3924 // remove package from internal structures. Note that we want deletePackageX to
3925 // delete the package data and cache directories that it created in
3926 // scanPackageLocked, unless those directories existed before we even tried to
3927 // install.
3928 deletePackageLI(
3929 pkgName, true,
3930 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3931 res.removedInfo);
3932 }
3933 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003934 if (onSd && res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3935 // Destroy cache
3936 destroySdDir(pkgName);
3937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003939
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003940 private void replacePackageLI(PackageParser.Package pkg,
3941 int parseFlags,
3942 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02003943 String installerPackageName, PackageInstalledInfo res) {
3944
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003945 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003946 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 // First find the old package info and check signatures
3948 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003949 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003950 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
3951 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3953 return;
3954 }
3955 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003956 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 if(sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003958 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003960 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 }
3962 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003965 PackageParser.Package pkg,
3966 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02003967 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 PackageParser.Package newPackage = null;
3969 String pkgName = deletedPackage.packageName;
3970 boolean deletedPkg = true;
3971 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003972
Jacek Surazski65e13172009-04-28 15:26:38 +02003973 String oldInstallerPackageName = null;
3974 synchronized (mPackages) {
3975 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3976 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003977
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003978 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979 // First delete the existing package while retaining the data directory
3980 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3981 res.removedInfo)) {
3982 // If the existing package was'nt successfully deleted
3983 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3984 deletedPkg = false;
3985 } else {
3986 // Successfully deleted the old package. Now proceed with re-installation
3987 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003988 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003990 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3992 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08003993 }
3994 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003995 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02003996 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 res);
3998 updatedSettings = true;
3999 }
4000 }
4001
4002 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4003 // If we deleted an exisiting package, the old source and resource files that we
4004 // were keeping around in case we needed them (see below) can now be deleted
4005 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
4006 final ApplicationInfo installedPackageAppInfo =
4007 newPackage.applicationInfo;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004008 deletePackageResourcesLI(pkgName,
4009 !deletedPackageAppInfo.sourceDir
4010 .equals(installedPackageAppInfo.sourceDir)
4011 ? deletedPackageAppInfo.sourceDir : null,
4012 !deletedPackageAppInfo.publicSourceDir
4013 .equals(installedPackageAppInfo.publicSourceDir)
4014 ? deletedPackageAppInfo.publicSourceDir : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 //update signature on the new package setting
4016 //this should always succeed, since we checked the
4017 //signature earlier.
4018 synchronized(mPackages) {
4019 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
4020 parseFlags, true);
4021 }
4022 } else {
4023 // remove package from internal structures. Note that we want deletePackageX to
4024 // delete the package data and cache directories that it created in
4025 // scanPackageLocked, unless those directories existed before we even tried to
4026 // install.
4027 if(updatedSettings) {
4028 deletePackageLI(
4029 pkgName, true,
4030 PackageManager.DONT_DELETE_DATA,
4031 res.removedInfo);
4032 }
4033 // Since we failed to install the new package we need to restore the old
4034 // package that we deleted.
4035 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004036 File restoreFile = new File(deletedPackage.mPath);
4037 if (restoreFile == null) {
4038 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
4039 return;
4040 }
4041 File restoreTmpFile = createTempPackageFile();
4042 if (restoreTmpFile == null) {
4043 Log.e(TAG, "Failed creating temp file when restoring pkg : " + pkgName);
4044 return;
4045 }
4046 if (!FileUtils.copyFile(restoreFile, restoreTmpFile)) {
4047 Log.e(TAG, "Failed copying temp file when restoring pkg : " + pkgName);
4048 return;
4049 }
4050 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4051 restoreRes.removedInfo = new PackageRemovedInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 installPackageLI(
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004053 Uri.fromFile(restoreFile),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004055 ? PackageManager.INSTALL_FORWARD_LOCK
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004056 : 0, false, oldInstallerPackageName, restoreTmpFile, restoreRes);
4057 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4058 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 }
4061 }
4062 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004065 PackageParser.Package pkg,
4066 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004067 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 PackageParser.Package newPackage = null;
4069 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004070 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 PackageParser.PARSE_IS_SYSTEM;
4072 String packageName = deletedPackage.packageName;
4073 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4074 if (packageName == null) {
4075 Log.w(TAG, "Attempt to delete null packageName.");
4076 return;
4077 }
4078 PackageParser.Package oldPkg;
4079 PackageSetting oldPkgSetting;
4080 synchronized (mPackages) {
4081 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004082 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4084 (oldPkgSetting == null)) {
4085 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4086 return;
4087 }
4088 }
4089 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4090 res.removedInfo.removedPackage = packageName;
4091 // Remove existing system package
4092 removePackageLI(oldPkg, true);
4093 synchronized (mPackages) {
4094 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4095 }
4096
4097 // Successfully disabled the old package. Now proceed with re-installation
4098 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4099 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004100 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004102 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4104 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4105 }
4106 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004107 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 updatedSettings = true;
4109 }
4110
4111 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4112 //update signature on the new package setting
4113 //this should always succeed, since we checked the
4114 //signature earlier.
4115 synchronized(mPackages) {
4116 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4117 parseFlags, true);
4118 }
4119 } else {
4120 // Re installation failed. Restore old information
4121 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004122 if (newPackage != null) {
4123 removePackageLI(newPackage, true);
4124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004126 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004128 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 // Restore the old system information in Settings
4130 synchronized(mPackages) {
4131 if(updatedSettings) {
4132 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004133 mSettings.setInstallerPackageName(packageName,
4134 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 }
4136 mSettings.writeLP();
4137 }
4138 }
4139 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004140
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004141 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004142 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004143 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 synchronized (mPackages) {
4145 //write settings. the installStatus will be incomplete at this stage.
4146 //note that the new package setting would have already been
4147 //added to mPackages. It hasn't been persisted yet.
4148 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4149 mSettings.writeLP();
4150 }
4151
4152 int retCode = 0;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004153 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4154 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004156 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4158 return;
4159 }
4160 }
4161 // XXX There are probably some big issues here: upon doing
4162 // the rename, we have reached the point of no return (the
4163 // original .apk is gone!), so we can't fail. Yet... we can.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004164 File scanFile = new File(newPackage.mScanPath);
4165 if (!scanFile.renameTo(new File(newPackage.mPath))) {
4166 Log.e(TAG, "Couldn't move package file: " + newPackage.mScanPath + " to: " + newPackage.mPath);
4167 // TODO rename should work. Workaround
4168 if (!FileUtils.copyFile(scanFile, new File(newPackage.mPath))) {
4169 Log.e(TAG, "Couldn't move package file to: " + newPackage.mPath);
4170 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004173 res.returnCode = setPermissionsLI(newPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4175 return;
4176 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004177 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 }
4179 }
4180 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4181 if (mInstaller != null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004182 mInstaller.rmdex(newPackage.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 }
4184 }
4185
4186 synchronized (mPackages) {
4187 grantPermissionsLP(newPackage, true);
4188 res.name = pkgName;
4189 res.uid = newPackage.applicationInfo.uid;
4190 res.pkg = newPackage;
4191 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004192 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4194 //to update install status
4195 mSettings.writeLP();
4196 }
4197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004198
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004199 private File copyTempInstallFile(Uri pPackageURI,
4200 PackageInstalledInfo res) {
4201 File tmpPackageFile = createTempPackageFile();
4202 int retCode = PackageManager.INSTALL_SUCCEEDED;
4203 if (tmpPackageFile == null) {
4204 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4205 return null;
4206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004208 if (pPackageURI.getScheme().equals("file")) {
4209 final File srcPackageFile = new File(pPackageURI.getPath());
4210 // We copy the source package file to a temp file and then rename it to the
4211 // destination file in order to eliminate a window where the package directory
4212 // scanner notices the new package file but it's not completely copied yet.
4213 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
4214 Log.e(TAG, "Couldn't copy package file to temp file.");
4215 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004217 } else if (pPackageURI.getScheme().equals("content")) {
4218 ParcelFileDescriptor fd = null;
4219 try {
4220 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
4221 } catch (FileNotFoundException e) {
4222 Log.e(TAG, "Couldn't open file descriptor from download service. Failed with exception " + e);
4223 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4224 }
4225 if (fd == null) {
4226 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
4227 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4228 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 if (Config.LOGV) {
4230 Log.v(TAG, "Opened file descriptor from download service.");
4231 }
4232 ParcelFileDescriptor.AutoCloseInputStream
4233 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
4234 // We copy the source package file to a temp file and then rename it to the
4235 // destination file in order to eliminate a window where the package directory
4236 // scanner notices the new package file but it's not completely copied yet.
4237 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
4238 Log.e(TAG, "Couldn't copy package stream to temp file.");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004239 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004242 } else {
4243 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
4244 retCode = PackageManager.INSTALL_FAILED_INVALID_URI;
4245 }
4246
4247 res.returnCode = retCode;
4248 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
4249 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4250 tmpPackageFile.delete();
4251 }
4252 return null;
4253 }
4254 return tmpPackageFile;
4255 }
4256
4257 private void installPackageLI(Uri pPackageURI,
4258 int pFlags, boolean newInstall, String installerPackageName,
4259 File tmpPackageFile, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004260 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
4261 boolean onSd = ((pFlags & PackageManager.INSTALL_ON_SDCARD) != 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004262 boolean replacingExistingPackage = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004263 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
4264 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004265 // Result object to be returned
4266 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4267
4268 main_flow: try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 // Retrieve PackageSettings and parse package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004270 int parseFlags = PackageParser.PARSE_CHATTY |
4271 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
4272 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 parseFlags |= mDefParseFlags;
4274 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4275 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004277 null, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 if (pkg == null) {
4279 res.returnCode = pp.getParseError();
4280 break main_flow;
4281 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004282 String pkgName = res.name = pkg.packageName;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004283 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4284 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4285 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4286 break main_flow;
4287 }
4288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4290 res.returnCode = pp.getParseError();
4291 break main_flow;
4292 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 synchronized (mPackages) {
4295 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004296 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 && mPackages.containsKey(pkgName)) {
4298 replacingExistingPackage = true;
4299 }
4300 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 if(replacingExistingPackage) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004303 replacePackageLI(pkg, parseFlags, scanMode,
4304 installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004306 installNewPackageLI(pkg, parseFlags, scanMode,
4307 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 }
4309 } finally {
4310 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4311 tmpPackageFile.delete();
4312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 }
4314 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004315
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004316 private int setPermissionsLI(PackageParser.Package newPackage) {
4317 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 int retCode;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004319 if ((newPackage.applicationInfo.flags
4320 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
4321 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 try {
4323 extractPublicFiles(newPackage, destResourceFile);
4324 } catch (IOException e) {
4325 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
4326 " forward-locked app.");
4327 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4328 } finally {
4329 //TODO clean up the extracted public files
4330 }
4331 if (mInstaller != null) {
4332 retCode = mInstaller.setForwardLockPerm(pkgName,
4333 newPackage.applicationInfo.uid);
4334 } else {
4335 final int filePermissions =
4336 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004337 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 newPackage.applicationInfo.uid);
4339 }
4340 } else {
4341 final int filePermissions =
4342 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4343 |FileUtils.S_IROTH;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004344 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 }
4346 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004347 Log.e(TAG, "Couldn't set new package file permissions for " +
4348 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 + ". The return code was: " + retCode);
4350 }
4351 return PackageManager.INSTALL_SUCCEEDED;
4352 }
4353
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004354 private boolean isForwardLocked(PackageParser.Package pkg) {
4355 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 }
4357
4358 private void extractPublicFiles(PackageParser.Package newPackage,
4359 File publicZipFile) throws IOException {
4360 final ZipOutputStream publicZipOutStream =
4361 new ZipOutputStream(new FileOutputStream(publicZipFile));
4362 final ZipFile privateZip = new ZipFile(newPackage.mPath);
4363
4364 // Copy manifest, resources.arsc and res directory to public zip
4365
4366 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
4367 while (privateZipEntries.hasMoreElements()) {
4368 final ZipEntry zipEntry = privateZipEntries.nextElement();
4369 final String zipEntryName = zipEntry.getName();
4370 if ("AndroidManifest.xml".equals(zipEntryName)
4371 || "resources.arsc".equals(zipEntryName)
4372 || zipEntryName.startsWith("res/")) {
4373 try {
4374 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
4375 } catch (IOException e) {
4376 try {
4377 publicZipOutStream.close();
4378 throw e;
4379 } finally {
4380 publicZipFile.delete();
4381 }
4382 }
4383 }
4384 }
4385
4386 publicZipOutStream.close();
4387 FileUtils.setPermissions(
4388 publicZipFile.getAbsolutePath(),
4389 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4390 -1, -1);
4391 }
4392
4393 private static void copyZipEntry(ZipEntry zipEntry,
4394 ZipFile inZipFile,
4395 ZipOutputStream outZipStream) throws IOException {
4396 byte[] buffer = new byte[4096];
4397 int num;
4398
4399 ZipEntry newEntry;
4400 if (zipEntry.getMethod() == ZipEntry.STORED) {
4401 // Preserve the STORED method of the input entry.
4402 newEntry = new ZipEntry(zipEntry);
4403 } else {
4404 // Create a new entry so that the compressed len is recomputed.
4405 newEntry = new ZipEntry(zipEntry.getName());
4406 }
4407 outZipStream.putNextEntry(newEntry);
4408
4409 InputStream data = inZipFile.getInputStream(zipEntry);
4410 while ((num = data.read(buffer)) > 0) {
4411 outZipStream.write(buffer, 0, num);
4412 }
4413 outZipStream.flush();
4414 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 private void deleteTempPackageFiles() {
4417 FilenameFilter filter = new FilenameFilter() {
4418 public boolean accept(File dir, String name) {
4419 return name.startsWith("vmdl") && name.endsWith(".tmp");
4420 }
4421 };
4422 String tmpFilesList[] = mAppInstallDir.list(filter);
4423 if(tmpFilesList == null) {
4424 return;
4425 }
4426 for(int i = 0; i < tmpFilesList.length; i++) {
4427 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4428 tmpFile.delete();
4429 }
4430 }
4431
4432 private File createTempPackageFile() {
4433 File tmpPackageFile;
4434 try {
4435 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
4436 } catch (IOException e) {
4437 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4438 return null;
4439 }
4440 try {
4441 FileUtils.setPermissions(
4442 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4443 -1, -1);
4444 } catch (IOException e) {
4445 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4446 return null;
4447 }
4448 return tmpPackageFile;
4449 }
4450
4451 public void deletePackage(final String packageName,
4452 final IPackageDeleteObserver observer,
4453 final int flags) {
4454 mContext.enforceCallingOrSelfPermission(
4455 android.Manifest.permission.DELETE_PACKAGES, null);
4456 // Queue up an async operation since the package deletion may take a little while.
4457 mHandler.post(new Runnable() {
4458 public void run() {
4459 mHandler.removeCallbacks(this);
4460 final boolean succeded = deletePackageX(packageName, true, true, flags);
4461 if (observer != null) {
4462 try {
4463 observer.packageDeleted(succeded);
4464 } catch (RemoteException e) {
4465 Log.i(TAG, "Observer no longer exists.");
4466 } //end catch
4467 } //end if
4468 } //end run
4469 });
4470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 /**
4473 * This method is an internal method that could be get invoked either
4474 * to delete an installed package or to clean up a failed installation.
4475 * After deleting an installed package, a broadcast is sent to notify any
4476 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004477 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 * installation wouldn't have sent the initial broadcast either
4479 * The key steps in deleting a package are
4480 * deleting the package information in internal structures like mPackages,
4481 * deleting the packages base directories through installd
4482 * updating mSettings to reflect current status
4483 * persisting settings for later use
4484 * sending a broadcast if necessary
4485 */
4486
4487 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4488 boolean deleteCodeAndResources, int flags) {
4489 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004490 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491
4492 synchronized (mInstallLock) {
4493 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4494 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004497 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4498 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4499
4500 // If the removed package was a system update, the old system packaged
4501 // was re-enabled; we need to broadcast this information
4502 if (systemUpdate) {
4503 Bundle extras = new Bundle(1);
4504 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4505 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4506
4507 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4508 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 }
4511 return res;
4512 }
4513
4514 static class PackageRemovedInfo {
4515 String removedPackage;
4516 int uid = -1;
4517 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004518 boolean isRemovedPackageSystemUpdate = false;
4519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 void sendBroadcast(boolean fullRemove, boolean replacing) {
4521 Bundle extras = new Bundle(1);
4522 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4523 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4524 if (replacing) {
4525 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4526 }
4527 if (removedPackage != null) {
4528 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4529 }
4530 if (removedUid >= 0) {
4531 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4532 }
4533 }
4534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004536 /*
4537 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4538 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004539 * 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 -08004540 * delete a partially installed application.
4541 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004542 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 int flags) {
4544 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004545 if (outInfo != null) {
4546 outInfo.removedPackage = packageName;
4547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004548 removePackageLI(p, true);
4549 // Retrieve object to delete permissions for shared user later on
4550 PackageSetting deletedPs;
4551 synchronized (mPackages) {
4552 deletedPs = mSettings.mPackages.get(packageName);
4553 }
4554 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004555 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004557 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004558 if (retCode < 0) {
4559 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4560 + packageName + ", retcode=" + retCode);
4561 // we don't consider this to be a failure of the core package deletion
4562 }
4563 } else {
4564 //for emulator
4565 PackageParser.Package pkg = mPackages.get(packageName);
4566 File dataDir = new File(pkg.applicationInfo.dataDir);
4567 dataDir.delete();
4568 }
4569 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004570 if (outInfo != null) {
4571 outInfo.removedUid = mSettings.removePackageLP(packageName);
4572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004573 }
4574 }
4575 synchronized (mPackages) {
4576 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4577 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004578 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004579 }
4580 // Save settings now
4581 mSettings.writeLP ();
4582 }
4583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 /*
4586 * Tries to delete system package.
4587 */
4588 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004589 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 ApplicationInfo applicationInfo = p.applicationInfo;
4591 //applicable for non-partially installed applications only
4592 if (applicationInfo == null) {
4593 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4594 return false;
4595 }
4596 PackageSetting ps = null;
4597 // Confirm if the system package has been updated
4598 // An updated system app can be deleted. This will also have to restore
4599 // the system pkg from system partition
4600 synchronized (mPackages) {
4601 ps = mSettings.getDisabledSystemPkg(p.packageName);
4602 }
4603 if (ps == null) {
4604 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4605 return false;
4606 } else {
4607 Log.i(TAG, "Deleting system pkg from data partition");
4608 }
4609 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004610 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004611 boolean deleteCodeAndResources = false;
4612 if (ps.versionCode < p.mVersionCode) {
4613 // Delete code and resources for downgrades
4614 deleteCodeAndResources = true;
4615 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4616 flags &= ~PackageManager.DONT_DELETE_DATA;
4617 }
4618 } else {
4619 // Preserve data by setting flag
4620 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4621 flags |= PackageManager.DONT_DELETE_DATA;
4622 }
4623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4625 if (!ret) {
4626 return false;
4627 }
4628 synchronized (mPackages) {
4629 // Reinstate the old system package
4630 mSettings.enableSystemPackageLP(p.packageName);
4631 }
4632 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004633 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004635 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 if (newPkg == null) {
4638 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4639 return false;
4640 }
4641 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07004642 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004643 mSettings.writeLP();
4644 }
4645 return true;
4646 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004647
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004648 private void deletePackageResourcesLI(String packageName,
4649 String sourceDir, String publicSourceDir) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004650 if (sourceDir != null) {
4651 File sourceFile = new File(sourceDir);
4652 if (!sourceFile.exists()) {
4653 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4654 }
4655 // Delete application's code and resources
4656 sourceFile.delete();
4657 if (mInstaller != null) {
4658 int retCode = mInstaller.rmdex(sourceFile.toString());
4659 if (retCode < 0) {
4660 Log.w(TAG, "Couldn't remove dex file for package: "
4661 + packageName + " at location "
4662 + sourceFile.toString() + ", retcode=" + retCode);
4663 // we don't consider this to be a failure of the core package deletion
4664 }
4665 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004666 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004667 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4668 final File publicSourceFile = new File(publicSourceDir);
4669 if (!publicSourceFile.exists()) {
4670 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4671 }
4672 if (publicSourceFile.exists()) {
4673 publicSourceFile.delete();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004674 }
4675 }
4676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004678 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4679 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4680 ApplicationInfo applicationInfo = p.applicationInfo;
4681 if (applicationInfo == null) {
4682 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4683 return false;
4684 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004685 if (outInfo != null) {
4686 outInfo.uid = applicationInfo.uid;
4687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004688
4689 // Delete package data from internal structures and also remove data if flag is set
4690 removePackageDataLI(p, outInfo, flags);
4691
4692 // Delete application code and resources
4693 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004694 deletePackageResourcesLI(applicationInfo.packageName,
4695 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696 }
4697 return true;
4698 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 /*
4701 * This method handles package deletion in general
4702 */
4703 private boolean deletePackageLI(String packageName,
4704 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4705 if (packageName == null) {
4706 Log.w(TAG, "Attempt to delete null packageName.");
4707 return false;
4708 }
4709 PackageParser.Package p;
4710 boolean dataOnly = false;
4711 synchronized (mPackages) {
4712 p = mPackages.get(packageName);
4713 if (p == null) {
4714 //this retrieves partially installed apps
4715 dataOnly = true;
4716 PackageSetting ps = mSettings.mPackages.get(packageName);
4717 if (ps == null) {
4718 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4719 return false;
4720 }
4721 p = ps.pkg;
4722 }
4723 }
4724 if (p == null) {
4725 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4726 return false;
4727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 if (dataOnly) {
4730 // Delete application data first
4731 removePackageDataLI(p, outInfo, flags);
4732 return true;
4733 }
4734 // At this point the package should have ApplicationInfo associated with it
4735 if (p.applicationInfo == null) {
4736 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4737 return false;
4738 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004739 boolean onSd = (p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0;
4740 // Mount sd container if needed
4741 if (onSd) {
4742 // TODO Better error handling from MountService api later
4743 mountSdDir(p.packageName, Process.SYSTEM_UID) ;
4744 }
4745 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4747 Log.i(TAG, "Removing system package:"+p.packageName);
4748 // When an updated system application is deleted we delete the existing resources as well and
4749 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004750 ret = deleteSystemPackageLI(p, flags, outInfo);
4751 } else {
4752 Log.i(TAG, "Removing non-system package:"+p.packageName);
4753 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004754 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004755 if (ret && onSd) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08004756 if (deleteCodeAndResources) {
4757 // Post a delayed destroy on the container since there might
4758 // be active processes holding open file handles to package
4759 // resources which will get killed by the process killer when
4760 // destroying the container. This might even kill the current
4761 // process and crash the system. Delay the destroy a bit so
4762 // that the active processes get to handle the uninstall broadcasts.
4763 sendDelayedDestroySdDir(packageName);
4764 } else {
4765 // Just unmount the directory
4766 unMountSdDir(packageName);
4767 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004768 }
4769 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004772 public void clearApplicationUserData(final String packageName,
4773 final IPackageDataObserver observer) {
4774 mContext.enforceCallingOrSelfPermission(
4775 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4776 // Queue up an async operation since the package deletion may take a little while.
4777 mHandler.post(new Runnable() {
4778 public void run() {
4779 mHandler.removeCallbacks(this);
4780 final boolean succeeded;
4781 synchronized (mInstallLock) {
4782 succeeded = clearApplicationUserDataLI(packageName);
4783 }
4784 if (succeeded) {
4785 // invoke DeviceStorageMonitor's update method to clear any notifications
4786 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4787 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4788 if (dsm != null) {
4789 dsm.updateMemory();
4790 }
4791 }
4792 if(observer != null) {
4793 try {
4794 observer.onRemoveCompleted(packageName, succeeded);
4795 } catch (RemoteException e) {
4796 Log.i(TAG, "Observer no longer exists.");
4797 }
4798 } //end if observer
4799 } //end run
4800 });
4801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803 private boolean clearApplicationUserDataLI(String packageName) {
4804 if (packageName == null) {
4805 Log.w(TAG, "Attempt to delete null packageName.");
4806 return false;
4807 }
4808 PackageParser.Package p;
4809 boolean dataOnly = false;
4810 synchronized (mPackages) {
4811 p = mPackages.get(packageName);
4812 if(p == null) {
4813 dataOnly = true;
4814 PackageSetting ps = mSettings.mPackages.get(packageName);
4815 if((ps == null) || (ps.pkg == null)) {
4816 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4817 return false;
4818 }
4819 p = ps.pkg;
4820 }
4821 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004822 boolean useEncryptedFSDir = false;
4823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 if(!dataOnly) {
4825 //need to check this only for fully installed applications
4826 if (p == null) {
4827 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4828 return false;
4829 }
4830 final ApplicationInfo applicationInfo = p.applicationInfo;
4831 if (applicationInfo == null) {
4832 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4833 return false;
4834 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004835 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004836 }
4837 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004838 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 if (retCode < 0) {
4840 Log.w(TAG, "Couldn't remove cache files for package: "
4841 + packageName);
4842 return false;
4843 }
4844 }
4845 return true;
4846 }
4847
4848 public void deleteApplicationCacheFiles(final String packageName,
4849 final IPackageDataObserver observer) {
4850 mContext.enforceCallingOrSelfPermission(
4851 android.Manifest.permission.DELETE_CACHE_FILES, null);
4852 // Queue up an async operation since the package deletion may take a little while.
4853 mHandler.post(new Runnable() {
4854 public void run() {
4855 mHandler.removeCallbacks(this);
4856 final boolean succeded;
4857 synchronized (mInstallLock) {
4858 succeded = deleteApplicationCacheFilesLI(packageName);
4859 }
4860 if(observer != null) {
4861 try {
4862 observer.onRemoveCompleted(packageName, succeded);
4863 } catch (RemoteException e) {
4864 Log.i(TAG, "Observer no longer exists.");
4865 }
4866 } //end if observer
4867 } //end run
4868 });
4869 }
4870
4871 private boolean deleteApplicationCacheFilesLI(String packageName) {
4872 if (packageName == null) {
4873 Log.w(TAG, "Attempt to delete null packageName.");
4874 return false;
4875 }
4876 PackageParser.Package p;
4877 synchronized (mPackages) {
4878 p = mPackages.get(packageName);
4879 }
4880 if (p == null) {
4881 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4882 return false;
4883 }
4884 final ApplicationInfo applicationInfo = p.applicationInfo;
4885 if (applicationInfo == null) {
4886 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4887 return false;
4888 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004889 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004891 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004892 if (retCode < 0) {
4893 Log.w(TAG, "Couldn't remove cache files for package: "
4894 + packageName);
4895 return false;
4896 }
4897 }
4898 return true;
4899 }
4900
4901 public void getPackageSizeInfo(final String packageName,
4902 final IPackageStatsObserver observer) {
4903 mContext.enforceCallingOrSelfPermission(
4904 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4905 // Queue up an async operation since the package deletion may take a little while.
4906 mHandler.post(new Runnable() {
4907 public void run() {
4908 mHandler.removeCallbacks(this);
4909 PackageStats lStats = new PackageStats(packageName);
4910 final boolean succeded;
4911 synchronized (mInstallLock) {
4912 succeded = getPackageSizeInfoLI(packageName, lStats);
4913 }
4914 if(observer != null) {
4915 try {
4916 observer.onGetStatsCompleted(lStats, succeded);
4917 } catch (RemoteException e) {
4918 Log.i(TAG, "Observer no longer exists.");
4919 }
4920 } //end if observer
4921 } //end run
4922 });
4923 }
4924
4925 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4926 if (packageName == null) {
4927 Log.w(TAG, "Attempt to get size of null packageName.");
4928 return false;
4929 }
4930 PackageParser.Package p;
4931 boolean dataOnly = false;
4932 synchronized (mPackages) {
4933 p = mPackages.get(packageName);
4934 if(p == null) {
4935 dataOnly = true;
4936 PackageSetting ps = mSettings.mPackages.get(packageName);
4937 if((ps == null) || (ps.pkg == null)) {
4938 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4939 return false;
4940 }
4941 p = ps.pkg;
4942 }
4943 }
4944 String publicSrcDir = null;
4945 if(!dataOnly) {
4946 final ApplicationInfo applicationInfo = p.applicationInfo;
4947 if (applicationInfo == null) {
4948 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4949 return false;
4950 }
4951 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4952 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004953 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 if (mInstaller != null) {
4955 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08004956 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 if (res < 0) {
4958 return false;
4959 } else {
4960 return true;
4961 }
4962 }
4963 return true;
4964 }
4965
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004967 public void addPackageToPreferred(String packageName) {
4968 mContext.enforceCallingOrSelfPermission(
4969 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004970 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 }
4972
4973 public void removePackageFromPreferred(String packageName) {
4974 mContext.enforceCallingOrSelfPermission(
4975 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004976 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 }
4978
4979 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004980 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 }
4982
4983 public void addPreferredActivity(IntentFilter filter, int match,
4984 ComponentName[] set, ComponentName activity) {
4985 mContext.enforceCallingOrSelfPermission(
4986 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4987
4988 synchronized (mPackages) {
4989 Log.i(TAG, "Adding preferred activity " + activity + ":");
4990 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4991 mSettings.mPreferredActivities.addFilter(
4992 new PreferredActivity(filter, match, set, activity));
4993 mSettings.writeLP();
4994 }
4995 }
4996
Satish Sampath8dbe6122009-06-02 23:35:54 +01004997 public void replacePreferredActivity(IntentFilter filter, int match,
4998 ComponentName[] set, ComponentName activity) {
4999 mContext.enforceCallingOrSelfPermission(
5000 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5001 if (filter.countActions() != 1) {
5002 throw new IllegalArgumentException(
5003 "replacePreferredActivity expects filter to have only 1 action.");
5004 }
5005 if (filter.countCategories() != 1) {
5006 throw new IllegalArgumentException(
5007 "replacePreferredActivity expects filter to have only 1 category.");
5008 }
5009 if (filter.countDataAuthorities() != 0
5010 || filter.countDataPaths() != 0
5011 || filter.countDataSchemes() != 0
5012 || filter.countDataTypes() != 0) {
5013 throw new IllegalArgumentException(
5014 "replacePreferredActivity expects filter to have no data authorities, " +
5015 "paths, schemes or types.");
5016 }
5017 synchronized (mPackages) {
5018 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5019 String action = filter.getAction(0);
5020 String category = filter.getCategory(0);
5021 while (it.hasNext()) {
5022 PreferredActivity pa = it.next();
5023 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5024 it.remove();
5025 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5026 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5027 }
5028 }
5029 addPreferredActivity(filter, match, set, activity);
5030 }
5031 }
5032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005033 public void clearPackagePreferredActivities(String packageName) {
5034 mContext.enforceCallingOrSelfPermission(
5035 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5036
5037 synchronized (mPackages) {
5038 if (clearPackagePreferredActivitiesLP(packageName)) {
5039 mSettings.writeLP();
5040 }
5041 }
5042 }
5043
5044 boolean clearPackagePreferredActivitiesLP(String packageName) {
5045 boolean changed = false;
5046 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5047 while (it.hasNext()) {
5048 PreferredActivity pa = it.next();
5049 if (pa.mActivity.getPackageName().equals(packageName)) {
5050 it.remove();
5051 changed = true;
5052 }
5053 }
5054 return changed;
5055 }
5056
5057 public int getPreferredActivities(List<IntentFilter> outFilters,
5058 List<ComponentName> outActivities, String packageName) {
5059
5060 int num = 0;
5061 synchronized (mPackages) {
5062 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5063 while (it.hasNext()) {
5064 PreferredActivity pa = it.next();
5065 if (packageName == null
5066 || pa.mActivity.getPackageName().equals(packageName)) {
5067 if (outFilters != null) {
5068 outFilters.add(new IntentFilter(pa));
5069 }
5070 if (outActivities != null) {
5071 outActivities.add(pa.mActivity);
5072 }
5073 }
5074 }
5075 }
5076
5077 return num;
5078 }
5079
5080 public void setApplicationEnabledSetting(String appPackageName,
5081 int newState, int flags) {
5082 setEnabledSetting(appPackageName, null, newState, flags);
5083 }
5084
5085 public void setComponentEnabledSetting(ComponentName componentName,
5086 int newState, int flags) {
5087 setEnabledSetting(componentName.getPackageName(),
5088 componentName.getClassName(), newState, flags);
5089 }
5090
5091 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005092 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005093 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5094 || newState == COMPONENT_ENABLED_STATE_ENABLED
5095 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5096 throw new IllegalArgumentException("Invalid new component state: "
5097 + newState);
5098 }
5099 PackageSetting pkgSetting;
5100 final int uid = Binder.getCallingUid();
5101 final int permission = mContext.checkCallingPermission(
5102 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5103 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005104 boolean sendNow = false;
5105 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005106 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005108 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005110 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005112 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005113 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005114 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005115 }
5116 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005117 "Unknown component: " + packageName
5118 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005119 }
5120 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5121 throw new SecurityException(
5122 "Permission Denial: attempt to change component state from pid="
5123 + Binder.getCallingPid()
5124 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5125 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005126 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005127 // We're dealing with an application/package level state change
5128 pkgSetting.enabled = newState;
5129 } else {
5130 // We're dealing with a component level state change
5131 switch (newState) {
5132 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005133 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134 break;
5135 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005136 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 break;
5138 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005139 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 break;
5141 default:
5142 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005143 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 }
5145 }
5146 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005147 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005148 components = mPendingBroadcasts.get(packageName);
5149 boolean newPackage = components == null;
5150 if (newPackage) {
5151 components = new ArrayList<String>();
5152 }
5153 if (!components.contains(componentName)) {
5154 components.add(componentName);
5155 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005156 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5157 sendNow = true;
5158 // Purge entry from pending broadcast list if another one exists already
5159 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005160 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005161 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005162 if (newPackage) {
5163 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005164 }
5165 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5166 // Schedule a message
5167 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5168 }
5169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005170 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005172 long callingId = Binder.clearCallingIdentity();
5173 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005174 if (sendNow) {
5175 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005176 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005178 } finally {
5179 Binder.restoreCallingIdentity(callingId);
5180 }
5181 }
5182
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005183 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005184 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5185 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5186 + " components=" + componentNames);
5187 Bundle extras = new Bundle(4);
5188 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5189 String nameList[] = new String[componentNames.size()];
5190 componentNames.toArray(nameList);
5191 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005192 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5193 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005194 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005195 }
5196
Jacek Surazski65e13172009-04-28 15:26:38 +02005197 public String getInstallerPackageName(String packageName) {
5198 synchronized (mPackages) {
5199 PackageSetting pkg = mSettings.mPackages.get(packageName);
5200 if (pkg == null) {
5201 throw new IllegalArgumentException("Unknown package: " + packageName);
5202 }
5203 return pkg.installerPackageName;
5204 }
5205 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 public int getApplicationEnabledSetting(String appPackageName) {
5208 synchronized (mPackages) {
5209 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5210 if (pkg == null) {
5211 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5212 }
5213 return pkg.enabled;
5214 }
5215 }
5216
5217 public int getComponentEnabledSetting(ComponentName componentName) {
5218 synchronized (mPackages) {
5219 final String packageNameStr = componentName.getPackageName();
5220 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5221 if (pkg == null) {
5222 throw new IllegalArgumentException("Unknown component: " + componentName);
5223 }
5224 final String classNameStr = componentName.getClassName();
5225 return pkg.currentEnabledStateLP(classNameStr);
5226 }
5227 }
5228
5229 public void enterSafeMode() {
5230 if (!mSystemReady) {
5231 mSafeMode = true;
5232 }
5233 }
5234
5235 public void systemReady() {
5236 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005237
5238 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005239 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005240 mContext.getContentResolver(),
5241 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005242 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005243 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005244 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 }
5247
5248 public boolean isSafeMode() {
5249 return mSafeMode;
5250 }
5251
5252 public boolean hasSystemUidErrors() {
5253 return mHasSystemUidErrors;
5254 }
5255
5256 static String arrayToString(int[] array) {
5257 StringBuffer buf = new StringBuffer(128);
5258 buf.append('[');
5259 if (array != null) {
5260 for (int i=0; i<array.length; i++) {
5261 if (i > 0) buf.append(", ");
5262 buf.append(array[i]);
5263 }
5264 }
5265 buf.append(']');
5266 return buf.toString();
5267 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 @Override
5270 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5271 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5272 != PackageManager.PERMISSION_GRANTED) {
5273 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5274 + Binder.getCallingPid()
5275 + ", uid=" + Binder.getCallingUid()
5276 + " without permission "
5277 + android.Manifest.permission.DUMP);
5278 return;
5279 }
5280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005281 synchronized (mPackages) {
5282 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005283 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005284 pw.println(" ");
5285 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005286 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 pw.println(" ");
5288 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005289 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290 pw.println(" ");
5291 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005292 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005293 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 pw.println("Permissions:");
5295 {
5296 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005297 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5298 pw.print(Integer.toHexString(System.identityHashCode(p)));
5299 pw.println("):");
5300 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5301 pw.print(" uid="); pw.print(p.uid);
5302 pw.print(" gids="); pw.print(arrayToString(p.gids));
5303 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005304 }
5305 }
5306 pw.println(" ");
5307 pw.println("Packages:");
5308 {
5309 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005310 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5311 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5312 pw.println("):");
5313 pw.print(" userId="); pw.print(ps.userId);
5314 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5315 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5316 pw.print(" pkg="); pw.println(ps.pkg);
5317 pw.print(" codePath="); pw.println(ps.codePathString);
5318 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005319 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005320 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005321 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005322 pw.print(" supportsScreens=[");
5323 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005324 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005325 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005326 if (!first) pw.print(", ");
5327 first = false;
5328 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005329 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005330 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005331 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005332 if (!first) pw.print(", ");
5333 first = false;
5334 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005336 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005337 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005338 if (!first) pw.print(", ");
5339 first = false;
5340 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005341 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005342 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005343 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005344 if (!first) pw.print(", ");
5345 first = false;
5346 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005347 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005348 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005349 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
5350 if (!first) pw.print(", ");
5351 first = false;
5352 pw.print("anyDensity");
5353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005355 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005356 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
5357 pw.print(" signatures="); pw.println(ps.signatures);
5358 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
5359 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
5360 pw.print(" installStatus="); pw.print(ps.installStatus);
5361 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 if (ps.disabledComponents.size() > 0) {
5363 pw.println(" disabledComponents:");
5364 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005365 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366 }
5367 }
5368 if (ps.enabledComponents.size() > 0) {
5369 pw.println(" enabledComponents:");
5370 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005371 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 }
5373 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005374 if (ps.grantedPermissions.size() > 0) {
5375 pw.println(" grantedPermissions:");
5376 for (String s : ps.grantedPermissions) {
5377 pw.print(" "); pw.println(s);
5378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005379 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005380 if (ps.loadedPermissions.size() > 0) {
5381 pw.println(" loadedPermissions:");
5382 for (String s : ps.loadedPermissions) {
5383 pw.print(" "); pw.println(s);
5384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 }
5386 }
5387 }
5388 pw.println(" ");
5389 pw.println("Shared Users:");
5390 {
5391 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005392 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5393 pw.print(Integer.toHexString(System.identityHashCode(su)));
5394 pw.println("):");
5395 pw.print(" userId="); pw.print(su.userId);
5396 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 pw.println(" grantedPermissions:");
5398 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005399 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005400 }
5401 pw.println(" loadedPermissions:");
5402 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005403 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005404 }
5405 }
5406 }
5407 pw.println(" ");
5408 pw.println("Settings parse messages:");
5409 pw.println(mSettings.mReadMessages.toString());
5410 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05005411
5412 synchronized (mProviders) {
5413 pw.println(" ");
5414 pw.println("Registered ContentProviders:");
5415 for (PackageParser.Provider p : mProviders.values()) {
5416 pw.println(" ["); pw.println(p.info.authority); pw.println("]: ");
5417 pw.println(p.toString());
5418 }
5419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 }
5421
5422 static final class BasePermission {
5423 final static int TYPE_NORMAL = 0;
5424 final static int TYPE_BUILTIN = 1;
5425 final static int TYPE_DYNAMIC = 2;
5426
5427 final String name;
5428 final String sourcePackage;
5429 final int type;
5430 PackageParser.Permission perm;
5431 PermissionInfo pendingInfo;
5432 int uid;
5433 int[] gids;
5434
5435 BasePermission(String _name, String _sourcePackage, int _type) {
5436 name = _name;
5437 sourcePackage = _sourcePackage;
5438 type = _type;
5439 }
5440 }
5441
5442 static class PackageSignatures {
5443 private Signature[] mSignatures;
5444
5445 PackageSignatures(Signature[] sigs) {
5446 assignSignatures(sigs);
5447 }
5448
5449 PackageSignatures() {
5450 }
5451
5452 void writeXml(XmlSerializer serializer, String tagName,
5453 ArrayList<Signature> pastSignatures) throws IOException {
5454 if (mSignatures == null) {
5455 return;
5456 }
5457 serializer.startTag(null, tagName);
5458 serializer.attribute(null, "count",
5459 Integer.toString(mSignatures.length));
5460 for (int i=0; i<mSignatures.length; i++) {
5461 serializer.startTag(null, "cert");
5462 final Signature sig = mSignatures[i];
5463 final int sigHash = sig.hashCode();
5464 final int numPast = pastSignatures.size();
5465 int j;
5466 for (j=0; j<numPast; j++) {
5467 Signature pastSig = pastSignatures.get(j);
5468 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5469 serializer.attribute(null, "index", Integer.toString(j));
5470 break;
5471 }
5472 }
5473 if (j >= numPast) {
5474 pastSignatures.add(sig);
5475 serializer.attribute(null, "index", Integer.toString(numPast));
5476 serializer.attribute(null, "key", sig.toCharsString());
5477 }
5478 serializer.endTag(null, "cert");
5479 }
5480 serializer.endTag(null, tagName);
5481 }
5482
5483 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5484 throws IOException, XmlPullParserException {
5485 String countStr = parser.getAttributeValue(null, "count");
5486 if (countStr == null) {
5487 reportSettingsProblem(Log.WARN,
5488 "Error in package manager settings: <signatures> has"
5489 + " no count at " + parser.getPositionDescription());
5490 XmlUtils.skipCurrentTag(parser);
5491 }
5492 final int count = Integer.parseInt(countStr);
5493 mSignatures = new Signature[count];
5494 int pos = 0;
5495
5496 int outerDepth = parser.getDepth();
5497 int type;
5498 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5499 && (type != XmlPullParser.END_TAG
5500 || parser.getDepth() > outerDepth)) {
5501 if (type == XmlPullParser.END_TAG
5502 || type == XmlPullParser.TEXT) {
5503 continue;
5504 }
5505
5506 String tagName = parser.getName();
5507 if (tagName.equals("cert")) {
5508 if (pos < count) {
5509 String index = parser.getAttributeValue(null, "index");
5510 if (index != null) {
5511 try {
5512 int idx = Integer.parseInt(index);
5513 String key = parser.getAttributeValue(null, "key");
5514 if (key == null) {
5515 if (idx >= 0 && idx < pastSignatures.size()) {
5516 Signature sig = pastSignatures.get(idx);
5517 if (sig != null) {
5518 mSignatures[pos] = pastSignatures.get(idx);
5519 pos++;
5520 } else {
5521 reportSettingsProblem(Log.WARN,
5522 "Error in package manager settings: <cert> "
5523 + "index " + index + " is not defined at "
5524 + parser.getPositionDescription());
5525 }
5526 } else {
5527 reportSettingsProblem(Log.WARN,
5528 "Error in package manager settings: <cert> "
5529 + "index " + index + " is out of bounds at "
5530 + parser.getPositionDescription());
5531 }
5532 } else {
5533 while (pastSignatures.size() <= idx) {
5534 pastSignatures.add(null);
5535 }
5536 Signature sig = new Signature(key);
5537 pastSignatures.set(idx, sig);
5538 mSignatures[pos] = sig;
5539 pos++;
5540 }
5541 } catch (NumberFormatException e) {
5542 reportSettingsProblem(Log.WARN,
5543 "Error in package manager settings: <cert> "
5544 + "index " + index + " is not a number at "
5545 + parser.getPositionDescription());
5546 }
5547 } else {
5548 reportSettingsProblem(Log.WARN,
5549 "Error in package manager settings: <cert> has"
5550 + " no index at " + parser.getPositionDescription());
5551 }
5552 } else {
5553 reportSettingsProblem(Log.WARN,
5554 "Error in package manager settings: too "
5555 + "many <cert> tags, expected " + count
5556 + " at " + parser.getPositionDescription());
5557 }
5558 } else {
5559 reportSettingsProblem(Log.WARN,
5560 "Unknown element under <cert>: "
5561 + parser.getName());
5562 }
5563 XmlUtils.skipCurrentTag(parser);
5564 }
5565
5566 if (pos < count) {
5567 // Should never happen -- there is an error in the written
5568 // settings -- but if it does we don't want to generate
5569 // a bad array.
5570 Signature[] newSigs = new Signature[pos];
5571 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5572 mSignatures = newSigs;
5573 }
5574 }
5575
5576 /**
5577 * If any of the given 'sigs' is contained in the existing signatures,
5578 * then completely replace the current signatures with the ones in
5579 * 'sigs'. This is used for updating an existing package to a newly
5580 * installed version.
5581 */
5582 boolean updateSignatures(Signature[] sigs, boolean update) {
5583 if (mSignatures == null) {
5584 if (update) {
5585 assignSignatures(sigs);
5586 }
5587 return true;
5588 }
5589 if (sigs == null) {
5590 return false;
5591 }
5592
5593 for (int i=0; i<sigs.length; i++) {
5594 Signature sig = sigs[i];
5595 for (int j=0; j<mSignatures.length; j++) {
5596 if (mSignatures[j].equals(sig)) {
5597 if (update) {
5598 assignSignatures(sigs);
5599 }
5600 return true;
5601 }
5602 }
5603 }
5604 return false;
5605 }
5606
5607 /**
5608 * If any of the given 'sigs' is contained in the existing signatures,
5609 * then add in any new signatures found in 'sigs'. This is used for
5610 * including a new package into an existing shared user id.
5611 */
5612 boolean mergeSignatures(Signature[] sigs, boolean update) {
5613 if (mSignatures == null) {
5614 if (update) {
5615 assignSignatures(sigs);
5616 }
5617 return true;
5618 }
5619 if (sigs == null) {
5620 return false;
5621 }
5622
5623 Signature[] added = null;
5624 int addedCount = 0;
5625 boolean haveMatch = false;
5626 for (int i=0; i<sigs.length; i++) {
5627 Signature sig = sigs[i];
5628 boolean found = false;
5629 for (int j=0; j<mSignatures.length; j++) {
5630 if (mSignatures[j].equals(sig)) {
5631 found = true;
5632 haveMatch = true;
5633 break;
5634 }
5635 }
5636
5637 if (!found) {
5638 if (added == null) {
5639 added = new Signature[sigs.length];
5640 }
5641 added[i] = sig;
5642 addedCount++;
5643 }
5644 }
5645
5646 if (!haveMatch) {
5647 // Nothing matched -- reject the new signatures.
5648 return false;
5649 }
5650 if (added == null) {
5651 // Completely matched -- nothing else to do.
5652 return true;
5653 }
5654
5655 // Add additional signatures in.
5656 if (update) {
5657 Signature[] total = new Signature[addedCount+mSignatures.length];
5658 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5659 int j = mSignatures.length;
5660 for (int i=0; i<added.length; i++) {
5661 if (added[i] != null) {
5662 total[j] = added[i];
5663 j++;
5664 }
5665 }
5666 mSignatures = total;
5667 }
5668 return true;
5669 }
5670
5671 private void assignSignatures(Signature[] sigs) {
5672 if (sigs == null) {
5673 mSignatures = null;
5674 return;
5675 }
5676 mSignatures = new Signature[sigs.length];
5677 for (int i=0; i<sigs.length; i++) {
5678 mSignatures[i] = sigs[i];
5679 }
5680 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 @Override
5683 public String toString() {
5684 StringBuffer buf = new StringBuffer(128);
5685 buf.append("PackageSignatures{");
5686 buf.append(Integer.toHexString(System.identityHashCode(this)));
5687 buf.append(" [");
5688 if (mSignatures != null) {
5689 for (int i=0; i<mSignatures.length; i++) {
5690 if (i > 0) buf.append(", ");
5691 buf.append(Integer.toHexString(
5692 System.identityHashCode(mSignatures[i])));
5693 }
5694 }
5695 buf.append("]}");
5696 return buf.toString();
5697 }
5698 }
5699
5700 static class PreferredActivity extends IntentFilter {
5701 final int mMatch;
5702 final String[] mSetPackages;
5703 final String[] mSetClasses;
5704 final String[] mSetComponents;
5705 final ComponentName mActivity;
5706 final String mShortActivity;
5707 String mParseError;
5708
5709 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5710 ComponentName activity) {
5711 super(filter);
5712 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5713 mActivity = activity;
5714 mShortActivity = activity.flattenToShortString();
5715 mParseError = null;
5716 if (set != null) {
5717 final int N = set.length;
5718 String[] myPackages = new String[N];
5719 String[] myClasses = new String[N];
5720 String[] myComponents = new String[N];
5721 for (int i=0; i<N; i++) {
5722 ComponentName cn = set[i];
5723 if (cn == null) {
5724 mSetPackages = null;
5725 mSetClasses = null;
5726 mSetComponents = null;
5727 return;
5728 }
5729 myPackages[i] = cn.getPackageName().intern();
5730 myClasses[i] = cn.getClassName().intern();
5731 myComponents[i] = cn.flattenToShortString().intern();
5732 }
5733 mSetPackages = myPackages;
5734 mSetClasses = myClasses;
5735 mSetComponents = myComponents;
5736 } else {
5737 mSetPackages = null;
5738 mSetClasses = null;
5739 mSetComponents = null;
5740 }
5741 }
5742
5743 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5744 IOException {
5745 mShortActivity = parser.getAttributeValue(null, "name");
5746 mActivity = ComponentName.unflattenFromString(mShortActivity);
5747 if (mActivity == null) {
5748 mParseError = "Bad activity name " + mShortActivity;
5749 }
5750 String matchStr = parser.getAttributeValue(null, "match");
5751 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5752 String setCountStr = parser.getAttributeValue(null, "set");
5753 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5754
5755 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5756 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5757 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5758
5759 int setPos = 0;
5760
5761 int outerDepth = parser.getDepth();
5762 int type;
5763 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5764 && (type != XmlPullParser.END_TAG
5765 || parser.getDepth() > outerDepth)) {
5766 if (type == XmlPullParser.END_TAG
5767 || type == XmlPullParser.TEXT) {
5768 continue;
5769 }
5770
5771 String tagName = parser.getName();
5772 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5773 // + parser.getDepth() + " tag=" + tagName);
5774 if (tagName.equals("set")) {
5775 String name = parser.getAttributeValue(null, "name");
5776 if (name == null) {
5777 if (mParseError == null) {
5778 mParseError = "No name in set tag in preferred activity "
5779 + mShortActivity;
5780 }
5781 } else if (setPos >= setCount) {
5782 if (mParseError == null) {
5783 mParseError = "Too many set tags in preferred activity "
5784 + mShortActivity;
5785 }
5786 } else {
5787 ComponentName cn = ComponentName.unflattenFromString(name);
5788 if (cn == null) {
5789 if (mParseError == null) {
5790 mParseError = "Bad set name " + name + " in preferred activity "
5791 + mShortActivity;
5792 }
5793 } else {
5794 myPackages[setPos] = cn.getPackageName();
5795 myClasses[setPos] = cn.getClassName();
5796 myComponents[setPos] = name;
5797 setPos++;
5798 }
5799 }
5800 XmlUtils.skipCurrentTag(parser);
5801 } else if (tagName.equals("filter")) {
5802 //Log.i(TAG, "Starting to parse filter...");
5803 readFromXml(parser);
5804 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5805 // + parser.getDepth() + " tag=" + parser.getName());
5806 } else {
5807 reportSettingsProblem(Log.WARN,
5808 "Unknown element under <preferred-activities>: "
5809 + parser.getName());
5810 XmlUtils.skipCurrentTag(parser);
5811 }
5812 }
5813
5814 if (setPos != setCount) {
5815 if (mParseError == null) {
5816 mParseError = "Not enough set tags (expected " + setCount
5817 + " but found " + setPos + ") in " + mShortActivity;
5818 }
5819 }
5820
5821 mSetPackages = myPackages;
5822 mSetClasses = myClasses;
5823 mSetComponents = myComponents;
5824 }
5825
5826 public void writeToXml(XmlSerializer serializer) throws IOException {
5827 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5828 serializer.attribute(null, "name", mShortActivity);
5829 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5830 serializer.attribute(null, "set", Integer.toString(NS));
5831 for (int s=0; s<NS; s++) {
5832 serializer.startTag(null, "set");
5833 serializer.attribute(null, "name", mSetComponents[s]);
5834 serializer.endTag(null, "set");
5835 }
5836 serializer.startTag(null, "filter");
5837 super.writeToXml(serializer);
5838 serializer.endTag(null, "filter");
5839 }
5840
5841 boolean sameSet(List<ResolveInfo> query, int priority) {
5842 if (mSetPackages == null) return false;
5843 final int NQ = query.size();
5844 final int NS = mSetPackages.length;
5845 int numMatch = 0;
5846 for (int i=0; i<NQ; i++) {
5847 ResolveInfo ri = query.get(i);
5848 if (ri.priority != priority) continue;
5849 ActivityInfo ai = ri.activityInfo;
5850 boolean good = false;
5851 for (int j=0; j<NS; j++) {
5852 if (mSetPackages[j].equals(ai.packageName)
5853 && mSetClasses[j].equals(ai.name)) {
5854 numMatch++;
5855 good = true;
5856 break;
5857 }
5858 }
5859 if (!good) return false;
5860 }
5861 return numMatch == NS;
5862 }
5863 }
5864
5865 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07005866 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 HashSet<String> grantedPermissions = new HashSet<String>();
5869 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08005874 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
5875 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
5876 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 }
5878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 /**
5881 * Settings base class for pending and resolved classes.
5882 */
5883 static class PackageSettingBase extends GrantedPermissions {
5884 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005885 File codePath;
5886 String codePathString;
5887 File resourcePath;
5888 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 private long timeStamp;
5890 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005891 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892
5893 PackageSignatures signatures = new PackageSignatures();
5894
5895 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 /* Explicitly disabled components */
5898 HashSet<String> disabledComponents = new HashSet<String>(0);
5899 /* Explicitly enabled components */
5900 HashSet<String> enabledComponents = new HashSet<String>(0);
5901 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5902 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005903
Jacek Surazski65e13172009-04-28 15:26:38 +02005904 /* package name of the app that installed this package */
5905 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906
5907 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005908 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 super(pkgFlags);
5910 this.name = name;
5911 this.codePath = codePath;
5912 this.codePathString = codePath.toString();
5913 this.resourcePath = resourcePath;
5914 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005915 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 }
5917
Jacek Surazski65e13172009-04-28 15:26:38 +02005918 public void setInstallerPackageName(String packageName) {
5919 installerPackageName = packageName;
5920 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005921
Jacek Surazski65e13172009-04-28 15:26:38 +02005922 String getInstallerPackageName() {
5923 return installerPackageName;
5924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926 public void setInstallStatus(int newStatus) {
5927 installStatus = newStatus;
5928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 public int getInstallStatus() {
5931 return installStatus;
5932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 public void setTimeStamp(long newStamp) {
5935 if (newStamp != timeStamp) {
5936 timeStamp = newStamp;
5937 timeStampString = Long.toString(newStamp);
5938 }
5939 }
5940
5941 public void setTimeStamp(long newStamp, String newStampStr) {
5942 timeStamp = newStamp;
5943 timeStampString = newStampStr;
5944 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 public long getTimeStamp() {
5947 return timeStamp;
5948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 public String getTimeStampStr() {
5951 return timeStampString;
5952 }
5953
5954 public void copyFrom(PackageSettingBase base) {
5955 grantedPermissions = base.grantedPermissions;
5956 gids = base.gids;
5957 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 timeStamp = base.timeStamp;
5960 timeStampString = base.timeStampString;
5961 signatures = base.signatures;
5962 permissionsFixed = base.permissionsFixed;
5963 disabledComponents = base.disabledComponents;
5964 enabledComponents = base.enabledComponents;
5965 enabled = base.enabled;
5966 installStatus = base.installStatus;
5967 }
5968
5969 void enableComponentLP(String componentClassName) {
5970 disabledComponents.remove(componentClassName);
5971 enabledComponents.add(componentClassName);
5972 }
5973
5974 void disableComponentLP(String componentClassName) {
5975 enabledComponents.remove(componentClassName);
5976 disabledComponents.add(componentClassName);
5977 }
5978
5979 void restoreComponentLP(String componentClassName) {
5980 enabledComponents.remove(componentClassName);
5981 disabledComponents.remove(componentClassName);
5982 }
5983
5984 int currentEnabledStateLP(String componentName) {
5985 if (enabledComponents.contains(componentName)) {
5986 return COMPONENT_ENABLED_STATE_ENABLED;
5987 } else if (disabledComponents.contains(componentName)) {
5988 return COMPONENT_ENABLED_STATE_DISABLED;
5989 } else {
5990 return COMPONENT_ENABLED_STATE_DEFAULT;
5991 }
5992 }
5993 }
5994
5995 /**
5996 * Settings data for a particular package we know about.
5997 */
5998 static final class PackageSetting extends PackageSettingBase {
5999 int userId;
6000 PackageParser.Package pkg;
6001 SharedUserSetting sharedUser;
6002
6003 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006004 int pVersionCode, int pkgFlags) {
6005 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 @Override
6009 public String toString() {
6010 return "PackageSetting{"
6011 + Integer.toHexString(System.identityHashCode(this))
6012 + " " + name + "/" + userId + "}";
6013 }
6014 }
6015
6016 /**
6017 * Settings data for a particular shared user ID we know about.
6018 */
6019 static final class SharedUserSetting extends GrantedPermissions {
6020 final String name;
6021 int userId;
6022 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6023 final PackageSignatures signatures = new PackageSignatures();
6024
6025 SharedUserSetting(String _name, int _pkgFlags) {
6026 super(_pkgFlags);
6027 name = _name;
6028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 @Override
6031 public String toString() {
6032 return "SharedUserSetting{"
6033 + Integer.toHexString(System.identityHashCode(this))
6034 + " " + name + "/" + userId + "}";
6035 }
6036 }
6037
6038 /**
6039 * Holds information about dynamic settings.
6040 */
6041 private static final class Settings {
6042 private final File mSettingsFilename;
6043 private final File mBackupSettingsFilename;
6044 private final HashMap<String, PackageSetting> mPackages =
6045 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 // List of replaced system applications
6047 final HashMap<String, PackageSetting> mDisabledSysPackages =
6048 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 // The user's preferred activities associated with particular intent
6051 // filters.
6052 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6053 new IntentResolver<PreferredActivity, PreferredActivity>() {
6054 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006055 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006057 out.print(prefix); out.print(
6058 Integer.toHexString(System.identityHashCode(filter)));
6059 out.print(' ');
6060 out.print(filter.mActivity.flattenToShortString());
6061 out.print(" match=0x");
6062 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006064 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006066 out.print(prefix); out.print(" ");
6067 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 }
6069 }
6070 }
6071 };
6072 private final HashMap<String, SharedUserSetting> mSharedUsers =
6073 new HashMap<String, SharedUserSetting>();
6074 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6075 private final SparseArray<Object> mOtherUserIds =
6076 new SparseArray<Object>();
6077
6078 // For reading/writing settings file.
6079 private final ArrayList<Signature> mPastSignatures =
6080 new ArrayList<Signature>();
6081
6082 // Mapping from permission names to info about them.
6083 final HashMap<String, BasePermission> mPermissions =
6084 new HashMap<String, BasePermission>();
6085
6086 // Mapping from permission tree names to info about them.
6087 final HashMap<String, BasePermission> mPermissionTrees =
6088 new HashMap<String, BasePermission>();
6089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006090 private final StringBuilder mReadMessages = new StringBuilder();
6091
6092 private static final class PendingPackage extends PackageSettingBase {
6093 final int sharedId;
6094
6095 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006096 int sharedId, int pVersionCode, int pkgFlags) {
6097 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 this.sharedId = sharedId;
6099 }
6100 }
6101 private final ArrayList<PendingPackage> mPendingPackages
6102 = new ArrayList<PendingPackage>();
6103
6104 Settings() {
6105 File dataDir = Environment.getDataDirectory();
6106 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08006107 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
6108 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006110 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 FileUtils.setPermissions(systemDir.toString(),
6112 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6113 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6114 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08006115 FileUtils.setPermissions(systemSecureDir.toString(),
6116 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6117 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6118 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 mSettingsFilename = new File(systemDir, "packages.xml");
6120 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6121 }
6122
6123 PackageSetting getPackageLP(PackageParser.Package pkg,
6124 SharedUserSetting sharedUser, File codePath, File resourcePath,
6125 int pkgFlags, boolean create, boolean add) {
6126 final String name = pkg.packageName;
6127 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006128 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 return p;
6130 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006131
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006132 PackageSetting peekPackageLP(String name) {
6133 return mPackages.get(name);
6134 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 PackageSetting p = mPackages.get(name);
6136 if (p != null && p.codePath.getPath().equals(codePath)) {
6137 return p;
6138 }
6139 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006140 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 void setInstallStatus(String pkgName, int status) {
6144 PackageSetting p = mPackages.get(pkgName);
6145 if(p != null) {
6146 if(p.getInstallStatus() != status) {
6147 p.setInstallStatus(status);
6148 }
6149 }
6150 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006151
Jacek Surazski65e13172009-04-28 15:26:38 +02006152 void setInstallerPackageName(String pkgName,
6153 String installerPkgName) {
6154 PackageSetting p = mPackages.get(pkgName);
6155 if(p != null) {
6156 p.setInstallerPackageName(installerPkgName);
6157 }
6158 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006159
Jacek Surazski65e13172009-04-28 15:26:38 +02006160 String getInstallerPackageName(String pkgName) {
6161 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006162 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02006163 }
6164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165 int getInstallStatus(String pkgName) {
6166 PackageSetting p = mPackages.get(pkgName);
6167 if(p != null) {
6168 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 return -1;
6171 }
6172
6173 SharedUserSetting getSharedUserLP(String name,
6174 int pkgFlags, boolean create) {
6175 SharedUserSetting s = mSharedUsers.get(name);
6176 if (s == null) {
6177 if (!create) {
6178 return null;
6179 }
6180 s = new SharedUserSetting(name, pkgFlags);
6181 if (MULTIPLE_APPLICATION_UIDS) {
6182 s.userId = newUserIdLP(s);
6183 } else {
6184 s.userId = FIRST_APPLICATION_UID;
6185 }
6186 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6187 // < 0 means we couldn't assign a userid; fall out and return
6188 // s, which is currently null
6189 if (s.userId >= 0) {
6190 mSharedUsers.put(name, s);
6191 }
6192 }
6193
6194 return s;
6195 }
6196
6197 int disableSystemPackageLP(String name) {
6198 PackageSetting p = mPackages.get(name);
6199 if(p == null) {
6200 Log.w(TAG, "Package:"+name+" is not an installed package");
6201 return -1;
6202 }
6203 PackageSetting dp = mDisabledSysPackages.get(name);
6204 // always make sure the system package code and resource paths dont change
6205 if(dp == null) {
6206 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6207 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6208 }
6209 mDisabledSysPackages.put(name, p);
6210 }
6211 return removePackageLP(name);
6212 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 PackageSetting enableSystemPackageLP(String name) {
6215 PackageSetting p = mDisabledSysPackages.get(name);
6216 if(p == null) {
6217 Log.w(TAG, "Package:"+name+" is not disabled");
6218 return null;
6219 }
6220 // Reset flag in ApplicationInfo object
6221 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6222 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6223 }
6224 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006225 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 mDisabledSysPackages.remove(name);
6227 return ret;
6228 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006231 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 PackageSetting p = mPackages.get(name);
6233 if (p != null) {
6234 if (p.userId == uid) {
6235 return p;
6236 }
6237 reportSettingsProblem(Log.ERROR,
6238 "Adding duplicate package, keeping first: " + name);
6239 return null;
6240 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006241 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 p.userId = uid;
6243 if (addUserIdLP(uid, p, name)) {
6244 mPackages.put(name, p);
6245 return p;
6246 }
6247 return null;
6248 }
6249
6250 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6251 SharedUserSetting s = mSharedUsers.get(name);
6252 if (s != null) {
6253 if (s.userId == uid) {
6254 return s;
6255 }
6256 reportSettingsProblem(Log.ERROR,
6257 "Adding duplicate shared user, keeping first: " + name);
6258 return null;
6259 }
6260 s = new SharedUserSetting(name, pkgFlags);
6261 s.userId = uid;
6262 if (addUserIdLP(uid, s, name)) {
6263 mSharedUsers.put(name, s);
6264 return s;
6265 }
6266 return null;
6267 }
6268
6269 private PackageSetting getPackageLP(String name,
6270 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006271 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 PackageSetting p = mPackages.get(name);
6273 if (p != null) {
6274 if (!p.codePath.equals(codePath)) {
6275 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006276 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006277 // This is an updated system app with versions in both system
6278 // and data partition. Just let the most recent version
6279 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006280 Log.w(TAG, "Trying to update system app code path from " +
6281 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006282 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006283 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07006284 reportSettingsProblem(Log.WARN,
6285 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006286 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006287 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006288 }
6289 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 reportSettingsProblem(Log.WARN,
6291 "Package " + name + " shared user changed from "
6292 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
6293 + " to "
6294 + (sharedUser != null ? sharedUser.name : "<nothing>")
6295 + "; replacing with new");
6296 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006297 } else {
6298 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6299 // If what we are scanning is a system package, then
6300 // make it so, regardless of whether it was previously
6301 // installed only in the data partition.
6302 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 }
6305 }
6306 if (p == null) {
6307 // Create a new PackageSettings entry. this can end up here because
6308 // of code path mismatch or user id mismatch of an updated system partition
6309 if (!create) {
6310 return null;
6311 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006312 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07006314 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 if (sharedUser != null) {
6316 p.userId = sharedUser.userId;
6317 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006318 // Clone the setting here for disabled system packages
6319 PackageSetting dis = mDisabledSysPackages.get(name);
6320 if (dis != null) {
6321 // For disabled packages a new setting is created
6322 // from the existing user id. This still has to be
6323 // added to list of user id's
6324 // Copy signatures from previous setting
6325 if (dis.signatures.mSignatures != null) {
6326 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
6327 }
6328 p.userId = dis.userId;
6329 // Clone permissions
6330 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
6331 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
6332 // Clone component info
6333 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
6334 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
6335 // Add new setting to list of user ids
6336 addUserIdLP(p.userId, p, name);
6337 } else {
6338 // Assign new user id
6339 p.userId = newUserIdLP(p);
6340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 } else {
6342 p.userId = FIRST_APPLICATION_UID;
6343 }
6344 if (p.userId < 0) {
6345 reportSettingsProblem(Log.WARN,
6346 "Package " + name + " could not be assigned a valid uid");
6347 return null;
6348 }
6349 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006350 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006352 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 }
6354 }
6355 return p;
6356 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006357
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006358 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006359 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006360 String codePath = pkg.applicationInfo.sourceDir;
6361 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006362 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006363 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006364 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006365 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006366 p.codePath = new File(codePath);
6367 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006368 }
6369 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006370 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006371 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006372 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006373 p.resourcePath = new File(resourcePath);
6374 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006375 }
6376 // Update version code if needed
6377 if (pkg.mVersionCode != p.versionCode) {
6378 p.versionCode = pkg.mVersionCode;
6379 }
6380 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
6381 }
6382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 // Utility method that adds a PackageSetting to mPackages and
6384 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006385 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 SharedUserSetting sharedUser) {
6387 mPackages.put(name, p);
6388 if (sharedUser != null) {
6389 if (p.sharedUser != null && p.sharedUser != sharedUser) {
6390 reportSettingsProblem(Log.ERROR,
6391 "Package " + p.name + " was user "
6392 + p.sharedUser + " but is now " + sharedUser
6393 + "; I am not changing its files so it will probably fail!");
6394 p.sharedUser.packages.remove(p);
6395 } else if (p.userId != sharedUser.userId) {
6396 reportSettingsProblem(Log.ERROR,
6397 "Package " + p.name + " was user id " + p.userId
6398 + " but is now user " + sharedUser
6399 + " with id " + sharedUser.userId
6400 + "; I am not changing its files so it will probably fail!");
6401 }
6402
6403 sharedUser.packages.add(p);
6404 p.sharedUser = sharedUser;
6405 p.userId = sharedUser.userId;
6406 }
6407 }
6408
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006409 /*
6410 * Update the shared user setting when a package using
6411 * specifying the shared user id is removed. The gids
6412 * associated with each permission of the deleted package
6413 * are removed from the shared user's gid list only if its
6414 * not in use by other permissions of packages in the
6415 * shared user setting.
6416 */
6417 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6419 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6420 return;
6421 }
6422 // No sharedUserId
6423 if (deletedPs.sharedUser == null) {
6424 return;
6425 }
6426 SharedUserSetting sus = deletedPs.sharedUser;
6427 // Update permissions
6428 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6429 boolean used = false;
6430 if (!sus.grantedPermissions.contains (eachPerm)) {
6431 continue;
6432 }
6433 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006434 if (pkg.pkg != null &&
6435 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
6436 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 used = true;
6438 break;
6439 }
6440 }
6441 if (!used) {
6442 // can safely delete this permission from list
6443 sus.grantedPermissions.remove(eachPerm);
6444 sus.loadedPermissions.remove(eachPerm);
6445 }
6446 }
6447 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006448 int newGids[] = globalGids;
6449 for (String eachPerm : sus.grantedPermissions) {
6450 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006451 if (bp != null) {
6452 newGids = appendInts(newGids, bp.gids);
6453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 }
6455 sus.gids = newGids;
6456 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 private int removePackageLP(String name) {
6459 PackageSetting p = mPackages.get(name);
6460 if (p != null) {
6461 mPackages.remove(name);
6462 if (p.sharedUser != null) {
6463 p.sharedUser.packages.remove(p);
6464 if (p.sharedUser.packages.size() == 0) {
6465 mSharedUsers.remove(p.sharedUser.name);
6466 removeUserIdLP(p.sharedUser.userId);
6467 return p.sharedUser.userId;
6468 }
6469 } else {
6470 removeUserIdLP(p.userId);
6471 return p.userId;
6472 }
6473 }
6474 return -1;
6475 }
6476
6477 private boolean addUserIdLP(int uid, Object obj, Object name) {
6478 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6479 return false;
6480 }
6481
6482 if (uid >= FIRST_APPLICATION_UID) {
6483 int N = mUserIds.size();
6484 final int index = uid - FIRST_APPLICATION_UID;
6485 while (index >= N) {
6486 mUserIds.add(null);
6487 N++;
6488 }
6489 if (mUserIds.get(index) != null) {
6490 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006491 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 + " name=" + name);
6493 return false;
6494 }
6495 mUserIds.set(index, obj);
6496 } else {
6497 if (mOtherUserIds.get(uid) != null) {
6498 reportSettingsProblem(Log.ERROR,
6499 "Adding duplicate shared id: " + uid
6500 + " name=" + name);
6501 return false;
6502 }
6503 mOtherUserIds.put(uid, obj);
6504 }
6505 return true;
6506 }
6507
6508 public Object getUserIdLP(int uid) {
6509 if (uid >= FIRST_APPLICATION_UID) {
6510 int N = mUserIds.size();
6511 final int index = uid - FIRST_APPLICATION_UID;
6512 return index < N ? mUserIds.get(index) : null;
6513 } else {
6514 return mOtherUserIds.get(uid);
6515 }
6516 }
6517
6518 private void removeUserIdLP(int uid) {
6519 if (uid >= FIRST_APPLICATION_UID) {
6520 int N = mUserIds.size();
6521 final int index = uid - FIRST_APPLICATION_UID;
6522 if (index < N) mUserIds.set(index, null);
6523 } else {
6524 mOtherUserIds.remove(uid);
6525 }
6526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 void writeLP() {
6529 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6530
6531 // Keep the old settings around until we know the new ones have
6532 // been successfully written.
6533 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006534 // Presence of backup settings file indicates that we failed
6535 // to persist settings earlier. So preserve the older
6536 // backup for future reference since the current settings
6537 // might have been corrupted.
6538 if (!mBackupSettingsFilename.exists()) {
6539 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
6540 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
6541 return;
6542 }
6543 } else {
6544 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07006545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 }
6547
6548 mPastSignatures.clear();
6549
6550 try {
6551 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6552
6553 //XmlSerializer serializer = XmlUtils.serializerInstance();
6554 XmlSerializer serializer = new FastXmlSerializer();
6555 serializer.setOutput(str, "utf-8");
6556 serializer.startDocument(null, true);
6557 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6558
6559 serializer.startTag(null, "packages");
6560
6561 serializer.startTag(null, "permission-trees");
6562 for (BasePermission bp : mPermissionTrees.values()) {
6563 writePermission(serializer, bp);
6564 }
6565 serializer.endTag(null, "permission-trees");
6566
6567 serializer.startTag(null, "permissions");
6568 for (BasePermission bp : mPermissions.values()) {
6569 writePermission(serializer, bp);
6570 }
6571 serializer.endTag(null, "permissions");
6572
6573 for (PackageSetting pkg : mPackages.values()) {
6574 writePackage(serializer, pkg);
6575 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6578 writeDisabledSysPackage(serializer, pkg);
6579 }
6580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 serializer.startTag(null, "preferred-activities");
6582 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6583 serializer.startTag(null, "item");
6584 pa.writeToXml(serializer);
6585 serializer.endTag(null, "item");
6586 }
6587 serializer.endTag(null, "preferred-activities");
6588
6589 for (SharedUserSetting usr : mSharedUsers.values()) {
6590 serializer.startTag(null, "shared-user");
6591 serializer.attribute(null, "name", usr.name);
6592 serializer.attribute(null, "userId",
6593 Integer.toString(usr.userId));
6594 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6595 serializer.startTag(null, "perms");
6596 for (String name : usr.grantedPermissions) {
6597 serializer.startTag(null, "item");
6598 serializer.attribute(null, "name", name);
6599 serializer.endTag(null, "item");
6600 }
6601 serializer.endTag(null, "perms");
6602 serializer.endTag(null, "shared-user");
6603 }
6604
6605 serializer.endTag(null, "packages");
6606
6607 serializer.endDocument();
6608
6609 str.flush();
6610 str.close();
6611
6612 // New settings successfully written, old ones are no longer
6613 // needed.
6614 mBackupSettingsFilename.delete();
6615 FileUtils.setPermissions(mSettingsFilename.toString(),
6616 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6617 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6618 |FileUtils.S_IROTH,
6619 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006620 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621
6622 } catch(XmlPullParserException e) {
6623 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 -08006624 } catch(java.io.IOException e) {
6625 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 -08006626 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006627 // Clean up partially written file
6628 if (mSettingsFilename.exists()) {
6629 if (!mSettingsFilename.delete()) {
6630 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
6631 }
6632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 //Debug.stopMethodTracing();
6634 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006635
6636 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 throws java.io.IOException {
6638 serializer.startTag(null, "updated-package");
6639 serializer.attribute(null, "name", pkg.name);
6640 serializer.attribute(null, "codePath", pkg.codePathString);
6641 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006642 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6644 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6645 }
6646 if (pkg.sharedUser == null) {
6647 serializer.attribute(null, "userId",
6648 Integer.toString(pkg.userId));
6649 } else {
6650 serializer.attribute(null, "sharedUserId",
6651 Integer.toString(pkg.userId));
6652 }
6653 serializer.startTag(null, "perms");
6654 if (pkg.sharedUser == null) {
6655 // If this is a shared user, the permissions will
6656 // be written there. We still need to write an
6657 // empty permissions list so permissionsFixed will
6658 // be set.
6659 for (final String name : pkg.grantedPermissions) {
6660 BasePermission bp = mPermissions.get(name);
6661 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6662 // We only need to write signature or system permissions but this wont
6663 // match the semantics of grantedPermissions. So write all permissions.
6664 serializer.startTag(null, "item");
6665 serializer.attribute(null, "name", name);
6666 serializer.endTag(null, "item");
6667 }
6668 }
6669 }
6670 serializer.endTag(null, "perms");
6671 serializer.endTag(null, "updated-package");
6672 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006673
6674 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 throws java.io.IOException {
6676 serializer.startTag(null, "package");
6677 serializer.attribute(null, "name", pkg.name);
6678 serializer.attribute(null, "codePath", pkg.codePathString);
6679 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6680 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6681 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006682 serializer.attribute(null, "flags",
6683 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006684 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006685 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006686 if (pkg.sharedUser == null) {
6687 serializer.attribute(null, "userId",
6688 Integer.toString(pkg.userId));
6689 } else {
6690 serializer.attribute(null, "sharedUserId",
6691 Integer.toString(pkg.userId));
6692 }
6693 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6694 serializer.attribute(null, "enabled",
6695 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6696 ? "true" : "false");
6697 }
6698 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6699 serializer.attribute(null, "installStatus", "false");
6700 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006701 if (pkg.installerPackageName != null) {
6702 serializer.attribute(null, "installer", pkg.installerPackageName);
6703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6705 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6706 serializer.startTag(null, "perms");
6707 if (pkg.sharedUser == null) {
6708 // If this is a shared user, the permissions will
6709 // be written there. We still need to write an
6710 // empty permissions list so permissionsFixed will
6711 // be set.
6712 for (final String name : pkg.grantedPermissions) {
6713 serializer.startTag(null, "item");
6714 serializer.attribute(null, "name", name);
6715 serializer.endTag(null, "item");
6716 }
6717 }
6718 serializer.endTag(null, "perms");
6719 }
6720 if (pkg.disabledComponents.size() > 0) {
6721 serializer.startTag(null, "disabled-components");
6722 for (final String name : pkg.disabledComponents) {
6723 serializer.startTag(null, "item");
6724 serializer.attribute(null, "name", name);
6725 serializer.endTag(null, "item");
6726 }
6727 serializer.endTag(null, "disabled-components");
6728 }
6729 if (pkg.enabledComponents.size() > 0) {
6730 serializer.startTag(null, "enabled-components");
6731 for (final String name : pkg.enabledComponents) {
6732 serializer.startTag(null, "item");
6733 serializer.attribute(null, "name", name);
6734 serializer.endTag(null, "item");
6735 }
6736 serializer.endTag(null, "enabled-components");
6737 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 serializer.endTag(null, "package");
6740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 void writePermission(XmlSerializer serializer, BasePermission bp)
6743 throws XmlPullParserException, java.io.IOException {
6744 if (bp.type != BasePermission.TYPE_BUILTIN
6745 && bp.sourcePackage != null) {
6746 serializer.startTag(null, "item");
6747 serializer.attribute(null, "name", bp.name);
6748 serializer.attribute(null, "package", bp.sourcePackage);
6749 if (DEBUG_SETTINGS) Log.v(TAG,
6750 "Writing perm: name=" + bp.name + " type=" + bp.type);
6751 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6752 PermissionInfo pi = bp.perm != null ? bp.perm.info
6753 : bp.pendingInfo;
6754 if (pi != null) {
6755 serializer.attribute(null, "type", "dynamic");
6756 if (pi.icon != 0) {
6757 serializer.attribute(null, "icon",
6758 Integer.toString(pi.icon));
6759 }
6760 if (pi.nonLocalizedLabel != null) {
6761 serializer.attribute(null, "label",
6762 pi.nonLocalizedLabel.toString());
6763 }
6764 if (pi.protectionLevel !=
6765 PermissionInfo.PROTECTION_NORMAL) {
6766 serializer.attribute(null, "protection",
6767 Integer.toString(pi.protectionLevel));
6768 }
6769 }
6770 }
6771 serializer.endTag(null, "item");
6772 }
6773 }
6774
6775 String getReadMessagesLP() {
6776 return mReadMessages.toString();
6777 }
6778
Oscar Montemayora8529f62009-11-18 10:14:20 -08006779 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006780 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6781 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006782 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 while(its.hasNext()) {
6784 String key = its.next();
6785 PackageSetting ps = mPackages.get(key);
6786 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006787 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 }
6789 }
6790 return ret;
6791 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 boolean readLP() {
6794 FileInputStream str = null;
6795 if (mBackupSettingsFilename.exists()) {
6796 try {
6797 str = new FileInputStream(mBackupSettingsFilename);
6798 mReadMessages.append("Reading from backup settings file\n");
6799 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006800 if (mSettingsFilename.exists()) {
6801 // If both the backup and settings file exist, we
6802 // ignore the settings since it might have been
6803 // corrupted.
6804 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
6805 mSettingsFilename.delete();
6806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 } catch (java.io.IOException e) {
6808 // We'll try for the normal settings file.
6809 }
6810 }
6811
6812 mPastSignatures.clear();
6813
6814 try {
6815 if (str == null) {
6816 if (!mSettingsFilename.exists()) {
6817 mReadMessages.append("No settings file found\n");
6818 Log.i(TAG, "No current settings file!");
6819 return false;
6820 }
6821 str = new FileInputStream(mSettingsFilename);
6822 }
6823 XmlPullParser parser = Xml.newPullParser();
6824 parser.setInput(str, null);
6825
6826 int type;
6827 while ((type=parser.next()) != XmlPullParser.START_TAG
6828 && type != XmlPullParser.END_DOCUMENT) {
6829 ;
6830 }
6831
6832 if (type != XmlPullParser.START_TAG) {
6833 mReadMessages.append("No start tag found in settings file\n");
6834 Log.e(TAG, "No start tag found in package manager settings");
6835 return false;
6836 }
6837
6838 int outerDepth = parser.getDepth();
6839 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6840 && (type != XmlPullParser.END_TAG
6841 || parser.getDepth() > outerDepth)) {
6842 if (type == XmlPullParser.END_TAG
6843 || type == XmlPullParser.TEXT) {
6844 continue;
6845 }
6846
6847 String tagName = parser.getName();
6848 if (tagName.equals("package")) {
6849 readPackageLP(parser);
6850 } else if (tagName.equals("permissions")) {
6851 readPermissionsLP(mPermissions, parser);
6852 } else if (tagName.equals("permission-trees")) {
6853 readPermissionsLP(mPermissionTrees, parser);
6854 } else if (tagName.equals("shared-user")) {
6855 readSharedUserLP(parser);
6856 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006857 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 } else if (tagName.equals("preferred-activities")) {
6859 readPreferredActivitiesLP(parser);
6860 } else if(tagName.equals("updated-package")) {
6861 readDisabledSysPackageLP(parser);
6862 } else {
6863 Log.w(TAG, "Unknown element under <packages>: "
6864 + parser.getName());
6865 XmlUtils.skipCurrentTag(parser);
6866 }
6867 }
6868
6869 str.close();
6870
6871 } catch(XmlPullParserException e) {
6872 mReadMessages.append("Error reading: " + e.toString());
6873 Log.e(TAG, "Error reading package manager settings", e);
6874
6875 } catch(java.io.IOException e) {
6876 mReadMessages.append("Error reading: " + e.toString());
6877 Log.e(TAG, "Error reading package manager settings", e);
6878
6879 }
6880
6881 int N = mPendingPackages.size();
6882 for (int i=0; i<N; i++) {
6883 final PendingPackage pp = mPendingPackages.get(i);
6884 Object idObj = getUserIdLP(pp.sharedId);
6885 if (idObj != null && idObj instanceof SharedUserSetting) {
6886 PackageSetting p = getPackageLP(pp.name,
6887 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006888 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006889 if (p == null) {
6890 Log.w(TAG, "Unable to create application package for "
6891 + pp.name);
6892 continue;
6893 }
6894 p.copyFrom(pp);
6895 } else if (idObj != null) {
6896 String msg = "Bad package setting: package " + pp.name
6897 + " has shared uid " + pp.sharedId
6898 + " that is not a shared uid\n";
6899 mReadMessages.append(msg);
6900 Log.e(TAG, msg);
6901 } else {
6902 String msg = "Bad package setting: package " + pp.name
6903 + " has shared uid " + pp.sharedId
6904 + " that is not defined\n";
6905 mReadMessages.append(msg);
6906 Log.e(TAG, msg);
6907 }
6908 }
6909 mPendingPackages.clear();
6910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006911 mReadMessages.append("Read completed successfully: "
6912 + mPackages.size() + " packages, "
6913 + mSharedUsers.size() + " shared uids\n");
6914
6915 return true;
6916 }
6917
6918 private int readInt(XmlPullParser parser, String ns, String name,
6919 int defValue) {
6920 String v = parser.getAttributeValue(ns, name);
6921 try {
6922 if (v == null) {
6923 return defValue;
6924 }
6925 return Integer.parseInt(v);
6926 } catch (NumberFormatException e) {
6927 reportSettingsProblem(Log.WARN,
6928 "Error in package manager settings: attribute " +
6929 name + " has bad integer value " + v + " at "
6930 + parser.getPositionDescription());
6931 }
6932 return defValue;
6933 }
6934
6935 private void readPermissionsLP(HashMap<String, BasePermission> out,
6936 XmlPullParser parser)
6937 throws IOException, XmlPullParserException {
6938 int outerDepth = parser.getDepth();
6939 int type;
6940 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6941 && (type != XmlPullParser.END_TAG
6942 || parser.getDepth() > outerDepth)) {
6943 if (type == XmlPullParser.END_TAG
6944 || type == XmlPullParser.TEXT) {
6945 continue;
6946 }
6947
6948 String tagName = parser.getName();
6949 if (tagName.equals("item")) {
6950 String name = parser.getAttributeValue(null, "name");
6951 String sourcePackage = parser.getAttributeValue(null, "package");
6952 String ptype = parser.getAttributeValue(null, "type");
6953 if (name != null && sourcePackage != null) {
6954 boolean dynamic = "dynamic".equals(ptype);
6955 BasePermission bp = new BasePermission(name, sourcePackage,
6956 dynamic
6957 ? BasePermission.TYPE_DYNAMIC
6958 : BasePermission.TYPE_NORMAL);
6959 if (dynamic) {
6960 PermissionInfo pi = new PermissionInfo();
6961 pi.packageName = sourcePackage.intern();
6962 pi.name = name.intern();
6963 pi.icon = readInt(parser, null, "icon", 0);
6964 pi.nonLocalizedLabel = parser.getAttributeValue(
6965 null, "label");
6966 pi.protectionLevel = readInt(parser, null, "protection",
6967 PermissionInfo.PROTECTION_NORMAL);
6968 bp.pendingInfo = pi;
6969 }
6970 out.put(bp.name, bp);
6971 } else {
6972 reportSettingsProblem(Log.WARN,
6973 "Error in package manager settings: permissions has"
6974 + " no name at " + parser.getPositionDescription());
6975 }
6976 } else {
6977 reportSettingsProblem(Log.WARN,
6978 "Unknown element reading permissions: "
6979 + parser.getName() + " at "
6980 + parser.getPositionDescription());
6981 }
6982 XmlUtils.skipCurrentTag(parser);
6983 }
6984 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006986 private void readDisabledSysPackageLP(XmlPullParser parser)
6987 throws XmlPullParserException, IOException {
6988 String name = parser.getAttributeValue(null, "name");
6989 String codePathStr = parser.getAttributeValue(null, "codePath");
6990 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6991 if(resourcePathStr == null) {
6992 resourcePathStr = codePathStr;
6993 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006994 String version = parser.getAttributeValue(null, "version");
6995 int versionCode = 0;
6996 if (version != null) {
6997 try {
6998 versionCode = Integer.parseInt(version);
6999 } catch (NumberFormatException e) {
7000 }
7001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007003 int pkgFlags = 0;
7004 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007005 PackageSetting ps = new PackageSetting(name,
7006 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007007 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007008 String timeStampStr = parser.getAttributeValue(null, "ts");
7009 if (timeStampStr != null) {
7010 try {
7011 long timeStamp = Long.parseLong(timeStampStr);
7012 ps.setTimeStamp(timeStamp, timeStampStr);
7013 } catch (NumberFormatException e) {
7014 }
7015 }
7016 String idStr = parser.getAttributeValue(null, "userId");
7017 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
7018 if(ps.userId <= 0) {
7019 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7020 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7021 }
7022 int outerDepth = parser.getDepth();
7023 int type;
7024 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7025 && (type != XmlPullParser.END_TAG
7026 || parser.getDepth() > outerDepth)) {
7027 if (type == XmlPullParser.END_TAG
7028 || type == XmlPullParser.TEXT) {
7029 continue;
7030 }
7031
7032 String tagName = parser.getName();
7033 if (tagName.equals("perms")) {
7034 readGrantedPermissionsLP(parser,
7035 ps.grantedPermissions);
7036 } else {
7037 reportSettingsProblem(Log.WARN,
7038 "Unknown element under <updated-package>: "
7039 + parser.getName());
7040 XmlUtils.skipCurrentTag(parser);
7041 }
7042 }
7043 mDisabledSysPackages.put(name, ps);
7044 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007046 private void readPackageLP(XmlPullParser parser)
7047 throws XmlPullParserException, IOException {
7048 String name = null;
7049 String idStr = null;
7050 String sharedIdStr = null;
7051 String codePathStr = null;
7052 String resourcePathStr = null;
7053 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007054 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 int pkgFlags = 0;
7056 String timeStampStr;
7057 long timeStamp = 0;
7058 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007059 String version = null;
7060 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 try {
7062 name = parser.getAttributeValue(null, "name");
7063 idStr = parser.getAttributeValue(null, "userId");
7064 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7065 codePathStr = parser.getAttributeValue(null, "codePath");
7066 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007067 version = parser.getAttributeValue(null, "version");
7068 if (version != null) {
7069 try {
7070 versionCode = Integer.parseInt(version);
7071 } catch (NumberFormatException e) {
7072 }
7073 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007074 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007075
7076 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007078 try {
7079 pkgFlags = Integer.parseInt(systemStr);
7080 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 }
7082 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007083 // For backward compatibility
7084 systemStr = parser.getAttributeValue(null, "system");
7085 if (systemStr != null) {
7086 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
7087 } else {
7088 // Old settings that don't specify system... just treat
7089 // them as system, good enough.
7090 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 }
7093 timeStampStr = parser.getAttributeValue(null, "ts");
7094 if (timeStampStr != null) {
7095 try {
7096 timeStamp = Long.parseLong(timeStampStr);
7097 } catch (NumberFormatException e) {
7098 }
7099 }
7100 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7101 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7102 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7103 if (resourcePathStr == null) {
7104 resourcePathStr = codePathStr;
7105 }
7106 if (name == null) {
7107 reportSettingsProblem(Log.WARN,
7108 "Error in package manager settings: <package> has no name at "
7109 + parser.getPositionDescription());
7110 } else if (codePathStr == null) {
7111 reportSettingsProblem(Log.WARN,
7112 "Error in package manager settings: <package> has no codePath at "
7113 + parser.getPositionDescription());
7114 } else if (userId > 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007115 packageSetting = addPackageLP(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 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7118 + ": userId=" + userId + " pkg=" + packageSetting);
7119 if (packageSetting == null) {
7120 reportSettingsProblem(Log.ERROR,
7121 "Failure adding uid " + userId
7122 + " while parsing settings at "
7123 + parser.getPositionDescription());
7124 } else {
7125 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7126 }
7127 } else if (sharedIdStr != null) {
7128 userId = sharedIdStr != null
7129 ? Integer.parseInt(sharedIdStr) : 0;
7130 if (userId > 0) {
7131 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007132 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007133 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7134 mPendingPackages.add((PendingPackage) packageSetting);
7135 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7136 + ": sharedUserId=" + userId + " pkg="
7137 + packageSetting);
7138 } else {
7139 reportSettingsProblem(Log.WARN,
7140 "Error in package manager settings: package "
7141 + name + " has bad sharedId " + sharedIdStr
7142 + " at " + parser.getPositionDescription());
7143 }
7144 } else {
7145 reportSettingsProblem(Log.WARN,
7146 "Error in package manager settings: package "
7147 + name + " has bad userId " + idStr + " at "
7148 + parser.getPositionDescription());
7149 }
7150 } catch (NumberFormatException e) {
7151 reportSettingsProblem(Log.WARN,
7152 "Error in package manager settings: package "
7153 + name + " has bad userId " + idStr + " at "
7154 + parser.getPositionDescription());
7155 }
7156 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02007157 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007158 final String enabledStr = parser.getAttributeValue(null, "enabled");
7159 if (enabledStr != null) {
7160 if (enabledStr.equalsIgnoreCase("true")) {
7161 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7162 } else if (enabledStr.equalsIgnoreCase("false")) {
7163 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7164 } else if (enabledStr.equalsIgnoreCase("default")) {
7165 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7166 } else {
7167 reportSettingsProblem(Log.WARN,
7168 "Error in package manager settings: package "
7169 + name + " has bad enabled value: " + idStr
7170 + " at " + parser.getPositionDescription());
7171 }
7172 } else {
7173 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7174 }
7175 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7176 if (installStatusStr != null) {
7177 if (installStatusStr.equalsIgnoreCase("false")) {
7178 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7179 } else {
7180 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7181 }
7182 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 int outerDepth = parser.getDepth();
7185 int type;
7186 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7187 && (type != XmlPullParser.END_TAG
7188 || parser.getDepth() > outerDepth)) {
7189 if (type == XmlPullParser.END_TAG
7190 || type == XmlPullParser.TEXT) {
7191 continue;
7192 }
7193
7194 String tagName = parser.getName();
7195 if (tagName.equals("disabled-components")) {
7196 readDisabledComponentsLP(packageSetting, parser);
7197 } else if (tagName.equals("enabled-components")) {
7198 readEnabledComponentsLP(packageSetting, parser);
7199 } else if (tagName.equals("sigs")) {
7200 packageSetting.signatures.readXml(parser, mPastSignatures);
7201 } else if (tagName.equals("perms")) {
7202 readGrantedPermissionsLP(parser,
7203 packageSetting.loadedPermissions);
7204 packageSetting.permissionsFixed = true;
7205 } else {
7206 reportSettingsProblem(Log.WARN,
7207 "Unknown element under <package>: "
7208 + parser.getName());
7209 XmlUtils.skipCurrentTag(parser);
7210 }
7211 }
7212 } else {
7213 XmlUtils.skipCurrentTag(parser);
7214 }
7215 }
7216
7217 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7218 XmlPullParser parser)
7219 throws IOException, XmlPullParserException {
7220 int outerDepth = parser.getDepth();
7221 int type;
7222 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7223 && (type != XmlPullParser.END_TAG
7224 || parser.getDepth() > outerDepth)) {
7225 if (type == XmlPullParser.END_TAG
7226 || type == XmlPullParser.TEXT) {
7227 continue;
7228 }
7229
7230 String tagName = parser.getName();
7231 if (tagName.equals("item")) {
7232 String name = parser.getAttributeValue(null, "name");
7233 if (name != null) {
7234 packageSetting.disabledComponents.add(name.intern());
7235 } else {
7236 reportSettingsProblem(Log.WARN,
7237 "Error in package manager settings: <disabled-components> has"
7238 + " no name at " + parser.getPositionDescription());
7239 }
7240 } else {
7241 reportSettingsProblem(Log.WARN,
7242 "Unknown element under <disabled-components>: "
7243 + parser.getName());
7244 }
7245 XmlUtils.skipCurrentTag(parser);
7246 }
7247 }
7248
7249 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
7250 XmlPullParser parser)
7251 throws IOException, XmlPullParserException {
7252 int outerDepth = parser.getDepth();
7253 int type;
7254 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7255 && (type != XmlPullParser.END_TAG
7256 || parser.getDepth() > outerDepth)) {
7257 if (type == XmlPullParser.END_TAG
7258 || type == XmlPullParser.TEXT) {
7259 continue;
7260 }
7261
7262 String tagName = parser.getName();
7263 if (tagName.equals("item")) {
7264 String name = parser.getAttributeValue(null, "name");
7265 if (name != null) {
7266 packageSetting.enabledComponents.add(name.intern());
7267 } else {
7268 reportSettingsProblem(Log.WARN,
7269 "Error in package manager settings: <enabled-components> has"
7270 + " no name at " + parser.getPositionDescription());
7271 }
7272 } else {
7273 reportSettingsProblem(Log.WARN,
7274 "Unknown element under <enabled-components>: "
7275 + parser.getName());
7276 }
7277 XmlUtils.skipCurrentTag(parser);
7278 }
7279 }
7280
7281 private void readSharedUserLP(XmlPullParser parser)
7282 throws XmlPullParserException, IOException {
7283 String name = null;
7284 String idStr = null;
7285 int pkgFlags = 0;
7286 SharedUserSetting su = null;
7287 try {
7288 name = parser.getAttributeValue(null, "name");
7289 idStr = parser.getAttributeValue(null, "userId");
7290 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7291 if ("true".equals(parser.getAttributeValue(null, "system"))) {
7292 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7293 }
7294 if (name == null) {
7295 reportSettingsProblem(Log.WARN,
7296 "Error in package manager settings: <shared-user> has no name at "
7297 + parser.getPositionDescription());
7298 } else if (userId == 0) {
7299 reportSettingsProblem(Log.WARN,
7300 "Error in package manager settings: shared-user "
7301 + name + " has bad userId " + idStr + " at "
7302 + parser.getPositionDescription());
7303 } else {
7304 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
7305 reportSettingsProblem(Log.ERROR,
7306 "Occurred while parsing settings at "
7307 + parser.getPositionDescription());
7308 }
7309 }
7310 } catch (NumberFormatException e) {
7311 reportSettingsProblem(Log.WARN,
7312 "Error in package manager settings: package "
7313 + name + " has bad userId " + idStr + " at "
7314 + parser.getPositionDescription());
7315 };
7316
7317 if (su != null) {
7318 int outerDepth = parser.getDepth();
7319 int type;
7320 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7321 && (type != XmlPullParser.END_TAG
7322 || parser.getDepth() > outerDepth)) {
7323 if (type == XmlPullParser.END_TAG
7324 || type == XmlPullParser.TEXT) {
7325 continue;
7326 }
7327
7328 String tagName = parser.getName();
7329 if (tagName.equals("sigs")) {
7330 su.signatures.readXml(parser, mPastSignatures);
7331 } else if (tagName.equals("perms")) {
7332 readGrantedPermissionsLP(parser, su.loadedPermissions);
7333 } else {
7334 reportSettingsProblem(Log.WARN,
7335 "Unknown element under <shared-user>: "
7336 + parser.getName());
7337 XmlUtils.skipCurrentTag(parser);
7338 }
7339 }
7340
7341 } else {
7342 XmlUtils.skipCurrentTag(parser);
7343 }
7344 }
7345
7346 private void readGrantedPermissionsLP(XmlPullParser parser,
7347 HashSet<String> outPerms) throws IOException, XmlPullParserException {
7348 int outerDepth = parser.getDepth();
7349 int type;
7350 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7351 && (type != XmlPullParser.END_TAG
7352 || parser.getDepth() > outerDepth)) {
7353 if (type == XmlPullParser.END_TAG
7354 || type == XmlPullParser.TEXT) {
7355 continue;
7356 }
7357
7358 String tagName = parser.getName();
7359 if (tagName.equals("item")) {
7360 String name = parser.getAttributeValue(null, "name");
7361 if (name != null) {
7362 outPerms.add(name.intern());
7363 } else {
7364 reportSettingsProblem(Log.WARN,
7365 "Error in package manager settings: <perms> has"
7366 + " no name at " + parser.getPositionDescription());
7367 }
7368 } else {
7369 reportSettingsProblem(Log.WARN,
7370 "Unknown element under <perms>: "
7371 + parser.getName());
7372 }
7373 XmlUtils.skipCurrentTag(parser);
7374 }
7375 }
7376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007377 private void readPreferredActivitiesLP(XmlPullParser parser)
7378 throws XmlPullParserException, IOException {
7379 int outerDepth = parser.getDepth();
7380 int type;
7381 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7382 && (type != XmlPullParser.END_TAG
7383 || parser.getDepth() > outerDepth)) {
7384 if (type == XmlPullParser.END_TAG
7385 || type == XmlPullParser.TEXT) {
7386 continue;
7387 }
7388
7389 String tagName = parser.getName();
7390 if (tagName.equals("item")) {
7391 PreferredActivity pa = new PreferredActivity(parser);
7392 if (pa.mParseError == null) {
7393 mPreferredActivities.addFilter(pa);
7394 } else {
7395 reportSettingsProblem(Log.WARN,
7396 "Error in package manager settings: <preferred-activity> "
7397 + pa.mParseError + " at "
7398 + parser.getPositionDescription());
7399 }
7400 } else {
7401 reportSettingsProblem(Log.WARN,
7402 "Unknown element under <preferred-activities>: "
7403 + parser.getName());
7404 XmlUtils.skipCurrentTag(parser);
7405 }
7406 }
7407 }
7408
7409 // Returns -1 if we could not find an available UserId to assign
7410 private int newUserIdLP(Object obj) {
7411 // Let's be stupidly inefficient for now...
7412 final int N = mUserIds.size();
7413 for (int i=0; i<N; i++) {
7414 if (mUserIds.get(i) == null) {
7415 mUserIds.set(i, obj);
7416 return FIRST_APPLICATION_UID + i;
7417 }
7418 }
7419
7420 // None left?
7421 if (N >= MAX_APPLICATION_UIDS) {
7422 return -1;
7423 }
7424
7425 mUserIds.add(obj);
7426 return FIRST_APPLICATION_UID + N;
7427 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 public PackageSetting getDisabledSystemPkg(String name) {
7430 synchronized(mPackages) {
7431 PackageSetting ps = mDisabledSysPackages.get(name);
7432 return ps;
7433 }
7434 }
7435
7436 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7437 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7438 if (Config.LOGV) {
7439 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7440 + " componentName = " + componentInfo.name);
7441 Log.v(TAG, "enabledComponents: "
7442 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7443 Log.v(TAG, "disabledComponents: "
7444 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7445 }
7446 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7447 || ((componentInfo.enabled
7448 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7449 || (componentInfo.applicationInfo.enabled
7450 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7451 && !packageSettings.disabledComponents.contains(componentInfo.name))
7452 || packageSettings.enabledComponents.contains(componentInfo.name));
7453 }
7454 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007455
7456 // ------- apps on sdcard specific code -------
7457 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08007458 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08007459 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007460 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007461
7462 private MountService getMountService() {
7463 return (MountService) ServiceManager.getService("mount");
7464 }
7465
7466 private String createSdDir(File tmpPackageFile, String pkgName) {
7467 // Create mount point via MountService
7468 MountService mountService = getMountService();
7469 long len = tmpPackageFile.length();
7470 int mbLen = (int) (len/(1024*1024));
7471 if ((len - (mbLen * 1024 * 1024)) > 0) {
7472 mbLen++;
7473 }
7474 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
7475 String cachePath = null;
7476 // Remove any pending destroy messages
7477 mHandler.removeMessages(DESTROY_SD_CONTAINER, pkgName);
Oscar Montemayord02546b2010-01-14 16:38:40 -08007478 String sdEncKey;
7479 try {
7480 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
7481 if (sdEncKey == null) {
7482 sdEncKey = SystemKeyStore.getInstance().
7483 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
7484 if (sdEncKey == null) {
7485 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
7486 return null;
7487 }
7488 }
7489 } catch (NoSuchAlgorithmException nsae) {
7490 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
7491 return null;
7492 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007493 try {
7494 cachePath = mountService.createSecureContainer(pkgName,
7495 mbLen,
Oscar Montemayord02546b2010-01-14 16:38:40 -08007496 "vfat", sdEncKey, Process.SYSTEM_UID);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007497 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
7498 return cachePath;
7499 } catch(IllegalStateException e) {
7500 Log.e(TAG, "Failed to create storage on sdcard with exception: " + e);
7501 }
7502 // TODO just fail here and let the user delete later on.
7503 try {
7504 mountService.destroySecureContainer(pkgName);
7505 if (DEBUG_SD_INSTALL) Log.i(TAG, "Destroying cache for " + pkgName + ", cachePath =" + cachePath);
7506 } catch(IllegalStateException e) {
7507 Log.e(TAG, "Failed to destroy existing cache: " + e);
7508 return null;
7509 }
7510 try {
7511 cachePath = mountService.createSecureContainer(pkgName,
7512 mbLen,
Oscar Montemayord02546b2010-01-14 16:38:40 -08007513 "vfat", sdEncKey, Process.SYSTEM_UID);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007514 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install again " + pkgName + ", cachePath =" + cachePath);
7515 return cachePath;
7516 } catch(IllegalStateException e) {
7517 Log.e(TAG, "Failed to create storage on sdcard with exception: " + e);
7518 return null;
7519 }
7520 }
7521
7522 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08007523 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
7524 if (sdEncKey == null) {
7525 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
7526 return null;
7527 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007528 try {
Oscar Montemayord02546b2010-01-14 16:38:40 -08007529 return getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007530 } catch (IllegalStateException e) {
7531 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " exception : " + e);
7532 }
7533 return null;
7534 }
7535
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007536 private boolean unMountSdDir(String pkgName) {
7537 // STOPSHIP unmount directory
7538 return true;
7539 }
7540
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007541 private String getSdDir(String pkgName) {
7542 String cachePath = null;
7543 try {
7544 cachePath = getMountService().getSecureContainerPath(pkgName);
7545 } catch (IllegalStateException e) {
7546 Log.e(TAG, "Failed to retrieve secure container path for pkg : " + pkgName + " with exception " + e);
7547 }
7548 return cachePath;
7549 }
7550
7551 private boolean finalizeSdDir(String pkgName) {
7552 try {
7553 getMountService().finalizeSecureContainer(pkgName);
7554 return true;
7555 } catch (IllegalStateException e) {
7556 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
7557 return false;
7558 }
7559 }
7560
7561 private boolean destroySdDir(String pkgName) {
7562 try {
7563 if (mHandler.hasMessages(DESTROY_SD_CONTAINER, pkgName)) {
7564 // Don't have to send message again
7565 mHandler.removeMessages(DESTROY_SD_CONTAINER, pkgName);
7566 }
7567 // We need to destroy right away
7568 getMountService().destroySecureContainer(pkgName);
7569 return true;
7570 } catch (IllegalStateException e) {
7571 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
7572 return false;
7573 }
7574 }
7575
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007576 private String[] getSecureContainerList() {
7577 try {
7578 return getMountService().getSecureContainerList();
7579 } catch (IllegalStateException e) {
7580 Log.i(TAG, "Failed to getSecureContainerList");
7581 }
7582 return null;
7583 }
7584
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007585 private void sendDelayedDestroySdDir(String pkgName) {
7586 if (mHandler.hasMessages(DESTROY_SD_CONTAINER, pkgName)) {
7587 // Don't have to send message again
7588 return;
7589 }
7590 Message msg = mHandler.obtainMessage(DESTROY_SD_CONTAINER, pkgName);
7591 mHandler.sendMessageDelayed(msg, DESTROY_SD_CONTAINER_DELAY);
7592 }
7593
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007594 public void updateExternalMediaStatus(final boolean mediaStatus) {
7595 if (mediaStatus == mMediaMounted) {
7596 return;
7597 }
7598 mMediaMounted = mediaStatus;
7599 // Queue up an async operation since the package installation may take a little while.
7600 mHandler.post(new Runnable() {
7601 public void run() {
7602 mHandler.removeCallbacks(this);
7603 final String list[] = getSecureContainerList();
7604 if (list == null || list.length == 0) {
7605 return;
7606 }
7607 for (int i = 0; i < list.length; i++) {
7608 String mountPkg = list[i];
7609 // TODO compare with default package
7610 synchronized (mPackages) {
7611 PackageSetting ps = mSettings.mPackages.get(mountPkg);
7612 if (ps != null && (ps.pkgFlags & ApplicationInfo.FLAG_ON_SDCARD) != 0) {
7613 if (mediaStatus) {
7614 String pkgPath = getSdDir(mountPkg);
7615 if (pkgPath == null) {
7616 continue;
7617 }
7618 pkgPath = ps.codePathString;
7619 int parseFlags = PackageParser.PARSE_CHATTY |
7620 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
7621 PackageParser pp = new PackageParser(pkgPath);
7622 pp.setSeparateProcesses(mSeparateProcesses);
7623 final PackageParser.Package pkg = pp.parsePackage(new File(pkgPath),
7624 null, mMetrics, parseFlags);
7625 if (pkg == null) {
7626 Log.w(TAG, "Failed to install package : " + mountPkg + " from sd card");
7627 continue;
7628 }
7629 int scanMode = SCAN_MONITOR;
7630 // Scan the package
7631 if (scanPackageLI(pkg, parseFlags, scanMode) != null) {
7632 // Grant permissions
7633 grantPermissionsLP(pkg, false);
7634 // Persist settings
7635 mSettings.writeLP();
7636 } else {
7637 Log.i(TAG, "Failed to install package: " + mountPkg + " from sdcard");
7638 }
7639 } else {
7640 // Delete package
7641 PackageRemovedInfo outInfo = new PackageRemovedInfo();
7642 boolean res = deletePackageLI(mountPkg, false, PackageManager.DONT_DELETE_DATA, outInfo);
7643 if (!res) {
7644 Log.e(TAG, "Failed to delete pkg from sdcard : " + mountPkg);
7645 }
7646 }
7647 }
7648 }
7649 }
7650 }
7651 });
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653}