blob: 65dc2667e782f7037908a68fa7dea38c77a42eaf [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) {
4756 // Post a delayed destroy on the container since there might
4757 // be active processes holding open file handles to package
4758 // resources which will get killed by the process killer when
4759 // destroying the container. This might even kill the current
4760 // process and crash the system. Delay the destroy a bit so
4761 // that the active processes get to handle the uninstall broadcasts.
4762 sendDelayedDestroySdDir(packageName);
4763 }
4764 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004767 public void clearApplicationUserData(final String packageName,
4768 final IPackageDataObserver observer) {
4769 mContext.enforceCallingOrSelfPermission(
4770 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4771 // Queue up an async operation since the package deletion may take a little while.
4772 mHandler.post(new Runnable() {
4773 public void run() {
4774 mHandler.removeCallbacks(this);
4775 final boolean succeeded;
4776 synchronized (mInstallLock) {
4777 succeeded = clearApplicationUserDataLI(packageName);
4778 }
4779 if (succeeded) {
4780 // invoke DeviceStorageMonitor's update method to clear any notifications
4781 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4782 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4783 if (dsm != null) {
4784 dsm.updateMemory();
4785 }
4786 }
4787 if(observer != null) {
4788 try {
4789 observer.onRemoveCompleted(packageName, succeeded);
4790 } catch (RemoteException e) {
4791 Log.i(TAG, "Observer no longer exists.");
4792 }
4793 } //end if observer
4794 } //end run
4795 });
4796 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004798 private boolean clearApplicationUserDataLI(String packageName) {
4799 if (packageName == null) {
4800 Log.w(TAG, "Attempt to delete null packageName.");
4801 return false;
4802 }
4803 PackageParser.Package p;
4804 boolean dataOnly = false;
4805 synchronized (mPackages) {
4806 p = mPackages.get(packageName);
4807 if(p == null) {
4808 dataOnly = true;
4809 PackageSetting ps = mSettings.mPackages.get(packageName);
4810 if((ps == null) || (ps.pkg == null)) {
4811 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4812 return false;
4813 }
4814 p = ps.pkg;
4815 }
4816 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004817 boolean useEncryptedFSDir = false;
4818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004819 if(!dataOnly) {
4820 //need to check this only for fully installed applications
4821 if (p == null) {
4822 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4823 return false;
4824 }
4825 final ApplicationInfo applicationInfo = p.applicationInfo;
4826 if (applicationInfo == null) {
4827 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4828 return false;
4829 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004830 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004831 }
4832 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004833 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004834 if (retCode < 0) {
4835 Log.w(TAG, "Couldn't remove cache files for package: "
4836 + packageName);
4837 return false;
4838 }
4839 }
4840 return true;
4841 }
4842
4843 public void deleteApplicationCacheFiles(final String packageName,
4844 final IPackageDataObserver observer) {
4845 mContext.enforceCallingOrSelfPermission(
4846 android.Manifest.permission.DELETE_CACHE_FILES, null);
4847 // Queue up an async operation since the package deletion may take a little while.
4848 mHandler.post(new Runnable() {
4849 public void run() {
4850 mHandler.removeCallbacks(this);
4851 final boolean succeded;
4852 synchronized (mInstallLock) {
4853 succeded = deleteApplicationCacheFilesLI(packageName);
4854 }
4855 if(observer != null) {
4856 try {
4857 observer.onRemoveCompleted(packageName, succeded);
4858 } catch (RemoteException e) {
4859 Log.i(TAG, "Observer no longer exists.");
4860 }
4861 } //end if observer
4862 } //end run
4863 });
4864 }
4865
4866 private boolean deleteApplicationCacheFilesLI(String packageName) {
4867 if (packageName == null) {
4868 Log.w(TAG, "Attempt to delete null packageName.");
4869 return false;
4870 }
4871 PackageParser.Package p;
4872 synchronized (mPackages) {
4873 p = mPackages.get(packageName);
4874 }
4875 if (p == null) {
4876 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4877 return false;
4878 }
4879 final ApplicationInfo applicationInfo = p.applicationInfo;
4880 if (applicationInfo == null) {
4881 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4882 return false;
4883 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004884 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004885 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004886 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004887 if (retCode < 0) {
4888 Log.w(TAG, "Couldn't remove cache files for package: "
4889 + packageName);
4890 return false;
4891 }
4892 }
4893 return true;
4894 }
4895
4896 public void getPackageSizeInfo(final String packageName,
4897 final IPackageStatsObserver observer) {
4898 mContext.enforceCallingOrSelfPermission(
4899 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4900 // Queue up an async operation since the package deletion may take a little while.
4901 mHandler.post(new Runnable() {
4902 public void run() {
4903 mHandler.removeCallbacks(this);
4904 PackageStats lStats = new PackageStats(packageName);
4905 final boolean succeded;
4906 synchronized (mInstallLock) {
4907 succeded = getPackageSizeInfoLI(packageName, lStats);
4908 }
4909 if(observer != null) {
4910 try {
4911 observer.onGetStatsCompleted(lStats, succeded);
4912 } catch (RemoteException e) {
4913 Log.i(TAG, "Observer no longer exists.");
4914 }
4915 } //end if observer
4916 } //end run
4917 });
4918 }
4919
4920 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4921 if (packageName == null) {
4922 Log.w(TAG, "Attempt to get size of null packageName.");
4923 return false;
4924 }
4925 PackageParser.Package p;
4926 boolean dataOnly = false;
4927 synchronized (mPackages) {
4928 p = mPackages.get(packageName);
4929 if(p == null) {
4930 dataOnly = true;
4931 PackageSetting ps = mSettings.mPackages.get(packageName);
4932 if((ps == null) || (ps.pkg == null)) {
4933 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4934 return false;
4935 }
4936 p = ps.pkg;
4937 }
4938 }
4939 String publicSrcDir = null;
4940 if(!dataOnly) {
4941 final ApplicationInfo applicationInfo = p.applicationInfo;
4942 if (applicationInfo == null) {
4943 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4944 return false;
4945 }
4946 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4947 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004948 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004949 if (mInstaller != null) {
4950 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08004951 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 if (res < 0) {
4953 return false;
4954 } else {
4955 return true;
4956 }
4957 }
4958 return true;
4959 }
4960
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 public void addPackageToPreferred(String packageName) {
4963 mContext.enforceCallingOrSelfPermission(
4964 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004965 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004966 }
4967
4968 public void removePackageFromPreferred(String packageName) {
4969 mContext.enforceCallingOrSelfPermission(
4970 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004971 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 }
4973
4974 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08004975 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 }
4977
4978 public void addPreferredActivity(IntentFilter filter, int match,
4979 ComponentName[] set, ComponentName activity) {
4980 mContext.enforceCallingOrSelfPermission(
4981 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4982
4983 synchronized (mPackages) {
4984 Log.i(TAG, "Adding preferred activity " + activity + ":");
4985 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4986 mSettings.mPreferredActivities.addFilter(
4987 new PreferredActivity(filter, match, set, activity));
4988 mSettings.writeLP();
4989 }
4990 }
4991
Satish Sampath8dbe6122009-06-02 23:35:54 +01004992 public void replacePreferredActivity(IntentFilter filter, int match,
4993 ComponentName[] set, ComponentName activity) {
4994 mContext.enforceCallingOrSelfPermission(
4995 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4996 if (filter.countActions() != 1) {
4997 throw new IllegalArgumentException(
4998 "replacePreferredActivity expects filter to have only 1 action.");
4999 }
5000 if (filter.countCategories() != 1) {
5001 throw new IllegalArgumentException(
5002 "replacePreferredActivity expects filter to have only 1 category.");
5003 }
5004 if (filter.countDataAuthorities() != 0
5005 || filter.countDataPaths() != 0
5006 || filter.countDataSchemes() != 0
5007 || filter.countDataTypes() != 0) {
5008 throw new IllegalArgumentException(
5009 "replacePreferredActivity expects filter to have no data authorities, " +
5010 "paths, schemes or types.");
5011 }
5012 synchronized (mPackages) {
5013 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5014 String action = filter.getAction(0);
5015 String category = filter.getCategory(0);
5016 while (it.hasNext()) {
5017 PreferredActivity pa = it.next();
5018 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5019 it.remove();
5020 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5021 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5022 }
5023 }
5024 addPreferredActivity(filter, match, set, activity);
5025 }
5026 }
5027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 public void clearPackagePreferredActivities(String packageName) {
5029 mContext.enforceCallingOrSelfPermission(
5030 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5031
5032 synchronized (mPackages) {
5033 if (clearPackagePreferredActivitiesLP(packageName)) {
5034 mSettings.writeLP();
5035 }
5036 }
5037 }
5038
5039 boolean clearPackagePreferredActivitiesLP(String packageName) {
5040 boolean changed = false;
5041 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5042 while (it.hasNext()) {
5043 PreferredActivity pa = it.next();
5044 if (pa.mActivity.getPackageName().equals(packageName)) {
5045 it.remove();
5046 changed = true;
5047 }
5048 }
5049 return changed;
5050 }
5051
5052 public int getPreferredActivities(List<IntentFilter> outFilters,
5053 List<ComponentName> outActivities, String packageName) {
5054
5055 int num = 0;
5056 synchronized (mPackages) {
5057 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5058 while (it.hasNext()) {
5059 PreferredActivity pa = it.next();
5060 if (packageName == null
5061 || pa.mActivity.getPackageName().equals(packageName)) {
5062 if (outFilters != null) {
5063 outFilters.add(new IntentFilter(pa));
5064 }
5065 if (outActivities != null) {
5066 outActivities.add(pa.mActivity);
5067 }
5068 }
5069 }
5070 }
5071
5072 return num;
5073 }
5074
5075 public void setApplicationEnabledSetting(String appPackageName,
5076 int newState, int flags) {
5077 setEnabledSetting(appPackageName, null, newState, flags);
5078 }
5079
5080 public void setComponentEnabledSetting(ComponentName componentName,
5081 int newState, int flags) {
5082 setEnabledSetting(componentName.getPackageName(),
5083 componentName.getClassName(), newState, flags);
5084 }
5085
5086 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005087 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5089 || newState == COMPONENT_ENABLED_STATE_ENABLED
5090 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5091 throw new IllegalArgumentException("Invalid new component state: "
5092 + newState);
5093 }
5094 PackageSetting pkgSetting;
5095 final int uid = Binder.getCallingUid();
5096 final int permission = mContext.checkCallingPermission(
5097 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5098 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005099 boolean sendNow = false;
5100 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005101 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005103 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005105 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005107 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005108 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005109 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005110 }
5111 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005112 "Unknown component: " + packageName
5113 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 }
5115 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5116 throw new SecurityException(
5117 "Permission Denial: attempt to change component state from pid="
5118 + Binder.getCallingPid()
5119 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5120 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005121 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005122 // We're dealing with an application/package level state change
5123 pkgSetting.enabled = newState;
5124 } else {
5125 // We're dealing with a component level state change
5126 switch (newState) {
5127 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005128 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 break;
5130 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005131 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005132 break;
5133 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005134 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 break;
5136 default:
5137 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005138 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 }
5140 }
5141 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005142 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005143 components = mPendingBroadcasts.get(packageName);
5144 boolean newPackage = components == null;
5145 if (newPackage) {
5146 components = new ArrayList<String>();
5147 }
5148 if (!components.contains(componentName)) {
5149 components.add(componentName);
5150 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005151 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5152 sendNow = true;
5153 // Purge entry from pending broadcast list if another one exists already
5154 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005155 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005156 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005157 if (newPackage) {
5158 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005159 }
5160 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5161 // Schedule a message
5162 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5163 }
5164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005165 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005167 long callingId = Binder.clearCallingIdentity();
5168 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005169 if (sendNow) {
5170 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005171 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 } finally {
5174 Binder.restoreCallingIdentity(callingId);
5175 }
5176 }
5177
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005178 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005179 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5180 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5181 + " components=" + componentNames);
5182 Bundle extras = new Bundle(4);
5183 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5184 String nameList[] = new String[componentNames.size()];
5185 componentNames.toArray(nameList);
5186 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005187 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5188 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005189 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005190 }
5191
Jacek Surazski65e13172009-04-28 15:26:38 +02005192 public String getInstallerPackageName(String packageName) {
5193 synchronized (mPackages) {
5194 PackageSetting pkg = mSettings.mPackages.get(packageName);
5195 if (pkg == null) {
5196 throw new IllegalArgumentException("Unknown package: " + packageName);
5197 }
5198 return pkg.installerPackageName;
5199 }
5200 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 public int getApplicationEnabledSetting(String appPackageName) {
5203 synchronized (mPackages) {
5204 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5205 if (pkg == null) {
5206 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5207 }
5208 return pkg.enabled;
5209 }
5210 }
5211
5212 public int getComponentEnabledSetting(ComponentName componentName) {
5213 synchronized (mPackages) {
5214 final String packageNameStr = componentName.getPackageName();
5215 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5216 if (pkg == null) {
5217 throw new IllegalArgumentException("Unknown component: " + componentName);
5218 }
5219 final String classNameStr = componentName.getClassName();
5220 return pkg.currentEnabledStateLP(classNameStr);
5221 }
5222 }
5223
5224 public void enterSafeMode() {
5225 if (!mSystemReady) {
5226 mSafeMode = true;
5227 }
5228 }
5229
5230 public void systemReady() {
5231 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005232
5233 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005234 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005235 mContext.getContentResolver(),
5236 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005237 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005238 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005239 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241 }
5242
5243 public boolean isSafeMode() {
5244 return mSafeMode;
5245 }
5246
5247 public boolean hasSystemUidErrors() {
5248 return mHasSystemUidErrors;
5249 }
5250
5251 static String arrayToString(int[] array) {
5252 StringBuffer buf = new StringBuffer(128);
5253 buf.append('[');
5254 if (array != null) {
5255 for (int i=0; i<array.length; i++) {
5256 if (i > 0) buf.append(", ");
5257 buf.append(array[i]);
5258 }
5259 }
5260 buf.append(']');
5261 return buf.toString();
5262 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005264 @Override
5265 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5266 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5267 != PackageManager.PERMISSION_GRANTED) {
5268 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5269 + Binder.getCallingPid()
5270 + ", uid=" + Binder.getCallingUid()
5271 + " without permission "
5272 + android.Manifest.permission.DUMP);
5273 return;
5274 }
5275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005276 synchronized (mPackages) {
5277 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005278 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005279 pw.println(" ");
5280 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005281 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 pw.println(" ");
5283 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005284 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005285 pw.println(" ");
5286 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005287 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 pw.println("Permissions:");
5290 {
5291 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005292 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5293 pw.print(Integer.toHexString(System.identityHashCode(p)));
5294 pw.println("):");
5295 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5296 pw.print(" uid="); pw.print(p.uid);
5297 pw.print(" gids="); pw.print(arrayToString(p.gids));
5298 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299 }
5300 }
5301 pw.println(" ");
5302 pw.println("Packages:");
5303 {
5304 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005305 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5306 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5307 pw.println("):");
5308 pw.print(" userId="); pw.print(ps.userId);
5309 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5310 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5311 pw.print(" pkg="); pw.println(ps.pkg);
5312 pw.print(" codePath="); pw.println(ps.codePathString);
5313 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005315 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005316 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005317 pw.print(" supportsScreens=[");
5318 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005319 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005320 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005321 if (!first) pw.print(", ");
5322 first = false;
5323 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005324 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005325 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005326 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005327 if (!first) pw.print(", ");
5328 first = false;
5329 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005330 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005331 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005332 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005333 if (!first) pw.print(", ");
5334 first = false;
5335 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005337 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005338 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005339 if (!first) pw.print(", ");
5340 first = false;
5341 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005342 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005343 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005344 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
5345 if (!first) pw.print(", ");
5346 first = false;
5347 pw.print("anyDensity");
5348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005350 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005351 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
5352 pw.print(" signatures="); pw.println(ps.signatures);
5353 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
5354 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
5355 pw.print(" installStatus="); pw.print(ps.installStatus);
5356 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 if (ps.disabledComponents.size() > 0) {
5358 pw.println(" disabledComponents:");
5359 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005360 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 }
5362 }
5363 if (ps.enabledComponents.size() > 0) {
5364 pw.println(" enabledComponents:");
5365 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005366 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 }
5368 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005369 if (ps.grantedPermissions.size() > 0) {
5370 pw.println(" grantedPermissions:");
5371 for (String s : ps.grantedPermissions) {
5372 pw.print(" "); pw.println(s);
5373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005375 if (ps.loadedPermissions.size() > 0) {
5376 pw.println(" loadedPermissions:");
5377 for (String s : ps.loadedPermissions) {
5378 pw.print(" "); pw.println(s);
5379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 }
5381 }
5382 }
5383 pw.println(" ");
5384 pw.println("Shared Users:");
5385 {
5386 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005387 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5388 pw.print(Integer.toHexString(System.identityHashCode(su)));
5389 pw.println("):");
5390 pw.print(" userId="); pw.print(su.userId);
5391 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 pw.println(" grantedPermissions:");
5393 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005394 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 }
5396 pw.println(" loadedPermissions:");
5397 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005398 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 }
5400 }
5401 }
5402 pw.println(" ");
5403 pw.println("Settings parse messages:");
5404 pw.println(mSettings.mReadMessages.toString());
5405 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05005406
5407 synchronized (mProviders) {
5408 pw.println(" ");
5409 pw.println("Registered ContentProviders:");
5410 for (PackageParser.Provider p : mProviders.values()) {
5411 pw.println(" ["); pw.println(p.info.authority); pw.println("]: ");
5412 pw.println(p.toString());
5413 }
5414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 }
5416
5417 static final class BasePermission {
5418 final static int TYPE_NORMAL = 0;
5419 final static int TYPE_BUILTIN = 1;
5420 final static int TYPE_DYNAMIC = 2;
5421
5422 final String name;
5423 final String sourcePackage;
5424 final int type;
5425 PackageParser.Permission perm;
5426 PermissionInfo pendingInfo;
5427 int uid;
5428 int[] gids;
5429
5430 BasePermission(String _name, String _sourcePackage, int _type) {
5431 name = _name;
5432 sourcePackage = _sourcePackage;
5433 type = _type;
5434 }
5435 }
5436
5437 static class PackageSignatures {
5438 private Signature[] mSignatures;
5439
5440 PackageSignatures(Signature[] sigs) {
5441 assignSignatures(sigs);
5442 }
5443
5444 PackageSignatures() {
5445 }
5446
5447 void writeXml(XmlSerializer serializer, String tagName,
5448 ArrayList<Signature> pastSignatures) throws IOException {
5449 if (mSignatures == null) {
5450 return;
5451 }
5452 serializer.startTag(null, tagName);
5453 serializer.attribute(null, "count",
5454 Integer.toString(mSignatures.length));
5455 for (int i=0; i<mSignatures.length; i++) {
5456 serializer.startTag(null, "cert");
5457 final Signature sig = mSignatures[i];
5458 final int sigHash = sig.hashCode();
5459 final int numPast = pastSignatures.size();
5460 int j;
5461 for (j=0; j<numPast; j++) {
5462 Signature pastSig = pastSignatures.get(j);
5463 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5464 serializer.attribute(null, "index", Integer.toString(j));
5465 break;
5466 }
5467 }
5468 if (j >= numPast) {
5469 pastSignatures.add(sig);
5470 serializer.attribute(null, "index", Integer.toString(numPast));
5471 serializer.attribute(null, "key", sig.toCharsString());
5472 }
5473 serializer.endTag(null, "cert");
5474 }
5475 serializer.endTag(null, tagName);
5476 }
5477
5478 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5479 throws IOException, XmlPullParserException {
5480 String countStr = parser.getAttributeValue(null, "count");
5481 if (countStr == null) {
5482 reportSettingsProblem(Log.WARN,
5483 "Error in package manager settings: <signatures> has"
5484 + " no count at " + parser.getPositionDescription());
5485 XmlUtils.skipCurrentTag(parser);
5486 }
5487 final int count = Integer.parseInt(countStr);
5488 mSignatures = new Signature[count];
5489 int pos = 0;
5490
5491 int outerDepth = parser.getDepth();
5492 int type;
5493 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5494 && (type != XmlPullParser.END_TAG
5495 || parser.getDepth() > outerDepth)) {
5496 if (type == XmlPullParser.END_TAG
5497 || type == XmlPullParser.TEXT) {
5498 continue;
5499 }
5500
5501 String tagName = parser.getName();
5502 if (tagName.equals("cert")) {
5503 if (pos < count) {
5504 String index = parser.getAttributeValue(null, "index");
5505 if (index != null) {
5506 try {
5507 int idx = Integer.parseInt(index);
5508 String key = parser.getAttributeValue(null, "key");
5509 if (key == null) {
5510 if (idx >= 0 && idx < pastSignatures.size()) {
5511 Signature sig = pastSignatures.get(idx);
5512 if (sig != null) {
5513 mSignatures[pos] = pastSignatures.get(idx);
5514 pos++;
5515 } else {
5516 reportSettingsProblem(Log.WARN,
5517 "Error in package manager settings: <cert> "
5518 + "index " + index + " is not defined at "
5519 + parser.getPositionDescription());
5520 }
5521 } else {
5522 reportSettingsProblem(Log.WARN,
5523 "Error in package manager settings: <cert> "
5524 + "index " + index + " is out of bounds at "
5525 + parser.getPositionDescription());
5526 }
5527 } else {
5528 while (pastSignatures.size() <= idx) {
5529 pastSignatures.add(null);
5530 }
5531 Signature sig = new Signature(key);
5532 pastSignatures.set(idx, sig);
5533 mSignatures[pos] = sig;
5534 pos++;
5535 }
5536 } catch (NumberFormatException e) {
5537 reportSettingsProblem(Log.WARN,
5538 "Error in package manager settings: <cert> "
5539 + "index " + index + " is not a number at "
5540 + parser.getPositionDescription());
5541 }
5542 } else {
5543 reportSettingsProblem(Log.WARN,
5544 "Error in package manager settings: <cert> has"
5545 + " no index at " + parser.getPositionDescription());
5546 }
5547 } else {
5548 reportSettingsProblem(Log.WARN,
5549 "Error in package manager settings: too "
5550 + "many <cert> tags, expected " + count
5551 + " at " + parser.getPositionDescription());
5552 }
5553 } else {
5554 reportSettingsProblem(Log.WARN,
5555 "Unknown element under <cert>: "
5556 + parser.getName());
5557 }
5558 XmlUtils.skipCurrentTag(parser);
5559 }
5560
5561 if (pos < count) {
5562 // Should never happen -- there is an error in the written
5563 // settings -- but if it does we don't want to generate
5564 // a bad array.
5565 Signature[] newSigs = new Signature[pos];
5566 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5567 mSignatures = newSigs;
5568 }
5569 }
5570
5571 /**
5572 * If any of the given 'sigs' is contained in the existing signatures,
5573 * then completely replace the current signatures with the ones in
5574 * 'sigs'. This is used for updating an existing package to a newly
5575 * installed version.
5576 */
5577 boolean updateSignatures(Signature[] sigs, boolean update) {
5578 if (mSignatures == null) {
5579 if (update) {
5580 assignSignatures(sigs);
5581 }
5582 return true;
5583 }
5584 if (sigs == null) {
5585 return false;
5586 }
5587
5588 for (int i=0; i<sigs.length; i++) {
5589 Signature sig = sigs[i];
5590 for (int j=0; j<mSignatures.length; j++) {
5591 if (mSignatures[j].equals(sig)) {
5592 if (update) {
5593 assignSignatures(sigs);
5594 }
5595 return true;
5596 }
5597 }
5598 }
5599 return false;
5600 }
5601
5602 /**
5603 * If any of the given 'sigs' is contained in the existing signatures,
5604 * then add in any new signatures found in 'sigs'. This is used for
5605 * including a new package into an existing shared user id.
5606 */
5607 boolean mergeSignatures(Signature[] sigs, boolean update) {
5608 if (mSignatures == null) {
5609 if (update) {
5610 assignSignatures(sigs);
5611 }
5612 return true;
5613 }
5614 if (sigs == null) {
5615 return false;
5616 }
5617
5618 Signature[] added = null;
5619 int addedCount = 0;
5620 boolean haveMatch = false;
5621 for (int i=0; i<sigs.length; i++) {
5622 Signature sig = sigs[i];
5623 boolean found = false;
5624 for (int j=0; j<mSignatures.length; j++) {
5625 if (mSignatures[j].equals(sig)) {
5626 found = true;
5627 haveMatch = true;
5628 break;
5629 }
5630 }
5631
5632 if (!found) {
5633 if (added == null) {
5634 added = new Signature[sigs.length];
5635 }
5636 added[i] = sig;
5637 addedCount++;
5638 }
5639 }
5640
5641 if (!haveMatch) {
5642 // Nothing matched -- reject the new signatures.
5643 return false;
5644 }
5645 if (added == null) {
5646 // Completely matched -- nothing else to do.
5647 return true;
5648 }
5649
5650 // Add additional signatures in.
5651 if (update) {
5652 Signature[] total = new Signature[addedCount+mSignatures.length];
5653 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5654 int j = mSignatures.length;
5655 for (int i=0; i<added.length; i++) {
5656 if (added[i] != null) {
5657 total[j] = added[i];
5658 j++;
5659 }
5660 }
5661 mSignatures = total;
5662 }
5663 return true;
5664 }
5665
5666 private void assignSignatures(Signature[] sigs) {
5667 if (sigs == null) {
5668 mSignatures = null;
5669 return;
5670 }
5671 mSignatures = new Signature[sigs.length];
5672 for (int i=0; i<sigs.length; i++) {
5673 mSignatures[i] = sigs[i];
5674 }
5675 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 @Override
5678 public String toString() {
5679 StringBuffer buf = new StringBuffer(128);
5680 buf.append("PackageSignatures{");
5681 buf.append(Integer.toHexString(System.identityHashCode(this)));
5682 buf.append(" [");
5683 if (mSignatures != null) {
5684 for (int i=0; i<mSignatures.length; i++) {
5685 if (i > 0) buf.append(", ");
5686 buf.append(Integer.toHexString(
5687 System.identityHashCode(mSignatures[i])));
5688 }
5689 }
5690 buf.append("]}");
5691 return buf.toString();
5692 }
5693 }
5694
5695 static class PreferredActivity extends IntentFilter {
5696 final int mMatch;
5697 final String[] mSetPackages;
5698 final String[] mSetClasses;
5699 final String[] mSetComponents;
5700 final ComponentName mActivity;
5701 final String mShortActivity;
5702 String mParseError;
5703
5704 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5705 ComponentName activity) {
5706 super(filter);
5707 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5708 mActivity = activity;
5709 mShortActivity = activity.flattenToShortString();
5710 mParseError = null;
5711 if (set != null) {
5712 final int N = set.length;
5713 String[] myPackages = new String[N];
5714 String[] myClasses = new String[N];
5715 String[] myComponents = new String[N];
5716 for (int i=0; i<N; i++) {
5717 ComponentName cn = set[i];
5718 if (cn == null) {
5719 mSetPackages = null;
5720 mSetClasses = null;
5721 mSetComponents = null;
5722 return;
5723 }
5724 myPackages[i] = cn.getPackageName().intern();
5725 myClasses[i] = cn.getClassName().intern();
5726 myComponents[i] = cn.flattenToShortString().intern();
5727 }
5728 mSetPackages = myPackages;
5729 mSetClasses = myClasses;
5730 mSetComponents = myComponents;
5731 } else {
5732 mSetPackages = null;
5733 mSetClasses = null;
5734 mSetComponents = null;
5735 }
5736 }
5737
5738 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5739 IOException {
5740 mShortActivity = parser.getAttributeValue(null, "name");
5741 mActivity = ComponentName.unflattenFromString(mShortActivity);
5742 if (mActivity == null) {
5743 mParseError = "Bad activity name " + mShortActivity;
5744 }
5745 String matchStr = parser.getAttributeValue(null, "match");
5746 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5747 String setCountStr = parser.getAttributeValue(null, "set");
5748 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5749
5750 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5751 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5752 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5753
5754 int setPos = 0;
5755
5756 int outerDepth = parser.getDepth();
5757 int type;
5758 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5759 && (type != XmlPullParser.END_TAG
5760 || parser.getDepth() > outerDepth)) {
5761 if (type == XmlPullParser.END_TAG
5762 || type == XmlPullParser.TEXT) {
5763 continue;
5764 }
5765
5766 String tagName = parser.getName();
5767 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5768 // + parser.getDepth() + " tag=" + tagName);
5769 if (tagName.equals("set")) {
5770 String name = parser.getAttributeValue(null, "name");
5771 if (name == null) {
5772 if (mParseError == null) {
5773 mParseError = "No name in set tag in preferred activity "
5774 + mShortActivity;
5775 }
5776 } else if (setPos >= setCount) {
5777 if (mParseError == null) {
5778 mParseError = "Too many set tags in preferred activity "
5779 + mShortActivity;
5780 }
5781 } else {
5782 ComponentName cn = ComponentName.unflattenFromString(name);
5783 if (cn == null) {
5784 if (mParseError == null) {
5785 mParseError = "Bad set name " + name + " in preferred activity "
5786 + mShortActivity;
5787 }
5788 } else {
5789 myPackages[setPos] = cn.getPackageName();
5790 myClasses[setPos] = cn.getClassName();
5791 myComponents[setPos] = name;
5792 setPos++;
5793 }
5794 }
5795 XmlUtils.skipCurrentTag(parser);
5796 } else if (tagName.equals("filter")) {
5797 //Log.i(TAG, "Starting to parse filter...");
5798 readFromXml(parser);
5799 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5800 // + parser.getDepth() + " tag=" + parser.getName());
5801 } else {
5802 reportSettingsProblem(Log.WARN,
5803 "Unknown element under <preferred-activities>: "
5804 + parser.getName());
5805 XmlUtils.skipCurrentTag(parser);
5806 }
5807 }
5808
5809 if (setPos != setCount) {
5810 if (mParseError == null) {
5811 mParseError = "Not enough set tags (expected " + setCount
5812 + " but found " + setPos + ") in " + mShortActivity;
5813 }
5814 }
5815
5816 mSetPackages = myPackages;
5817 mSetClasses = myClasses;
5818 mSetComponents = myComponents;
5819 }
5820
5821 public void writeToXml(XmlSerializer serializer) throws IOException {
5822 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5823 serializer.attribute(null, "name", mShortActivity);
5824 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5825 serializer.attribute(null, "set", Integer.toString(NS));
5826 for (int s=0; s<NS; s++) {
5827 serializer.startTag(null, "set");
5828 serializer.attribute(null, "name", mSetComponents[s]);
5829 serializer.endTag(null, "set");
5830 }
5831 serializer.startTag(null, "filter");
5832 super.writeToXml(serializer);
5833 serializer.endTag(null, "filter");
5834 }
5835
5836 boolean sameSet(List<ResolveInfo> query, int priority) {
5837 if (mSetPackages == null) return false;
5838 final int NQ = query.size();
5839 final int NS = mSetPackages.length;
5840 int numMatch = 0;
5841 for (int i=0; i<NQ; i++) {
5842 ResolveInfo ri = query.get(i);
5843 if (ri.priority != priority) continue;
5844 ActivityInfo ai = ri.activityInfo;
5845 boolean good = false;
5846 for (int j=0; j<NS; j++) {
5847 if (mSetPackages[j].equals(ai.packageName)
5848 && mSetClasses[j].equals(ai.name)) {
5849 numMatch++;
5850 good = true;
5851 break;
5852 }
5853 }
5854 if (!good) return false;
5855 }
5856 return numMatch == NS;
5857 }
5858 }
5859
5860 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07005861 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 HashSet<String> grantedPermissions = new HashSet<String>();
5864 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 GrantedPermissions(int pkgFlags) {
5869 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5870 }
5871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 /**
5874 * Settings base class for pending and resolved classes.
5875 */
5876 static class PackageSettingBase extends GrantedPermissions {
5877 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005878 File codePath;
5879 String codePathString;
5880 File resourcePath;
5881 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005882 private long timeStamp;
5883 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005884 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885
5886 PackageSignatures signatures = new PackageSignatures();
5887
5888 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 /* Explicitly disabled components */
5891 HashSet<String> disabledComponents = new HashSet<String>(0);
5892 /* Explicitly enabled components */
5893 HashSet<String> enabledComponents = new HashSet<String>(0);
5894 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5895 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005896
Jacek Surazski65e13172009-04-28 15:26:38 +02005897 /* package name of the app that installed this package */
5898 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899
5900 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005901 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 super(pkgFlags);
5903 this.name = name;
5904 this.codePath = codePath;
5905 this.codePathString = codePath.toString();
5906 this.resourcePath = resourcePath;
5907 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005908 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 }
5910
Jacek Surazski65e13172009-04-28 15:26:38 +02005911 public void setInstallerPackageName(String packageName) {
5912 installerPackageName = packageName;
5913 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005914
Jacek Surazski65e13172009-04-28 15:26:38 +02005915 String getInstallerPackageName() {
5916 return installerPackageName;
5917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005919 public void setInstallStatus(int newStatus) {
5920 installStatus = newStatus;
5921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 public int getInstallStatus() {
5924 return installStatus;
5925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 public void setTimeStamp(long newStamp) {
5928 if (newStamp != timeStamp) {
5929 timeStamp = newStamp;
5930 timeStampString = Long.toString(newStamp);
5931 }
5932 }
5933
5934 public void setTimeStamp(long newStamp, String newStampStr) {
5935 timeStamp = newStamp;
5936 timeStampString = newStampStr;
5937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 public long getTimeStamp() {
5940 return timeStamp;
5941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 public String getTimeStampStr() {
5944 return timeStampString;
5945 }
5946
5947 public void copyFrom(PackageSettingBase base) {
5948 grantedPermissions = base.grantedPermissions;
5949 gids = base.gids;
5950 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 timeStamp = base.timeStamp;
5953 timeStampString = base.timeStampString;
5954 signatures = base.signatures;
5955 permissionsFixed = base.permissionsFixed;
5956 disabledComponents = base.disabledComponents;
5957 enabledComponents = base.enabledComponents;
5958 enabled = base.enabled;
5959 installStatus = base.installStatus;
5960 }
5961
5962 void enableComponentLP(String componentClassName) {
5963 disabledComponents.remove(componentClassName);
5964 enabledComponents.add(componentClassName);
5965 }
5966
5967 void disableComponentLP(String componentClassName) {
5968 enabledComponents.remove(componentClassName);
5969 disabledComponents.add(componentClassName);
5970 }
5971
5972 void restoreComponentLP(String componentClassName) {
5973 enabledComponents.remove(componentClassName);
5974 disabledComponents.remove(componentClassName);
5975 }
5976
5977 int currentEnabledStateLP(String componentName) {
5978 if (enabledComponents.contains(componentName)) {
5979 return COMPONENT_ENABLED_STATE_ENABLED;
5980 } else if (disabledComponents.contains(componentName)) {
5981 return COMPONENT_ENABLED_STATE_DISABLED;
5982 } else {
5983 return COMPONENT_ENABLED_STATE_DEFAULT;
5984 }
5985 }
5986 }
5987
5988 /**
5989 * Settings data for a particular package we know about.
5990 */
5991 static final class PackageSetting extends PackageSettingBase {
5992 int userId;
5993 PackageParser.Package pkg;
5994 SharedUserSetting sharedUser;
5995
5996 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005997 int pVersionCode, int pkgFlags) {
5998 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 @Override
6002 public String toString() {
6003 return "PackageSetting{"
6004 + Integer.toHexString(System.identityHashCode(this))
6005 + " " + name + "/" + userId + "}";
6006 }
6007 }
6008
6009 /**
6010 * Settings data for a particular shared user ID we know about.
6011 */
6012 static final class SharedUserSetting extends GrantedPermissions {
6013 final String name;
6014 int userId;
6015 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6016 final PackageSignatures signatures = new PackageSignatures();
6017
6018 SharedUserSetting(String _name, int _pkgFlags) {
6019 super(_pkgFlags);
6020 name = _name;
6021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 @Override
6024 public String toString() {
6025 return "SharedUserSetting{"
6026 + Integer.toHexString(System.identityHashCode(this))
6027 + " " + name + "/" + userId + "}";
6028 }
6029 }
6030
6031 /**
6032 * Holds information about dynamic settings.
6033 */
6034 private static final class Settings {
6035 private final File mSettingsFilename;
6036 private final File mBackupSettingsFilename;
6037 private final HashMap<String, PackageSetting> mPackages =
6038 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 // List of replaced system applications
6040 final HashMap<String, PackageSetting> mDisabledSysPackages =
6041 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 // The user's preferred activities associated with particular intent
6044 // filters.
6045 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6046 new IntentResolver<PreferredActivity, PreferredActivity>() {
6047 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006048 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006050 out.print(prefix); out.print(
6051 Integer.toHexString(System.identityHashCode(filter)));
6052 out.print(' ');
6053 out.print(filter.mActivity.flattenToShortString());
6054 out.print(" match=0x");
6055 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006057 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006059 out.print(prefix); out.print(" ");
6060 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 }
6062 }
6063 }
6064 };
6065 private final HashMap<String, SharedUserSetting> mSharedUsers =
6066 new HashMap<String, SharedUserSetting>();
6067 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6068 private final SparseArray<Object> mOtherUserIds =
6069 new SparseArray<Object>();
6070
6071 // For reading/writing settings file.
6072 private final ArrayList<Signature> mPastSignatures =
6073 new ArrayList<Signature>();
6074
6075 // Mapping from permission names to info about them.
6076 final HashMap<String, BasePermission> mPermissions =
6077 new HashMap<String, BasePermission>();
6078
6079 // Mapping from permission tree names to info about them.
6080 final HashMap<String, BasePermission> mPermissionTrees =
6081 new HashMap<String, BasePermission>();
6082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 private final StringBuilder mReadMessages = new StringBuilder();
6084
6085 private static final class PendingPackage extends PackageSettingBase {
6086 final int sharedId;
6087
6088 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006089 int sharedId, int pVersionCode, int pkgFlags) {
6090 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 this.sharedId = sharedId;
6092 }
6093 }
6094 private final ArrayList<PendingPackage> mPendingPackages
6095 = new ArrayList<PendingPackage>();
6096
6097 Settings() {
6098 File dataDir = Environment.getDataDirectory();
6099 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08006100 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
6101 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006103 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 FileUtils.setPermissions(systemDir.toString(),
6105 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6106 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6107 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08006108 FileUtils.setPermissions(systemSecureDir.toString(),
6109 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6110 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6111 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 mSettingsFilename = new File(systemDir, "packages.xml");
6113 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6114 }
6115
6116 PackageSetting getPackageLP(PackageParser.Package pkg,
6117 SharedUserSetting sharedUser, File codePath, File resourcePath,
6118 int pkgFlags, boolean create, boolean add) {
6119 final String name = pkg.packageName;
6120 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006121 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 return p;
6123 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006124
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006125 PackageSetting peekPackageLP(String name) {
6126 return mPackages.get(name);
6127 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 PackageSetting p = mPackages.get(name);
6129 if (p != null && p.codePath.getPath().equals(codePath)) {
6130 return p;
6131 }
6132 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006133 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006134 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 void setInstallStatus(String pkgName, int status) {
6137 PackageSetting p = mPackages.get(pkgName);
6138 if(p != null) {
6139 if(p.getInstallStatus() != status) {
6140 p.setInstallStatus(status);
6141 }
6142 }
6143 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006144
Jacek Surazski65e13172009-04-28 15:26:38 +02006145 void setInstallerPackageName(String pkgName,
6146 String installerPkgName) {
6147 PackageSetting p = mPackages.get(pkgName);
6148 if(p != null) {
6149 p.setInstallerPackageName(installerPkgName);
6150 }
6151 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006152
Jacek Surazski65e13172009-04-28 15:26:38 +02006153 String getInstallerPackageName(String pkgName) {
6154 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006155 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02006156 }
6157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 int getInstallStatus(String pkgName) {
6159 PackageSetting p = mPackages.get(pkgName);
6160 if(p != null) {
6161 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 return -1;
6164 }
6165
6166 SharedUserSetting getSharedUserLP(String name,
6167 int pkgFlags, boolean create) {
6168 SharedUserSetting s = mSharedUsers.get(name);
6169 if (s == null) {
6170 if (!create) {
6171 return null;
6172 }
6173 s = new SharedUserSetting(name, pkgFlags);
6174 if (MULTIPLE_APPLICATION_UIDS) {
6175 s.userId = newUserIdLP(s);
6176 } else {
6177 s.userId = FIRST_APPLICATION_UID;
6178 }
6179 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6180 // < 0 means we couldn't assign a userid; fall out and return
6181 // s, which is currently null
6182 if (s.userId >= 0) {
6183 mSharedUsers.put(name, s);
6184 }
6185 }
6186
6187 return s;
6188 }
6189
6190 int disableSystemPackageLP(String name) {
6191 PackageSetting p = mPackages.get(name);
6192 if(p == null) {
6193 Log.w(TAG, "Package:"+name+" is not an installed package");
6194 return -1;
6195 }
6196 PackageSetting dp = mDisabledSysPackages.get(name);
6197 // always make sure the system package code and resource paths dont change
6198 if(dp == null) {
6199 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6200 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6201 }
6202 mDisabledSysPackages.put(name, p);
6203 }
6204 return removePackageLP(name);
6205 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 PackageSetting enableSystemPackageLP(String name) {
6208 PackageSetting p = mDisabledSysPackages.get(name);
6209 if(p == null) {
6210 Log.w(TAG, "Package:"+name+" is not disabled");
6211 return null;
6212 }
6213 // Reset flag in ApplicationInfo object
6214 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6215 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6216 }
6217 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006218 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 mDisabledSysPackages.remove(name);
6220 return ret;
6221 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006224 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 PackageSetting p = mPackages.get(name);
6226 if (p != null) {
6227 if (p.userId == uid) {
6228 return p;
6229 }
6230 reportSettingsProblem(Log.ERROR,
6231 "Adding duplicate package, keeping first: " + name);
6232 return null;
6233 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006234 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 p.userId = uid;
6236 if (addUserIdLP(uid, p, name)) {
6237 mPackages.put(name, p);
6238 return p;
6239 }
6240 return null;
6241 }
6242
6243 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6244 SharedUserSetting s = mSharedUsers.get(name);
6245 if (s != null) {
6246 if (s.userId == uid) {
6247 return s;
6248 }
6249 reportSettingsProblem(Log.ERROR,
6250 "Adding duplicate shared user, keeping first: " + name);
6251 return null;
6252 }
6253 s = new SharedUserSetting(name, pkgFlags);
6254 s.userId = uid;
6255 if (addUserIdLP(uid, s, name)) {
6256 mSharedUsers.put(name, s);
6257 return s;
6258 }
6259 return null;
6260 }
6261
6262 private PackageSetting getPackageLP(String name,
6263 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006264 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 PackageSetting p = mPackages.get(name);
6266 if (p != null) {
6267 if (!p.codePath.equals(codePath)) {
6268 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006269 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006270 // This is an updated system app with versions in both system
6271 // and data partition. Just let the most recent version
6272 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006273 Log.w(TAG, "Trying to update system app code path from " +
6274 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006275 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006276 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07006277 reportSettingsProblem(Log.WARN,
6278 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006279 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006281 }
6282 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 reportSettingsProblem(Log.WARN,
6284 "Package " + name + " shared user changed from "
6285 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
6286 + " to "
6287 + (sharedUser != null ? sharedUser.name : "<nothing>")
6288 + "; replacing with new");
6289 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006290 } else {
6291 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6292 // If what we are scanning is a system package, then
6293 // make it so, regardless of whether it was previously
6294 // installed only in the data partition.
6295 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 }
6298 }
6299 if (p == null) {
6300 // Create a new PackageSettings entry. this can end up here because
6301 // of code path mismatch or user id mismatch of an updated system partition
6302 if (!create) {
6303 return null;
6304 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006305 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07006307 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 if (sharedUser != null) {
6309 p.userId = sharedUser.userId;
6310 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006311 // Clone the setting here for disabled system packages
6312 PackageSetting dis = mDisabledSysPackages.get(name);
6313 if (dis != null) {
6314 // For disabled packages a new setting is created
6315 // from the existing user id. This still has to be
6316 // added to list of user id's
6317 // Copy signatures from previous setting
6318 if (dis.signatures.mSignatures != null) {
6319 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
6320 }
6321 p.userId = dis.userId;
6322 // Clone permissions
6323 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
6324 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
6325 // Clone component info
6326 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
6327 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
6328 // Add new setting to list of user ids
6329 addUserIdLP(p.userId, p, name);
6330 } else {
6331 // Assign new user id
6332 p.userId = newUserIdLP(p);
6333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 } else {
6335 p.userId = FIRST_APPLICATION_UID;
6336 }
6337 if (p.userId < 0) {
6338 reportSettingsProblem(Log.WARN,
6339 "Package " + name + " could not be assigned a valid uid");
6340 return null;
6341 }
6342 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006343 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006345 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 }
6347 }
6348 return p;
6349 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006350
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006351 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006352 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006353 String codePath = pkg.applicationInfo.sourceDir;
6354 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006355 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006356 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006357 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006358 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006359 p.codePath = new File(codePath);
6360 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006361 }
6362 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006363 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006364 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006365 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006366 p.resourcePath = new File(resourcePath);
6367 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006368 }
6369 // Update version code if needed
6370 if (pkg.mVersionCode != p.versionCode) {
6371 p.versionCode = pkg.mVersionCode;
6372 }
6373 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
6374 }
6375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 // Utility method that adds a PackageSetting to mPackages and
6377 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006378 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 SharedUserSetting sharedUser) {
6380 mPackages.put(name, p);
6381 if (sharedUser != null) {
6382 if (p.sharedUser != null && p.sharedUser != sharedUser) {
6383 reportSettingsProblem(Log.ERROR,
6384 "Package " + p.name + " was user "
6385 + p.sharedUser + " but is now " + sharedUser
6386 + "; I am not changing its files so it will probably fail!");
6387 p.sharedUser.packages.remove(p);
6388 } else if (p.userId != sharedUser.userId) {
6389 reportSettingsProblem(Log.ERROR,
6390 "Package " + p.name + " was user id " + p.userId
6391 + " but is now user " + sharedUser
6392 + " with id " + sharedUser.userId
6393 + "; I am not changing its files so it will probably fail!");
6394 }
6395
6396 sharedUser.packages.add(p);
6397 p.sharedUser = sharedUser;
6398 p.userId = sharedUser.userId;
6399 }
6400 }
6401
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006402 /*
6403 * Update the shared user setting when a package using
6404 * specifying the shared user id is removed. The gids
6405 * associated with each permission of the deleted package
6406 * are removed from the shared user's gid list only if its
6407 * not in use by other permissions of packages in the
6408 * shared user setting.
6409 */
6410 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6412 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6413 return;
6414 }
6415 // No sharedUserId
6416 if (deletedPs.sharedUser == null) {
6417 return;
6418 }
6419 SharedUserSetting sus = deletedPs.sharedUser;
6420 // Update permissions
6421 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6422 boolean used = false;
6423 if (!sus.grantedPermissions.contains (eachPerm)) {
6424 continue;
6425 }
6426 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006427 if (pkg.pkg != null &&
6428 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
6429 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 used = true;
6431 break;
6432 }
6433 }
6434 if (!used) {
6435 // can safely delete this permission from list
6436 sus.grantedPermissions.remove(eachPerm);
6437 sus.loadedPermissions.remove(eachPerm);
6438 }
6439 }
6440 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006441 int newGids[] = globalGids;
6442 for (String eachPerm : sus.grantedPermissions) {
6443 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006444 if (bp != null) {
6445 newGids = appendInts(newGids, bp.gids);
6446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 }
6448 sus.gids = newGids;
6449 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 private int removePackageLP(String name) {
6452 PackageSetting p = mPackages.get(name);
6453 if (p != null) {
6454 mPackages.remove(name);
6455 if (p.sharedUser != null) {
6456 p.sharedUser.packages.remove(p);
6457 if (p.sharedUser.packages.size() == 0) {
6458 mSharedUsers.remove(p.sharedUser.name);
6459 removeUserIdLP(p.sharedUser.userId);
6460 return p.sharedUser.userId;
6461 }
6462 } else {
6463 removeUserIdLP(p.userId);
6464 return p.userId;
6465 }
6466 }
6467 return -1;
6468 }
6469
6470 private boolean addUserIdLP(int uid, Object obj, Object name) {
6471 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6472 return false;
6473 }
6474
6475 if (uid >= FIRST_APPLICATION_UID) {
6476 int N = mUserIds.size();
6477 final int index = uid - FIRST_APPLICATION_UID;
6478 while (index >= N) {
6479 mUserIds.add(null);
6480 N++;
6481 }
6482 if (mUserIds.get(index) != null) {
6483 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006484 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 + " name=" + name);
6486 return false;
6487 }
6488 mUserIds.set(index, obj);
6489 } else {
6490 if (mOtherUserIds.get(uid) != null) {
6491 reportSettingsProblem(Log.ERROR,
6492 "Adding duplicate shared id: " + uid
6493 + " name=" + name);
6494 return false;
6495 }
6496 mOtherUserIds.put(uid, obj);
6497 }
6498 return true;
6499 }
6500
6501 public Object getUserIdLP(int uid) {
6502 if (uid >= FIRST_APPLICATION_UID) {
6503 int N = mUserIds.size();
6504 final int index = uid - FIRST_APPLICATION_UID;
6505 return index < N ? mUserIds.get(index) : null;
6506 } else {
6507 return mOtherUserIds.get(uid);
6508 }
6509 }
6510
6511 private void removeUserIdLP(int uid) {
6512 if (uid >= FIRST_APPLICATION_UID) {
6513 int N = mUserIds.size();
6514 final int index = uid - FIRST_APPLICATION_UID;
6515 if (index < N) mUserIds.set(index, null);
6516 } else {
6517 mOtherUserIds.remove(uid);
6518 }
6519 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 void writeLP() {
6522 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6523
6524 // Keep the old settings around until we know the new ones have
6525 // been successfully written.
6526 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006527 // Presence of backup settings file indicates that we failed
6528 // to persist settings earlier. So preserve the older
6529 // backup for future reference since the current settings
6530 // might have been corrupted.
6531 if (!mBackupSettingsFilename.exists()) {
6532 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
6533 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
6534 return;
6535 }
6536 } else {
6537 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07006538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 }
6540
6541 mPastSignatures.clear();
6542
6543 try {
6544 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6545
6546 //XmlSerializer serializer = XmlUtils.serializerInstance();
6547 XmlSerializer serializer = new FastXmlSerializer();
6548 serializer.setOutput(str, "utf-8");
6549 serializer.startDocument(null, true);
6550 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6551
6552 serializer.startTag(null, "packages");
6553
6554 serializer.startTag(null, "permission-trees");
6555 for (BasePermission bp : mPermissionTrees.values()) {
6556 writePermission(serializer, bp);
6557 }
6558 serializer.endTag(null, "permission-trees");
6559
6560 serializer.startTag(null, "permissions");
6561 for (BasePermission bp : mPermissions.values()) {
6562 writePermission(serializer, bp);
6563 }
6564 serializer.endTag(null, "permissions");
6565
6566 for (PackageSetting pkg : mPackages.values()) {
6567 writePackage(serializer, pkg);
6568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6571 writeDisabledSysPackage(serializer, pkg);
6572 }
6573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006574 serializer.startTag(null, "preferred-activities");
6575 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6576 serializer.startTag(null, "item");
6577 pa.writeToXml(serializer);
6578 serializer.endTag(null, "item");
6579 }
6580 serializer.endTag(null, "preferred-activities");
6581
6582 for (SharedUserSetting usr : mSharedUsers.values()) {
6583 serializer.startTag(null, "shared-user");
6584 serializer.attribute(null, "name", usr.name);
6585 serializer.attribute(null, "userId",
6586 Integer.toString(usr.userId));
6587 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6588 serializer.startTag(null, "perms");
6589 for (String name : usr.grantedPermissions) {
6590 serializer.startTag(null, "item");
6591 serializer.attribute(null, "name", name);
6592 serializer.endTag(null, "item");
6593 }
6594 serializer.endTag(null, "perms");
6595 serializer.endTag(null, "shared-user");
6596 }
6597
6598 serializer.endTag(null, "packages");
6599
6600 serializer.endDocument();
6601
6602 str.flush();
6603 str.close();
6604
6605 // New settings successfully written, old ones are no longer
6606 // needed.
6607 mBackupSettingsFilename.delete();
6608 FileUtils.setPermissions(mSettingsFilename.toString(),
6609 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6610 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6611 |FileUtils.S_IROTH,
6612 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006613 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614
6615 } catch(XmlPullParserException e) {
6616 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 } catch(java.io.IOException e) {
6618 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 -08006619 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006620 // Clean up partially written file
6621 if (mSettingsFilename.exists()) {
6622 if (!mSettingsFilename.delete()) {
6623 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
6624 }
6625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006626 //Debug.stopMethodTracing();
6627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006628
6629 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 throws java.io.IOException {
6631 serializer.startTag(null, "updated-package");
6632 serializer.attribute(null, "name", pkg.name);
6633 serializer.attribute(null, "codePath", pkg.codePathString);
6634 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006635 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6637 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6638 }
6639 if (pkg.sharedUser == null) {
6640 serializer.attribute(null, "userId",
6641 Integer.toString(pkg.userId));
6642 } else {
6643 serializer.attribute(null, "sharedUserId",
6644 Integer.toString(pkg.userId));
6645 }
6646 serializer.startTag(null, "perms");
6647 if (pkg.sharedUser == null) {
6648 // If this is a shared user, the permissions will
6649 // be written there. We still need to write an
6650 // empty permissions list so permissionsFixed will
6651 // be set.
6652 for (final String name : pkg.grantedPermissions) {
6653 BasePermission bp = mPermissions.get(name);
6654 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6655 // We only need to write signature or system permissions but this wont
6656 // match the semantics of grantedPermissions. So write all permissions.
6657 serializer.startTag(null, "item");
6658 serializer.attribute(null, "name", name);
6659 serializer.endTag(null, "item");
6660 }
6661 }
6662 }
6663 serializer.endTag(null, "perms");
6664 serializer.endTag(null, "updated-package");
6665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006666
6667 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 throws java.io.IOException {
6669 serializer.startTag(null, "package");
6670 serializer.attribute(null, "name", pkg.name);
6671 serializer.attribute(null, "codePath", pkg.codePathString);
6672 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6673 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6674 }
6675 serializer.attribute(null, "system",
6676 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6677 ? "true" : "false");
6678 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006679 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006680 if (pkg.sharedUser == null) {
6681 serializer.attribute(null, "userId",
6682 Integer.toString(pkg.userId));
6683 } else {
6684 serializer.attribute(null, "sharedUserId",
6685 Integer.toString(pkg.userId));
6686 }
6687 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6688 serializer.attribute(null, "enabled",
6689 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6690 ? "true" : "false");
6691 }
6692 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6693 serializer.attribute(null, "installStatus", "false");
6694 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006695 if (pkg.installerPackageName != null) {
6696 serializer.attribute(null, "installer", pkg.installerPackageName);
6697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6699 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6700 serializer.startTag(null, "perms");
6701 if (pkg.sharedUser == null) {
6702 // If this is a shared user, the permissions will
6703 // be written there. We still need to write an
6704 // empty permissions list so permissionsFixed will
6705 // be set.
6706 for (final String name : pkg.grantedPermissions) {
6707 serializer.startTag(null, "item");
6708 serializer.attribute(null, "name", name);
6709 serializer.endTag(null, "item");
6710 }
6711 }
6712 serializer.endTag(null, "perms");
6713 }
6714 if (pkg.disabledComponents.size() > 0) {
6715 serializer.startTag(null, "disabled-components");
6716 for (final String name : pkg.disabledComponents) {
6717 serializer.startTag(null, "item");
6718 serializer.attribute(null, "name", name);
6719 serializer.endTag(null, "item");
6720 }
6721 serializer.endTag(null, "disabled-components");
6722 }
6723 if (pkg.enabledComponents.size() > 0) {
6724 serializer.startTag(null, "enabled-components");
6725 for (final String name : pkg.enabledComponents) {
6726 serializer.startTag(null, "item");
6727 serializer.attribute(null, "name", name);
6728 serializer.endTag(null, "item");
6729 }
6730 serializer.endTag(null, "enabled-components");
6731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 serializer.endTag(null, "package");
6734 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 void writePermission(XmlSerializer serializer, BasePermission bp)
6737 throws XmlPullParserException, java.io.IOException {
6738 if (bp.type != BasePermission.TYPE_BUILTIN
6739 && bp.sourcePackage != null) {
6740 serializer.startTag(null, "item");
6741 serializer.attribute(null, "name", bp.name);
6742 serializer.attribute(null, "package", bp.sourcePackage);
6743 if (DEBUG_SETTINGS) Log.v(TAG,
6744 "Writing perm: name=" + bp.name + " type=" + bp.type);
6745 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6746 PermissionInfo pi = bp.perm != null ? bp.perm.info
6747 : bp.pendingInfo;
6748 if (pi != null) {
6749 serializer.attribute(null, "type", "dynamic");
6750 if (pi.icon != 0) {
6751 serializer.attribute(null, "icon",
6752 Integer.toString(pi.icon));
6753 }
6754 if (pi.nonLocalizedLabel != null) {
6755 serializer.attribute(null, "label",
6756 pi.nonLocalizedLabel.toString());
6757 }
6758 if (pi.protectionLevel !=
6759 PermissionInfo.PROTECTION_NORMAL) {
6760 serializer.attribute(null, "protection",
6761 Integer.toString(pi.protectionLevel));
6762 }
6763 }
6764 }
6765 serializer.endTag(null, "item");
6766 }
6767 }
6768
6769 String getReadMessagesLP() {
6770 return mReadMessages.toString();
6771 }
6772
Oscar Montemayora8529f62009-11-18 10:14:20 -08006773 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6775 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006776 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 while(its.hasNext()) {
6778 String key = its.next();
6779 PackageSetting ps = mPackages.get(key);
6780 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006781 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 }
6783 }
6784 return ret;
6785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 boolean readLP() {
6788 FileInputStream str = null;
6789 if (mBackupSettingsFilename.exists()) {
6790 try {
6791 str = new FileInputStream(mBackupSettingsFilename);
6792 mReadMessages.append("Reading from backup settings file\n");
6793 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006794 if (mSettingsFilename.exists()) {
6795 // If both the backup and settings file exist, we
6796 // ignore the settings since it might have been
6797 // corrupted.
6798 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
6799 mSettingsFilename.delete();
6800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 } catch (java.io.IOException e) {
6802 // We'll try for the normal settings file.
6803 }
6804 }
6805
6806 mPastSignatures.clear();
6807
6808 try {
6809 if (str == null) {
6810 if (!mSettingsFilename.exists()) {
6811 mReadMessages.append("No settings file found\n");
6812 Log.i(TAG, "No current settings file!");
6813 return false;
6814 }
6815 str = new FileInputStream(mSettingsFilename);
6816 }
6817 XmlPullParser parser = Xml.newPullParser();
6818 parser.setInput(str, null);
6819
6820 int type;
6821 while ((type=parser.next()) != XmlPullParser.START_TAG
6822 && type != XmlPullParser.END_DOCUMENT) {
6823 ;
6824 }
6825
6826 if (type != XmlPullParser.START_TAG) {
6827 mReadMessages.append("No start tag found in settings file\n");
6828 Log.e(TAG, "No start tag found in package manager settings");
6829 return false;
6830 }
6831
6832 int outerDepth = parser.getDepth();
6833 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6834 && (type != XmlPullParser.END_TAG
6835 || parser.getDepth() > outerDepth)) {
6836 if (type == XmlPullParser.END_TAG
6837 || type == XmlPullParser.TEXT) {
6838 continue;
6839 }
6840
6841 String tagName = parser.getName();
6842 if (tagName.equals("package")) {
6843 readPackageLP(parser);
6844 } else if (tagName.equals("permissions")) {
6845 readPermissionsLP(mPermissions, parser);
6846 } else if (tagName.equals("permission-trees")) {
6847 readPermissionsLP(mPermissionTrees, parser);
6848 } else if (tagName.equals("shared-user")) {
6849 readSharedUserLP(parser);
6850 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006851 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006852 } else if (tagName.equals("preferred-activities")) {
6853 readPreferredActivitiesLP(parser);
6854 } else if(tagName.equals("updated-package")) {
6855 readDisabledSysPackageLP(parser);
6856 } else {
6857 Log.w(TAG, "Unknown element under <packages>: "
6858 + parser.getName());
6859 XmlUtils.skipCurrentTag(parser);
6860 }
6861 }
6862
6863 str.close();
6864
6865 } catch(XmlPullParserException e) {
6866 mReadMessages.append("Error reading: " + e.toString());
6867 Log.e(TAG, "Error reading package manager settings", e);
6868
6869 } catch(java.io.IOException e) {
6870 mReadMessages.append("Error reading: " + e.toString());
6871 Log.e(TAG, "Error reading package manager settings", e);
6872
6873 }
6874
6875 int N = mPendingPackages.size();
6876 for (int i=0; i<N; i++) {
6877 final PendingPackage pp = mPendingPackages.get(i);
6878 Object idObj = getUserIdLP(pp.sharedId);
6879 if (idObj != null && idObj instanceof SharedUserSetting) {
6880 PackageSetting p = getPackageLP(pp.name,
6881 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006882 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006883 if (p == null) {
6884 Log.w(TAG, "Unable to create application package for "
6885 + pp.name);
6886 continue;
6887 }
6888 p.copyFrom(pp);
6889 } else if (idObj != null) {
6890 String msg = "Bad package setting: package " + pp.name
6891 + " has shared uid " + pp.sharedId
6892 + " that is not a shared uid\n";
6893 mReadMessages.append(msg);
6894 Log.e(TAG, msg);
6895 } else {
6896 String msg = "Bad package setting: package " + pp.name
6897 + " has shared uid " + pp.sharedId
6898 + " that is not defined\n";
6899 mReadMessages.append(msg);
6900 Log.e(TAG, msg);
6901 }
6902 }
6903 mPendingPackages.clear();
6904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006905 mReadMessages.append("Read completed successfully: "
6906 + mPackages.size() + " packages, "
6907 + mSharedUsers.size() + " shared uids\n");
6908
6909 return true;
6910 }
6911
6912 private int readInt(XmlPullParser parser, String ns, String name,
6913 int defValue) {
6914 String v = parser.getAttributeValue(ns, name);
6915 try {
6916 if (v == null) {
6917 return defValue;
6918 }
6919 return Integer.parseInt(v);
6920 } catch (NumberFormatException e) {
6921 reportSettingsProblem(Log.WARN,
6922 "Error in package manager settings: attribute " +
6923 name + " has bad integer value " + v + " at "
6924 + parser.getPositionDescription());
6925 }
6926 return defValue;
6927 }
6928
6929 private void readPermissionsLP(HashMap<String, BasePermission> out,
6930 XmlPullParser parser)
6931 throws IOException, XmlPullParserException {
6932 int outerDepth = parser.getDepth();
6933 int type;
6934 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6935 && (type != XmlPullParser.END_TAG
6936 || parser.getDepth() > outerDepth)) {
6937 if (type == XmlPullParser.END_TAG
6938 || type == XmlPullParser.TEXT) {
6939 continue;
6940 }
6941
6942 String tagName = parser.getName();
6943 if (tagName.equals("item")) {
6944 String name = parser.getAttributeValue(null, "name");
6945 String sourcePackage = parser.getAttributeValue(null, "package");
6946 String ptype = parser.getAttributeValue(null, "type");
6947 if (name != null && sourcePackage != null) {
6948 boolean dynamic = "dynamic".equals(ptype);
6949 BasePermission bp = new BasePermission(name, sourcePackage,
6950 dynamic
6951 ? BasePermission.TYPE_DYNAMIC
6952 : BasePermission.TYPE_NORMAL);
6953 if (dynamic) {
6954 PermissionInfo pi = new PermissionInfo();
6955 pi.packageName = sourcePackage.intern();
6956 pi.name = name.intern();
6957 pi.icon = readInt(parser, null, "icon", 0);
6958 pi.nonLocalizedLabel = parser.getAttributeValue(
6959 null, "label");
6960 pi.protectionLevel = readInt(parser, null, "protection",
6961 PermissionInfo.PROTECTION_NORMAL);
6962 bp.pendingInfo = pi;
6963 }
6964 out.put(bp.name, bp);
6965 } else {
6966 reportSettingsProblem(Log.WARN,
6967 "Error in package manager settings: permissions has"
6968 + " no name at " + parser.getPositionDescription());
6969 }
6970 } else {
6971 reportSettingsProblem(Log.WARN,
6972 "Unknown element reading permissions: "
6973 + parser.getName() + " at "
6974 + parser.getPositionDescription());
6975 }
6976 XmlUtils.skipCurrentTag(parser);
6977 }
6978 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006980 private void readDisabledSysPackageLP(XmlPullParser parser)
6981 throws XmlPullParserException, IOException {
6982 String name = parser.getAttributeValue(null, "name");
6983 String codePathStr = parser.getAttributeValue(null, "codePath");
6984 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6985 if(resourcePathStr == null) {
6986 resourcePathStr = codePathStr;
6987 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006988 String version = parser.getAttributeValue(null, "version");
6989 int versionCode = 0;
6990 if (version != null) {
6991 try {
6992 versionCode = Integer.parseInt(version);
6993 } catch (NumberFormatException e) {
6994 }
6995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 int pkgFlags = 0;
6998 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006999 PackageSetting ps = new PackageSetting(name,
7000 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007001 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 String timeStampStr = parser.getAttributeValue(null, "ts");
7003 if (timeStampStr != null) {
7004 try {
7005 long timeStamp = Long.parseLong(timeStampStr);
7006 ps.setTimeStamp(timeStamp, timeStampStr);
7007 } catch (NumberFormatException e) {
7008 }
7009 }
7010 String idStr = parser.getAttributeValue(null, "userId");
7011 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
7012 if(ps.userId <= 0) {
7013 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7014 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7015 }
7016 int outerDepth = parser.getDepth();
7017 int type;
7018 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7019 && (type != XmlPullParser.END_TAG
7020 || parser.getDepth() > outerDepth)) {
7021 if (type == XmlPullParser.END_TAG
7022 || type == XmlPullParser.TEXT) {
7023 continue;
7024 }
7025
7026 String tagName = parser.getName();
7027 if (tagName.equals("perms")) {
7028 readGrantedPermissionsLP(parser,
7029 ps.grantedPermissions);
7030 } else {
7031 reportSettingsProblem(Log.WARN,
7032 "Unknown element under <updated-package>: "
7033 + parser.getName());
7034 XmlUtils.skipCurrentTag(parser);
7035 }
7036 }
7037 mDisabledSysPackages.put(name, ps);
7038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 private void readPackageLP(XmlPullParser parser)
7041 throws XmlPullParserException, IOException {
7042 String name = null;
7043 String idStr = null;
7044 String sharedIdStr = null;
7045 String codePathStr = null;
7046 String resourcePathStr = null;
7047 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007048 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007049 int pkgFlags = 0;
7050 String timeStampStr;
7051 long timeStamp = 0;
7052 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007053 String version = null;
7054 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 try {
7056 name = parser.getAttributeValue(null, "name");
7057 idStr = parser.getAttributeValue(null, "userId");
7058 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7059 codePathStr = parser.getAttributeValue(null, "codePath");
7060 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007061 version = parser.getAttributeValue(null, "version");
7062 if (version != null) {
7063 try {
7064 versionCode = Integer.parseInt(version);
7065 } catch (NumberFormatException e) {
7066 }
7067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazski65e13172009-04-28 15:26:38 +02007069 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007070 if (systemStr != null) {
7071 if ("true".equals(systemStr)) {
7072 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7073 }
7074 } else {
7075 // Old settings that don't specify system... just treat
7076 // them as system, good enough.
7077 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7078 }
7079 timeStampStr = parser.getAttributeValue(null, "ts");
7080 if (timeStampStr != null) {
7081 try {
7082 timeStamp = Long.parseLong(timeStampStr);
7083 } catch (NumberFormatException e) {
7084 }
7085 }
7086 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7087 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7088 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7089 if (resourcePathStr == null) {
7090 resourcePathStr = codePathStr;
7091 }
7092 if (name == null) {
7093 reportSettingsProblem(Log.WARN,
7094 "Error in package manager settings: <package> has no name at "
7095 + parser.getPositionDescription());
7096 } else if (codePathStr == null) {
7097 reportSettingsProblem(Log.WARN,
7098 "Error in package manager settings: <package> has no codePath at "
7099 + parser.getPositionDescription());
7100 } else if (userId > 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007101 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007102 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7104 + ": userId=" + userId + " pkg=" + packageSetting);
7105 if (packageSetting == null) {
7106 reportSettingsProblem(Log.ERROR,
7107 "Failure adding uid " + userId
7108 + " while parsing settings at "
7109 + parser.getPositionDescription());
7110 } else {
7111 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7112 }
7113 } else if (sharedIdStr != null) {
7114 userId = sharedIdStr != null
7115 ? Integer.parseInt(sharedIdStr) : 0;
7116 if (userId > 0) {
7117 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007118 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7120 mPendingPackages.add((PendingPackage) packageSetting);
7121 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7122 + ": sharedUserId=" + userId + " pkg="
7123 + packageSetting);
7124 } else {
7125 reportSettingsProblem(Log.WARN,
7126 "Error in package manager settings: package "
7127 + name + " has bad sharedId " + sharedIdStr
7128 + " at " + parser.getPositionDescription());
7129 }
7130 } else {
7131 reportSettingsProblem(Log.WARN,
7132 "Error in package manager settings: package "
7133 + name + " has bad userId " + idStr + " at "
7134 + parser.getPositionDescription());
7135 }
7136 } catch (NumberFormatException e) {
7137 reportSettingsProblem(Log.WARN,
7138 "Error in package manager settings: package "
7139 + name + " has bad userId " + idStr + " at "
7140 + parser.getPositionDescription());
7141 }
7142 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02007143 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007144 final String enabledStr = parser.getAttributeValue(null, "enabled");
7145 if (enabledStr != null) {
7146 if (enabledStr.equalsIgnoreCase("true")) {
7147 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7148 } else if (enabledStr.equalsIgnoreCase("false")) {
7149 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7150 } else if (enabledStr.equalsIgnoreCase("default")) {
7151 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7152 } else {
7153 reportSettingsProblem(Log.WARN,
7154 "Error in package manager settings: package "
7155 + name + " has bad enabled value: " + idStr
7156 + " at " + parser.getPositionDescription());
7157 }
7158 } else {
7159 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7160 }
7161 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7162 if (installStatusStr != null) {
7163 if (installStatusStr.equalsIgnoreCase("false")) {
7164 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7165 } else {
7166 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7167 }
7168 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007170 int outerDepth = parser.getDepth();
7171 int type;
7172 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7173 && (type != XmlPullParser.END_TAG
7174 || parser.getDepth() > outerDepth)) {
7175 if (type == XmlPullParser.END_TAG
7176 || type == XmlPullParser.TEXT) {
7177 continue;
7178 }
7179
7180 String tagName = parser.getName();
7181 if (tagName.equals("disabled-components")) {
7182 readDisabledComponentsLP(packageSetting, parser);
7183 } else if (tagName.equals("enabled-components")) {
7184 readEnabledComponentsLP(packageSetting, parser);
7185 } else if (tagName.equals("sigs")) {
7186 packageSetting.signatures.readXml(parser, mPastSignatures);
7187 } else if (tagName.equals("perms")) {
7188 readGrantedPermissionsLP(parser,
7189 packageSetting.loadedPermissions);
7190 packageSetting.permissionsFixed = true;
7191 } else {
7192 reportSettingsProblem(Log.WARN,
7193 "Unknown element under <package>: "
7194 + parser.getName());
7195 XmlUtils.skipCurrentTag(parser);
7196 }
7197 }
7198 } else {
7199 XmlUtils.skipCurrentTag(parser);
7200 }
7201 }
7202
7203 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7204 XmlPullParser parser)
7205 throws IOException, XmlPullParserException {
7206 int outerDepth = parser.getDepth();
7207 int type;
7208 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7209 && (type != XmlPullParser.END_TAG
7210 || parser.getDepth() > outerDepth)) {
7211 if (type == XmlPullParser.END_TAG
7212 || type == XmlPullParser.TEXT) {
7213 continue;
7214 }
7215
7216 String tagName = parser.getName();
7217 if (tagName.equals("item")) {
7218 String name = parser.getAttributeValue(null, "name");
7219 if (name != null) {
7220 packageSetting.disabledComponents.add(name.intern());
7221 } else {
7222 reportSettingsProblem(Log.WARN,
7223 "Error in package manager settings: <disabled-components> has"
7224 + " no name at " + parser.getPositionDescription());
7225 }
7226 } else {
7227 reportSettingsProblem(Log.WARN,
7228 "Unknown element under <disabled-components>: "
7229 + parser.getName());
7230 }
7231 XmlUtils.skipCurrentTag(parser);
7232 }
7233 }
7234
7235 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
7236 XmlPullParser parser)
7237 throws IOException, XmlPullParserException {
7238 int outerDepth = parser.getDepth();
7239 int type;
7240 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7241 && (type != XmlPullParser.END_TAG
7242 || parser.getDepth() > outerDepth)) {
7243 if (type == XmlPullParser.END_TAG
7244 || type == XmlPullParser.TEXT) {
7245 continue;
7246 }
7247
7248 String tagName = parser.getName();
7249 if (tagName.equals("item")) {
7250 String name = parser.getAttributeValue(null, "name");
7251 if (name != null) {
7252 packageSetting.enabledComponents.add(name.intern());
7253 } else {
7254 reportSettingsProblem(Log.WARN,
7255 "Error in package manager settings: <enabled-components> has"
7256 + " no name at " + parser.getPositionDescription());
7257 }
7258 } else {
7259 reportSettingsProblem(Log.WARN,
7260 "Unknown element under <enabled-components>: "
7261 + parser.getName());
7262 }
7263 XmlUtils.skipCurrentTag(parser);
7264 }
7265 }
7266
7267 private void readSharedUserLP(XmlPullParser parser)
7268 throws XmlPullParserException, IOException {
7269 String name = null;
7270 String idStr = null;
7271 int pkgFlags = 0;
7272 SharedUserSetting su = null;
7273 try {
7274 name = parser.getAttributeValue(null, "name");
7275 idStr = parser.getAttributeValue(null, "userId");
7276 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7277 if ("true".equals(parser.getAttributeValue(null, "system"))) {
7278 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7279 }
7280 if (name == null) {
7281 reportSettingsProblem(Log.WARN,
7282 "Error in package manager settings: <shared-user> has no name at "
7283 + parser.getPositionDescription());
7284 } else if (userId == 0) {
7285 reportSettingsProblem(Log.WARN,
7286 "Error in package manager settings: shared-user "
7287 + name + " has bad userId " + idStr + " at "
7288 + parser.getPositionDescription());
7289 } else {
7290 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
7291 reportSettingsProblem(Log.ERROR,
7292 "Occurred while parsing settings at "
7293 + parser.getPositionDescription());
7294 }
7295 }
7296 } catch (NumberFormatException e) {
7297 reportSettingsProblem(Log.WARN,
7298 "Error in package manager settings: package "
7299 + name + " has bad userId " + idStr + " at "
7300 + parser.getPositionDescription());
7301 };
7302
7303 if (su != null) {
7304 int outerDepth = parser.getDepth();
7305 int type;
7306 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7307 && (type != XmlPullParser.END_TAG
7308 || parser.getDepth() > outerDepth)) {
7309 if (type == XmlPullParser.END_TAG
7310 || type == XmlPullParser.TEXT) {
7311 continue;
7312 }
7313
7314 String tagName = parser.getName();
7315 if (tagName.equals("sigs")) {
7316 su.signatures.readXml(parser, mPastSignatures);
7317 } else if (tagName.equals("perms")) {
7318 readGrantedPermissionsLP(parser, su.loadedPermissions);
7319 } else {
7320 reportSettingsProblem(Log.WARN,
7321 "Unknown element under <shared-user>: "
7322 + parser.getName());
7323 XmlUtils.skipCurrentTag(parser);
7324 }
7325 }
7326
7327 } else {
7328 XmlUtils.skipCurrentTag(parser);
7329 }
7330 }
7331
7332 private void readGrantedPermissionsLP(XmlPullParser parser,
7333 HashSet<String> outPerms) throws IOException, XmlPullParserException {
7334 int outerDepth = parser.getDepth();
7335 int type;
7336 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7337 && (type != XmlPullParser.END_TAG
7338 || parser.getDepth() > outerDepth)) {
7339 if (type == XmlPullParser.END_TAG
7340 || type == XmlPullParser.TEXT) {
7341 continue;
7342 }
7343
7344 String tagName = parser.getName();
7345 if (tagName.equals("item")) {
7346 String name = parser.getAttributeValue(null, "name");
7347 if (name != null) {
7348 outPerms.add(name.intern());
7349 } else {
7350 reportSettingsProblem(Log.WARN,
7351 "Error in package manager settings: <perms> has"
7352 + " no name at " + parser.getPositionDescription());
7353 }
7354 } else {
7355 reportSettingsProblem(Log.WARN,
7356 "Unknown element under <perms>: "
7357 + parser.getName());
7358 }
7359 XmlUtils.skipCurrentTag(parser);
7360 }
7361 }
7362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007363 private void readPreferredActivitiesLP(XmlPullParser parser)
7364 throws XmlPullParserException, IOException {
7365 int outerDepth = parser.getDepth();
7366 int type;
7367 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7368 && (type != XmlPullParser.END_TAG
7369 || parser.getDepth() > outerDepth)) {
7370 if (type == XmlPullParser.END_TAG
7371 || type == XmlPullParser.TEXT) {
7372 continue;
7373 }
7374
7375 String tagName = parser.getName();
7376 if (tagName.equals("item")) {
7377 PreferredActivity pa = new PreferredActivity(parser);
7378 if (pa.mParseError == null) {
7379 mPreferredActivities.addFilter(pa);
7380 } else {
7381 reportSettingsProblem(Log.WARN,
7382 "Error in package manager settings: <preferred-activity> "
7383 + pa.mParseError + " at "
7384 + parser.getPositionDescription());
7385 }
7386 } else {
7387 reportSettingsProblem(Log.WARN,
7388 "Unknown element under <preferred-activities>: "
7389 + parser.getName());
7390 XmlUtils.skipCurrentTag(parser);
7391 }
7392 }
7393 }
7394
7395 // Returns -1 if we could not find an available UserId to assign
7396 private int newUserIdLP(Object obj) {
7397 // Let's be stupidly inefficient for now...
7398 final int N = mUserIds.size();
7399 for (int i=0; i<N; i++) {
7400 if (mUserIds.get(i) == null) {
7401 mUserIds.set(i, obj);
7402 return FIRST_APPLICATION_UID + i;
7403 }
7404 }
7405
7406 // None left?
7407 if (N >= MAX_APPLICATION_UIDS) {
7408 return -1;
7409 }
7410
7411 mUserIds.add(obj);
7412 return FIRST_APPLICATION_UID + N;
7413 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 public PackageSetting getDisabledSystemPkg(String name) {
7416 synchronized(mPackages) {
7417 PackageSetting ps = mDisabledSysPackages.get(name);
7418 return ps;
7419 }
7420 }
7421
7422 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7423 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7424 if (Config.LOGV) {
7425 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7426 + " componentName = " + componentInfo.name);
7427 Log.v(TAG, "enabledComponents: "
7428 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7429 Log.v(TAG, "disabledComponents: "
7430 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7431 }
7432 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7433 || ((componentInfo.enabled
7434 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7435 || (componentInfo.applicationInfo.enabled
7436 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7437 && !packageSettings.disabledComponents.contains(componentInfo.name))
7438 || packageSettings.enabledComponents.contains(componentInfo.name));
7439 }
7440 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007441
7442 // ------- apps on sdcard specific code -------
7443 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08007444 final private String mSdEncryptKey = "AppsOnSD";
7445 final private String mSdEncryptAlg = "Blowfish";
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007446
7447 private MountService getMountService() {
7448 return (MountService) ServiceManager.getService("mount");
7449 }
7450
7451 private String createSdDir(File tmpPackageFile, String pkgName) {
7452 // Create mount point via MountService
7453 MountService mountService = getMountService();
7454 long len = tmpPackageFile.length();
7455 int mbLen = (int) (len/(1024*1024));
7456 if ((len - (mbLen * 1024 * 1024)) > 0) {
7457 mbLen++;
7458 }
7459 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
7460 String cachePath = null;
7461 // Remove any pending destroy messages
7462 mHandler.removeMessages(DESTROY_SD_CONTAINER, pkgName);
Oscar Montemayord02546b2010-01-14 16:38:40 -08007463 String sdEncKey;
7464 try {
7465 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
7466 if (sdEncKey == null) {
7467 sdEncKey = SystemKeyStore.getInstance().
7468 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
7469 if (sdEncKey == null) {
7470 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
7471 return null;
7472 }
7473 }
7474 } catch (NoSuchAlgorithmException nsae) {
7475 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
7476 return null;
7477 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007478 try {
7479 cachePath = mountService.createSecureContainer(pkgName,
7480 mbLen,
Oscar Montemayord02546b2010-01-14 16:38:40 -08007481 "vfat", sdEncKey, Process.SYSTEM_UID);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007482 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
7483 return cachePath;
7484 } catch(IllegalStateException e) {
7485 Log.e(TAG, "Failed to create storage on sdcard with exception: " + e);
7486 }
7487 // TODO just fail here and let the user delete later on.
7488 try {
7489 mountService.destroySecureContainer(pkgName);
7490 if (DEBUG_SD_INSTALL) Log.i(TAG, "Destroying cache for " + pkgName + ", cachePath =" + cachePath);
7491 } catch(IllegalStateException e) {
7492 Log.e(TAG, "Failed to destroy existing cache: " + e);
7493 return null;
7494 }
7495 try {
7496 cachePath = mountService.createSecureContainer(pkgName,
7497 mbLen,
Oscar Montemayord02546b2010-01-14 16:38:40 -08007498 "vfat", sdEncKey, Process.SYSTEM_UID);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007499 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install again " + pkgName + ", cachePath =" + cachePath);
7500 return cachePath;
7501 } catch(IllegalStateException e) {
7502 Log.e(TAG, "Failed to create storage on sdcard with exception: " + e);
7503 return null;
7504 }
7505 }
7506
7507 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08007508 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
7509 if (sdEncKey == null) {
7510 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
7511 return null;
7512 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007513 try {
Oscar Montemayord02546b2010-01-14 16:38:40 -08007514 return getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007515 } catch (IllegalStateException e) {
7516 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " exception : " + e);
7517 }
7518 return null;
7519 }
7520
7521 private String getSdDir(String pkgName) {
7522 String cachePath = null;
7523 try {
7524 cachePath = getMountService().getSecureContainerPath(pkgName);
7525 } catch (IllegalStateException e) {
7526 Log.e(TAG, "Failed to retrieve secure container path for pkg : " + pkgName + " with exception " + e);
7527 }
7528 return cachePath;
7529 }
7530
7531 private boolean finalizeSdDir(String pkgName) {
7532 try {
7533 getMountService().finalizeSecureContainer(pkgName);
7534 return true;
7535 } catch (IllegalStateException e) {
7536 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
7537 return false;
7538 }
7539 }
7540
7541 private boolean destroySdDir(String pkgName) {
7542 try {
7543 if (mHandler.hasMessages(DESTROY_SD_CONTAINER, pkgName)) {
7544 // Don't have to send message again
7545 mHandler.removeMessages(DESTROY_SD_CONTAINER, pkgName);
7546 }
7547 // We need to destroy right away
7548 getMountService().destroySecureContainer(pkgName);
7549 return true;
7550 } catch (IllegalStateException e) {
7551 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
7552 return false;
7553 }
7554 }
7555
7556 private void sendDelayedDestroySdDir(String pkgName) {
7557 if (mHandler.hasMessages(DESTROY_SD_CONTAINER, pkgName)) {
7558 // Don't have to send message again
7559 return;
7560 }
7561 Message msg = mHandler.obtainMessage(DESTROY_SD_CONTAINER, pkgName);
7562 mHandler.sendMessageDelayed(msg, DESTROY_SD_CONTAINER_DELAY);
7563 }
7564
7565 public void updateExternalMediaStatus(boolean mediaStatus) {
7566 // TODO
7567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568}