blob: 02b3666aace337b47e6d3dfd0a569243a2dbbe0f [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
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070023import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080024import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080033import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070038import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080039import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.ActivityInfo;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070044import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.IPackageDataObserver;
46import android.content.pm.IPackageDeleteObserver;
47import android.content.pm.IPackageInstallObserver;
48import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080049import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.pm.IPackageStatsObserver;
51import android.content.pm.InstrumentationInfo;
52import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080053import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.pm.PackageManager;
55import android.content.pm.PackageStats;
56import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.pm.PackageParser;
60import android.content.pm.PermissionInfo;
61import android.content.pm.PermissionGroupInfo;
62import android.content.pm.ProviderInfo;
63import android.content.pm.ResolveInfo;
64import android.content.pm.ServiceInfo;
65import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.Uri;
67import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070068import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080070import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080072import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070073import android.os.Looper;
74import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Parcel;
76import android.os.RemoteException;
77import android.os.Environment;
78import android.os.FileObserver;
79import android.os.FileUtils;
80import android.os.Handler;
81import android.os.ParcelFileDescriptor;
82import android.os.Process;
83import android.os.ServiceManager;
84import android.os.SystemClock;
85import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080086import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.util.*;
88import android.view.Display;
89import android.view.WindowManager;
90
91import java.io.File;
92import java.io.FileDescriptor;
93import java.io.FileInputStream;
94import java.io.FileNotFoundException;
95import java.io.FileOutputStream;
96import java.io.FileReader;
97import java.io.FilenameFilter;
98import java.io.IOException;
99import java.io.InputStream;
100import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800101import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800102import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.ArrayList;
104import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700105import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Collections;
107import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800108import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Enumeration;
110import java.util.HashMap;
111import java.util.HashSet;
112import java.util.Iterator;
113import java.util.List;
114import java.util.Map;
115import java.util.Set;
116import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800117import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.zip.ZipFile;
119import java.util.zip.ZipOutputStream;
120
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700121/**
122 * Keep track of all those .apks everywhere.
123 *
124 * This is very central to the platform's security; please run the unit
125 * tests whenever making modifications here:
126 *
127mmm frameworks/base/tests/AndroidTests
128adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
129adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
130 *
131 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132class PackageManagerService extends IPackageManager.Stub {
133 private static final String TAG = "PackageManager";
134 private static final boolean DEBUG_SETTINGS = false;
135 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800136 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800137 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
139 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
140 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400141 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private static final int FIRST_APPLICATION_UID =
143 Process.FIRST_APPLICATION_UID;
144 private static final int MAX_APPLICATION_UIDS = 1000;
145
146 private static final boolean SHOW_INFO = false;
147
148 private static final boolean GET_CERTIFICATES = true;
149
Oscar Montemayora8529f62009-11-18 10:14:20 -0800150 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private static final int REMOVE_EVENTS =
153 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
154 private static final int ADD_EVENTS =
155 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
156
157 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800158 // Suffix used during package installation when copying/moving
159 // package apks to install directory.
160 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800162 /**
163 * Indicates the state of installation. Used by PackageManager to
164 * figure out incomplete installations. Say a package is being installed
165 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
166 * the package installation is successful or unsuccesful lin which case
167 * the PackageManager will no longer maintain state information associated
168 * with the package. If some exception(like device freeze or battery being
169 * pulled out) occurs during installation of a package, the PackageManager
170 * needs this information to clean up the previously failed installation.
171 */
172 private static final int PKG_INSTALL_INCOMPLETE = 0;
173 private static final int PKG_INSTALL_COMPLETE = 1;
174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final int SCAN_MONITOR = 1<<0;
176 static final int SCAN_NO_DEX = 1<<1;
177 static final int SCAN_FORCE_DEX = 1<<2;
178 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800179 static final int SCAN_NEW_INSTALL = 1<<4;
180 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800182 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
183 "com.android.defcontainer",
184 "com.android.defcontainer.DefaultContainerService");
185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
187 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700188 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Dianne Hackborn851a5412009-05-08 12:06:44 -0700190 final int mSdkVersion = Build.VERSION.SDK_INT;
191 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
192 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 final Context mContext;
195 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700196 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final DisplayMetrics mMetrics;
198 final int mDefParseFlags;
199 final String[] mSeparateProcesses;
200
201 // This is where all application persistent data goes.
202 final File mAppDataDir;
203
Oscar Montemayora8529f62009-11-18 10:14:20 -0800204 // If Encrypted File System feature is enabled, all application persistent data
205 // should go here instead.
206 final File mSecureAppDataDir;
207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 // This is the object monitoring the framework dir.
209 final FileObserver mFrameworkInstallObserver;
210
211 // This is the object monitoring the system app dir.
212 final FileObserver mSystemInstallObserver;
213
214 // This is the object monitoring mAppInstallDir.
215 final FileObserver mAppInstallObserver;
216
217 // This is the object monitoring mDrmAppPrivateInstallDir.
218 final FileObserver mDrmAppInstallObserver;
219
220 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
221 // LOCK HELD. Can be called with mInstallLock held.
222 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 final File mFrameworkDir;
225 final File mSystemAppDir;
226 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700227 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
229 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
230 // apps.
231 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 // Lock for state used when installing and doing other long running
236 // operations. Methods that must be called with this lock held have
237 // the prefix "LI".
238 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // These are the directories in the 3rd party applications installed dir
241 // that we have currently loaded packages from. Keys are the application's
242 // installed zip file (absolute codePath), and values are Package.
243 final HashMap<String, PackageParser.Package> mAppDirs =
244 new HashMap<String, PackageParser.Package>();
245
246 // Information for the parser to write more useful error messages.
247 File mScanningPath;
248 int mLastScanError;
249
250 final int[] mOutPermissions = new int[3];
251
252 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // Keys are String (package name), values are Package. This also serves
255 // as the lock for the global state. Methods that must be called with
256 // this lock held have the prefix "LP".
257 final HashMap<String, PackageParser.Package> mPackages =
258 new HashMap<String, PackageParser.Package>();
259
260 final Settings mSettings;
261 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
263 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
264 int[] mGlobalGids;
265
266 // These are the built-in uid -> permission mappings that were read from the
267 // etc/permissions.xml file.
268 final SparseArray<HashSet<String>> mSystemPermissions =
269 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 // These are the built-in shared libraries that were read from the
272 // etc/permissions.xml file.
273 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800274
Dianne Hackborn49237342009-08-27 20:08:01 -0700275 // Temporary for building the final shared libraries for an .apk.
276 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800277
Dianne Hackborn49237342009-08-27 20:08:01 -0700278 // These are the features this devices supports that were read from the
279 // etc/permissions.xml file.
280 final HashMap<String, FeatureInfo> mAvailableFeatures =
281 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 // All available activities, for your resolving pleasure.
284 final ActivityIntentResolver mActivities =
285 new ActivityIntentResolver();
286
287 // All available receivers, for your resolving pleasure.
288 final ActivityIntentResolver mReceivers =
289 new ActivityIntentResolver();
290
291 // All available services, for your resolving pleasure.
292 final ServiceIntentResolver mServices = new ServiceIntentResolver();
293
294 // Keys are String (provider class name), values are Provider.
295 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
296 new HashMap<ComponentName, PackageParser.Provider>();
297
298 // Mapping from provider base names (first directory in content URI codePath)
299 // to the provider information.
300 final HashMap<String, PackageParser.Provider> mProviders =
301 new HashMap<String, PackageParser.Provider>();
302
303 // Mapping from instrumentation class names to info about them.
304 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
305 new HashMap<ComponentName, PackageParser.Instrumentation>();
306
307 // Mapping from permission names to info about them.
308 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
309 new HashMap<String, PackageParser.PermissionGroup>();
310
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800311 // Packages whose data we have transfered into another package, thus
312 // should no longer exist.
313 final HashSet<String> mTransferedPackages = new HashSet<String>();
314
Dianne Hackborn854060af2009-07-09 18:14:31 -0700315 // Broadcast actions that are only available to the system.
316 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 boolean mSystemReady;
319 boolean mSafeMode;
320 boolean mHasSystemUidErrors;
321
322 ApplicationInfo mAndroidApplication;
323 final ActivityInfo mResolveActivity = new ActivityInfo();
324 final ResolveInfo mResolveInfo = new ResolveInfo();
325 ComponentName mResolveComponentName;
326 PackageParser.Package mPlatformPackage;
327
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700328 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800329 final HashMap<String, ArrayList<String>> mPendingBroadcasts
330 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800331 // Service Connection to remote media container service to copy
332 // package uri's from external media onto secure containers
333 // or internal storage.
334 private IMediaContainerService mContainerService = null;
335
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700336 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800337 static final int MCS_BOUND = 3;
338 static final int END_COPY = 4;
339 static final int INIT_COPY = 5;
340 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800341 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800342 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800343 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800344 static final int MCS_RECONNECT = 10;
345 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700346 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700347 static final int WRITE_SETTINGS = 13;
348
349 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800350
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700351 // Delay time in millisecs
352 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800353 final private DefaultContainerConnection mDefContainerConn =
354 new DefaultContainerConnection();
355 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800356 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800357 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800358 IMediaContainerService imcs =
359 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800360 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800361 }
362
363 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800364 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800365 }
366 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700367
Christopher Tate1bb69062010-02-19 17:02:12 -0800368 // Recordkeeping of restore-after-install operations that are currently in flight
369 // between the Package Manager and the Backup Manager
370 class PostInstallData {
371 public InstallArgs args;
372 public PackageInstalledInfo res;
373
374 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
375 args = _a;
376 res = _r;
377 }
378 };
379 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
380 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
381
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700382 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800383 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800384 final ArrayList<HandlerParams> mPendingInstalls =
385 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800386
387 private boolean connectToService() {
388 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
389 " DefaultContainerService");
390 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700391 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800392 if (mContext.bindService(service, mDefContainerConn,
393 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700394 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800395 mBound = true;
396 return true;
397 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700398 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800399 return false;
400 }
401
402 private void disconnectService() {
403 mContainerService = null;
404 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700405 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700407 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800408 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800409
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700410 PackageHandler(Looper looper) {
411 super(looper);
412 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700413
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700414 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700415 try {
416 doHandleMessage(msg);
417 } finally {
418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
419 }
420 }
421
422 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700423 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800424 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800425 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800426 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800427 int idx = mPendingInstalls.size();
428 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
429 // If a bind was already initiated we dont really
430 // need to do anything. The pending install
431 // will be processed later on.
432 if (!mBound) {
433 // If this is the only one pending we might
434 // have to bind to the service again.
435 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800436 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800437 params.serviceError();
438 return;
439 } else {
440 // Once we bind to the service, the first
441 // pending request will be processed.
442 mPendingInstalls.add(idx, params);
443 }
444 } else {
445 mPendingInstalls.add(idx, params);
446 // Already bound to the service. Just make
447 // sure we trigger off processing the first request.
448 if (idx == 0) {
449 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800450 }
451 }
452 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800453 }
454 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800455 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800456 if (msg.obj != null) {
457 mContainerService = (IMediaContainerService) msg.obj;
458 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800459 if (mContainerService == null) {
460 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800461 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800462 for (HandlerParams params : mPendingInstalls) {
463 mPendingInstalls.remove(0);
464 // Indicate service bind error
465 params.serviceError();
466 }
467 mPendingInstalls.clear();
468 } else if (mPendingInstalls.size() > 0) {
469 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800470 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800471 params.startCopy();
472 }
473 } else {
474 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800475 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800476 }
477 break;
478 }
479 case MCS_RECONNECT : {
480 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
481 if (mPendingInstalls.size() > 0) {
482 if (mBound) {
483 disconnectService();
484 }
485 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800486 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 for (HandlerParams params : mPendingInstalls) {
488 mPendingInstalls.remove(0);
489 // Indicate service bind error
490 params.serviceError();
491 }
492 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800493 }
494 }
495 break;
496 }
497 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800498 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
499 // Delete pending install
500 if (mPendingInstalls.size() > 0) {
501 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800502 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800503 if (mPendingInstalls.size() == 0) {
504 if (mBound) {
505 disconnectService();
506 }
507 } else {
508 // There are more pending requests in queue.
509 // Just post MCS_BOUND message to trigger processing
510 // of next pending install.
511 mHandler.sendEmptyMessage(MCS_BOUND);
512 }
513 break;
514 }
515 case MCS_GIVE_UP: {
516 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
517 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800518 break;
519 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700520 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800521 String packages[];
522 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700523 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700524 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700525 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700526 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800527 if (mPendingBroadcasts == null) {
528 return;
529 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700530 size = mPendingBroadcasts.size();
531 if (size <= 0) {
532 // Nothing to be done. Just return
533 return;
534 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800535 packages = new String[size];
536 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800538 Iterator<HashMap.Entry<String, ArrayList<String>>>
539 it = mPendingBroadcasts.entrySet().iterator();
540 int i = 0;
541 while (it.hasNext() && i < size) {
542 HashMap.Entry<String, ArrayList<String>> ent = it.next();
543 packages[i] = ent.getKey();
544 components[i] = ent.getValue();
545 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700546 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800547 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700548 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800549 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700550 mPendingBroadcasts.clear();
551 }
552 // Send broadcasts
553 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 sendPackageChangedBroadcast(packages[i], true,
555 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700556 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700557 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700558 break;
559 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800560 case START_CLEANING_PACKAGE: {
561 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700562 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800563 synchronized (mPackages) {
564 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
565 mSettings.mPackagesToBeCleaned.add(packageName);
566 }
567 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800569 startCleaningPackages();
570 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800571 case POST_INSTALL: {
572 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
573 PostInstallData data = mRunningInstalls.get(msg.arg1);
574 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800575 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800576
577 if (data != null) {
578 InstallArgs args = data.args;
579 PackageInstalledInfo res = data.res;
580
581 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
582 res.removedInfo.sendBroadcast(false, true);
583 Bundle extras = new Bundle(1);
584 extras.putInt(Intent.EXTRA_UID, res.uid);
585 final boolean update = res.removedInfo.removedPackage != null;
586 if (update) {
587 extras.putBoolean(Intent.EXTRA_REPLACING, true);
588 }
589 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
590 res.pkg.applicationInfo.packageName,
591 extras);
592 if (update) {
593 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
594 res.pkg.applicationInfo.packageName,
595 extras);
596 }
597 if (res.removedInfo.args != null) {
598 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800599 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800600 }
601 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800602 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800603 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800604 // We delete after a gc for applications on sdcard.
605 if (deleteOld) {
606 synchronized (mInstallLock) {
607 res.removedInfo.args.doPostDeleteLI(true);
608 }
609 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800610 if (args.observer != null) {
611 try {
612 args.observer.packageInstalled(res.name, res.returnCode);
613 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800614 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800615 }
616 }
617 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800618 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800619 }
620 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700621 case UPDATED_MEDIA_STATUS: {
622 try {
623 PackageHelper.getMountService().finishMediaUpdate();
624 } catch (RemoteException e) {
625 Log.e(TAG, "MountService not running?");
626 }
627 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700628 case WRITE_SETTINGS: {
629 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
630 synchronized (mPackages) {
631 removeMessages(WRITE_SETTINGS);
632 mSettings.writeLP();
633 }
634 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
635 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700636 }
637 }
638 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800639
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700640 void scheduleWriteSettingsLocked() {
641 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
642 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
643 }
644 }
645
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800646 static boolean installOnSd(int flags) {
647 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700648 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800649 return false;
650 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700651 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
652 return true;
653 }
654 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800655 }
656
657 static boolean isFwdLocked(int flags) {
658 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
659 return true;
660 }
661 return false;
662 }
663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 public static final IPackageManager main(Context context, boolean factoryTest) {
665 PackageManagerService m = new PackageManagerService(context, factoryTest);
666 ServiceManager.addService("package", m);
667 return m;
668 }
669
670 static String[] splitString(String str, char sep) {
671 int count = 1;
672 int i = 0;
673 while ((i=str.indexOf(sep, i)) >= 0) {
674 count++;
675 i++;
676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 String[] res = new String[count];
679 i=0;
680 count = 0;
681 int lastI=0;
682 while ((i=str.indexOf(sep, i)) >= 0) {
683 res[count] = str.substring(lastI, i);
684 count++;
685 i++;
686 lastI = i;
687 }
688 res[count] = str.substring(lastI, str.length());
689 return res;
690 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800693 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800697 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 mContext = context;
701 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700702 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 mMetrics = new DisplayMetrics();
704 mSettings = new Settings();
705 mSettings.addSharedUserLP("android.uid.system",
706 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
707 mSettings.addSharedUserLP("android.uid.phone",
708 MULTIPLE_APPLICATION_UIDS
709 ? RADIO_UID : FIRST_APPLICATION_UID,
710 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400711 mSettings.addSharedUserLP("android.uid.log",
712 MULTIPLE_APPLICATION_UIDS
713 ? LOG_UID : FIRST_APPLICATION_UID,
714 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715
716 String separateProcesses = SystemProperties.get("debug.separate_processes");
717 if (separateProcesses != null && separateProcesses.length() > 0) {
718 if ("*".equals(separateProcesses)) {
719 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
720 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800721 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 } else {
723 mDefParseFlags = 0;
724 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800725 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 + separateProcesses);
727 }
728 } else {
729 mDefParseFlags = 0;
730 mSeparateProcesses = null;
731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 Installer installer = new Installer();
734 // Little hacky thing to check if installd is here, to determine
735 // whether we are running on the simulator and thus need to take
736 // care of building the /data file structure ourself.
737 // (apparently the sim now has a working installer)
738 if (installer.ping() && Process.supportsProcesses()) {
739 mInstaller = installer;
740 } else {
741 mInstaller = null;
742 }
743
744 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
745 Display d = wm.getDefaultDisplay();
746 d.getMetrics(mMetrics);
747
748 synchronized (mInstallLock) {
749 synchronized (mPackages) {
750 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700751 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 File dataDir = Environment.getDataDirectory();
754 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800755 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
757
758 if (mInstaller == null) {
759 // Make sure these dirs exist, when we are running in
760 // the simulator.
761 // Make a wide-open directory for random misc stuff.
762 File miscDir = new File(dataDir, "misc");
763 miscDir.mkdirs();
764 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800765 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 mDrmAppPrivateInstallDir.mkdirs();
767 }
768
769 readPermissions();
770
771 mRestoredSettings = mSettings.readLP();
772 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773
774 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800776
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800777 // Set flag to monitor and not change apk file paths when
778 // scanning install directories.
779 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700780 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800781 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800782 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700788 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700791 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 /**
794 * Out of paranoia, ensure that everything in the boot class
795 * path has been dexed.
796 */
797 String bootClassPath = System.getProperty("java.boot.class.path");
798 if (bootClassPath != null) {
799 String[] paths = splitString(bootClassPath, ':');
800 for (int i=0; i<paths.length; i++) {
801 try {
802 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
803 libFiles.add(paths[i]);
804 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700805 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 }
807 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800808 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800810 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 }
812 }
813 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800814 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 /**
818 * Also ensure all external libraries have had dexopt run on them.
819 */
820 if (mSharedLibraries.size() > 0) {
821 Iterator<String> libs = mSharedLibraries.values().iterator();
822 while (libs.hasNext()) {
823 String lib = libs.next();
824 try {
825 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
826 libFiles.add(lib);
827 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700828 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 }
830 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800831 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800833 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835 }
836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 // Gross hack for now: we know this file doesn't contain any
839 // code, so don't dexopt it to avoid the resulting log spew.
840 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 /**
843 * And there are a number of commands implemented in Java, which
844 * we currently need to do the dexopt on so that they can be
845 * run from a non-root shell.
846 */
847 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700848 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 for (int i=0; i<frameworkFiles.length; i++) {
850 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
851 String path = libPath.getPath();
852 // Skip the file if we alrady did it.
853 if (libFiles.contains(path)) {
854 continue;
855 }
856 // Skip the file if it is not a type we want to dexopt.
857 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
858 continue;
859 }
860 try {
861 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
862 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700863 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 }
865 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800866 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800868 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 }
870 }
871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800872
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700873 if (didDexOpt) {
874 // If we had to do a dexopt of one of the previous
875 // things, then something on the system has changed.
876 // Consider this significant, and wipe away all other
877 // existing dexopt files to ensure we don't leave any
878 // dangling around.
879 String[] files = mDalvikCacheDir.list();
880 if (files != null) {
881 for (int i=0; i<files.length; i++) {
882 String fn = files[i];
883 if (fn.startsWith("data@app@")
884 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800885 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700886 (new File(mDalvikCacheDir, fn)).delete();
887 }
888 }
889 }
890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800892
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800893 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 mFrameworkInstallObserver = new AppDirObserver(
895 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
896 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700897 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
898 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800899 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800900
901 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
903 mSystemInstallObserver = new AppDirObserver(
904 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
905 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700906 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
907 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800908
909 if (mInstaller != null) {
910 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
911 mInstaller.moveFiles();
912 }
913
914 // Prune any system packages that no longer exist.
915 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
916 while (psit.hasNext()) {
917 PackageSetting ps = psit.next();
918 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800919 && !mPackages.containsKey(ps.name)
920 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800921 psit.remove();
922 String msg = "System package " + ps.name
923 + " no longer exists; wiping its data";
924 reportSettingsProblem(Log.WARN, msg);
925 if (mInstaller != null) {
926 // XXX how to set useEncryptedFSDir for packages that
927 // are not encrypted?
928 mInstaller.remove(ps.name, true);
929 }
930 }
931 }
932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 mAppInstallDir = new File(dataDir, "app");
934 if (mInstaller == null) {
935 // Make sure these dirs exist, when we are running in
936 // the simulator.
937 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
938 }
939 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800940 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 //clean up list
942 for(int i = 0; i < deletePkgsList.size(); i++) {
943 //clean up here
944 cleanupInstallFailedPackage(deletePkgsList.get(i));
945 }
946 //delete tmp files
947 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800948
949 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 SystemClock.uptimeMillis());
951 mAppInstallObserver = new AppDirObserver(
952 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
953 mAppInstallObserver.startWatching();
954 scanDirLI(mAppInstallDir, 0, scanMode);
955
956 mDrmAppInstallObserver = new AppDirObserver(
957 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
958 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800959 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800961 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800963 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 + ((SystemClock.uptimeMillis()-startTime)/1000f)
965 + " seconds");
966
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700967 updatePermissionsLP(null, null, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968
969 mSettings.writeLP();
970
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800971 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 // Now after opening every single application zip, make sure they
975 // are all flushed. Not really needed, but keeps things nice and
976 // tidy.
977 Runtime.getRuntime().gc();
978 } // synchronized (mPackages)
979 } // synchronized (mInstallLock)
980 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 @Override
983 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
984 throws RemoteException {
985 try {
986 return super.onTransact(code, data, reply, flags);
987 } catch (RuntimeException e) {
988 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800989 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
991 throw e;
992 }
993 }
994
Dianne Hackborne6620b22010-01-22 14:46:21 -0800995 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800996 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800998 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
999 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001001 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001002 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 }
1004 } else {
1005 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001006 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 File dataDir = new File(pkg.applicationInfo.dataDir);
1008 dataDir.delete();
1009 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001010 if (ps.codePath != null) {
1011 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001012 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001013 }
1014 }
1015 if (ps.resourcePath != null) {
1016 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001017 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001018 }
1019 }
1020 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
1022
1023 void readPermissions() {
1024 // Read permissions from .../etc/permission directory.
1025 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1026 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001027 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 return;
1029 }
1030 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001031 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 return;
1033 }
1034
1035 // Iterate over the files in the directory and scan .xml files
1036 for (File f : libraryDir.listFiles()) {
1037 // We'll read platform.xml last
1038 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1039 continue;
1040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001043 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 continue;
1045 }
1046 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001047 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 continue;
1049 }
1050
1051 readPermissionsFromXml(f);
1052 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1055 final File permFile = new File(Environment.getRootDirectory(),
1056 "etc/permissions/platform.xml");
1057 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001058
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001059 StringBuilder sb = new StringBuilder(128);
1060 sb.append("Libs:");
1061 Iterator<String> it = mSharedLibraries.keySet().iterator();
1062 while (it.hasNext()) {
1063 sb.append(' ');
1064 String name = it.next();
1065 sb.append(name);
1066 sb.append(':');
1067 sb.append(mSharedLibraries.get(name));
1068 }
1069 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001070
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001071 sb.setLength(0);
1072 sb.append("Features:");
1073 it = mAvailableFeatures.keySet().iterator();
1074 while (it.hasNext()) {
1075 sb.append(' ');
1076 sb.append(it.next());
1077 }
1078 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001080
1081 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 FileReader permReader = null;
1083 try {
1084 permReader = new FileReader(permFile);
1085 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001086 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 return;
1088 }
1089
1090 try {
1091 XmlPullParser parser = Xml.newPullParser();
1092 parser.setInput(permReader);
1093
1094 XmlUtils.beginDocument(parser, "permissions");
1095
1096 while (true) {
1097 XmlUtils.nextElement(parser);
1098 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1099 break;
1100 }
1101
1102 String name = parser.getName();
1103 if ("group".equals(name)) {
1104 String gidStr = parser.getAttributeValue(null, "gid");
1105 if (gidStr != null) {
1106 int gid = Integer.parseInt(gidStr);
1107 mGlobalGids = appendInt(mGlobalGids, gid);
1108 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001109 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 + parser.getPositionDescription());
1111 }
1112
1113 XmlUtils.skipCurrentTag(parser);
1114 continue;
1115 } else if ("permission".equals(name)) {
1116 String perm = parser.getAttributeValue(null, "name");
1117 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001118 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 + parser.getPositionDescription());
1120 XmlUtils.skipCurrentTag(parser);
1121 continue;
1122 }
1123 perm = perm.intern();
1124 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 } else if ("assign-permission".equals(name)) {
1127 String perm = parser.getAttributeValue(null, "name");
1128 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001129 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 + parser.getPositionDescription());
1131 XmlUtils.skipCurrentTag(parser);
1132 continue;
1133 }
1134 String uidStr = parser.getAttributeValue(null, "uid");
1135 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001136 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 + parser.getPositionDescription());
1138 XmlUtils.skipCurrentTag(parser);
1139 continue;
1140 }
1141 int uid = Process.getUidForName(uidStr);
1142 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + uidStr + "\" at "
1145 + parser.getPositionDescription());
1146 XmlUtils.skipCurrentTag(parser);
1147 continue;
1148 }
1149 perm = perm.intern();
1150 HashSet<String> perms = mSystemPermissions.get(uid);
1151 if (perms == null) {
1152 perms = new HashSet<String>();
1153 mSystemPermissions.put(uid, perms);
1154 }
1155 perms.add(perm);
1156 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 } else if ("library".equals(name)) {
1159 String lname = parser.getAttributeValue(null, "name");
1160 String lfile = parser.getAttributeValue(null, "file");
1161 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001162 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 + parser.getPositionDescription());
1164 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001165 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 + parser.getPositionDescription());
1167 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001168 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001169 mSharedLibraries.put(lname, lfile);
1170 }
1171 XmlUtils.skipCurrentTag(parser);
1172 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001173
Dianne Hackborn49237342009-08-27 20:08:01 -07001174 } else if ("feature".equals(name)) {
1175 String fname = parser.getAttributeValue(null, "name");
1176 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001178 + parser.getPositionDescription());
1179 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001180 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001181 FeatureInfo fi = new FeatureInfo();
1182 fi.name = fname;
1183 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185 XmlUtils.skipCurrentTag(parser);
1186 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 } else {
1189 XmlUtils.skipCurrentTag(parser);
1190 continue;
1191 }
1192
1193 }
1194 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001195 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001197 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
1199 }
1200
1201 void readPermission(XmlPullParser parser, String name)
1202 throws IOException, XmlPullParserException {
1203
1204 name = name.intern();
1205
1206 BasePermission bp = mSettings.mPermissions.get(name);
1207 if (bp == null) {
1208 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1209 mSettings.mPermissions.put(name, bp);
1210 }
1211 int outerDepth = parser.getDepth();
1212 int type;
1213 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1214 && (type != XmlPullParser.END_TAG
1215 || parser.getDepth() > outerDepth)) {
1216 if (type == XmlPullParser.END_TAG
1217 || type == XmlPullParser.TEXT) {
1218 continue;
1219 }
1220
1221 String tagName = parser.getName();
1222 if ("group".equals(tagName)) {
1223 String gidStr = parser.getAttributeValue(null, "gid");
1224 if (gidStr != null) {
1225 int gid = Process.getGidForName(gidStr);
1226 bp.gids = appendInt(bp.gids, gid);
1227 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001228 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 + parser.getPositionDescription());
1230 }
1231 }
1232 XmlUtils.skipCurrentTag(parser);
1233 }
1234 }
1235
1236 static int[] appendInt(int[] cur, int val) {
1237 if (cur == null) {
1238 return new int[] { val };
1239 }
1240 final int N = cur.length;
1241 for (int i=0; i<N; i++) {
1242 if (cur[i] == val) {
1243 return cur;
1244 }
1245 }
1246 int[] ret = new int[N+1];
1247 System.arraycopy(cur, 0, ret, 0, N);
1248 ret[N] = val;
1249 return ret;
1250 }
1251
1252 static int[] appendInts(int[] cur, int[] add) {
1253 if (add == null) return cur;
1254 if (cur == null) return add;
1255 final int N = add.length;
1256 for (int i=0; i<N; i++) {
1257 cur = appendInt(cur, add[i]);
1258 }
1259 return cur;
1260 }
1261
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001262 static int[] removeInt(int[] cur, int val) {
1263 if (cur == null) {
1264 return null;
1265 }
1266 final int N = cur.length;
1267 for (int i=0; i<N; i++) {
1268 if (cur[i] == val) {
1269 int[] ret = new int[N-1];
1270 if (i > 0) {
1271 System.arraycopy(cur, 0, ret, 0, i);
1272 }
1273 if (i < (N-1)) {
1274 System.arraycopy(cur, i, ret, i+1, N-i-1);
1275 }
1276 return ret;
1277 }
1278 }
1279 return cur;
1280 }
1281
1282 static int[] removeInts(int[] cur, int[] rem) {
1283 if (rem == null) return cur;
1284 if (cur == null) return cur;
1285 final int N = rem.length;
1286 for (int i=0; i<N; i++) {
1287 cur = removeInt(cur, rem[i]);
1288 }
1289 return cur;
1290 }
1291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001293 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1294 // The package has been uninstalled but has retained data and resources.
1295 return PackageParser.generatePackageInfo(p, null, flags);
1296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 final PackageSetting ps = (PackageSetting)p.mExtras;
1298 if (ps == null) {
1299 return null;
1300 }
1301 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1302 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1303 }
1304
1305 public PackageInfo getPackageInfo(String packageName, int flags) {
1306 synchronized (mPackages) {
1307 PackageParser.Package p = mPackages.get(packageName);
1308 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001309 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 + ": " + p);
1311 if (p != null) {
1312 return generatePackageInfo(p, flags);
1313 }
1314 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1315 return generatePackageInfoFromSettingsLP(packageName, flags);
1316 }
1317 }
1318 return null;
1319 }
1320
Dianne Hackborn47096932010-02-11 15:57:09 -08001321 public String[] currentToCanonicalPackageNames(String[] names) {
1322 String[] out = new String[names.length];
1323 synchronized (mPackages) {
1324 for (int i=names.length-1; i>=0; i--) {
1325 PackageSetting ps = mSettings.mPackages.get(names[i]);
1326 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1327 }
1328 }
1329 return out;
1330 }
1331
1332 public String[] canonicalToCurrentPackageNames(String[] names) {
1333 String[] out = new String[names.length];
1334 synchronized (mPackages) {
1335 for (int i=names.length-1; i>=0; i--) {
1336 String cur = mSettings.mRenamedPackages.get(names[i]);
1337 out[i] = cur != null ? cur : names[i];
1338 }
1339 }
1340 return out;
1341 }
1342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 public int getPackageUid(String packageName) {
1344 synchronized (mPackages) {
1345 PackageParser.Package p = mPackages.get(packageName);
1346 if(p != null) {
1347 return p.applicationInfo.uid;
1348 }
1349 PackageSetting ps = mSettings.mPackages.get(packageName);
1350 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1351 return -1;
1352 }
1353 p = ps.pkg;
1354 return p != null ? p.applicationInfo.uid : -1;
1355 }
1356 }
1357
1358 public int[] getPackageGids(String packageName) {
1359 synchronized (mPackages) {
1360 PackageParser.Package p = mPackages.get(packageName);
1361 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001362 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 + ": " + p);
1364 if (p != null) {
1365 final PackageSetting ps = (PackageSetting)p.mExtras;
1366 final SharedUserSetting suid = ps.sharedUser;
1367 return suid != null ? suid.gids : ps.gids;
1368 }
1369 }
1370 // stupid thing to indicate an error.
1371 return new int[0];
1372 }
1373
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001374 static final PermissionInfo generatePermissionInfo(
1375 BasePermission bp, int flags) {
1376 if (bp.perm != null) {
1377 return PackageParser.generatePermissionInfo(bp.perm, flags);
1378 }
1379 PermissionInfo pi = new PermissionInfo();
1380 pi.name = bp.name;
1381 pi.packageName = bp.sourcePackage;
1382 pi.nonLocalizedLabel = bp.name;
1383 pi.protectionLevel = bp.protectionLevel;
1384 return pi;
1385 }
1386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 public PermissionInfo getPermissionInfo(String name, int flags) {
1388 synchronized (mPackages) {
1389 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001390 if (p != null) {
1391 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
1393 return null;
1394 }
1395 }
1396
1397 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1398 synchronized (mPackages) {
1399 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1400 for (BasePermission p : mSettings.mPermissions.values()) {
1401 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001402 if (p.perm == null || p.perm.info.group == null) {
1403 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
1405 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001406 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1408 }
1409 }
1410 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 if (out.size() > 0) {
1413 return out;
1414 }
1415 return mPermissionGroups.containsKey(group) ? out : null;
1416 }
1417 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1420 synchronized (mPackages) {
1421 return PackageParser.generatePermissionGroupInfo(
1422 mPermissionGroups.get(name), flags);
1423 }
1424 }
1425
1426 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1427 synchronized (mPackages) {
1428 final int N = mPermissionGroups.size();
1429 ArrayList<PermissionGroupInfo> out
1430 = new ArrayList<PermissionGroupInfo>(N);
1431 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1432 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1433 }
1434 return out;
1435 }
1436 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1439 PackageSetting ps = mSettings.mPackages.get(packageName);
1440 if(ps != null) {
1441 if(ps.pkg == null) {
1442 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1443 if(pInfo != null) {
1444 return pInfo.applicationInfo;
1445 }
1446 return null;
1447 }
1448 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1449 }
1450 return null;
1451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1454 PackageSetting ps = mSettings.mPackages.get(packageName);
1455 if(ps != null) {
1456 if(ps.pkg == null) {
1457 ps.pkg = new PackageParser.Package(packageName);
1458 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001459 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1460 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1461 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1462 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
1464 return generatePackageInfo(ps.pkg, flags);
1465 }
1466 return null;
1467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1470 synchronized (mPackages) {
1471 PackageParser.Package p = mPackages.get(packageName);
1472 if (Config.LOGV) Log.v(
1473 TAG, "getApplicationInfo " + packageName
1474 + ": " + p);
1475 if (p != null) {
1476 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001477 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
1479 if ("android".equals(packageName)||"system".equals(packageName)) {
1480 return mAndroidApplication;
1481 }
1482 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1483 return generateApplicationInfoFromSettingsLP(packageName, flags);
1484 }
1485 }
1486 return null;
1487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001488
1489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1491 mContext.enforceCallingOrSelfPermission(
1492 android.Manifest.permission.CLEAR_APP_CACHE, null);
1493 // Queue up an async operation since clearing cache may take a little while.
1494 mHandler.post(new Runnable() {
1495 public void run() {
1496 mHandler.removeCallbacks(this);
1497 int retCode = -1;
1498 if (mInstaller != null) {
1499 retCode = mInstaller.freeCache(freeStorageSize);
1500 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001501 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
1503 } //end if mInstaller
1504 if (observer != null) {
1505 try {
1506 observer.onRemoveCompleted(null, (retCode >= 0));
1507 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001508 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 }
1510 }
1511 }
1512 });
1513 }
1514
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001515 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001516 mContext.enforceCallingOrSelfPermission(
1517 android.Manifest.permission.CLEAR_APP_CACHE, null);
1518 // Queue up an async operation since clearing cache may take a little while.
1519 mHandler.post(new Runnable() {
1520 public void run() {
1521 mHandler.removeCallbacks(this);
1522 int retCode = -1;
1523 if (mInstaller != null) {
1524 retCode = mInstaller.freeCache(freeStorageSize);
1525 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001526 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001527 }
1528 }
1529 if(pi != null) {
1530 try {
1531 // Callback via pending intent
1532 int code = (retCode >= 0) ? 1 : 0;
1533 pi.sendIntent(null, code, null,
1534 null, null);
1535 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001536 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001537 }
1538 }
1539 }
1540 });
1541 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1544 synchronized (mPackages) {
1545 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001546
1547 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001549 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551 if (mResolveComponentName.equals(component)) {
1552 return mResolveActivity;
1553 }
1554 }
1555 return null;
1556 }
1557
1558 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1559 synchronized (mPackages) {
1560 PackageParser.Activity a = mReceivers.mActivities.get(component);
1561 if (Config.LOGV) Log.v(
1562 TAG, "getReceiverInfo " + component + ": " + a);
1563 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1564 return PackageParser.generateActivityInfo(a, flags);
1565 }
1566 }
1567 return null;
1568 }
1569
1570 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1571 synchronized (mPackages) {
1572 PackageParser.Service s = mServices.mServices.get(component);
1573 if (Config.LOGV) Log.v(
1574 TAG, "getServiceInfo " + component + ": " + s);
1575 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1576 return PackageParser.generateServiceInfo(s, flags);
1577 }
1578 }
1579 return null;
1580 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 public String[] getSystemSharedLibraryNames() {
1583 Set<String> libSet;
1584 synchronized (mPackages) {
1585 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001586 int size = libSet.size();
1587 if (size > 0) {
1588 String[] libs = new String[size];
1589 libSet.toArray(libs);
1590 return libs;
1591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001593 return null;
1594 }
1595
1596 public FeatureInfo[] getSystemAvailableFeatures() {
1597 Collection<FeatureInfo> featSet;
1598 synchronized (mPackages) {
1599 featSet = mAvailableFeatures.values();
1600 int size = featSet.size();
1601 if (size > 0) {
1602 FeatureInfo[] features = new FeatureInfo[size+1];
1603 featSet.toArray(features);
1604 FeatureInfo fi = new FeatureInfo();
1605 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1606 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1607 features[size] = fi;
1608 return features;
1609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
1611 return null;
1612 }
1613
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001614 public boolean hasSystemFeature(String name) {
1615 synchronized (mPackages) {
1616 return mAvailableFeatures.containsKey(name);
1617 }
1618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 public int checkPermission(String permName, String pkgName) {
1621 synchronized (mPackages) {
1622 PackageParser.Package p = mPackages.get(pkgName);
1623 if (p != null && p.mExtras != null) {
1624 PackageSetting ps = (PackageSetting)p.mExtras;
1625 if (ps.sharedUser != null) {
1626 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1627 return PackageManager.PERMISSION_GRANTED;
1628 }
1629 } else if (ps.grantedPermissions.contains(permName)) {
1630 return PackageManager.PERMISSION_GRANTED;
1631 }
1632 }
1633 }
1634 return PackageManager.PERMISSION_DENIED;
1635 }
1636
1637 public int checkUidPermission(String permName, int uid) {
1638 synchronized (mPackages) {
1639 Object obj = mSettings.getUserIdLP(uid);
1640 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001641 GrantedPermissions gp = (GrantedPermissions)obj;
1642 if (gp.grantedPermissions.contains(permName)) {
1643 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 } else {
1646 HashSet<String> perms = mSystemPermissions.get(uid);
1647 if (perms != null && perms.contains(permName)) {
1648 return PackageManager.PERMISSION_GRANTED;
1649 }
1650 }
1651 }
1652 return PackageManager.PERMISSION_DENIED;
1653 }
1654
1655 private BasePermission findPermissionTreeLP(String permName) {
1656 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1657 if (permName.startsWith(bp.name) &&
1658 permName.length() > bp.name.length() &&
1659 permName.charAt(bp.name.length()) == '.') {
1660 return bp;
1661 }
1662 }
1663 return null;
1664 }
1665
1666 private BasePermission checkPermissionTreeLP(String permName) {
1667 if (permName != null) {
1668 BasePermission bp = findPermissionTreeLP(permName);
1669 if (bp != null) {
1670 if (bp.uid == Binder.getCallingUid()) {
1671 return bp;
1672 }
1673 throw new SecurityException("Calling uid "
1674 + Binder.getCallingUid()
1675 + " is not allowed to add to permission tree "
1676 + bp.name + " owned by uid " + bp.uid);
1677 }
1678 }
1679 throw new SecurityException("No permission tree found for " + permName);
1680 }
1681
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001682 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1683 if (s1 == null) {
1684 return s2 == null;
1685 }
1686 if (s2 == null) {
1687 return false;
1688 }
1689 if (s1.getClass() != s2.getClass()) {
1690 return false;
1691 }
1692 return s1.equals(s2);
1693 }
1694
1695 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1696 if (pi1.icon != pi2.icon) return false;
1697 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1698 if (!compareStrings(pi1.name, pi2.name)) return false;
1699 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1700 // We'll take care of setting this one.
1701 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1702 // These are not currently stored in settings.
1703 //if (!compareStrings(pi1.group, pi2.group)) return false;
1704 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1705 //if (pi1.labelRes != pi2.labelRes) return false;
1706 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1707 return true;
1708 }
1709
1710 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1711 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1712 throw new SecurityException("Label must be specified in permission");
1713 }
1714 BasePermission tree = checkPermissionTreeLP(info.name);
1715 BasePermission bp = mSettings.mPermissions.get(info.name);
1716 boolean added = bp == null;
1717 boolean changed = true;
1718 if (added) {
1719 bp = new BasePermission(info.name, tree.sourcePackage,
1720 BasePermission.TYPE_DYNAMIC);
1721 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1722 throw new SecurityException(
1723 "Not allowed to modify non-dynamic permission "
1724 + info.name);
1725 } else {
1726 if (bp.protectionLevel == info.protectionLevel
1727 && bp.perm.owner.equals(tree.perm.owner)
1728 && bp.uid == tree.uid
1729 && comparePermissionInfos(bp.perm.info, info)) {
1730 changed = false;
1731 }
1732 }
1733 bp.protectionLevel = info.protectionLevel;
1734 bp.perm = new PackageParser.Permission(tree.perm.owner,
1735 new PermissionInfo(info));
1736 bp.perm.info.packageName = tree.perm.info.packageName;
1737 bp.uid = tree.uid;
1738 if (added) {
1739 mSettings.mPermissions.put(info.name, bp);
1740 }
1741 if (changed) {
1742 if (!async) {
1743 mSettings.writeLP();
1744 } else {
1745 scheduleWriteSettingsLocked();
1746 }
1747 }
1748 return added;
1749 }
1750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 public boolean addPermission(PermissionInfo info) {
1752 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001753 return addPermissionLocked(info, false);
1754 }
1755 }
1756
1757 public boolean addPermissionAsync(PermissionInfo info) {
1758 synchronized (mPackages) {
1759 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761 }
1762
1763 public void removePermission(String name) {
1764 synchronized (mPackages) {
1765 checkPermissionTreeLP(name);
1766 BasePermission bp = mSettings.mPermissions.get(name);
1767 if (bp != null) {
1768 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1769 throw new SecurityException(
1770 "Not allowed to modify non-dynamic permission "
1771 + name);
1772 }
1773 mSettings.mPermissions.remove(name);
1774 mSettings.writeLP();
1775 }
1776 }
1777 }
1778
Dianne Hackborn854060af2009-07-09 18:14:31 -07001779 public boolean isProtectedBroadcast(String actionName) {
1780 synchronized (mPackages) {
1781 return mProtectedBroadcasts.contains(actionName);
1782 }
1783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 public int checkSignatures(String pkg1, String pkg2) {
1786 synchronized (mPackages) {
1787 PackageParser.Package p1 = mPackages.get(pkg1);
1788 PackageParser.Package p2 = mPackages.get(pkg2);
1789 if (p1 == null || p1.mExtras == null
1790 || p2 == null || p2.mExtras == null) {
1791 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1792 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001793 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
1795 }
1796
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001797 public int checkUidSignatures(int uid1, int uid2) {
1798 synchronized (mPackages) {
1799 Signature[] s1;
1800 Signature[] s2;
1801 Object obj = mSettings.getUserIdLP(uid1);
1802 if (obj != null) {
1803 if (obj instanceof SharedUserSetting) {
1804 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1805 } else if (obj instanceof PackageSetting) {
1806 s1 = ((PackageSetting)obj).signatures.mSignatures;
1807 } else {
1808 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1809 }
1810 } else {
1811 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1812 }
1813 obj = mSettings.getUserIdLP(uid2);
1814 if (obj != null) {
1815 if (obj instanceof SharedUserSetting) {
1816 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1817 } else if (obj instanceof PackageSetting) {
1818 s2 = ((PackageSetting)obj).signatures.mSignatures;
1819 } else {
1820 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1821 }
1822 } else {
1823 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1824 }
1825 return checkSignaturesLP(s1, s2);
1826 }
1827 }
1828
1829 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1830 if (s1 == null) {
1831 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1833 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1834 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001835 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1837 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001838 HashSet<Signature> set1 = new HashSet<Signature>();
1839 for (Signature sig : s1) {
1840 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001842 HashSet<Signature> set2 = new HashSet<Signature>();
1843 for (Signature sig : s2) {
1844 set2.add(sig);
1845 }
1846 // Make sure s2 contains all signatures in s1.
1847 if (set1.equals(set2)) {
1848 return PackageManager.SIGNATURE_MATCH;
1849 }
1850 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 }
1852
1853 public String[] getPackagesForUid(int uid) {
1854 synchronized (mPackages) {
1855 Object obj = mSettings.getUserIdLP(uid);
1856 if (obj instanceof SharedUserSetting) {
1857 SharedUserSetting sus = (SharedUserSetting)obj;
1858 final int N = sus.packages.size();
1859 String[] res = new String[N];
1860 Iterator<PackageSetting> it = sus.packages.iterator();
1861 int i=0;
1862 while (it.hasNext()) {
1863 res[i++] = it.next().name;
1864 }
1865 return res;
1866 } else if (obj instanceof PackageSetting) {
1867 PackageSetting ps = (PackageSetting)obj;
1868 return new String[] { ps.name };
1869 }
1870 }
1871 return null;
1872 }
1873
1874 public String getNameForUid(int uid) {
1875 synchronized (mPackages) {
1876 Object obj = mSettings.getUserIdLP(uid);
1877 if (obj instanceof SharedUserSetting) {
1878 SharedUserSetting sus = (SharedUserSetting)obj;
1879 return sus.name + ":" + sus.userId;
1880 } else if (obj instanceof PackageSetting) {
1881 PackageSetting ps = (PackageSetting)obj;
1882 return ps.name;
1883 }
1884 }
1885 return null;
1886 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 public int getUidForSharedUser(String sharedUserName) {
1889 if(sharedUserName == null) {
1890 return -1;
1891 }
1892 synchronized (mPackages) {
1893 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1894 if(suid == null) {
1895 return -1;
1896 }
1897 return suid.userId;
1898 }
1899 }
1900
1901 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1902 int flags) {
1903 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001904 return chooseBestActivity(intent, resolvedType, flags, query);
1905 }
1906
Mihai Predaeae850c2009-05-13 10:13:48 +02001907 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1908 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 if (query != null) {
1910 final int N = query.size();
1911 if (N == 1) {
1912 return query.get(0);
1913 } else if (N > 1) {
1914 // If there is more than one activity with the same priority,
1915 // then let the user decide between them.
1916 ResolveInfo r0 = query.get(0);
1917 ResolveInfo r1 = query.get(1);
1918 if (false) {
1919 System.out.println(r0.activityInfo.name +
1920 "=" + r0.priority + " vs " +
1921 r1.activityInfo.name +
1922 "=" + r1.priority);
1923 }
1924 // If the first activity has a higher priority, or a different
1925 // default, then it is always desireable to pick it.
1926 if (r0.priority != r1.priority
1927 || r0.preferredOrder != r1.preferredOrder
1928 || r0.isDefault != r1.isDefault) {
1929 return query.get(0);
1930 }
1931 // If we have saved a preference for a preferred activity for
1932 // this Intent, use that.
1933 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1934 flags, query, r0.priority);
1935 if (ri != null) {
1936 return ri;
1937 }
1938 return mResolveInfo;
1939 }
1940 }
1941 return null;
1942 }
1943
1944 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1945 int flags, List<ResolveInfo> query, int priority) {
1946 synchronized (mPackages) {
1947 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1948 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001949 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1951 if (prefs != null && prefs.size() > 0) {
1952 // First figure out how good the original match set is.
1953 // We will only allow preferred activities that came
1954 // from the same match quality.
1955 int match = 0;
1956 final int N = query.size();
1957 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1958 for (int j=0; j<N; j++) {
1959 ResolveInfo ri = query.get(j);
1960 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1961 + ": 0x" + Integer.toHexString(match));
1962 if (ri.match > match) match = ri.match;
1963 }
1964 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1965 + Integer.toHexString(match));
1966 match &= IntentFilter.MATCH_CATEGORY_MASK;
1967 final int M = prefs.size();
1968 for (int i=0; i<M; i++) {
1969 PreferredActivity pa = prefs.get(i);
1970 if (pa.mMatch != match) {
1971 continue;
1972 }
1973 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1974 if (DEBUG_PREFERRED) {
1975 Log.v(TAG, "Got preferred activity:");
1976 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1977 }
1978 if (ai != null) {
1979 for (int j=0; j<N; j++) {
1980 ResolveInfo ri = query.get(j);
1981 if (!ri.activityInfo.applicationInfo.packageName
1982 .equals(ai.applicationInfo.packageName)) {
1983 continue;
1984 }
1985 if (!ri.activityInfo.name.equals(ai.name)) {
1986 continue;
1987 }
1988
1989 // Okay we found a previously set preferred app.
1990 // If the result set is different from when this
1991 // was created, we need to clear it and re-ask the
1992 // user their preference.
1993 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001994 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 + intent + " type " + resolvedType);
1996 mSettings.mPreferredActivities.removeFilter(pa);
1997 return null;
1998 }
1999
2000 // Yay!
2001 return ri;
2002 }
2003 }
2004 }
2005 }
2006 }
2007 return null;
2008 }
2009
2010 public List<ResolveInfo> queryIntentActivities(Intent intent,
2011 String resolvedType, int flags) {
2012 ComponentName comp = intent.getComponent();
2013 if (comp != null) {
2014 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2015 ActivityInfo ai = getActivityInfo(comp, flags);
2016 if (ai != null) {
2017 ResolveInfo ri = new ResolveInfo();
2018 ri.activityInfo = ai;
2019 list.add(ri);
2020 }
2021 return list;
2022 }
2023
2024 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002025 String pkgName = intent.getPackage();
2026 if (pkgName == null) {
2027 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2028 resolvedType, flags);
2029 }
2030 PackageParser.Package pkg = mPackages.get(pkgName);
2031 if (pkg != null) {
2032 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2033 resolvedType, flags, pkg.activities);
2034 }
2035 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
2037 }
2038
2039 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2040 Intent[] specifics, String[] specificTypes, Intent intent,
2041 String resolvedType, int flags) {
2042 final String resultsAction = intent.getAction();
2043
2044 List<ResolveInfo> results = queryIntentActivities(
2045 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2046 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2047
2048 int specificsPos = 0;
2049 int N;
2050
2051 // todo: note that the algorithm used here is O(N^2). This
2052 // isn't a problem in our current environment, but if we start running
2053 // into situations where we have more than 5 or 10 matches then this
2054 // should probably be changed to something smarter...
2055
2056 // First we go through and resolve each of the specific items
2057 // that were supplied, taking care of removing any corresponding
2058 // duplicate items in the generic resolve list.
2059 if (specifics != null) {
2060 for (int i=0; i<specifics.length; i++) {
2061 final Intent sintent = specifics[i];
2062 if (sintent == null) {
2063 continue;
2064 }
2065
2066 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2067 String action = sintent.getAction();
2068 if (resultsAction != null && resultsAction.equals(action)) {
2069 // If this action was explicitly requested, then don't
2070 // remove things that have it.
2071 action = null;
2072 }
2073 ComponentName comp = sintent.getComponent();
2074 ResolveInfo ri = null;
2075 ActivityInfo ai = null;
2076 if (comp == null) {
2077 ri = resolveIntent(
2078 sintent,
2079 specificTypes != null ? specificTypes[i] : null,
2080 flags);
2081 if (ri == null) {
2082 continue;
2083 }
2084 if (ri == mResolveInfo) {
2085 // ACK! Must do something better with this.
2086 }
2087 ai = ri.activityInfo;
2088 comp = new ComponentName(ai.applicationInfo.packageName,
2089 ai.name);
2090 } else {
2091 ai = getActivityInfo(comp, flags);
2092 if (ai == null) {
2093 continue;
2094 }
2095 }
2096
2097 // Look for any generic query activities that are duplicates
2098 // of this specific one, and remove them from the results.
2099 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2100 N = results.size();
2101 int j;
2102 for (j=specificsPos; j<N; j++) {
2103 ResolveInfo sri = results.get(j);
2104 if ((sri.activityInfo.name.equals(comp.getClassName())
2105 && sri.activityInfo.applicationInfo.packageName.equals(
2106 comp.getPackageName()))
2107 || (action != null && sri.filter.matchAction(action))) {
2108 results.remove(j);
2109 if (Config.LOGV) Log.v(
2110 TAG, "Removing duplicate item from " + j
2111 + " due to specific " + specificsPos);
2112 if (ri == null) {
2113 ri = sri;
2114 }
2115 j--;
2116 N--;
2117 }
2118 }
2119
2120 // Add this specific item to its proper place.
2121 if (ri == null) {
2122 ri = new ResolveInfo();
2123 ri.activityInfo = ai;
2124 }
2125 results.add(specificsPos, ri);
2126 ri.specificIndex = i;
2127 specificsPos++;
2128 }
2129 }
2130
2131 // Now we go through the remaining generic results and remove any
2132 // duplicate actions that are found here.
2133 N = results.size();
2134 for (int i=specificsPos; i<N-1; i++) {
2135 final ResolveInfo rii = results.get(i);
2136 if (rii.filter == null) {
2137 continue;
2138 }
2139
2140 // Iterate over all of the actions of this result's intent
2141 // filter... typically this should be just one.
2142 final Iterator<String> it = rii.filter.actionsIterator();
2143 if (it == null) {
2144 continue;
2145 }
2146 while (it.hasNext()) {
2147 final String action = it.next();
2148 if (resultsAction != null && resultsAction.equals(action)) {
2149 // If this action was explicitly requested, then don't
2150 // remove things that have it.
2151 continue;
2152 }
2153 for (int j=i+1; j<N; j++) {
2154 final ResolveInfo rij = results.get(j);
2155 if (rij.filter != null && rij.filter.hasAction(action)) {
2156 results.remove(j);
2157 if (Config.LOGV) Log.v(
2158 TAG, "Removing duplicate item from " + j
2159 + " due to action " + action + " at " + i);
2160 j--;
2161 N--;
2162 }
2163 }
2164 }
2165
2166 // If the caller didn't request filter information, drop it now
2167 // so we don't have to marshall/unmarshall it.
2168 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2169 rii.filter = null;
2170 }
2171 }
2172
2173 // Filter out the caller activity if so requested.
2174 if (caller != null) {
2175 N = results.size();
2176 for (int i=0; i<N; i++) {
2177 ActivityInfo ainfo = results.get(i).activityInfo;
2178 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2179 && caller.getClassName().equals(ainfo.name)) {
2180 results.remove(i);
2181 break;
2182 }
2183 }
2184 }
2185
2186 // If the caller didn't request filter information,
2187 // drop them now so we don't have to
2188 // marshall/unmarshall it.
2189 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2190 N = results.size();
2191 for (int i=0; i<N; i++) {
2192 results.get(i).filter = null;
2193 }
2194 }
2195
2196 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2197 return results;
2198 }
2199
2200 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2201 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002202 ComponentName comp = intent.getComponent();
2203 if (comp != null) {
2204 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2205 ActivityInfo ai = getReceiverInfo(comp, flags);
2206 if (ai != null) {
2207 ResolveInfo ri = new ResolveInfo();
2208 ri.activityInfo = ai;
2209 list.add(ri);
2210 }
2211 return list;
2212 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002215 String pkgName = intent.getPackage();
2216 if (pkgName == null) {
2217 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2218 resolvedType, flags);
2219 }
2220 PackageParser.Package pkg = mPackages.get(pkgName);
2221 if (pkg != null) {
2222 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2223 resolvedType, flags, pkg.receivers);
2224 }
2225 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 }
2227 }
2228
2229 public ResolveInfo resolveService(Intent intent, String resolvedType,
2230 int flags) {
2231 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2232 flags);
2233 if (query != null) {
2234 if (query.size() >= 1) {
2235 // If there is more than one service with the same priority,
2236 // just arbitrarily pick the first one.
2237 return query.get(0);
2238 }
2239 }
2240 return null;
2241 }
2242
2243 public List<ResolveInfo> queryIntentServices(Intent intent,
2244 String resolvedType, int flags) {
2245 ComponentName comp = intent.getComponent();
2246 if (comp != null) {
2247 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2248 ServiceInfo si = getServiceInfo(comp, flags);
2249 if (si != null) {
2250 ResolveInfo ri = new ResolveInfo();
2251 ri.serviceInfo = si;
2252 list.add(ri);
2253 }
2254 return list;
2255 }
2256
2257 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002258 String pkgName = intent.getPackage();
2259 if (pkgName == null) {
2260 return (List<ResolveInfo>)mServices.queryIntent(intent,
2261 resolvedType, flags);
2262 }
2263 PackageParser.Package pkg = mPackages.get(pkgName);
2264 if (pkg != null) {
2265 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2266 resolvedType, flags, pkg.services);
2267 }
2268 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 }
2270 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 public List<PackageInfo> getInstalledPackages(int flags) {
2273 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2274
2275 synchronized (mPackages) {
2276 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2277 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2278 while (i.hasNext()) {
2279 final PackageSetting ps = i.next();
2280 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2281 if(psPkg != null) {
2282 finalList.add(psPkg);
2283 }
2284 }
2285 }
2286 else {
2287 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2288 while (i.hasNext()) {
2289 final PackageParser.Package p = i.next();
2290 if (p.applicationInfo != null) {
2291 PackageInfo pi = generatePackageInfo(p, flags);
2292 if(pi != null) {
2293 finalList.add(pi);
2294 }
2295 }
2296 }
2297 }
2298 }
2299 return finalList;
2300 }
2301
2302 public List<ApplicationInfo> getInstalledApplications(int flags) {
2303 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2304 synchronized(mPackages) {
2305 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2306 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2307 while (i.hasNext()) {
2308 final PackageSetting ps = i.next();
2309 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2310 if(ai != null) {
2311 finalList.add(ai);
2312 }
2313 }
2314 }
2315 else {
2316 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2317 while (i.hasNext()) {
2318 final PackageParser.Package p = i.next();
2319 if (p.applicationInfo != null) {
2320 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2321 if(ai != null) {
2322 finalList.add(ai);
2323 }
2324 }
2325 }
2326 }
2327 }
2328 return finalList;
2329 }
2330
2331 public List<ApplicationInfo> getPersistentApplications(int flags) {
2332 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2333
2334 synchronized (mPackages) {
2335 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2336 while (i.hasNext()) {
2337 PackageParser.Package p = i.next();
2338 if (p.applicationInfo != null
2339 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2340 && (!mSafeMode || (p.applicationInfo.flags
2341 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2342 finalList.add(p.applicationInfo);
2343 }
2344 }
2345 }
2346
2347 return finalList;
2348 }
2349
2350 public ProviderInfo resolveContentProvider(String name, int flags) {
2351 synchronized (mPackages) {
2352 final PackageParser.Provider provider = mProviders.get(name);
2353 return provider != null
2354 && mSettings.isEnabledLP(provider.info, flags)
2355 && (!mSafeMode || (provider.info.applicationInfo.flags
2356 &ApplicationInfo.FLAG_SYSTEM) != 0)
2357 ? PackageParser.generateProviderInfo(provider, flags)
2358 : null;
2359 }
2360 }
2361
Fred Quintana718d8a22009-04-29 17:53:20 -07002362 /**
2363 * @deprecated
2364 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 public void querySyncProviders(List outNames, List outInfo) {
2366 synchronized (mPackages) {
2367 Iterator<Map.Entry<String, PackageParser.Provider>> i
2368 = mProviders.entrySet().iterator();
2369
2370 while (i.hasNext()) {
2371 Map.Entry<String, PackageParser.Provider> entry = i.next();
2372 PackageParser.Provider p = entry.getValue();
2373
2374 if (p.syncable
2375 && (!mSafeMode || (p.info.applicationInfo.flags
2376 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2377 outNames.add(entry.getKey());
2378 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2379 }
2380 }
2381 }
2382 }
2383
2384 public List<ProviderInfo> queryContentProviders(String processName,
2385 int uid, int flags) {
2386 ArrayList<ProviderInfo> finalList = null;
2387
2388 synchronized (mPackages) {
2389 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2390 while (i.hasNext()) {
2391 PackageParser.Provider p = i.next();
2392 if (p.info.authority != null
2393 && (processName == null ||
2394 (p.info.processName.equals(processName)
2395 && p.info.applicationInfo.uid == uid))
2396 && mSettings.isEnabledLP(p.info, flags)
2397 && (!mSafeMode || (p.info.applicationInfo.flags
2398 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2399 if (finalList == null) {
2400 finalList = new ArrayList<ProviderInfo>(3);
2401 }
2402 finalList.add(PackageParser.generateProviderInfo(p,
2403 flags));
2404 }
2405 }
2406 }
2407
2408 if (finalList != null) {
2409 Collections.sort(finalList, mProviderInitOrderSorter);
2410 }
2411
2412 return finalList;
2413 }
2414
2415 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2416 int flags) {
2417 synchronized (mPackages) {
2418 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2419 return PackageParser.generateInstrumentationInfo(i, flags);
2420 }
2421 }
2422
2423 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2424 int flags) {
2425 ArrayList<InstrumentationInfo> finalList =
2426 new ArrayList<InstrumentationInfo>();
2427
2428 synchronized (mPackages) {
2429 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2430 while (i.hasNext()) {
2431 PackageParser.Instrumentation p = i.next();
2432 if (targetPackage == null
2433 || targetPackage.equals(p.info.targetPackage)) {
2434 finalList.add(PackageParser.generateInstrumentationInfo(p,
2435 flags));
2436 }
2437 }
2438 }
2439
2440 return finalList;
2441 }
2442
2443 private void scanDirLI(File dir, int flags, int scanMode) {
2444 Log.d(TAG, "Scanning app dir " + dir);
2445
2446 String[] files = dir.list();
2447
2448 int i;
2449 for (i=0; i<files.length; i++) {
2450 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002451 if (!isPackageFilename(files[i])) {
2452 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002453 continue;
2454 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002455 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002457 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002458 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2459 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002460 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002461 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002462 file.delete();
2463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 }
2465 }
2466
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002467 private static File getSettingsProblemFile() {
2468 File dataDir = Environment.getDataDirectory();
2469 File systemDir = new File(dataDir, "system");
2470 File fname = new File(systemDir, "uiderrors.txt");
2471 return fname;
2472 }
2473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 private static void reportSettingsProblem(int priority, String msg) {
2475 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002476 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 FileOutputStream out = new FileOutputStream(fname, true);
2478 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002479 SimpleDateFormat formatter = new SimpleDateFormat();
2480 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2481 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 pw.close();
2483 FileUtils.setPermissions(
2484 fname.toString(),
2485 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2486 -1, -1);
2487 } catch (java.io.IOException e) {
2488 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002489 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 }
2491
2492 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2493 PackageParser.Package pkg, File srcFile, int parseFlags) {
2494 if (GET_CERTIFICATES) {
2495 if (ps == null || !ps.codePath.equals(srcFile)
2496 || ps.getTimeStamp() != srcFile.lastModified()) {
2497 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2498 if (!pp.collectCertificates(pkg, parseFlags)) {
2499 mLastScanError = pp.getParseError();
2500 return false;
2501 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002502 } else {
2503 // Lets implicitly assign existing certificates.
2504 pkg.mSignatures = ps.signatures.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 }
2506 }
2507 return true;
2508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 /*
2511 * Scan a package and return the newly parsed package.
2512 * Returns null in case of errors and the error code is stored in mLastScanError
2513 */
2514 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002515 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002517 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002519 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002522 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 if (pkg == null) {
2524 mLastScanError = pp.getParseError();
2525 return null;
2526 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002527 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 PackageSetting updatedPkg;
2529 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002530 // Look to see if we already know about this package.
2531 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002532 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002533 // This package has been renamed to its original name. Let's
2534 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002535 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002536 }
2537 // If there was no original package, see one for the real package name.
2538 if (ps == null) {
2539 ps = mSettings.peekPackageLP(pkg.packageName);
2540 }
2541 // Check to see if this package could be hiding/updating a system
2542 // package. Must look for it either under the original or real
2543 // package name depending on our state.
2544 updatedPkg = mSettings.mDisabledSysPackages.get(
2545 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002547 // First check if this is a system package that may involve an update
2548 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2549 if (!ps.codePath.equals(scanFile)) {
2550 // The path has changed from what was last scanned... check the
2551 // version of the new path against what we have stored to determine
2552 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002553 if (pkg.mVersionCode < ps.versionCode) {
2554 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002555 // Ignore entry. Skip it.
2556 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2557 + "ignored: updated version " + ps.versionCode
2558 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002559 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2560 return null;
2561 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002562 // The current app on the system partion is better than
2563 // what we have updated to on the data partition; switch
2564 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002565 // At this point, its safely assumed that package installation for
2566 // apps in system partition will go through. If not there won't be a working
2567 // version of the app
2568 synchronized (mPackages) {
2569 // Just remove the loaded entries from package lists.
2570 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002571 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002572 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002573 + "reverting from " + ps.codePathString
2574 + ": new version " + pkg.mVersionCode
2575 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002576 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2577 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002578 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 }
2581 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002582 if (updatedPkg != null) {
2583 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2584 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2585 }
2586 // Verify certificates against what was last scanned
2587 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002588 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002589 return null;
2590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 // The apk is forward locked (not public) if its code and resources
2592 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002593 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002595 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002596 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002597
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002598 String codePath = null;
2599 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002600 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2601 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002602 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002603 } else {
2604 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002605 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002606 }
2607 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002608 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002609 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002610 codePath = pkg.mScanPath;
2611 // Set application objects path explicitly.
2612 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002614 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 }
2616
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002617 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2618 String destCodePath, String destResPath) {
2619 pkg.mPath = pkg.mScanPath = destCodePath;
2620 pkg.applicationInfo.sourceDir = destCodePath;
2621 pkg.applicationInfo.publicSourceDir = destResPath;
2622 }
2623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 private static String fixProcessName(String defProcessName,
2625 String processName, int uid) {
2626 if (processName == null) {
2627 return defProcessName;
2628 }
2629 return processName;
2630 }
2631
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002632 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002633 PackageParser.Package pkg) {
2634 if (pkgSetting.signatures.mSignatures != null) {
2635 // Already existing package. Make sure signatures match
2636 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2637 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002638 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002639 + " signatures do not match the previously installed version; ignoring!");
2640 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 return false;
2642 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002643 }
2644 // Check for shared user signatures
2645 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2646 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2647 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2648 Slog.e(TAG, "Package " + pkg.packageName
2649 + " has no signatures that match those in shared user "
2650 + pkgSetting.sharedUser.name + "; ignoring!");
2651 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2652 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 }
2655 return true;
2656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002657
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002658 public boolean performDexOpt(String packageName) {
2659 if (!mNoDexOpt) {
2660 return false;
2661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002662
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002663 PackageParser.Package p;
2664 synchronized (mPackages) {
2665 p = mPackages.get(packageName);
2666 if (p == null || p.mDidDexOpt) {
2667 return false;
2668 }
2669 }
2670 synchronized (mInstallLock) {
2671 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2672 }
2673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002674
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002675 static final int DEX_OPT_SKIPPED = 0;
2676 static final int DEX_OPT_PERFORMED = 1;
2677 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002678
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002679 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2680 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002681 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002682 String path = pkg.mScanPath;
2683 int ret = 0;
2684 try {
2685 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002686 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002687 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002688 pkg.mDidDexOpt = true;
2689 performed = true;
2690 }
2691 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002692 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002693 ret = -1;
2694 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002695 Slog.w(TAG, "IOException reading apk: " + path, e);
2696 ret = -1;
2697 } catch (dalvik.system.StaleDexCacheError e) {
2698 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2699 ret = -1;
2700 } catch (Exception e) {
2701 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002702 ret = -1;
2703 }
2704 if (ret < 0) {
2705 //error from installer
2706 return DEX_OPT_FAILED;
2707 }
2708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002709
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002710 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2711 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002712
2713 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2714 return Environment.isEncryptedFilesystemEnabled() &&
2715 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2716 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002717
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002718 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2719 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002720 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002721 + " to " + newPkg.packageName
2722 + ": old package not in system partition");
2723 return false;
2724 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002725 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002726 + " to " + newPkg.packageName
2727 + ": old package still exists");
2728 return false;
2729 }
2730 return true;
2731 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002732
2733 private File getDataPathForPackage(PackageParser.Package pkg) {
2734 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2735 File dataPath;
2736 if (useEncryptedFSDir) {
2737 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2738 } else {
2739 dataPath = new File(mAppDataDir, pkg.packageName);
2740 }
2741 return dataPath;
2742 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002743
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002744 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2745 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002746 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002747 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2748 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002749 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002750 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002751 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2752 return null;
2753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 mScanningPath = scanFile;
2755 if (pkg == null) {
2756 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2757 return null;
2758 }
2759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2761 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2762 }
2763
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002764 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 synchronized (mPackages) {
2766 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002767 Slog.w(TAG, "*************************************************");
2768 Slog.w(TAG, "Core android package being redefined. Skipping.");
2769 Slog.w(TAG, " file=" + mScanningPath);
2770 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2772 return null;
2773 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 // Set up information for our fall-back user intent resolution
2776 // activity.
2777 mPlatformPackage = pkg;
2778 pkg.mVersionCode = mSdkVersion;
2779 mAndroidApplication = pkg.applicationInfo;
2780 mResolveActivity.applicationInfo = mAndroidApplication;
2781 mResolveActivity.name = ResolverActivity.class.getName();
2782 mResolveActivity.packageName = mAndroidApplication.packageName;
2783 mResolveActivity.processName = mAndroidApplication.processName;
2784 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2785 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2786 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2787 mResolveActivity.exported = true;
2788 mResolveActivity.enabled = true;
2789 mResolveInfo.activityInfo = mResolveActivity;
2790 mResolveInfo.priority = 0;
2791 mResolveInfo.preferredOrder = 0;
2792 mResolveInfo.match = 0;
2793 mResolveComponentName = new ComponentName(
2794 mAndroidApplication.packageName, mResolveActivity.name);
2795 }
2796 }
2797
2798 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002799 TAG, "Scanning package " + pkg.packageName);
2800 if (mPackages.containsKey(pkg.packageName)
2801 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002802 Slog.w(TAG, "*************************************************");
2803 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002805 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2807 return null;
2808 }
2809
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002810 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002811 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2812 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 SharedUserSetting suid = null;
2815 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002816
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002817 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2818 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002819 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002820 pkg.mRealPackage = null;
2821 pkg.mAdoptPermissions = null;
2822 }
2823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 synchronized (mPackages) {
2825 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002826 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2827 if (mTmpSharedLibraries == null ||
2828 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2829 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2830 }
2831 int num = 0;
2832 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2833 for (int i=0; i<N; i++) {
2834 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002836 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002838 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2840 return null;
2841 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002842 mTmpSharedLibraries[num] = file;
2843 num++;
2844 }
2845 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2846 for (int i=0; i<N; i++) {
2847 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2848 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002849 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002850 + " desires unavailable shared library "
2851 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2852 } else {
2853 mTmpSharedLibraries[num] = file;
2854 num++;
2855 }
2856 }
2857 if (num > 0) {
2858 pkg.usesLibraryFiles = new String[num];
2859 System.arraycopy(mTmpSharedLibraries, 0,
2860 pkg.usesLibraryFiles, 0, num);
2861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002862
Dianne Hackborn49237342009-08-27 20:08:01 -07002863 if (pkg.reqFeatures != null) {
2864 N = pkg.reqFeatures.size();
2865 for (int i=0; i<N; i++) {
2866 FeatureInfo fi = pkg.reqFeatures.get(i);
2867 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2868 // Don't care.
2869 continue;
2870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002871
Dianne Hackborn49237342009-08-27 20:08:01 -07002872 if (fi.name != null) {
2873 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002874 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002875 + " requires unavailable feature "
2876 + fi.name + "; failing!");
2877 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2878 return null;
2879 }
2880 }
2881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 }
2883 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 if (pkg.mSharedUserId != null) {
2886 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2887 pkg.applicationInfo.flags, true);
2888 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002889 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 + " for shared user failed");
2891 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2892 return null;
2893 }
2894 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2895 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2896 + suid.userId + "): packages=" + suid.packages);
2897 }
2898 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002899
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002900 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002901 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002902 Log.w(TAG, "WAITING FOR DEBUGGER");
2903 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002904 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2905 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002906 }
2907 }
2908
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002909 // Check if we are renaming from an original package name.
2910 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002911 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002912 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002913 // This package may need to be renamed to a previously
2914 // installed name. Let's check on that...
2915 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002916 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002917 // This package had originally been installed as the
2918 // original name, and we have already taken care of
2919 // transitioning to the new one. Just update the new
2920 // one to continue using the old name.
2921 realName = pkg.mRealPackage;
2922 if (!pkg.packageName.equals(renamed)) {
2923 // Callers into this function may have already taken
2924 // care of renaming the package; only do it here if
2925 // it is not already done.
2926 pkg.setPackageName(renamed);
2927 }
2928
Dianne Hackbornc1552392010-03-03 16:19:01 -08002929 } else {
2930 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2931 if ((origPackage=mSettings.peekPackageLP(
2932 pkg.mOriginalPackages.get(i))) != null) {
2933 // We do have the package already installed under its
2934 // original name... should we use it?
2935 if (!verifyPackageUpdate(origPackage, pkg)) {
2936 // New package is not compatible with original.
2937 origPackage = null;
2938 continue;
2939 } else if (origPackage.sharedUser != null) {
2940 // Make sure uid is compatible between packages.
2941 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002942 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002943 + " to " + pkg.packageName + ": old uid "
2944 + origPackage.sharedUser.name
2945 + " differs from " + pkg.mSharedUserId);
2946 origPackage = null;
2947 continue;
2948 }
2949 } else {
2950 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2951 + pkg.packageName + " to old name " + origPackage.name);
2952 }
2953 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002954 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002955 }
2956 }
2957 }
2958
2959 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002960 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002961 + " was transferred to another, but its .apk remains");
2962 }
2963
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002964 // Just create the setting, don't add it yet. For already existing packages
2965 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002966 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 destResourceFile, pkg.applicationInfo.flags, true, false);
2968 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002969 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2971 return null;
2972 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973
2974 if (pkgSetting.origPackage != null) {
2975 // If we are first transitioning from an original package,
2976 // fix up the new package's name now. We need to do this after
2977 // looking up the package under its new name, so getPackageLP
2978 // can take care of fiddling things correctly.
2979 pkg.setPackageName(origPackage.name);
2980
2981 // File a report about this.
2982 String msg = "New package " + pkgSetting.realName
2983 + " renamed to replace old package " + pkgSetting.name;
2984 reportSettingsProblem(Log.WARN, msg);
2985
2986 // Make a note of it.
2987 mTransferedPackages.add(origPackage.name);
2988
2989 // No longer need to retain this.
2990 pkgSetting.origPackage = null;
2991 }
2992
2993 if (realName != null) {
2994 // Make a note of it.
2995 mTransferedPackages.add(pkg.packageName);
2996 }
2997
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002998 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3000 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 pkg.applicationInfo.uid = pkgSetting.userId;
3003 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003004
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003005 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003006 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 return null;
3008 }
3009 // The signature has changed, but this package is in the system
3010 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003011 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 // However... if this package is part of a shared user, but it
3013 // doesn't match the signature of the shared user, let's fail.
3014 // What this means is that you can't change the signatures
3015 // associated with an overall shared user, which doesn't seem all
3016 // that unreasonable.
3017 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003018 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3019 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3020 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3022 return null;
3023 }
3024 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003025 // File a report about this.
3026 String msg = "System package " + pkg.packageName
3027 + " signature changed; retaining data.";
3028 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003030
The Android Open Source Project10592532009-03-18 17:39:46 -07003031 // Verify that this new package doesn't have any content providers
3032 // that conflict with existing packages. Only do this if the
3033 // package isn't already installed, since we don't want to break
3034 // things that are installed.
3035 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3036 int N = pkg.providers.size();
3037 int i;
3038 for (i=0; i<N; i++) {
3039 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003040 if (p.info.authority != null) {
3041 String names[] = p.info.authority.split(";");
3042 for (int j = 0; j < names.length; j++) {
3043 if (mProviders.containsKey(names[j])) {
3044 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003045 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003046 " (in package " + pkg.applicationInfo.packageName +
3047 ") is already used by "
3048 + ((other != null && other.getComponentName() != null)
3049 ? other.getComponentName().getPackageName() : "?"));
3050 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3051 return null;
3052 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003053 }
3054 }
3055 }
3056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 }
3058
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003059 final String pkgName = pkg.packageName;
3060
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003061 if (pkg.mAdoptPermissions != null) {
3062 // This package wants to adopt ownership of permissions from
3063 // another package.
3064 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3065 String origName = pkg.mAdoptPermissions.get(i);
3066 PackageSetting orig = mSettings.peekPackageLP(origName);
3067 if (orig != null) {
3068 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003069 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003070 + origName + " to " + pkg.packageName);
3071 mSettings.transferPermissions(origName, pkg.packageName);
3072 }
3073 }
3074 }
3075 }
3076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 long scanFileTime = scanFile.lastModified();
3078 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3079 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3080 pkg.applicationInfo.processName = fixProcessName(
3081 pkg.applicationInfo.packageName,
3082 pkg.applicationInfo.processName,
3083 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084
3085 File dataPath;
3086 if (mPlatformPackage == pkg) {
3087 // The system package is special.
3088 dataPath = new File (Environment.getDataDirectory(), "system");
3089 pkg.applicationInfo.dataDir = dataPath.getPath();
3090 } else {
3091 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003092 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003093 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003094
3095 boolean uidError = false;
3096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 if (dataPath.exists()) {
3098 mOutPermissions[1] = 0;
3099 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3100 if (mOutPermissions[1] == pkg.applicationInfo.uid
3101 || !Process.supportsProcesses()) {
3102 pkg.applicationInfo.dataDir = dataPath.getPath();
3103 } else {
3104 boolean recovered = false;
3105 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3106 // If this is a system app, we can at least delete its
3107 // current data so the application will still work.
3108 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003109 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003110 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 // Old data gone!
3112 String msg = "System package " + pkg.packageName
3113 + " has changed from uid: "
3114 + mOutPermissions[1] + " to "
3115 + pkg.applicationInfo.uid + "; old data erased";
3116 reportSettingsProblem(Log.WARN, msg);
3117 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003120 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 pkg.applicationInfo.uid);
3122 if (ret == -1) {
3123 // Ack should not happen!
3124 msg = "System package " + pkg.packageName
3125 + " could not have data directory re-created after delete.";
3126 reportSettingsProblem(Log.WARN, msg);
3127 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3128 return null;
3129 }
3130 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 if (!recovered) {
3133 mHasSystemUidErrors = true;
3134 }
3135 }
3136 if (!recovered) {
3137 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3138 + pkg.applicationInfo.uid + "/fs_"
3139 + mOutPermissions[1];
3140 String msg = "Package " + pkg.packageName
3141 + " has mismatched uid: "
3142 + mOutPermissions[1] + " on disk, "
3143 + pkg.applicationInfo.uid + " in settings";
3144 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003145 mSettings.mReadMessages.append(msg);
3146 mSettings.mReadMessages.append('\n');
3147 uidError = true;
3148 if (!pkgSetting.uidError) {
3149 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 }
3152 }
3153 }
3154 pkg.applicationInfo.dataDir = dataPath.getPath();
3155 } else {
3156 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3157 Log.v(TAG, "Want this data dir: " + dataPath);
3158 //invoke installer to do the actual installation
3159 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003160 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 pkg.applicationInfo.uid);
3162 if(ret < 0) {
3163 // Error from installer
3164 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3165 return null;
3166 }
3167 } else {
3168 dataPath.mkdirs();
3169 if (dataPath.exists()) {
3170 FileUtils.setPermissions(
3171 dataPath.toString(),
3172 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3173 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3174 }
3175 }
3176 if (dataPath.exists()) {
3177 pkg.applicationInfo.dataDir = dataPath.getPath();
3178 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003179 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 pkg.applicationInfo.dataDir = null;
3181 }
3182 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003183
3184 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 }
3186
3187 // Perform shared library installation and dex validation and
3188 // optimization, if this is not a system app.
3189 if (mInstaller != null) {
3190 String path = scanFile.getPath();
3191 if (scanFileNewer) {
3192 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003193 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3194 if (err != PackageManager.INSTALL_SUCCEEDED) {
3195 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 return null;
3197 }
3198 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003199 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003200
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003201 if ((scanMode&SCAN_NO_DEX) == 0) {
3202 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3204 return null;
3205 }
3206 }
3207 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 if (mFactoryTest && pkg.requestedPermissions.contains(
3210 android.Manifest.permission.FACTORY_TEST)) {
3211 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3212 }
3213
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003214 // Request the ActivityManager to kill the process(only for existing packages)
3215 // so that we do not end up in a confused state while the user is still using the older
3216 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003217 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003218 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003219 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003220 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003223 // We don't expect installation to fail beyond this point,
3224 if ((scanMode&SCAN_MONITOR) != 0) {
3225 mAppDirs.put(pkg.mPath, pkg);
3226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003228 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003230 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003231 // Make sure we don't accidentally delete its data.
3232 mSettings.mPackagesToBeCleaned.remove(pkgName);
3233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 int N = pkg.providers.size();
3235 StringBuilder r = null;
3236 int i;
3237 for (i=0; i<N; i++) {
3238 PackageParser.Provider p = pkg.providers.get(i);
3239 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3240 p.info.processName, pkg.applicationInfo.uid);
3241 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3242 p.info.name), p);
3243 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003244 if (p.info.authority != null) {
3245 String names[] = p.info.authority.split(";");
3246 p.info.authority = null;
3247 for (int j = 0; j < names.length; j++) {
3248 if (j == 1 && p.syncable) {
3249 // We only want the first authority for a provider to possibly be
3250 // syncable, so if we already added this provider using a different
3251 // authority clear the syncable flag. We copy the provider before
3252 // changing it because the mProviders object contains a reference
3253 // to a provider that we don't want to change.
3254 // Only do this for the second authority since the resulting provider
3255 // object can be the same for all future authorities for this provider.
3256 p = new PackageParser.Provider(p);
3257 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003259 if (!mProviders.containsKey(names[j])) {
3260 mProviders.put(names[j], p);
3261 if (p.info.authority == null) {
3262 p.info.authority = names[j];
3263 } else {
3264 p.info.authority = p.info.authority + ";" + names[j];
3265 }
3266 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3267 Log.d(TAG, "Registered content provider: " + names[j] +
3268 ", className = " + p.info.name +
3269 ", isSyncable = " + p.info.isSyncable);
3270 } else {
3271 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003272 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003273 " (in package " + pkg.applicationInfo.packageName +
3274 "): name already used by "
3275 + ((other != null && other.getComponentName() != null)
3276 ? other.getComponentName().getPackageName() : "?"));
3277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 }
3279 }
3280 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3281 if (r == null) {
3282 r = new StringBuilder(256);
3283 } else {
3284 r.append(' ');
3285 }
3286 r.append(p.info.name);
3287 }
3288 }
3289 if (r != null) {
3290 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3291 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 N = pkg.services.size();
3294 r = null;
3295 for (i=0; i<N; i++) {
3296 PackageParser.Service s = pkg.services.get(i);
3297 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3298 s.info.processName, pkg.applicationInfo.uid);
3299 mServices.addService(s);
3300 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3301 if (r == null) {
3302 r = new StringBuilder(256);
3303 } else {
3304 r.append(' ');
3305 }
3306 r.append(s.info.name);
3307 }
3308 }
3309 if (r != null) {
3310 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 N = pkg.receivers.size();
3314 r = null;
3315 for (i=0; i<N; i++) {
3316 PackageParser.Activity a = pkg.receivers.get(i);
3317 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3318 a.info.processName, pkg.applicationInfo.uid);
3319 mReceivers.addActivity(a, "receiver");
3320 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3321 if (r == null) {
3322 r = new StringBuilder(256);
3323 } else {
3324 r.append(' ');
3325 }
3326 r.append(a.info.name);
3327 }
3328 }
3329 if (r != null) {
3330 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3331 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 N = pkg.activities.size();
3334 r = null;
3335 for (i=0; i<N; i++) {
3336 PackageParser.Activity a = pkg.activities.get(i);
3337 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3338 a.info.processName, pkg.applicationInfo.uid);
3339 mActivities.addActivity(a, "activity");
3340 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3341 if (r == null) {
3342 r = new StringBuilder(256);
3343 } else {
3344 r.append(' ');
3345 }
3346 r.append(a.info.name);
3347 }
3348 }
3349 if (r != null) {
3350 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3351 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 N = pkg.permissionGroups.size();
3354 r = null;
3355 for (i=0; i<N; i++) {
3356 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3357 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3358 if (cur == null) {
3359 mPermissionGroups.put(pg.info.name, pg);
3360 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3361 if (r == null) {
3362 r = new StringBuilder(256);
3363 } else {
3364 r.append(' ');
3365 }
3366 r.append(pg.info.name);
3367 }
3368 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003369 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 + pg.info.packageName + " ignored: original from "
3371 + cur.info.packageName);
3372 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3373 if (r == null) {
3374 r = new StringBuilder(256);
3375 } else {
3376 r.append(' ');
3377 }
3378 r.append("DUP:");
3379 r.append(pg.info.name);
3380 }
3381 }
3382 }
3383 if (r != null) {
3384 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3385 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 N = pkg.permissions.size();
3388 r = null;
3389 for (i=0; i<N; i++) {
3390 PackageParser.Permission p = pkg.permissions.get(i);
3391 HashMap<String, BasePermission> permissionMap =
3392 p.tree ? mSettings.mPermissionTrees
3393 : mSettings.mPermissions;
3394 p.group = mPermissionGroups.get(p.info.group);
3395 if (p.info.group == null || p.group != null) {
3396 BasePermission bp = permissionMap.get(p.info.name);
3397 if (bp == null) {
3398 bp = new BasePermission(p.info.name, p.info.packageName,
3399 BasePermission.TYPE_NORMAL);
3400 permissionMap.put(p.info.name, bp);
3401 }
3402 if (bp.perm == null) {
3403 if (bp.sourcePackage == null
3404 || bp.sourcePackage.equals(p.info.packageName)) {
3405 BasePermission tree = findPermissionTreeLP(p.info.name);
3406 if (tree == null
3407 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003408 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 bp.perm = p;
3410 bp.uid = pkg.applicationInfo.uid;
3411 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3412 if (r == null) {
3413 r = new StringBuilder(256);
3414 } else {
3415 r.append(' ');
3416 }
3417 r.append(p.info.name);
3418 }
3419 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003420 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 + p.info.packageName + " ignored: base tree "
3422 + tree.name + " is from package "
3423 + tree.sourcePackage);
3424 }
3425 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003426 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 + p.info.packageName + " ignored: original from "
3428 + bp.sourcePackage);
3429 }
3430 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3431 if (r == null) {
3432 r = new StringBuilder(256);
3433 } else {
3434 r.append(' ');
3435 }
3436 r.append("DUP:");
3437 r.append(p.info.name);
3438 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003439 if (bp.perm == p) {
3440 bp.protectionLevel = p.info.protectionLevel;
3441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003443 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 + p.info.packageName + " ignored: no group "
3445 + p.group);
3446 }
3447 }
3448 if (r != null) {
3449 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 N = pkg.instrumentation.size();
3453 r = null;
3454 for (i=0; i<N; i++) {
3455 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3456 a.info.packageName = pkg.applicationInfo.packageName;
3457 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3458 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3459 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003460 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3462 if (r == null) {
3463 r = new StringBuilder(256);
3464 } else {
3465 r.append(' ');
3466 }
3467 r.append(a.info.name);
3468 }
3469 }
3470 if (r != null) {
3471 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003473
Dianne Hackborn854060af2009-07-09 18:14:31 -07003474 if (pkg.protectedBroadcasts != null) {
3475 N = pkg.protectedBroadcasts.size();
3476 for (i=0; i<N; i++) {
3477 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3478 }
3479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 pkgSetting.setTimeStamp(scanFileTime);
3482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 return pkg;
3485 }
3486
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003487 private void killApplication(String pkgName, int uid) {
3488 // Request the ActivityManager to kill the process(only for existing packages)
3489 // so that we do not end up in a confused state while the user is still using the older
3490 // version of the application while the new one gets installed.
3491 IActivityManager am = ActivityManagerNative.getDefault();
3492 if (am != null) {
3493 try {
3494 am.killApplicationWithUid(pkgName, uid);
3495 } catch (RemoteException e) {
3496 }
3497 }
3498 }
3499
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003500 // The following constants are returned by cachePackageSharedLibsForAbiLI
3501 // to indicate if native shared libraries were found in the package.
3502 // Values are:
3503 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3504 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3505 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3506 // in package (and not installed)
3507 //
3508 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3509 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3510 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003512 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3513 // and automatically copy them to /data/data/<appname>/lib if present.
3514 //
3515 // NOTE: this method may throw an IOException if the library cannot
3516 // be copied to its final destination, e.g. if there isn't enough
3517 // room left on the data partition, or a ZipException if the package
3518 // file is malformed.
3519 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003520 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3521 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003522 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3523 final String apkLib = "lib/";
3524 final int apkLibLen = apkLib.length();
3525 final int cpuAbiLen = cpuAbi.length();
3526 final String libPrefix = "lib";
3527 final int libPrefixLen = libPrefix.length();
3528 final String libSuffix = ".so";
3529 final int libSuffixLen = libSuffix.length();
3530 boolean hasNativeLibraries = false;
3531 boolean installedNativeLibraries = false;
3532
3533 // the minimum length of a valid native shared library of the form
3534 // lib/<something>/lib<name>.so.
3535 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3536
3537 ZipFile zipFile = new ZipFile(scanFile);
3538 Enumeration<ZipEntry> entries =
3539 (Enumeration<ZipEntry>) zipFile.entries();
3540
3541 while (entries.hasMoreElements()) {
3542 ZipEntry entry = entries.nextElement();
3543 // skip directories
3544 if (entry.isDirectory()) {
3545 continue;
3546 }
3547 String entryName = entry.getName();
3548
3549 // check that the entry looks like lib/<something>/lib<name>.so
3550 // here, but don't check the ABI just yet.
3551 //
3552 // - must be sufficiently long
3553 // - must end with libSuffix, i.e. ".so"
3554 // - must start with apkLib, i.e. "lib/"
3555 if (entryName.length() < minEntryLen ||
3556 !entryName.endsWith(libSuffix) ||
3557 !entryName.startsWith(apkLib) ) {
3558 continue;
3559 }
3560
3561 // file name must start with libPrefix, i.e. "lib"
3562 int lastSlash = entryName.lastIndexOf('/');
3563
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003564 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003565 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3566 continue;
3567 }
3568
3569 hasNativeLibraries = true;
3570
3571 // check the cpuAbi now, between lib/ and /lib<name>.so
3572 //
3573 if (lastSlash != apkLibLen + cpuAbiLen ||
3574 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3575 continue;
3576
3577 // extract the library file name, ensure it doesn't contain
3578 // weird characters. we're guaranteed here that it doesn't contain
3579 // a directory separator though.
3580 String libFileName = entryName.substring(lastSlash+1);
3581 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3582 continue;
3583 }
3584
3585 installedNativeLibraries = true;
3586
3587 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3588 File.separator + libFileName;
3589 File sharedLibraryFile = new File(sharedLibraryFilePath);
3590 if (! sharedLibraryFile.exists() ||
3591 sharedLibraryFile.length() != entry.getSize() ||
3592 sharedLibraryFile.lastModified() != entry.getTime()) {
3593 if (Config.LOGD) {
3594 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003596 if (mInstaller == null) {
3597 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003598 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003599 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003600 sharedLibraryFile);
3601 }
3602 }
3603 if (!hasNativeLibraries)
3604 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3605
3606 if (!installedNativeLibraries)
3607 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3608
3609 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3610 }
3611
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003612 // Find the gdbserver executable program in a package at
3613 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3614 //
3615 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3616 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3617 //
3618 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3619 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3620 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3621 final String GDBSERVER = "gdbserver";
3622 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3623
3624 ZipFile zipFile = new ZipFile(scanFile);
3625 Enumeration<ZipEntry> entries =
3626 (Enumeration<ZipEntry>) zipFile.entries();
3627
3628 while (entries.hasMoreElements()) {
3629 ZipEntry entry = entries.nextElement();
3630 // skip directories
3631 if (entry.isDirectory()) {
3632 continue;
3633 }
3634 String entryName = entry.getName();
3635
3636 if (!entryName.equals(apkGdbServerPath)) {
3637 continue;
3638 }
3639
3640 String installGdbServerPath = installGdbServerDir.getPath() +
3641 "/" + GDBSERVER;
3642 File installGdbServerFile = new File(installGdbServerPath);
3643 if (! installGdbServerFile.exists() ||
3644 installGdbServerFile.length() != entry.getSize() ||
3645 installGdbServerFile.lastModified() != entry.getTime()) {
3646 if (Config.LOGD) {
3647 Log.d(TAG, "Caching gdbserver " + entry.getName());
3648 }
3649 if (mInstaller == null) {
3650 installGdbServerDir.mkdir();
3651 }
3652 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3653 installGdbServerFile);
3654 }
3655 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3656 }
3657 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3658 }
3659
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003660 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3661 // and copy them to /data/data/<appname>/lib.
3662 //
3663 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3664 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3665 // one if ro.product.cpu.abi2 is defined.
3666 //
3667 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3668 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003669 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003670 try {
3671 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3672
3673 // some architectures are capable of supporting several CPU ABIs
3674 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3675 // this is indicated by the definition of the ro.product.cpu.abi2
3676 // system property.
3677 //
3678 // only scan the package twice in case of ABI mismatch
3679 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003680 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003681 if (cpuAbi2 != null) {
3682 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003684
3685 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003686 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003687 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003689
3690 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3691 cpuAbi = cpuAbi2;
3692 }
3693 }
3694
3695 // for debuggable packages, also extract gdbserver from lib/<abi>
3696 // into /data/data/<appname>/lib too.
3697 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3698 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3699 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3700 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3701 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003704 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003705 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003706 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003708 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003709 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003711 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 }
3713
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003714 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003716 File binaryDir,
3717 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 InputStream inputStream = zipFile.getInputStream(entry);
3719 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003720 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003722 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 // now need to be left as world readable and owned by the system.
3724 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3725 ! tempFile.setLastModified(entry.getTime()) ||
3726 FileUtils.setPermissions(tempFilePath,
3727 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003728 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003730 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 // Failed to properly write file.
3732 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003733 throw new IOException("Couldn't create cached binary "
3734 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 }
3736 } finally {
3737 inputStream.close();
3738 }
3739 }
3740
3741 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3742 if (chatty && Config.LOGD) Log.d(
3743 TAG, "Removing package " + pkg.applicationInfo.packageName );
3744
3745 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 mPackages.remove(pkg.applicationInfo.packageName);
3749 if (pkg.mPath != null) {
3750 mAppDirs.remove(pkg.mPath);
3751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 PackageSetting ps = (PackageSetting)pkg.mExtras;
3754 if (ps != null && ps.sharedUser != null) {
3755 // XXX don't do this until the data is removed.
3756 if (false) {
3757 ps.sharedUser.packages.remove(ps);
3758 if (ps.sharedUser.packages.size() == 0) {
3759 // Remove.
3760 }
3761 }
3762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 int N = pkg.providers.size();
3765 StringBuilder r = null;
3766 int i;
3767 for (i=0; i<N; i++) {
3768 PackageParser.Provider p = pkg.providers.get(i);
3769 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3770 p.info.name));
3771 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 /* The is another ContentProvider with this authority when
3774 * this app was installed so this authority is null,
3775 * Ignore it as we don't have to unregister the provider.
3776 */
3777 continue;
3778 }
3779 String names[] = p.info.authority.split(";");
3780 for (int j = 0; j < names.length; j++) {
3781 if (mProviders.get(names[j]) == p) {
3782 mProviders.remove(names[j]);
3783 if (chatty && Config.LOGD) Log.d(
3784 TAG, "Unregistered content provider: " + names[j] +
3785 ", className = " + p.info.name +
3786 ", isSyncable = " + p.info.isSyncable);
3787 }
3788 }
3789 if (chatty) {
3790 if (r == null) {
3791 r = new StringBuilder(256);
3792 } else {
3793 r.append(' ');
3794 }
3795 r.append(p.info.name);
3796 }
3797 }
3798 if (r != null) {
3799 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3800 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 N = pkg.services.size();
3803 r = null;
3804 for (i=0; i<N; i++) {
3805 PackageParser.Service s = pkg.services.get(i);
3806 mServices.removeService(s);
3807 if (chatty) {
3808 if (r == null) {
3809 r = new StringBuilder(256);
3810 } else {
3811 r.append(' ');
3812 }
3813 r.append(s.info.name);
3814 }
3815 }
3816 if (r != null) {
3817 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 N = pkg.receivers.size();
3821 r = null;
3822 for (i=0; i<N; i++) {
3823 PackageParser.Activity a = pkg.receivers.get(i);
3824 mReceivers.removeActivity(a, "receiver");
3825 if (chatty) {
3826 if (r == null) {
3827 r = new StringBuilder(256);
3828 } else {
3829 r.append(' ');
3830 }
3831 r.append(a.info.name);
3832 }
3833 }
3834 if (r != null) {
3835 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 N = pkg.activities.size();
3839 r = null;
3840 for (i=0; i<N; i++) {
3841 PackageParser.Activity a = pkg.activities.get(i);
3842 mActivities.removeActivity(a, "activity");
3843 if (chatty) {
3844 if (r == null) {
3845 r = new StringBuilder(256);
3846 } else {
3847 r.append(' ');
3848 }
3849 r.append(a.info.name);
3850 }
3851 }
3852 if (r != null) {
3853 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 N = pkg.permissions.size();
3857 r = null;
3858 for (i=0; i<N; i++) {
3859 PackageParser.Permission p = pkg.permissions.get(i);
3860 boolean tree = false;
3861 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3862 if (bp == null) {
3863 tree = true;
3864 bp = mSettings.mPermissionTrees.get(p.info.name);
3865 }
3866 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003867 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 if (chatty) {
3869 if (r == null) {
3870 r = new StringBuilder(256);
3871 } else {
3872 r.append(' ');
3873 }
3874 r.append(p.info.name);
3875 }
3876 }
3877 }
3878 if (r != null) {
3879 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 N = pkg.instrumentation.size();
3883 r = null;
3884 for (i=0; i<N; i++) {
3885 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003886 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 if (chatty) {
3888 if (r == null) {
3889 r = new StringBuilder(256);
3890 } else {
3891 r.append(' ');
3892 }
3893 r.append(a.info.name);
3894 }
3895 }
3896 if (r != null) {
3897 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3898 }
3899 }
3900 }
3901
3902 private static final boolean isPackageFilename(String name) {
3903 return name != null && name.endsWith(".apk");
3904 }
3905
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003906 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3907 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3908 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3909 return true;
3910 }
3911 }
3912 return false;
3913 }
3914
3915 private void updatePermissionsLP(String changingPkg,
3916 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 // Make sure there are no dangling permission trees.
3918 Iterator<BasePermission> it = mSettings.mPermissionTrees
3919 .values().iterator();
3920 while (it.hasNext()) {
3921 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003922 if (bp.packageSetting == null) {
3923 // We may not yet have parsed the package, so just see if
3924 // we still know about its settings.
3925 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3926 }
3927 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003928 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 + " from package " + bp.sourcePackage);
3930 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003931 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3932 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3933 Slog.i(TAG, "Removing old permission tree: " + bp.name
3934 + " from package " + bp.sourcePackage);
3935 grantPermissions = true;
3936 it.remove();
3937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 }
3939 }
3940
3941 // Make sure all dynamic permissions have been assigned to a package,
3942 // and make sure there are no dangling permissions.
3943 it = mSettings.mPermissions.values().iterator();
3944 while (it.hasNext()) {
3945 BasePermission bp = it.next();
3946 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3947 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3948 + bp.name + " pkg=" + bp.sourcePackage
3949 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003950 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 BasePermission tree = findPermissionTreeLP(bp.name);
3952 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003953 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 bp.perm = new PackageParser.Permission(tree.perm.owner,
3955 new PermissionInfo(bp.pendingInfo));
3956 bp.perm.info.packageName = tree.perm.info.packageName;
3957 bp.perm.info.name = bp.name;
3958 bp.uid = tree.uid;
3959 }
3960 }
3961 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003962 if (bp.packageSetting == null) {
3963 // We may not yet have parsed the package, so just see if
3964 // we still know about its settings.
3965 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3966 }
3967 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003968 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 + " from package " + bp.sourcePackage);
3970 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003971 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3972 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3973 Slog.i(TAG, "Removing old permission: " + bp.name
3974 + " from package " + bp.sourcePackage);
3975 grantPermissions = true;
3976 it.remove();
3977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 }
3979 }
3980
3981 // Now update the permissions for all packages, in particular
3982 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003983 if (grantPermissions) {
3984 for (PackageParser.Package pkg : mPackages.values()) {
3985 if (pkg != pkgInfo) {
3986 grantPermissionsLP(pkg, false);
3987 }
3988 }
3989 }
3990
3991 if (pkgInfo != null) {
3992 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 }
3994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3997 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3998 if (ps == null) {
3999 return;
4000 }
4001 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004002 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 if (replace) {
4005 ps.permissionsFixed = false;
4006 if (gp == ps) {
4007 gp.grantedPermissions.clear();
4008 gp.gids = mGlobalGids;
4009 }
4010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 if (gp.gids == null) {
4013 gp.gids = mGlobalGids;
4014 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 final int N = pkg.requestedPermissions.size();
4017 for (int i=0; i<N; i++) {
4018 String name = pkg.requestedPermissions.get(i);
4019 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 if (false) {
4021 if (gp != ps) {
4022 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004023 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 }
4025 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004026 if (bp != null && bp.packageSetting != null) {
4027 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004029 boolean allowedSig = false;
4030 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4031 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 allowed = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004033 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4034 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4035 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004037 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004039 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4041 // For updated system applications, the signatureOrSystem permission
4042 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004043 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4045 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4046 if(sysPs.grantedPermissions.contains(perm)) {
4047 allowed = true;
4048 } else {
4049 allowed = false;
4050 }
4051 } else {
4052 allowed = true;
4053 }
4054 }
4055 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004056 if (allowed) {
4057 allowedSig = true;
4058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 } else {
4060 allowed = false;
4061 }
4062 if (false) {
4063 if (gp != ps) {
4064 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4065 }
4066 }
4067 if (allowed) {
4068 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4069 && ps.permissionsFixed) {
4070 // If this is an existing, non-system package, then
4071 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004072 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004074 // Except... if this is a permission that was added
4075 // to the platform (note: need to only do this when
4076 // updating the platform).
4077 final int NP = PackageParser.NEW_PERMISSIONS.length;
4078 for (int ip=0; ip<NP; ip++) {
4079 final PackageParser.NewPermissionInfo npi
4080 = PackageParser.NEW_PERMISSIONS[ip];
4081 if (npi.name.equals(perm)
4082 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4083 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004084 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004085 + pkg.packageName);
4086 break;
4087 }
4088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 }
4090 }
4091 if (allowed) {
4092 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004093 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 gp.grantedPermissions.add(perm);
4095 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004096 } else if (!ps.haveGids) {
4097 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 }
4099 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004100 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 + " to package " + pkg.packageName
4102 + " because it was previously installed without");
4103 }
4104 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004105 if (gp.grantedPermissions.remove(perm)) {
4106 changedPermission = true;
4107 gp.gids = removeInts(gp.gids, bp.gids);
4108 Slog.i(TAG, "Un-granting permission " + perm
4109 + " from package " + pkg.packageName
4110 + " (protectionLevel=" + bp.protectionLevel
4111 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4112 + ")");
4113 } else {
4114 Slog.w(TAG, "Not granting permission " + perm
4115 + " to package " + pkg.packageName
4116 + " (protectionLevel=" + bp.protectionLevel
4117 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4118 + ")");
4119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 }
4121 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004122 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 + " in package " + pkg.packageName);
4124 }
4125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004126
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004127 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004128 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4129 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 // This is the first that we have heard about this package, so the
4131 // permissions we have now selected are fixed until explicitly
4132 // changed.
4133 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004135 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 private final class ActivityIntentResolver
4139 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004140 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004142 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 }
4144
Mihai Preda074edef2009-05-18 17:13:31 +02004145 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004147 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4149 }
4150
Mihai Predaeae850c2009-05-13 10:13:48 +02004151 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4152 ArrayList<PackageParser.Activity> packageActivities) {
4153 if (packageActivities == null) {
4154 return null;
4155 }
4156 mFlags = flags;
4157 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4158 int N = packageActivities.size();
4159 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4160 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004161
4162 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004163 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004164 intentFilters = packageActivities.get(i).intents;
4165 if (intentFilters != null && intentFilters.size() > 0) {
4166 listCut.add(intentFilters);
4167 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004168 }
4169 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4170 }
4171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004173 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 if (SHOW_INFO || Config.LOGV) Log.v(
4175 TAG, " " + type + " " +
4176 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4177 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4178 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004179 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4181 if (SHOW_INFO || Config.LOGV) {
4182 Log.v(TAG, " IntentFilter:");
4183 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4184 }
4185 if (!intent.debugCheck()) {
4186 Log.w(TAG, "==> For Activity " + a.info.name);
4187 }
4188 addFilter(intent);
4189 }
4190 }
4191
4192 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004193 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 if (SHOW_INFO || Config.LOGV) Log.v(
4195 TAG, " " + type + " " +
4196 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4197 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4198 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004199 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4201 if (SHOW_INFO || Config.LOGV) {
4202 Log.v(TAG, " IntentFilter:");
4203 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4204 }
4205 removeFilter(intent);
4206 }
4207 }
4208
4209 @Override
4210 protected boolean allowFilterResult(
4211 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4212 ActivityInfo filterAi = filter.activity.info;
4213 for (int i=dest.size()-1; i>=0; i--) {
4214 ActivityInfo destAi = dest.get(i).activityInfo;
4215 if (destAi.name == filterAi.name
4216 && destAi.packageName == filterAi.packageName) {
4217 return false;
4218 }
4219 }
4220 return true;
4221 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004224 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4225 return info.activity.owner.packageName;
4226 }
4227
4228 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4230 int match) {
4231 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4232 return null;
4233 }
4234 final PackageParser.Activity activity = info.activity;
4235 if (mSafeMode && (activity.info.applicationInfo.flags
4236 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4237 return null;
4238 }
4239 final ResolveInfo res = new ResolveInfo();
4240 res.activityInfo = PackageParser.generateActivityInfo(activity,
4241 mFlags);
4242 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4243 res.filter = info;
4244 }
4245 res.priority = info.getPriority();
4246 res.preferredOrder = activity.owner.mPreferredOrder;
4247 //System.out.println("Result: " + res.activityInfo.className +
4248 // " = " + res.priority);
4249 res.match = match;
4250 res.isDefault = info.hasDefault;
4251 res.labelRes = info.labelRes;
4252 res.nonLocalizedLabel = info.nonLocalizedLabel;
4253 res.icon = info.icon;
4254 return res;
4255 }
4256
4257 @Override
4258 protected void sortResults(List<ResolveInfo> results) {
4259 Collections.sort(results, mResolvePrioritySorter);
4260 }
4261
4262 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004263 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004265 out.print(prefix); out.print(
4266 Integer.toHexString(System.identityHashCode(filter.activity)));
4267 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004268 out.print(filter.activity.getComponentShortName());
4269 out.print(" filter ");
4270 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 }
4272
4273// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4274// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4275// final List<ResolveInfo> retList = Lists.newArrayList();
4276// while (i.hasNext()) {
4277// final ResolveInfo resolveInfo = i.next();
4278// if (isEnabledLP(resolveInfo.activityInfo)) {
4279// retList.add(resolveInfo);
4280// }
4281// }
4282// return retList;
4283// }
4284
4285 // Keys are String (activity class name), values are Activity.
4286 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4287 = new HashMap<ComponentName, PackageParser.Activity>();
4288 private int mFlags;
4289 }
4290
4291 private final class ServiceIntentResolver
4292 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004293 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004295 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 }
4297
Mihai Preda074edef2009-05-18 17:13:31 +02004298 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004300 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4302 }
4303
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004304 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4305 ArrayList<PackageParser.Service> packageServices) {
4306 if (packageServices == null) {
4307 return null;
4308 }
4309 mFlags = flags;
4310 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4311 int N = packageServices.size();
4312 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4313 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4314
4315 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4316 for (int i = 0; i < N; ++i) {
4317 intentFilters = packageServices.get(i).intents;
4318 if (intentFilters != null && intentFilters.size() > 0) {
4319 listCut.add(intentFilters);
4320 }
4321 }
4322 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4323 }
4324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004326 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 if (SHOW_INFO || Config.LOGV) Log.v(
4328 TAG, " " + (s.info.nonLocalizedLabel != null
4329 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4330 if (SHOW_INFO || Config.LOGV) Log.v(
4331 TAG, " Class=" + s.info.name);
4332 int NI = s.intents.size();
4333 int j;
4334 for (j=0; j<NI; j++) {
4335 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4336 if (SHOW_INFO || Config.LOGV) {
4337 Log.v(TAG, " IntentFilter:");
4338 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4339 }
4340 if (!intent.debugCheck()) {
4341 Log.w(TAG, "==> For Service " + s.info.name);
4342 }
4343 addFilter(intent);
4344 }
4345 }
4346
4347 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004348 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 if (SHOW_INFO || Config.LOGV) Log.v(
4350 TAG, " " + (s.info.nonLocalizedLabel != null
4351 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4352 if (SHOW_INFO || Config.LOGV) Log.v(
4353 TAG, " Class=" + s.info.name);
4354 int NI = s.intents.size();
4355 int j;
4356 for (j=0; j<NI; j++) {
4357 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4358 if (SHOW_INFO || Config.LOGV) {
4359 Log.v(TAG, " IntentFilter:");
4360 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4361 }
4362 removeFilter(intent);
4363 }
4364 }
4365
4366 @Override
4367 protected boolean allowFilterResult(
4368 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4369 ServiceInfo filterSi = filter.service.info;
4370 for (int i=dest.size()-1; i>=0; i--) {
4371 ServiceInfo destAi = dest.get(i).serviceInfo;
4372 if (destAi.name == filterSi.name
4373 && destAi.packageName == filterSi.packageName) {
4374 return false;
4375 }
4376 }
4377 return true;
4378 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004381 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4382 return info.service.owner.packageName;
4383 }
4384
4385 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4387 int match) {
4388 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4389 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4390 return null;
4391 }
4392 final PackageParser.Service service = info.service;
4393 if (mSafeMode && (service.info.applicationInfo.flags
4394 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4395 return null;
4396 }
4397 final ResolveInfo res = new ResolveInfo();
4398 res.serviceInfo = PackageParser.generateServiceInfo(service,
4399 mFlags);
4400 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4401 res.filter = filter;
4402 }
4403 res.priority = info.getPriority();
4404 res.preferredOrder = service.owner.mPreferredOrder;
4405 //System.out.println("Result: " + res.activityInfo.className +
4406 // " = " + res.priority);
4407 res.match = match;
4408 res.isDefault = info.hasDefault;
4409 res.labelRes = info.labelRes;
4410 res.nonLocalizedLabel = info.nonLocalizedLabel;
4411 res.icon = info.icon;
4412 return res;
4413 }
4414
4415 @Override
4416 protected void sortResults(List<ResolveInfo> results) {
4417 Collections.sort(results, mResolvePrioritySorter);
4418 }
4419
4420 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004421 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004423 out.print(prefix); out.print(
4424 Integer.toHexString(System.identityHashCode(filter.service)));
4425 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004426 out.print(filter.service.getComponentShortName());
4427 out.print(" filter ");
4428 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 }
4430
4431// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4432// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4433// final List<ResolveInfo> retList = Lists.newArrayList();
4434// while (i.hasNext()) {
4435// final ResolveInfo resolveInfo = (ResolveInfo) i;
4436// if (isEnabledLP(resolveInfo.serviceInfo)) {
4437// retList.add(resolveInfo);
4438// }
4439// }
4440// return retList;
4441// }
4442
4443 // Keys are String (activity class name), values are Activity.
4444 private final HashMap<ComponentName, PackageParser.Service> mServices
4445 = new HashMap<ComponentName, PackageParser.Service>();
4446 private int mFlags;
4447 };
4448
4449 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4450 new Comparator<ResolveInfo>() {
4451 public int compare(ResolveInfo r1, ResolveInfo r2) {
4452 int v1 = r1.priority;
4453 int v2 = r2.priority;
4454 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4455 if (v1 != v2) {
4456 return (v1 > v2) ? -1 : 1;
4457 }
4458 v1 = r1.preferredOrder;
4459 v2 = r2.preferredOrder;
4460 if (v1 != v2) {
4461 return (v1 > v2) ? -1 : 1;
4462 }
4463 if (r1.isDefault != r2.isDefault) {
4464 return r1.isDefault ? -1 : 1;
4465 }
4466 v1 = r1.match;
4467 v2 = r2.match;
4468 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4469 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4470 }
4471 };
4472
4473 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4474 new Comparator<ProviderInfo>() {
4475 public int compare(ProviderInfo p1, ProviderInfo p2) {
4476 final int v1 = p1.initOrder;
4477 final int v2 = p2.initOrder;
4478 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4479 }
4480 };
4481
4482 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4483 IActivityManager am = ActivityManagerNative.getDefault();
4484 if (am != null) {
4485 try {
4486 final Intent intent = new Intent(action,
4487 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4488 if (extras != null) {
4489 intent.putExtras(extras);
4490 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004491 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 am.broadcastIntent(
4493 null, intent,
4494 null, null, 0, null, null, null, false, false);
4495 } catch (RemoteException ex) {
4496 }
4497 }
4498 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004499
4500 public String nextPackageToClean(String lastPackage) {
4501 synchronized (mPackages) {
4502 if (!mMediaMounted) {
4503 // If the external storage is no longer mounted at this point,
4504 // the caller may not have been able to delete all of this
4505 // packages files and can not delete any more. Bail.
4506 return null;
4507 }
4508 if (lastPackage != null) {
4509 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4510 }
4511 return mSettings.mPackagesToBeCleaned.size() > 0
4512 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4513 }
4514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004516 void schedulePackageCleaning(String packageName) {
4517 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4518 }
4519
4520 void startCleaningPackages() {
4521 synchronized (mPackages) {
4522 if (!mMediaMounted) {
4523 return;
4524 }
4525 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4526 return;
4527 }
4528 }
4529 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4530 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4531 IActivityManager am = ActivityManagerNative.getDefault();
4532 if (am != null) {
4533 try {
4534 am.startService(null, intent, null);
4535 } catch (RemoteException e) {
4536 }
4537 }
4538 }
4539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004540 private final class AppDirObserver extends FileObserver {
4541 public AppDirObserver(String path, int mask, boolean isrom) {
4542 super(path, mask);
4543 mRootDir = path;
4544 mIsRom = isrom;
4545 }
4546
4547 public void onEvent(int event, String path) {
4548 String removedPackage = null;
4549 int removedUid = -1;
4550 String addedPackage = null;
4551 int addedUid = -1;
4552
4553 synchronized (mInstallLock) {
4554 String fullPathStr = null;
4555 File fullPath = null;
4556 if (path != null) {
4557 fullPath = new File(mRootDir, path);
4558 fullPathStr = fullPath.getPath();
4559 }
4560
4561 if (Config.LOGV) Log.v(
4562 TAG, "File " + fullPathStr + " changed: "
4563 + Integer.toHexString(event));
4564
4565 if (!isPackageFilename(path)) {
4566 if (Config.LOGV) Log.v(
4567 TAG, "Ignoring change of non-package file: " + fullPathStr);
4568 return;
4569 }
4570
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004571 // Ignore packages that are being installed or
4572 // have just been installed.
4573 if (ignoreCodePath(fullPathStr)) {
4574 return;
4575 }
4576 PackageParser.Package p = null;
4577 synchronized (mPackages) {
4578 p = mAppDirs.get(fullPathStr);
4579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004581 if (p != null) {
4582 removePackageLI(p, true);
4583 removedPackage = p.applicationInfo.packageName;
4584 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 }
4586 }
4587
4588 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004590 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004591 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4592 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 PackageParser.PARSE_CHATTY |
4594 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004595 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 if (p != null) {
4597 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004598 updatePermissionsLP(p.packageName, p,
4599 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600 }
4601 addedPackage = p.applicationInfo.packageName;
4602 addedUid = p.applicationInfo.uid;
4603 }
4604 }
4605 }
4606
4607 synchronized (mPackages) {
4608 mSettings.writeLP();
4609 }
4610 }
4611
4612 if (removedPackage != null) {
4613 Bundle extras = new Bundle(1);
4614 extras.putInt(Intent.EXTRA_UID, removedUid);
4615 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4616 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4617 }
4618 if (addedPackage != null) {
4619 Bundle extras = new Bundle(1);
4620 extras.putInt(Intent.EXTRA_UID, addedUid);
4621 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4622 }
4623 }
4624
4625 private final String mRootDir;
4626 private final boolean mIsRom;
4627 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 /* Called when a downloaded package installation has been confirmed by the user */
4630 public void installPackage(
4631 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004632 installPackage(packageURI, observer, flags, null);
4633 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004634
Jacek Surazski65e13172009-04-28 15:26:38 +02004635 /* Called when a downloaded package installation has been confirmed by the user */
4636 public void installPackage(
4637 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4638 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 mContext.enforceCallingOrSelfPermission(
4640 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004641
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004642 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004643 msg.obj = new InstallParams(packageURI, observer, flags,
4644 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004645 mHandler.sendMessage(msg);
4646 }
4647
Christopher Tate1bb69062010-02-19 17:02:12 -08004648 public void finishPackageInstall(int token) {
4649 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4650 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4651 mHandler.sendMessage(msg);
4652 }
4653
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004654 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004655 // Queue up an async operation since the package installation may take a little while.
4656 mHandler.post(new Runnable() {
4657 public void run() {
4658 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004659 // Result object to be returned
4660 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004661 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004662 res.uid = -1;
4663 res.pkg = null;
4664 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004665 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004666 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004667 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004668 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004669 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004670 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004672
4673 // A restore should be performed at this point if (a) the install
4674 // succeeded, (b) the operation is not an update, and (c) the new
4675 // package has a backupAgent defined.
4676 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004677 boolean doRestore = (!update
4678 && res.pkg != null
4679 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004680
4681 // Set up the post-install work request bookkeeping. This will be used
4682 // and cleaned up by the post-install event handling regardless of whether
4683 // there's a restore pass performed. Token values are >= 1.
4684 int token;
4685 if (mNextInstallToken < 0) mNextInstallToken = 1;
4686 token = mNextInstallToken++;
4687
4688 PostInstallData data = new PostInstallData(args, res);
4689 mRunningInstalls.put(token, data);
4690 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4691
4692 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4693 // Pass responsibility to the Backup Manager. It will perform a
4694 // restore if appropriate, then pass responsibility back to the
4695 // Package Manager to run the post-install observer callbacks
4696 // and broadcasts.
4697 IBackupManager bm = IBackupManager.Stub.asInterface(
4698 ServiceManager.getService(Context.BACKUP_SERVICE));
4699 if (bm != null) {
4700 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4701 + " to BM for possible restore");
4702 try {
4703 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4704 } catch (RemoteException e) {
4705 // can't happen; the backup manager is local
4706 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004707 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004708 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004709 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004710 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004711 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004712 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004715
4716 if (!doRestore) {
4717 // No restore possible, or the Backup Manager was mysteriously not
4718 // available -- just fire the post-install work request directly.
4719 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4720 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4721 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004723 }
4724 });
4725 }
4726
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004727 abstract class HandlerParams {
4728 final static int MAX_RETRIES = 4;
4729 int retry = 0;
4730 final void startCopy() {
4731 try {
4732 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4733 retry++;
4734 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004735 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004736 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4737 handleServiceError();
4738 return;
4739 } else {
4740 handleStartCopy();
4741 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4742 mHandler.sendEmptyMessage(MCS_UNBIND);
4743 }
4744 } catch (RemoteException e) {
4745 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4746 mHandler.sendEmptyMessage(MCS_RECONNECT);
4747 }
4748 handleReturnCode();
4749 }
4750
4751 final void serviceError() {
4752 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4753 handleServiceError();
4754 handleReturnCode();
4755 }
4756 abstract void handleStartCopy() throws RemoteException;
4757 abstract void handleServiceError();
4758 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004759 }
4760
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004761 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004762 final IPackageInstallObserver observer;
4763 int flags;
4764 final Uri packageURI;
4765 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004766 private InstallArgs mArgs;
4767 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004768 InstallParams(Uri packageURI,
4769 IPackageInstallObserver observer, int flags,
4770 String installerPackageName) {
4771 this.packageURI = packageURI;
4772 this.flags = flags;
4773 this.observer = observer;
4774 this.installerPackageName = installerPackageName;
4775 }
4776
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004777 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4778 String packageName = pkgLite.packageName;
4779 int installLocation = pkgLite.installLocation;
4780 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4781 synchronized (mPackages) {
4782 PackageParser.Package pkg = mPackages.get(packageName);
4783 if (pkg != null) {
4784 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4785 // Check for updated system application.
4786 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4787 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004788 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004789 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4790 }
4791 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4792 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004793 if (onSd) {
4794 // Install flag overrides everything.
4795 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4796 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004797 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004798 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4799 // Application explicitly specified internal.
4800 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4801 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4802 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004803 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004804 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004805 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4806 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4807 }
4808 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004809 }
4810 }
4811 } else {
4812 // Invalid install. Return error code
4813 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4814 }
4815 }
4816 }
4817 // All the special cases have been taken care of.
4818 // Return result based on recommended install location.
4819 if (onSd) {
4820 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4821 }
4822 return pkgLite.recommendedInstallLocation;
4823 }
4824
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004825 /*
4826 * Invoke remote method to get package information and install
4827 * location values. Override install location based on default
4828 * policy if needed and then create install arguments based
4829 * on the install location.
4830 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004831 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004832 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004833 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4834 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004835 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4836 if (onInt && onSd) {
4837 // Check if both bits are set.
4838 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4839 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4840 } else if (fwdLocked && onSd) {
4841 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004842 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004843 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004844 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004845 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004846 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004847 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004848 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4849 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4850 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4851 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4852 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004853 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4854 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4855 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004856 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4857 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004859 // Override with defaults if needed.
4860 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004861 if (!onSd && !onInt) {
4862 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004863 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4864 // Set the flag to install on external media.
4865 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004866 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004867 } else {
4868 // Make sure the flag for installing on external
4869 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004870 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004871 flags &= ~PackageManager.INSTALL_EXTERNAL;
4872 }
4873 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004874 }
4875 }
4876 // Create the file args now.
4877 mArgs = createInstallArgs(this);
4878 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4879 // Create copy only if we are not in an erroneous state.
4880 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004881 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004882 }
4883 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004884 }
4885
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004886 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004887 void handleReturnCode() {
4888 processPendingInstall(mArgs, mRet);
4889 }
4890
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004891 @Override
4892 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004893 mArgs = createInstallArgs(this);
4894 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004895 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004896 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004897
4898 /*
4899 * Utility class used in movePackage api.
4900 * srcArgs and targetArgs are not set for invalid flags and make
4901 * sure to do null checks when invoking methods on them.
4902 * We probably want to return ErrorPrams for both failed installs
4903 * and moves.
4904 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004905 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004906 final IPackageMoveObserver observer;
4907 final int flags;
4908 final String packageName;
4909 final InstallArgs srcArgs;
4910 final InstallArgs targetArgs;
4911 int mRet;
4912 MoveParams(InstallArgs srcArgs,
4913 IPackageMoveObserver observer,
4914 int flags, String packageName) {
4915 this.srcArgs = srcArgs;
4916 this.observer = observer;
4917 this.flags = flags;
4918 this.packageName = packageName;
4919 if (srcArgs != null) {
4920 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4921 targetArgs = createInstallArgs(packageUri, flags, packageName);
4922 } else {
4923 targetArgs = null;
4924 }
4925 }
4926
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004927 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004928 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4929 // Check for storage space on target medium
4930 if (!targetArgs.checkFreeStorage(mContainerService)) {
4931 Log.w(TAG, "Insufficient storage to install");
4932 return;
4933 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004934 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004935 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004936 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004937 if (DEBUG_SD_INSTALL) {
4938 StringBuilder builder = new StringBuilder();
4939 if (srcArgs != null) {
4940 builder.append("src: ");
4941 builder.append(srcArgs.getCodePath());
4942 }
4943 if (targetArgs != null) {
4944 builder.append(" target : ");
4945 builder.append(targetArgs.getCodePath());
4946 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004947 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004948 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004949 }
4950
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004951 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004952 void handleReturnCode() {
4953 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004954 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4955 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4956 currentStatus = PackageManager.MOVE_SUCCEEDED;
4957 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4958 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4959 }
4960 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 }
4962
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004963 @Override
4964 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004965 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004966 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004967 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004968
4969 private InstallArgs createInstallArgs(InstallParams params) {
4970 if (installOnSd(params.flags)) {
4971 return new SdInstallArgs(params);
4972 } else {
4973 return new FileInstallArgs(params);
4974 }
4975 }
4976
4977 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4978 if (installOnSd(flags)) {
4979 return new SdInstallArgs(fullCodePath, fullResourcePath);
4980 } else {
4981 return new FileInstallArgs(fullCodePath, fullResourcePath);
4982 }
4983 }
4984
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004985 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4986 if (installOnSd(flags)) {
4987 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4988 return new SdInstallArgs(packageURI, cid);
4989 } else {
4990 return new FileInstallArgs(packageURI, pkgName);
4991 }
4992 }
4993
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004994 static abstract class InstallArgs {
4995 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004996 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004997 final int flags;
4998 final Uri packageURI;
4999 final String installerPackageName;
5000
5001 InstallArgs(Uri packageURI,
5002 IPackageInstallObserver observer, int flags,
5003 String installerPackageName) {
5004 this.packageURI = packageURI;
5005 this.flags = flags;
5006 this.observer = observer;
5007 this.installerPackageName = installerPackageName;
5008 }
5009
5010 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005011 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005012 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005013 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005014 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005015 abstract String getCodePath();
5016 abstract String getResourcePath();
5017 // Need installer lock especially for dex file removal.
5018 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005019 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005020 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005021 }
5022
5023 class FileInstallArgs extends InstallArgs {
5024 File installDir;
5025 String codeFileName;
5026 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005027 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005028
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005029 FileInstallArgs(InstallParams params) {
5030 super(params.packageURI, params.observer,
5031 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005032 }
5033
5034 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5035 super(null, null, 0, null);
5036 File codeFile = new File(fullCodePath);
5037 installDir = codeFile.getParentFile();
5038 codeFileName = fullCodePath;
5039 resourceFileName = fullResourcePath;
5040 }
5041
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005042 FileInstallArgs(Uri packageURI, String pkgName) {
5043 super(packageURI, null, 0, null);
5044 boolean fwdLocked = isFwdLocked(flags);
5045 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5046 String apkName = getNextCodePath(null, pkgName, ".apk");
5047 codeFileName = new File(installDir, apkName + ".apk").getPath();
5048 resourceFileName = getResourcePathFromCodePath();
5049 }
5050
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005051 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5052 return imcs.checkFreeStorage(false, packageURI);
5053 }
5054
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005055 String getCodePath() {
5056 return codeFileName;
5057 }
5058
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005059 void createCopyFile() {
5060 boolean fwdLocked = isFwdLocked(flags);
5061 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5062 codeFileName = createTempPackageFile(installDir).getPath();
5063 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005064 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005065 }
5066
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005067 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005068 if (temp) {
5069 // Generate temp file name
5070 createCopyFile();
5071 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005072 // Get a ParcelFileDescriptor to write to the output file
5073 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005074 if (!created) {
5075 try {
5076 codeFile.createNewFile();
5077 // Set permissions
5078 if (!setPermissions()) {
5079 // Failed setting permissions.
5080 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5081 }
5082 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005083 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005084 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5085 }
5086 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005087 ParcelFileDescriptor out = null;
5088 try {
5089 out = ParcelFileDescriptor.open(codeFile,
5090 ParcelFileDescriptor.MODE_READ_WRITE);
5091 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005092 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005093 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5094 }
5095 // Copy the resource now
5096 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5097 try {
5098 if (imcs.copyResource(packageURI, out)) {
5099 ret = PackageManager.INSTALL_SUCCEEDED;
5100 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005101 } finally {
5102 try { if (out != null) out.close(); } catch (IOException e) {}
5103 }
5104 return ret;
5105 }
5106
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005107 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005108 if (status != PackageManager.INSTALL_SUCCEEDED) {
5109 cleanUp();
5110 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005111 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005112 }
5113
5114 boolean doRename(int status, final String pkgName, String oldCodePath) {
5115 if (status != PackageManager.INSTALL_SUCCEEDED) {
5116 cleanUp();
5117 return false;
5118 } else {
5119 // Rename based on packageName
5120 File codeFile = new File(getCodePath());
5121 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5122 File desFile = new File(installDir, apkName + ".apk");
5123 if (!codeFile.renameTo(desFile)) {
5124 return false;
5125 }
5126 // Reset paths since the file has been renamed.
5127 codeFileName = desFile.getPath();
5128 resourceFileName = getResourcePathFromCodePath();
5129 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005130 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005131 // Failed setting permissions.
5132 return false;
5133 }
5134 return true;
5135 }
5136 }
5137
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005138 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005139 if (status != PackageManager.INSTALL_SUCCEEDED) {
5140 cleanUp();
5141 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005142 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005143 }
5144
5145 String getResourcePath() {
5146 return resourceFileName;
5147 }
5148
5149 String getResourcePathFromCodePath() {
5150 String codePath = getCodePath();
5151 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5152 String apkNameOnly = getApkName(codePath);
5153 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5154 } else {
5155 return codePath;
5156 }
5157 }
5158
5159 private boolean cleanUp() {
5160 boolean ret = true;
5161 String sourceDir = getCodePath();
5162 String publicSourceDir = getResourcePath();
5163 if (sourceDir != null) {
5164 File sourceFile = new File(sourceDir);
5165 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005166 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005167 ret = false;
5168 }
5169 // Delete application's code and resources
5170 sourceFile.delete();
5171 }
5172 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5173 final File publicSourceFile = new File(publicSourceDir);
5174 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005175 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005176 }
5177 if (publicSourceFile.exists()) {
5178 publicSourceFile.delete();
5179 }
5180 }
5181 return ret;
5182 }
5183
5184 void cleanUpResourcesLI() {
5185 String sourceDir = getCodePath();
5186 if (cleanUp() && mInstaller != null) {
5187 int retCode = mInstaller.rmdex(sourceDir);
5188 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005189 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005190 + " at location "
5191 + sourceDir + ", retcode=" + retCode);
5192 // we don't consider this to be a failure of the core package deletion
5193 }
5194 }
5195 }
5196
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005197 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005198 // TODO Do this in a more elegant way later on. for now just a hack
5199 if (!isFwdLocked(flags)) {
5200 final int filePermissions =
5201 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5202 |FileUtils.S_IROTH;
5203 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5204 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005205 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005206 getCodePath()
5207 + ". The return code was: " + retCode);
5208 // TODO Define new internal error
5209 return false;
5210 }
5211 return true;
5212 }
5213 return true;
5214 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005215
5216 boolean doPostDeleteLI(boolean delete) {
5217 cleanUpResourcesLI();
5218 return true;
5219 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005220 }
5221
5222 class SdInstallArgs extends InstallArgs {
5223 String cid;
5224 String cachePath;
5225 static final String RES_FILE_NAME = "pkg.apk";
5226
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005227 SdInstallArgs(InstallParams params) {
5228 super(params.packageURI, params.observer,
5229 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005230 }
5231
5232 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005233 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005234 // Extract cid from fullCodePath
5235 int eidx = fullCodePath.lastIndexOf("/");
5236 String subStr1 = fullCodePath.substring(0, eidx);
5237 int sidx = subStr1.lastIndexOf("/");
5238 cid = subStr1.substring(sidx+1, eidx);
5239 cachePath = subStr1;
5240 }
5241
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005242 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005243 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5244 this.cid = cid;
5245 }
5246
5247 SdInstallArgs(Uri packageURI, String cid) {
5248 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005249 this.cid = cid;
5250 }
5251
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005252 void createCopyFile() {
5253 cid = getTempContainerId();
5254 }
5255
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005256 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5257 return imcs.checkFreeStorage(true, packageURI);
5258 }
5259
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005260 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005261 if (temp) {
5262 createCopyFile();
5263 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005264 cachePath = imcs.copyResourceToContainer(
5265 packageURI, cid,
5266 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005267 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5268 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005269 }
5270
5271 @Override
5272 String getCodePath() {
5273 return cachePath + "/" + RES_FILE_NAME;
5274 }
5275
5276 @Override
5277 String getResourcePath() {
5278 return cachePath + "/" + RES_FILE_NAME;
5279 }
5280
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005281 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005282 if (status != PackageManager.INSTALL_SUCCEEDED) {
5283 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005284 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005285 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005286 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005287 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005288 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005289 if (cachePath == null) {
5290 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5291 }
5292 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005293 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005294 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005295 }
5296
5297 boolean doRename(int status, final String pkgName,
5298 String oldCodePath) {
5299 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005300 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005301 if (PackageHelper.isContainerMounted(cid)) {
5302 // Unmount the container
5303 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005304 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005305 return false;
5306 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005307 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005308 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005309 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5310 " which might be stale. Will try to clean up.");
5311 // Clean up the stale container and proceed to recreate.
5312 if (!PackageHelper.destroySdDir(newCacheId)) {
5313 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5314 return false;
5315 }
5316 // Successfully cleaned up stale container. Try to rename again.
5317 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5318 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5319 + " inspite of cleaning it up.");
5320 return false;
5321 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005322 }
5323 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005324 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005325 newCachePath = PackageHelper.mountSdDir(newCacheId,
5326 getEncryptKey(), Process.SYSTEM_UID);
5327 } else {
5328 newCachePath = PackageHelper.getSdDir(newCacheId);
5329 }
5330 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005331 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005332 return false;
5333 }
5334 Log.i(TAG, "Succesfully renamed " + cid +
5335 " at path: " + cachePath + " to " + newCacheId +
5336 " at new path: " + newCachePath);
5337 cid = newCacheId;
5338 cachePath = newCachePath;
5339 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005340 }
5341
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005342 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005343 if (status != PackageManager.INSTALL_SUCCEEDED) {
5344 cleanUp();
5345 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005346 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005347 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005348 PackageHelper.mountSdDir(cid,
5349 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005350 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005351 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005352 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005353 }
5354
5355 private void cleanUp() {
5356 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005357 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005358 }
5359
5360 void cleanUpResourcesLI() {
5361 String sourceFile = getCodePath();
5362 // Remove dex file
5363 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005364 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005365 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005366 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005367 + " at location "
5368 + sourceFile.toString() + ", retcode=" + retCode);
5369 // we don't consider this to be a failure of the core package deletion
5370 }
5371 }
5372 cleanUp();
5373 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005374
5375 boolean matchContainer(String app) {
5376 if (cid.startsWith(app)) {
5377 return true;
5378 }
5379 return false;
5380 }
5381
5382 String getPackageName() {
5383 int idx = cid.lastIndexOf("-");
5384 if (idx == -1) {
5385 return cid;
5386 }
5387 return cid.substring(0, idx);
5388 }
5389
5390 boolean doPostDeleteLI(boolean delete) {
5391 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005392 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005393 if (mounted) {
5394 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005395 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005396 }
5397 if (ret && delete) {
5398 cleanUpResourcesLI();
5399 }
5400 return ret;
5401 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005402 };
5403
5404 // Utility method used to create code paths based on package name and available index.
5405 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5406 String idxStr = "";
5407 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005408 // Fall back to default value of idx=1 if prefix is not
5409 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005410 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005411 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005412 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005413 if (subStr.endsWith(suffix)) {
5414 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005415 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005416 // If oldCodePath already contains prefix find out the
5417 // ending index to either increment or decrement.
5418 int sidx = subStr.lastIndexOf(prefix);
5419 if (sidx != -1) {
5420 subStr = subStr.substring(sidx + prefix.length());
5421 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005422 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5423 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005424 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005425 try {
5426 idx = Integer.parseInt(subStr);
5427 if (idx <= 1) {
5428 idx++;
5429 } else {
5430 idx--;
5431 }
5432 } catch(NumberFormatException e) {
5433 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005434 }
5435 }
5436 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005437 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005438 return prefix + idxStr;
5439 }
5440
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005441 // Utility method used to ignore ADD/REMOVE events
5442 // by directory observer.
5443 private static boolean ignoreCodePath(String fullPathStr) {
5444 String apkName = getApkName(fullPathStr);
5445 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5446 if (idx != -1 && ((idx+1) < apkName.length())) {
5447 // Make sure the package ends with a numeral
5448 String version = apkName.substring(idx+1);
5449 try {
5450 Integer.parseInt(version);
5451 return true;
5452 } catch (NumberFormatException e) {}
5453 }
5454 return false;
5455 }
5456
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005457 // Utility method that returns the relative package path with respect
5458 // to the installation directory. Like say for /data/data/com.test-1.apk
5459 // string com.test-1 is returned.
5460 static String getApkName(String codePath) {
5461 if (codePath == null) {
5462 return null;
5463 }
5464 int sidx = codePath.lastIndexOf("/");
5465 int eidx = codePath.lastIndexOf(".");
5466 if (eidx == -1) {
5467 eidx = codePath.length();
5468 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005469 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005470 return null;
5471 }
5472 return codePath.substring(sidx+1, eidx);
5473 }
5474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 class PackageInstalledInfo {
5476 String name;
5477 int uid;
5478 PackageParser.Package pkg;
5479 int returnCode;
5480 PackageRemovedInfo removedInfo;
5481 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 /*
5484 * Install a non-existing package.
5485 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005486 private void installNewPackageLI(PackageParser.Package pkg,
5487 int parseFlags,
5488 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005489 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005491 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005492
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005493 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 res.name = pkgName;
5495 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005496 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5497 // A package with the same name is already installed, though
5498 // it has been renamed to an older name. The package we
5499 // are trying to install should be installed as an update to
5500 // the existing one, but that has not been requested, so bail.
5501 Slog.w(TAG, "Attempt to re-install " + pkgName
5502 + " without first uninstalling package running as "
5503 + mSettings.mRenamedPackages.get(pkgName));
5504 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5505 return;
5506 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005507 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005509 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 + " without first uninstalling.");
5511 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5512 return;
5513 }
5514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005516 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005518 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5520 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5521 }
5522 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005523 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005524 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 res);
5526 // delete the partially installed application. the data directory will have to be
5527 // restored if it was already existing
5528 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5529 // remove package from internal structures. Note that we want deletePackageX to
5530 // delete the package data and cache directories that it created in
5531 // scanPackageLocked, unless those directories existed before we even tried to
5532 // install.
5533 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005534 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5536 res.removedInfo);
5537 }
5538 }
5539 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005540
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005541 private void replacePackageLI(PackageParser.Package pkg,
5542 int parseFlags,
5543 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005544 String installerPackageName, PackageInstalledInfo res) {
5545
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005546 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005547 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 // First find the old package info and check signatures
5549 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005550 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005551 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005552 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5554 return;
5555 }
5556 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005557 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005558 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005559 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005561 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562 }
5563 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005566 PackageParser.Package pkg,
5567 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005568 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 PackageParser.Package newPackage = null;
5570 String pkgName = deletedPackage.packageName;
5571 boolean deletedPkg = true;
5572 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005573
Jacek Surazski65e13172009-04-28 15:26:38 +02005574 String oldInstallerPackageName = null;
5575 synchronized (mPackages) {
5576 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005580 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 res.removedInfo)) {
5582 // If the existing package was'nt successfully deleted
5583 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5584 deletedPkg = false;
5585 } else {
5586 // Successfully deleted the old package. Now proceed with re-installation
5587 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005588 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005590 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5592 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005593 }
5594 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005595 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005596 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 res);
5598 updatedSettings = true;
5599 }
5600 }
5601
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005602 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 // remove package from internal structures. Note that we want deletePackageX to
5604 // delete the package data and cache directories that it created in
5605 // scanPackageLocked, unless those directories existed before we even tried to
5606 // install.
5607 if(updatedSettings) {
5608 deletePackageLI(
5609 pkgName, true,
5610 PackageManager.DONT_DELETE_DATA,
5611 res.removedInfo);
5612 }
5613 // Since we failed to install the new package we need to restore the old
5614 // package that we deleted.
5615 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005616 File restoreFile = new File(deletedPackage.mPath);
5617 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005618 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005619 return;
5620 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005621 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005622 boolean oldOnSd = isExternal(deletedPackage);
5623 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5624 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5625 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5626 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5627 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5628 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5629 return;
5630 }
5631 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005632 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005633 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5634 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005635 mSettings.writeLP();
5636 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005637 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 }
5639 }
5640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005643 PackageParser.Package pkg,
5644 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005645 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 PackageParser.Package newPackage = null;
5647 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005648 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 PackageParser.PARSE_IS_SYSTEM;
5650 String packageName = deletedPackage.packageName;
5651 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5652 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005653 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 return;
5655 }
5656 PackageParser.Package oldPkg;
5657 PackageSetting oldPkgSetting;
5658 synchronized (mPackages) {
5659 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005660 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5662 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005663 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 return;
5665 }
5666 }
5667 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5668 res.removedInfo.removedPackage = packageName;
5669 // Remove existing system package
5670 removePackageLI(oldPkg, true);
5671 synchronized (mPackages) {
5672 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5673 }
5674
5675 // Successfully disabled the old package. Now proceed with re-installation
5676 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5677 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005678 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005679 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005680 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5682 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5683 }
5684 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005685 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 updatedSettings = true;
5687 }
5688
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005689 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005690 // Re installation failed. Restore old information
5691 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005692 if (newPackage != null) {
5693 removePackageLI(newPackage, true);
5694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005696 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005698 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 // Restore the old system information in Settings
5700 synchronized(mPackages) {
5701 if(updatedSettings) {
5702 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005703 mSettings.setInstallerPackageName(packageName,
5704 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 }
5706 mSettings.writeLP();
5707 }
5708 }
5709 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005710
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005711 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005712 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005713 int retCode;
5714 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5715 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5716 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005717 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005718 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5719 }
5720 }
5721 return PackageManager.INSTALL_SUCCEEDED;
5722 }
5723
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005724 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005725 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005726 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 synchronized (mPackages) {
5728 //write settings. the installStatus will be incomplete at this stage.
5729 //note that the new package setting would have already been
5730 //added to mPackages. It hasn't been persisted yet.
5731 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5732 mSettings.writeLP();
5733 }
5734
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005735 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005736 != PackageManager.INSTALL_SUCCEEDED) {
5737 // Discontinue if moving dex files failed.
5738 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005740 if((res.returnCode = setPermissionsLI(newPackage))
5741 != PackageManager.INSTALL_SUCCEEDED) {
5742 if (mInstaller != null) {
5743 mInstaller.rmdex(newPackage.mScanPath);
5744 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005745 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005747 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005750 updatePermissionsLP(newPackage.packageName, newPackage,
5751 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 res.name = pkgName;
5753 res.uid = newPackage.applicationInfo.uid;
5754 res.pkg = newPackage;
5755 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005756 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5758 //to update install status
5759 mSettings.writeLP();
5760 }
5761 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005762
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005763 private void installPackageLI(InstallArgs args,
5764 boolean newInstall, PackageInstalledInfo res) {
5765 int pFlags = args.flags;
5766 String installerPackageName = args.installerPackageName;
5767 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005768 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005769 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005770 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005771 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005772 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005773 // Result object to be returned
5774 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5775
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005776 // Retrieve PackageSettings and parse package
5777 int parseFlags = PackageParser.PARSE_CHATTY |
5778 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5779 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5780 parseFlags |= mDefParseFlags;
5781 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5782 pp.setSeparateProcesses(mSeparateProcesses);
5783 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5784 null, mMetrics, parseFlags);
5785 if (pkg == null) {
5786 res.returnCode = pp.getParseError();
5787 return;
5788 }
5789 String pkgName = res.name = pkg.packageName;
5790 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5791 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5792 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5793 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005795 }
5796 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5797 res.returnCode = pp.getParseError();
5798 return;
5799 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005800 // Get rid of all references to package scan path via parser.
5801 pp = null;
5802 String oldCodePath = null;
5803 boolean systemApp = false;
5804 synchronized (mPackages) {
5805 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005806 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5807 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005808 if (pkg.mOriginalPackages != null
5809 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005810 && mPackages.containsKey(oldName)) {
5811 // This package is derived from an original package,
5812 // and this device has been updating from that original
5813 // name. We must continue using the original name, so
5814 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005815 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005816 pkgName = pkg.packageName;
5817 replace = true;
5818 } else if (mPackages.containsKey(pkgName)) {
5819 // This package, under its official name, already exists
5820 // on the device; we should replace it.
5821 replace = true;
5822 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005823 }
5824 PackageSetting ps = mSettings.mPackages.get(pkgName);
5825 if (ps != null) {
5826 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5827 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5828 systemApp = (ps.pkg.applicationInfo.flags &
5829 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005830 }
5831 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005833
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005834 if (systemApp && onSd) {
5835 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005836 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005837 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5838 return;
5839 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005840
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005841 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5842 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5843 return;
5844 }
5845 // Set application objects path explicitly after the rename
5846 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005847 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005848 replacePackageLI(pkg, parseFlags, scanMode,
5849 installerPackageName, res);
5850 } else {
5851 installNewPackageLI(pkg, parseFlags, scanMode,
5852 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 }
5854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005855
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005856 private int setPermissionsLI(PackageParser.Package newPackage) {
5857 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005858 int retCode = 0;
5859 // TODO Gross hack but fix later. Ideally move this to be a post installation
5860 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005861 if ((newPackage.applicationInfo.flags
5862 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5863 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 try {
5865 extractPublicFiles(newPackage, destResourceFile);
5866 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005867 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 " forward-locked app.");
5869 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5870 } finally {
5871 //TODO clean up the extracted public files
5872 }
5873 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005874 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 newPackage.applicationInfo.uid);
5876 } else {
5877 final int filePermissions =
5878 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005879 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 newPackage.applicationInfo.uid);
5881 }
5882 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005883 // The permissions on the resource file was set when it was copied for
5884 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005888 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005889 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005891 // TODO Define new internal error
5892 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 }
5894 return PackageManager.INSTALL_SUCCEEDED;
5895 }
5896
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005897 private boolean isForwardLocked(PackageParser.Package pkg) {
5898 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 }
5900
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005901 private boolean isExternal(PackageParser.Package pkg) {
5902 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5903 }
5904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 private void extractPublicFiles(PackageParser.Package newPackage,
5906 File publicZipFile) throws IOException {
5907 final ZipOutputStream publicZipOutStream =
5908 new ZipOutputStream(new FileOutputStream(publicZipFile));
5909 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5910
5911 // Copy manifest, resources.arsc and res directory to public zip
5912
5913 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5914 while (privateZipEntries.hasMoreElements()) {
5915 final ZipEntry zipEntry = privateZipEntries.nextElement();
5916 final String zipEntryName = zipEntry.getName();
5917 if ("AndroidManifest.xml".equals(zipEntryName)
5918 || "resources.arsc".equals(zipEntryName)
5919 || zipEntryName.startsWith("res/")) {
5920 try {
5921 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5922 } catch (IOException e) {
5923 try {
5924 publicZipOutStream.close();
5925 throw e;
5926 } finally {
5927 publicZipFile.delete();
5928 }
5929 }
5930 }
5931 }
5932
5933 publicZipOutStream.close();
5934 FileUtils.setPermissions(
5935 publicZipFile.getAbsolutePath(),
5936 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5937 -1, -1);
5938 }
5939
5940 private static void copyZipEntry(ZipEntry zipEntry,
5941 ZipFile inZipFile,
5942 ZipOutputStream outZipStream) throws IOException {
5943 byte[] buffer = new byte[4096];
5944 int num;
5945
5946 ZipEntry newEntry;
5947 if (zipEntry.getMethod() == ZipEntry.STORED) {
5948 // Preserve the STORED method of the input entry.
5949 newEntry = new ZipEntry(zipEntry);
5950 } else {
5951 // Create a new entry so that the compressed len is recomputed.
5952 newEntry = new ZipEntry(zipEntry.getName());
5953 }
5954 outZipStream.putNextEntry(newEntry);
5955
5956 InputStream data = inZipFile.getInputStream(zipEntry);
5957 while ((num = data.read(buffer)) > 0) {
5958 outZipStream.write(buffer, 0, num);
5959 }
5960 outZipStream.flush();
5961 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 private void deleteTempPackageFiles() {
5964 FilenameFilter filter = new FilenameFilter() {
5965 public boolean accept(File dir, String name) {
5966 return name.startsWith("vmdl") && name.endsWith(".tmp");
5967 }
5968 };
5969 String tmpFilesList[] = mAppInstallDir.list(filter);
5970 if(tmpFilesList == null) {
5971 return;
5972 }
5973 for(int i = 0; i < tmpFilesList.length; i++) {
5974 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5975 tmpFile.delete();
5976 }
5977 }
5978
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005979 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 File tmpPackageFile;
5981 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005982 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005984 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 return null;
5986 }
5987 try {
5988 FileUtils.setPermissions(
5989 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5990 -1, -1);
5991 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005992 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 return null;
5994 }
5995 return tmpPackageFile;
5996 }
5997
5998 public void deletePackage(final String packageName,
5999 final IPackageDeleteObserver observer,
6000 final int flags) {
6001 mContext.enforceCallingOrSelfPermission(
6002 android.Manifest.permission.DELETE_PACKAGES, null);
6003 // Queue up an async operation since the package deletion may take a little while.
6004 mHandler.post(new Runnable() {
6005 public void run() {
6006 mHandler.removeCallbacks(this);
6007 final boolean succeded = deletePackageX(packageName, true, true, flags);
6008 if (observer != null) {
6009 try {
6010 observer.packageDeleted(succeded);
6011 } catch (RemoteException e) {
6012 Log.i(TAG, "Observer no longer exists.");
6013 } //end catch
6014 } //end if
6015 } //end run
6016 });
6017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 /**
6020 * This method is an internal method that could be get invoked either
6021 * to delete an installed package or to clean up a failed installation.
6022 * After deleting an installed package, a broadcast is sent to notify any
6023 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006024 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 * installation wouldn't have sent the initial broadcast either
6026 * The key steps in deleting a package are
6027 * deleting the package information in internal structures like mPackages,
6028 * deleting the packages base directories through installd
6029 * updating mSettings to reflect current status
6030 * persisting settings for later use
6031 * sending a broadcast if necessary
6032 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6034 boolean deleteCodeAndResources, int flags) {
6035 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006036 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006038 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6039 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6040 try {
6041 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006042 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006043 return false;
6044 }
6045 } catch (RemoteException e) {
6046 }
6047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 synchronized (mInstallLock) {
6049 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
6050 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006053 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6054 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6055
6056 // If the removed package was a system update, the old system packaged
6057 // was re-enabled; we need to broadcast this information
6058 if (systemUpdate) {
6059 Bundle extras = new Bundle(1);
6060 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6061 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6062
6063 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
6064 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
6065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006067 // Force a gc here.
6068 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006069 // Delete the resources here after sending the broadcast to let
6070 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006071 if (info.args != null) {
6072 synchronized (mInstallLock) {
6073 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006074 }
6075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 return res;
6077 }
6078
6079 static class PackageRemovedInfo {
6080 String removedPackage;
6081 int uid = -1;
6082 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006083 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006084 // Clean up resources deleted packages.
6085 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 void sendBroadcast(boolean fullRemove, boolean replacing) {
6088 Bundle extras = new Bundle(1);
6089 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6090 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6091 if (replacing) {
6092 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6093 }
6094 if (removedPackage != null) {
6095 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
6096 }
6097 if (removedUid >= 0) {
6098 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
6099 }
6100 }
6101 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 /*
6104 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6105 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006106 * 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 -08006107 * delete a partially installed application.
6108 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006109 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110 int flags) {
6111 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006112 if (outInfo != null) {
6113 outInfo.removedPackage = packageName;
6114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 removePackageLI(p, true);
6116 // Retrieve object to delete permissions for shared user later on
6117 PackageSetting deletedPs;
6118 synchronized (mPackages) {
6119 deletedPs = mSettings.mPackages.get(packageName);
6120 }
6121 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006122 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006124 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006126 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 + packageName + ", retcode=" + retCode);
6128 // we don't consider this to be a failure of the core package deletion
6129 }
6130 } else {
6131 //for emulator
6132 PackageParser.Package pkg = mPackages.get(packageName);
6133 File dataDir = new File(pkg.applicationInfo.dataDir);
6134 dataDir.delete();
6135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 }
6137 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006138 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006139 schedulePackageCleaning(packageName);
6140
6141 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6142 if (outInfo != null) {
6143 outInfo.removedUid = mSettings.removePackageLP(packageName);
6144 }
6145 if (deletedPs != null) {
6146 updatePermissionsLP(deletedPs.name, null, false, false);
6147 if (deletedPs.sharedUser != null) {
6148 // remove permissions associated with package
6149 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6150 }
6151 }
6152 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006153 // remove from preferred activities.
6154 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6155 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6156 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6157 removed.add(pa);
6158 }
6159 }
6160 for (PreferredActivity pa : removed) {
6161 mSettings.mPreferredActivities.removeFilter(pa);
6162 }
6163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006165 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 }
6167 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 /*
6170 * Tries to delete system package.
6171 */
6172 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006173 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174 ApplicationInfo applicationInfo = p.applicationInfo;
6175 //applicable for non-partially installed applications only
6176 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006177 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 return false;
6179 }
6180 PackageSetting ps = null;
6181 // Confirm if the system package has been updated
6182 // An updated system app can be deleted. This will also have to restore
6183 // the system pkg from system partition
6184 synchronized (mPackages) {
6185 ps = mSettings.getDisabledSystemPkg(p.packageName);
6186 }
6187 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006188 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 return false;
6190 } else {
6191 Log.i(TAG, "Deleting system pkg from data partition");
6192 }
6193 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006194 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006195 boolean deleteCodeAndResources = false;
6196 if (ps.versionCode < p.mVersionCode) {
6197 // Delete code and resources for downgrades
6198 deleteCodeAndResources = true;
6199 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6200 flags &= ~PackageManager.DONT_DELETE_DATA;
6201 }
6202 } else {
6203 // Preserve data by setting flag
6204 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6205 flags |= PackageManager.DONT_DELETE_DATA;
6206 }
6207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6209 if (!ret) {
6210 return false;
6211 }
6212 synchronized (mPackages) {
6213 // Reinstate the old system package
6214 mSettings.enableSystemPackageLP(p.packageName);
6215 }
6216 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006217 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006219 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006222 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 return false;
6224 }
6225 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006226 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 mSettings.writeLP();
6228 }
6229 return true;
6230 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6233 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6234 ApplicationInfo applicationInfo = p.applicationInfo;
6235 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006236 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 return false;
6238 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006239 if (outInfo != null) {
6240 outInfo.uid = applicationInfo.uid;
6241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242
6243 // Delete package data from internal structures and also remove data if flag is set
6244 removePackageDataLI(p, outInfo, flags);
6245
6246 // Delete application code and resources
6247 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006248 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006249 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006250 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006251 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6252 PackageManager.INSTALL_FORWARD_LOCK : 0;
6253 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006254 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 }
6256 return true;
6257 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 /*
6260 * This method handles package deletion in general
6261 */
6262 private boolean deletePackageLI(String packageName,
6263 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6264 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006265 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 return false;
6267 }
6268 PackageParser.Package p;
6269 boolean dataOnly = false;
6270 synchronized (mPackages) {
6271 p = mPackages.get(packageName);
6272 if (p == null) {
6273 //this retrieves partially installed apps
6274 dataOnly = true;
6275 PackageSetting ps = mSettings.mPackages.get(packageName);
6276 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006277 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 return false;
6279 }
6280 p = ps.pkg;
6281 }
6282 }
6283 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006284 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 return false;
6286 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 if (dataOnly) {
6289 // Delete application data first
6290 removePackageDataLI(p, outInfo, flags);
6291 return true;
6292 }
6293 // At this point the package should have ApplicationInfo associated with it
6294 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006295 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006296 return false;
6297 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006298 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6300 Log.i(TAG, "Removing system package:"+p.packageName);
6301 // When an updated system application is deleted we delete the existing resources as well and
6302 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006303 ret = deleteSystemPackageLI(p, flags, outInfo);
6304 } else {
6305 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006306 // Kill application pre-emptively especially for apps on sd.
6307 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006308 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006310 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 public void clearApplicationUserData(final String packageName,
6314 final IPackageDataObserver observer) {
6315 mContext.enforceCallingOrSelfPermission(
6316 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6317 // Queue up an async operation since the package deletion may take a little while.
6318 mHandler.post(new Runnable() {
6319 public void run() {
6320 mHandler.removeCallbacks(this);
6321 final boolean succeeded;
6322 synchronized (mInstallLock) {
6323 succeeded = clearApplicationUserDataLI(packageName);
6324 }
6325 if (succeeded) {
6326 // invoke DeviceStorageMonitor's update method to clear any notifications
6327 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6328 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6329 if (dsm != null) {
6330 dsm.updateMemory();
6331 }
6332 }
6333 if(observer != null) {
6334 try {
6335 observer.onRemoveCompleted(packageName, succeeded);
6336 } catch (RemoteException e) {
6337 Log.i(TAG, "Observer no longer exists.");
6338 }
6339 } //end if observer
6340 } //end run
6341 });
6342 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 private boolean clearApplicationUserDataLI(String packageName) {
6345 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006346 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 return false;
6348 }
6349 PackageParser.Package p;
6350 boolean dataOnly = false;
6351 synchronized (mPackages) {
6352 p = mPackages.get(packageName);
6353 if(p == null) {
6354 dataOnly = true;
6355 PackageSetting ps = mSettings.mPackages.get(packageName);
6356 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006357 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 return false;
6359 }
6360 p = ps.pkg;
6361 }
6362 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006363 boolean useEncryptedFSDir = false;
6364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 if(!dataOnly) {
6366 //need to check this only for fully installed applications
6367 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006368 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 return false;
6370 }
6371 final ApplicationInfo applicationInfo = p.applicationInfo;
6372 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006373 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 return false;
6375 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006376 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 }
6378 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006379 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006381 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 + packageName);
6383 return false;
6384 }
6385 }
6386 return true;
6387 }
6388
6389 public void deleteApplicationCacheFiles(final String packageName,
6390 final IPackageDataObserver observer) {
6391 mContext.enforceCallingOrSelfPermission(
6392 android.Manifest.permission.DELETE_CACHE_FILES, null);
6393 // Queue up an async operation since the package deletion may take a little while.
6394 mHandler.post(new Runnable() {
6395 public void run() {
6396 mHandler.removeCallbacks(this);
6397 final boolean succeded;
6398 synchronized (mInstallLock) {
6399 succeded = deleteApplicationCacheFilesLI(packageName);
6400 }
6401 if(observer != null) {
6402 try {
6403 observer.onRemoveCompleted(packageName, succeded);
6404 } catch (RemoteException e) {
6405 Log.i(TAG, "Observer no longer exists.");
6406 }
6407 } //end if observer
6408 } //end run
6409 });
6410 }
6411
6412 private boolean deleteApplicationCacheFilesLI(String packageName) {
6413 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006414 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 return false;
6416 }
6417 PackageParser.Package p;
6418 synchronized (mPackages) {
6419 p = mPackages.get(packageName);
6420 }
6421 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006422 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 return false;
6424 }
6425 final ApplicationInfo applicationInfo = p.applicationInfo;
6426 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006427 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 return false;
6429 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006430 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006432 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006434 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006435 + packageName);
6436 return false;
6437 }
6438 }
6439 return true;
6440 }
6441
6442 public void getPackageSizeInfo(final String packageName,
6443 final IPackageStatsObserver observer) {
6444 mContext.enforceCallingOrSelfPermission(
6445 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6446 // Queue up an async operation since the package deletion may take a little while.
6447 mHandler.post(new Runnable() {
6448 public void run() {
6449 mHandler.removeCallbacks(this);
6450 PackageStats lStats = new PackageStats(packageName);
6451 final boolean succeded;
6452 synchronized (mInstallLock) {
6453 succeded = getPackageSizeInfoLI(packageName, lStats);
6454 }
6455 if(observer != null) {
6456 try {
6457 observer.onGetStatsCompleted(lStats, succeded);
6458 } catch (RemoteException e) {
6459 Log.i(TAG, "Observer no longer exists.");
6460 }
6461 } //end if observer
6462 } //end run
6463 });
6464 }
6465
6466 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6467 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006468 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 return false;
6470 }
6471 PackageParser.Package p;
6472 boolean dataOnly = false;
6473 synchronized (mPackages) {
6474 p = mPackages.get(packageName);
6475 if(p == null) {
6476 dataOnly = true;
6477 PackageSetting ps = mSettings.mPackages.get(packageName);
6478 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006479 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 return false;
6481 }
6482 p = ps.pkg;
6483 }
6484 }
6485 String publicSrcDir = null;
6486 if(!dataOnly) {
6487 final ApplicationInfo applicationInfo = p.applicationInfo;
6488 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006489 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 return false;
6491 }
6492 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6493 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006494 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 if (mInstaller != null) {
6496 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006497 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 if (res < 0) {
6499 return false;
6500 } else {
6501 return true;
6502 }
6503 }
6504 return true;
6505 }
6506
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 public void addPackageToPreferred(String packageName) {
6509 mContext.enforceCallingOrSelfPermission(
6510 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006511 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 }
6513
6514 public void removePackageFromPreferred(String packageName) {
6515 mContext.enforceCallingOrSelfPermission(
6516 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006517 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 }
6519
6520 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006521 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 }
6523
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006524 int getUidTargetSdkVersionLockedLP(int uid) {
6525 Object obj = mSettings.getUserIdLP(uid);
6526 if (obj instanceof SharedUserSetting) {
6527 SharedUserSetting sus = (SharedUserSetting)obj;
6528 final int N = sus.packages.size();
6529 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6530 Iterator<PackageSetting> it = sus.packages.iterator();
6531 int i=0;
6532 while (it.hasNext()) {
6533 PackageSetting ps = it.next();
6534 if (ps.pkg != null) {
6535 int v = ps.pkg.applicationInfo.targetSdkVersion;
6536 if (v < vers) vers = v;
6537 }
6538 }
6539 return vers;
6540 } else if (obj instanceof PackageSetting) {
6541 PackageSetting ps = (PackageSetting)obj;
6542 if (ps.pkg != null) {
6543 return ps.pkg.applicationInfo.targetSdkVersion;
6544 }
6545 }
6546 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6547 }
6548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 public void addPreferredActivity(IntentFilter filter, int match,
6550 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006551 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006552 if (mContext.checkCallingOrSelfPermission(
6553 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6554 != PackageManager.PERMISSION_GRANTED) {
6555 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6556 < Build.VERSION_CODES.FROYO) {
6557 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6558 + Binder.getCallingUid());
6559 return;
6560 }
6561 mContext.enforceCallingOrSelfPermission(
6562 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6563 }
6564
6565 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6567 mSettings.mPreferredActivities.addFilter(
6568 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006569 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570 }
6571 }
6572
Satish Sampath8dbe6122009-06-02 23:35:54 +01006573 public void replacePreferredActivity(IntentFilter filter, int match,
6574 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006575 if (filter.countActions() != 1) {
6576 throw new IllegalArgumentException(
6577 "replacePreferredActivity expects filter to have only 1 action.");
6578 }
6579 if (filter.countCategories() != 1) {
6580 throw new IllegalArgumentException(
6581 "replacePreferredActivity expects filter to have only 1 category.");
6582 }
6583 if (filter.countDataAuthorities() != 0
6584 || filter.countDataPaths() != 0
6585 || filter.countDataSchemes() != 0
6586 || filter.countDataTypes() != 0) {
6587 throw new IllegalArgumentException(
6588 "replacePreferredActivity expects filter to have no data authorities, " +
6589 "paths, schemes or types.");
6590 }
6591 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006592 if (mContext.checkCallingOrSelfPermission(
6593 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6594 != PackageManager.PERMISSION_GRANTED) {
6595 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6596 < Build.VERSION_CODES.FROYO) {
6597 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6598 + Binder.getCallingUid());
6599 return;
6600 }
6601 mContext.enforceCallingOrSelfPermission(
6602 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6603 }
6604
Satish Sampath8dbe6122009-06-02 23:35:54 +01006605 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6606 String action = filter.getAction(0);
6607 String category = filter.getCategory(0);
6608 while (it.hasNext()) {
6609 PreferredActivity pa = it.next();
6610 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6611 it.remove();
6612 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6613 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6614 }
6615 }
6616 addPreferredActivity(filter, match, set, activity);
6617 }
6618 }
6619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006622 int uid = Binder.getCallingUid();
6623 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006624 if (pkg == null || pkg.applicationInfo.uid != uid) {
6625 if (mContext.checkCallingOrSelfPermission(
6626 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6627 != PackageManager.PERMISSION_GRANTED) {
6628 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6629 < Build.VERSION_CODES.FROYO) {
6630 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6631 + Binder.getCallingUid());
6632 return;
6633 }
6634 mContext.enforceCallingOrSelfPermission(
6635 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6636 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006637 }
6638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006640 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 }
6642 }
6643 }
6644
6645 boolean clearPackagePreferredActivitiesLP(String packageName) {
6646 boolean changed = false;
6647 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6648 while (it.hasNext()) {
6649 PreferredActivity pa = it.next();
6650 if (pa.mActivity.getPackageName().equals(packageName)) {
6651 it.remove();
6652 changed = true;
6653 }
6654 }
6655 return changed;
6656 }
6657
6658 public int getPreferredActivities(List<IntentFilter> outFilters,
6659 List<ComponentName> outActivities, String packageName) {
6660
6661 int num = 0;
6662 synchronized (mPackages) {
6663 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6664 while (it.hasNext()) {
6665 PreferredActivity pa = it.next();
6666 if (packageName == null
6667 || pa.mActivity.getPackageName().equals(packageName)) {
6668 if (outFilters != null) {
6669 outFilters.add(new IntentFilter(pa));
6670 }
6671 if (outActivities != null) {
6672 outActivities.add(pa.mActivity);
6673 }
6674 }
6675 }
6676 }
6677
6678 return num;
6679 }
6680
6681 public void setApplicationEnabledSetting(String appPackageName,
6682 int newState, int flags) {
6683 setEnabledSetting(appPackageName, null, newState, flags);
6684 }
6685
6686 public void setComponentEnabledSetting(ComponentName componentName,
6687 int newState, int flags) {
6688 setEnabledSetting(componentName.getPackageName(),
6689 componentName.getClassName(), newState, flags);
6690 }
6691
6692 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006693 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6695 || newState == COMPONENT_ENABLED_STATE_ENABLED
6696 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6697 throw new IllegalArgumentException("Invalid new component state: "
6698 + newState);
6699 }
6700 PackageSetting pkgSetting;
6701 final int uid = Binder.getCallingUid();
6702 final int permission = mContext.checkCallingPermission(
6703 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6704 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006705 boolean sendNow = false;
6706 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006707 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006709 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006711 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006713 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006714 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006715 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 }
6717 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006718 "Unknown component: " + packageName
6719 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 }
6721 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6722 throw new SecurityException(
6723 "Permission Denial: attempt to change component state from pid="
6724 + Binder.getCallingPid()
6725 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6726 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006727 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006729 if (pkgSetting.enabled == newState) {
6730 // Nothing to do
6731 return;
6732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 pkgSetting.enabled = newState;
6734 } else {
6735 // We're dealing with a component level state change
6736 switch (newState) {
6737 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006738 if (!pkgSetting.enableComponentLP(className)) {
6739 return;
6740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 break;
6742 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006743 if (!pkgSetting.disableComponentLP(className)) {
6744 return;
6745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 break;
6747 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006748 if (!pkgSetting.restoreComponentLP(className)) {
6749 return;
6750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006751 break;
6752 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006753 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006754 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 }
6756 }
6757 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006758 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006759 components = mPendingBroadcasts.get(packageName);
6760 boolean newPackage = components == null;
6761 if (newPackage) {
6762 components = new ArrayList<String>();
6763 }
6764 if (!components.contains(componentName)) {
6765 components.add(componentName);
6766 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006767 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6768 sendNow = true;
6769 // Purge entry from pending broadcast list if another one exists already
6770 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006771 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006772 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006773 if (newPackage) {
6774 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006775 }
6776 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6777 // Schedule a message
6778 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6779 }
6780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 long callingId = Binder.clearCallingIdentity();
6784 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006785 if (sendNow) {
6786 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006787 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006789 } finally {
6790 Binder.restoreCallingIdentity(callingId);
6791 }
6792 }
6793
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006794 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006795 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6796 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6797 + " components=" + componentNames);
6798 Bundle extras = new Bundle(4);
6799 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6800 String nameList[] = new String[componentNames.size()];
6801 componentNames.toArray(nameList);
6802 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006803 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6804 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006805 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006806 }
6807
Jacek Surazski65e13172009-04-28 15:26:38 +02006808 public String getInstallerPackageName(String packageName) {
6809 synchronized (mPackages) {
6810 PackageSetting pkg = mSettings.mPackages.get(packageName);
6811 if (pkg == null) {
6812 throw new IllegalArgumentException("Unknown package: " + packageName);
6813 }
6814 return pkg.installerPackageName;
6815 }
6816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 public int getApplicationEnabledSetting(String appPackageName) {
6819 synchronized (mPackages) {
6820 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6821 if (pkg == null) {
6822 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6823 }
6824 return pkg.enabled;
6825 }
6826 }
6827
6828 public int getComponentEnabledSetting(ComponentName componentName) {
6829 synchronized (mPackages) {
6830 final String packageNameStr = componentName.getPackageName();
6831 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6832 if (pkg == null) {
6833 throw new IllegalArgumentException("Unknown component: " + componentName);
6834 }
6835 final String classNameStr = componentName.getClassName();
6836 return pkg.currentEnabledStateLP(classNameStr);
6837 }
6838 }
6839
6840 public void enterSafeMode() {
6841 if (!mSystemReady) {
6842 mSafeMode = true;
6843 }
6844 }
6845
6846 public void systemReady() {
6847 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006848
6849 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006850 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006851 mContext.getContentResolver(),
6852 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006853 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006854 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006855 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 }
6858
6859 public boolean isSafeMode() {
6860 return mSafeMode;
6861 }
6862
6863 public boolean hasSystemUidErrors() {
6864 return mHasSystemUidErrors;
6865 }
6866
6867 static String arrayToString(int[] array) {
6868 StringBuffer buf = new StringBuffer(128);
6869 buf.append('[');
6870 if (array != null) {
6871 for (int i=0; i<array.length; i++) {
6872 if (i > 0) buf.append(", ");
6873 buf.append(array[i]);
6874 }
6875 }
6876 buf.append(']');
6877 return buf.toString();
6878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 @Override
6881 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6882 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6883 != PackageManager.PERMISSION_GRANTED) {
6884 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6885 + Binder.getCallingPid()
6886 + ", uid=" + Binder.getCallingUid()
6887 + " without permission "
6888 + android.Manifest.permission.DUMP);
6889 return;
6890 }
6891
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006892 String packageName = null;
6893
6894 int opti = 0;
6895 while (opti < args.length) {
6896 String opt = args[opti];
6897 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6898 break;
6899 }
6900 opti++;
6901 if ("-a".equals(opt)) {
6902 // Right now we only know how to print all.
6903 } else if ("-h".equals(opt)) {
6904 pw.println("Package manager dump options:");
6905 pw.println(" [-h] [cmd] ...");
6906 pw.println(" cmd may be one of:");
6907 pw.println(" [package.name]: info about given package");
6908 return;
6909 } else {
6910 pw.println("Unknown argument: " + opt + "; use -h for help");
6911 }
6912 }
6913
6914 // Is the caller requesting to dump a particular piece of data?
6915 if (opti < args.length) {
6916 String cmd = args[opti];
6917 opti++;
6918 // Is this a package name?
6919 if ("android".equals(cmd) || cmd.contains(".")) {
6920 packageName = cmd;
6921 }
6922 }
6923
6924 boolean printedTitle = false;
6925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006927 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6928 printedTitle = true;
6929 }
6930 if (mReceivers.dump(pw, printedTitle
6931 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6932 " ", packageName)) {
6933 printedTitle = true;
6934 }
6935 if (mServices.dump(pw, printedTitle
6936 ? "\nService Resolver Table:" : "Service Resolver Table:",
6937 " ", packageName)) {
6938 printedTitle = true;
6939 }
6940 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6941 ? "\nPreferred Activities:" : "Preferred Activities:",
6942 " ", packageName)) {
6943 printedTitle = true;
6944 }
6945 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 {
6947 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006948 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6949 continue;
6950 }
6951 if (!printedSomething) {
6952 if (printedTitle) pw.println(" ");
6953 pw.println("Permissions:");
6954 printedSomething = true;
6955 printedTitle = true;
6956 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006957 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6958 pw.print(Integer.toHexString(System.identityHashCode(p)));
6959 pw.println("):");
6960 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6961 pw.print(" uid="); pw.print(p.uid);
6962 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006963 pw.print(" type="); pw.print(p.type);
6964 pw.print(" prot="); pw.println(p.protectionLevel);
6965 if (p.packageSetting != null) {
6966 pw.print(" packageSetting="); pw.println(p.packageSetting);
6967 }
6968 if (p.perm != null) {
6969 pw.print(" perm="); pw.println(p.perm);
6970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006971 }
6972 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006973 printedSomething = false;
6974 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006975 {
6976 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006977 if (packageName != null && !packageName.equals(ps.realName)
6978 && !packageName.equals(ps.name)) {
6979 continue;
6980 }
6981 if (!printedSomething) {
6982 if (printedTitle) pw.println(" ");
6983 pw.println("Packages:");
6984 printedSomething = true;
6985 printedTitle = true;
6986 }
6987 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006988 pw.print(" Package [");
6989 pw.print(ps.realName != null ? ps.realName : ps.name);
6990 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006991 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6992 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006993 if (ps.realName != null) {
6994 pw.print(" compat name="); pw.println(ps.name);
6995 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006996 pw.print(" userId="); pw.print(ps.userId);
6997 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6998 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6999 pw.print(" pkg="); pw.println(ps.pkg);
7000 pw.print(" codePath="); pw.println(ps.codePathString);
7001 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007003 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007004 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007005 pw.print(" supportsScreens=[");
7006 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007007 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007008 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007009 if (!first) pw.print(", ");
7010 first = false;
7011 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007012 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007013 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007014 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007015 if (!first) pw.print(", ");
7016 first = false;
7017 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007018 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007019 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007020 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007021 if (!first) pw.print(", ");
7022 first = false;
7023 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007025 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007026 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007027 if (!first) pw.print(", ");
7028 first = false;
7029 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007031 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007032 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7033 if (!first) pw.print(", ");
7034 first = false;
7035 pw.print("anyDensity");
7036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007038 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007039 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7040 pw.print(" signatures="); pw.println(ps.signatures);
7041 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007042 pw.print(" haveGids="); pw.println(ps.haveGids);
7043 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007044 pw.print(" installStatus="); pw.print(ps.installStatus);
7045 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007046 if (ps.disabledComponents.size() > 0) {
7047 pw.println(" disabledComponents:");
7048 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007049 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 }
7051 }
7052 if (ps.enabledComponents.size() > 0) {
7053 pw.println(" enabledComponents:");
7054 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007055 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 }
7057 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007058 if (ps.grantedPermissions.size() > 0) {
7059 pw.println(" grantedPermissions:");
7060 for (String s : ps.grantedPermissions) {
7061 pw.print(" "); pw.println(s);
7062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007064 }
7065 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007066 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007067 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007068 for (HashMap.Entry<String, String> e
7069 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007070 if (packageName != null && !packageName.equals(e.getKey())
7071 && !packageName.equals(e.getValue())) {
7072 continue;
7073 }
7074 if (!printedSomething) {
7075 if (printedTitle) pw.println(" ");
7076 pw.println("Renamed packages:");
7077 printedSomething = true;
7078 printedTitle = true;
7079 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007080 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7081 pw.println(e.getValue());
7082 }
7083 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007084 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007085 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007086 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007087 if (packageName != null && !packageName.equals(ps.realName)
7088 && !packageName.equals(ps.name)) {
7089 continue;
7090 }
7091 if (!printedSomething) {
7092 if (printedTitle) pw.println(" ");
7093 pw.println("Hidden system packages:");
7094 printedSomething = true;
7095 printedTitle = true;
7096 }
7097 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007098 pw.print(ps.realName != null ? ps.realName : ps.name);
7099 pw.print("] (");
7100 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7101 pw.println("):");
7102 if (ps.realName != null) {
7103 pw.print(" compat name="); pw.println(ps.name);
7104 }
7105 pw.print(" userId="); pw.println(ps.userId);
7106 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7107 pw.print(" codePath="); pw.println(ps.codePathString);
7108 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7109 }
7110 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007111 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007112 {
7113 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007114 if (packageName != null && su != packageSharedUser) {
7115 continue;
7116 }
7117 if (!printedSomething) {
7118 if (printedTitle) pw.println(" ");
7119 pw.println("Shared users:");
7120 printedSomething = true;
7121 printedTitle = true;
7122 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007123 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7124 pw.print(Integer.toHexString(System.identityHashCode(su)));
7125 pw.println("):");
7126 pw.print(" userId="); pw.print(su.userId);
7127 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007128 pw.println(" grantedPermissions:");
7129 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007130 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 }
7133 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007134
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007135 if (packageName == null) {
7136 if (printedTitle) pw.println(" ");
7137 printedTitle = true;
7138 pw.println("Settings parse messages:");
7139 pw.println(mSettings.mReadMessages.toString());
7140
7141 pw.println(" ");
7142 pw.println("Package warning messages:");
7143 File fname = getSettingsProblemFile();
7144 FileInputStream in;
7145 try {
7146 in = new FileInputStream(fname);
7147 int avail = in.available();
7148 byte[] data = new byte[avail];
7149 in.read(data);
7150 pw.println(new String(data));
7151 } catch (FileNotFoundException e) {
7152 } catch (IOException e) {
7153 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007156
7157 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007158 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007159 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007160 if (packageName != null && !packageName.equals(p.info.packageName)) {
7161 continue;
7162 }
7163 if (!printedSomething) {
7164 if (printedTitle) pw.println(" ");
7165 pw.println("Registered ContentProviders:");
7166 printedSomething = true;
7167 printedTitle = true;
7168 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007169 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007170 pw.println(p.toString());
7171 }
7172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 }
7174
7175 static final class BasePermission {
7176 final static int TYPE_NORMAL = 0;
7177 final static int TYPE_BUILTIN = 1;
7178 final static int TYPE_DYNAMIC = 2;
7179
7180 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007181 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007182 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007184 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007185 PackageParser.Permission perm;
7186 PermissionInfo pendingInfo;
7187 int uid;
7188 int[] gids;
7189
7190 BasePermission(String _name, String _sourcePackage, int _type) {
7191 name = _name;
7192 sourcePackage = _sourcePackage;
7193 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007194 // Default to most conservative protection level.
7195 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7196 }
7197
7198 public String toString() {
7199 return "BasePermission{"
7200 + Integer.toHexString(System.identityHashCode(this))
7201 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 }
7203 }
7204
7205 static class PackageSignatures {
7206 private Signature[] mSignatures;
7207
7208 PackageSignatures(Signature[] sigs) {
7209 assignSignatures(sigs);
7210 }
7211
7212 PackageSignatures() {
7213 }
7214
7215 void writeXml(XmlSerializer serializer, String tagName,
7216 ArrayList<Signature> pastSignatures) throws IOException {
7217 if (mSignatures == null) {
7218 return;
7219 }
7220 serializer.startTag(null, tagName);
7221 serializer.attribute(null, "count",
7222 Integer.toString(mSignatures.length));
7223 for (int i=0; i<mSignatures.length; i++) {
7224 serializer.startTag(null, "cert");
7225 final Signature sig = mSignatures[i];
7226 final int sigHash = sig.hashCode();
7227 final int numPast = pastSignatures.size();
7228 int j;
7229 for (j=0; j<numPast; j++) {
7230 Signature pastSig = pastSignatures.get(j);
7231 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7232 serializer.attribute(null, "index", Integer.toString(j));
7233 break;
7234 }
7235 }
7236 if (j >= numPast) {
7237 pastSignatures.add(sig);
7238 serializer.attribute(null, "index", Integer.toString(numPast));
7239 serializer.attribute(null, "key", sig.toCharsString());
7240 }
7241 serializer.endTag(null, "cert");
7242 }
7243 serializer.endTag(null, tagName);
7244 }
7245
7246 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7247 throws IOException, XmlPullParserException {
7248 String countStr = parser.getAttributeValue(null, "count");
7249 if (countStr == null) {
7250 reportSettingsProblem(Log.WARN,
7251 "Error in package manager settings: <signatures> has"
7252 + " no count at " + parser.getPositionDescription());
7253 XmlUtils.skipCurrentTag(parser);
7254 }
7255 final int count = Integer.parseInt(countStr);
7256 mSignatures = new Signature[count];
7257 int pos = 0;
7258
7259 int outerDepth = parser.getDepth();
7260 int type;
7261 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7262 && (type != XmlPullParser.END_TAG
7263 || parser.getDepth() > outerDepth)) {
7264 if (type == XmlPullParser.END_TAG
7265 || type == XmlPullParser.TEXT) {
7266 continue;
7267 }
7268
7269 String tagName = parser.getName();
7270 if (tagName.equals("cert")) {
7271 if (pos < count) {
7272 String index = parser.getAttributeValue(null, "index");
7273 if (index != null) {
7274 try {
7275 int idx = Integer.parseInt(index);
7276 String key = parser.getAttributeValue(null, "key");
7277 if (key == null) {
7278 if (idx >= 0 && idx < pastSignatures.size()) {
7279 Signature sig = pastSignatures.get(idx);
7280 if (sig != null) {
7281 mSignatures[pos] = pastSignatures.get(idx);
7282 pos++;
7283 } else {
7284 reportSettingsProblem(Log.WARN,
7285 "Error in package manager settings: <cert> "
7286 + "index " + index + " is not defined at "
7287 + parser.getPositionDescription());
7288 }
7289 } else {
7290 reportSettingsProblem(Log.WARN,
7291 "Error in package manager settings: <cert> "
7292 + "index " + index + " is out of bounds at "
7293 + parser.getPositionDescription());
7294 }
7295 } else {
7296 while (pastSignatures.size() <= idx) {
7297 pastSignatures.add(null);
7298 }
7299 Signature sig = new Signature(key);
7300 pastSignatures.set(idx, sig);
7301 mSignatures[pos] = sig;
7302 pos++;
7303 }
7304 } catch (NumberFormatException e) {
7305 reportSettingsProblem(Log.WARN,
7306 "Error in package manager settings: <cert> "
7307 + "index " + index + " is not a number at "
7308 + parser.getPositionDescription());
7309 }
7310 } else {
7311 reportSettingsProblem(Log.WARN,
7312 "Error in package manager settings: <cert> has"
7313 + " no index at " + parser.getPositionDescription());
7314 }
7315 } else {
7316 reportSettingsProblem(Log.WARN,
7317 "Error in package manager settings: too "
7318 + "many <cert> tags, expected " + count
7319 + " at " + parser.getPositionDescription());
7320 }
7321 } else {
7322 reportSettingsProblem(Log.WARN,
7323 "Unknown element under <cert>: "
7324 + parser.getName());
7325 }
7326 XmlUtils.skipCurrentTag(parser);
7327 }
7328
7329 if (pos < count) {
7330 // Should never happen -- there is an error in the written
7331 // settings -- but if it does we don't want to generate
7332 // a bad array.
7333 Signature[] newSigs = new Signature[pos];
7334 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7335 mSignatures = newSigs;
7336 }
7337 }
7338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007339 private void assignSignatures(Signature[] sigs) {
7340 if (sigs == null) {
7341 mSignatures = null;
7342 return;
7343 }
7344 mSignatures = new Signature[sigs.length];
7345 for (int i=0; i<sigs.length; i++) {
7346 mSignatures[i] = sigs[i];
7347 }
7348 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007350 @Override
7351 public String toString() {
7352 StringBuffer buf = new StringBuffer(128);
7353 buf.append("PackageSignatures{");
7354 buf.append(Integer.toHexString(System.identityHashCode(this)));
7355 buf.append(" [");
7356 if (mSignatures != null) {
7357 for (int i=0; i<mSignatures.length; i++) {
7358 if (i > 0) buf.append(", ");
7359 buf.append(Integer.toHexString(
7360 System.identityHashCode(mSignatures[i])));
7361 }
7362 }
7363 buf.append("]}");
7364 return buf.toString();
7365 }
7366 }
7367
7368 static class PreferredActivity extends IntentFilter {
7369 final int mMatch;
7370 final String[] mSetPackages;
7371 final String[] mSetClasses;
7372 final String[] mSetComponents;
7373 final ComponentName mActivity;
7374 final String mShortActivity;
7375 String mParseError;
7376
7377 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7378 ComponentName activity) {
7379 super(filter);
7380 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7381 mActivity = activity;
7382 mShortActivity = activity.flattenToShortString();
7383 mParseError = null;
7384 if (set != null) {
7385 final int N = set.length;
7386 String[] myPackages = new String[N];
7387 String[] myClasses = new String[N];
7388 String[] myComponents = new String[N];
7389 for (int i=0; i<N; i++) {
7390 ComponentName cn = set[i];
7391 if (cn == null) {
7392 mSetPackages = null;
7393 mSetClasses = null;
7394 mSetComponents = null;
7395 return;
7396 }
7397 myPackages[i] = cn.getPackageName().intern();
7398 myClasses[i] = cn.getClassName().intern();
7399 myComponents[i] = cn.flattenToShortString().intern();
7400 }
7401 mSetPackages = myPackages;
7402 mSetClasses = myClasses;
7403 mSetComponents = myComponents;
7404 } else {
7405 mSetPackages = null;
7406 mSetClasses = null;
7407 mSetComponents = null;
7408 }
7409 }
7410
7411 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7412 IOException {
7413 mShortActivity = parser.getAttributeValue(null, "name");
7414 mActivity = ComponentName.unflattenFromString(mShortActivity);
7415 if (mActivity == null) {
7416 mParseError = "Bad activity name " + mShortActivity;
7417 }
7418 String matchStr = parser.getAttributeValue(null, "match");
7419 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7420 String setCountStr = parser.getAttributeValue(null, "set");
7421 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7422
7423 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7424 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7425 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7426
7427 int setPos = 0;
7428
7429 int outerDepth = parser.getDepth();
7430 int type;
7431 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7432 && (type != XmlPullParser.END_TAG
7433 || parser.getDepth() > outerDepth)) {
7434 if (type == XmlPullParser.END_TAG
7435 || type == XmlPullParser.TEXT) {
7436 continue;
7437 }
7438
7439 String tagName = parser.getName();
7440 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7441 // + parser.getDepth() + " tag=" + tagName);
7442 if (tagName.equals("set")) {
7443 String name = parser.getAttributeValue(null, "name");
7444 if (name == null) {
7445 if (mParseError == null) {
7446 mParseError = "No name in set tag in preferred activity "
7447 + mShortActivity;
7448 }
7449 } else if (setPos >= setCount) {
7450 if (mParseError == null) {
7451 mParseError = "Too many set tags in preferred activity "
7452 + mShortActivity;
7453 }
7454 } else {
7455 ComponentName cn = ComponentName.unflattenFromString(name);
7456 if (cn == null) {
7457 if (mParseError == null) {
7458 mParseError = "Bad set name " + name + " in preferred activity "
7459 + mShortActivity;
7460 }
7461 } else {
7462 myPackages[setPos] = cn.getPackageName();
7463 myClasses[setPos] = cn.getClassName();
7464 myComponents[setPos] = name;
7465 setPos++;
7466 }
7467 }
7468 XmlUtils.skipCurrentTag(parser);
7469 } else if (tagName.equals("filter")) {
7470 //Log.i(TAG, "Starting to parse filter...");
7471 readFromXml(parser);
7472 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7473 // + parser.getDepth() + " tag=" + parser.getName());
7474 } else {
7475 reportSettingsProblem(Log.WARN,
7476 "Unknown element under <preferred-activities>: "
7477 + parser.getName());
7478 XmlUtils.skipCurrentTag(parser);
7479 }
7480 }
7481
7482 if (setPos != setCount) {
7483 if (mParseError == null) {
7484 mParseError = "Not enough set tags (expected " + setCount
7485 + " but found " + setPos + ") in " + mShortActivity;
7486 }
7487 }
7488
7489 mSetPackages = myPackages;
7490 mSetClasses = myClasses;
7491 mSetComponents = myComponents;
7492 }
7493
7494 public void writeToXml(XmlSerializer serializer) throws IOException {
7495 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7496 serializer.attribute(null, "name", mShortActivity);
7497 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7498 serializer.attribute(null, "set", Integer.toString(NS));
7499 for (int s=0; s<NS; s++) {
7500 serializer.startTag(null, "set");
7501 serializer.attribute(null, "name", mSetComponents[s]);
7502 serializer.endTag(null, "set");
7503 }
7504 serializer.startTag(null, "filter");
7505 super.writeToXml(serializer);
7506 serializer.endTag(null, "filter");
7507 }
7508
7509 boolean sameSet(List<ResolveInfo> query, int priority) {
7510 if (mSetPackages == null) return false;
7511 final int NQ = query.size();
7512 final int NS = mSetPackages.length;
7513 int numMatch = 0;
7514 for (int i=0; i<NQ; i++) {
7515 ResolveInfo ri = query.get(i);
7516 if (ri.priority != priority) continue;
7517 ActivityInfo ai = ri.activityInfo;
7518 boolean good = false;
7519 for (int j=0; j<NS; j++) {
7520 if (mSetPackages[j].equals(ai.packageName)
7521 && mSetClasses[j].equals(ai.name)) {
7522 numMatch++;
7523 good = true;
7524 break;
7525 }
7526 }
7527 if (!good) return false;
7528 }
7529 return numMatch == NS;
7530 }
7531 }
7532
7533 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007534 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 HashSet<String> grantedPermissions = new HashSet<String>();
7537 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007540 setFlags(pkgFlags);
7541 }
7542
7543 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007544 this.pkgFlags = pkgFlags & (
7545 ApplicationInfo.FLAG_SYSTEM |
7546 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007547 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007548 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549 }
7550 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 /**
7553 * Settings base class for pending and resolved classes.
7554 */
7555 static class PackageSettingBase extends GrantedPermissions {
7556 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007557 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007558 File codePath;
7559 String codePathString;
7560 File resourcePath;
7561 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 private long timeStamp;
7563 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007564 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007566 boolean uidError;
7567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568 PackageSignatures signatures = new PackageSignatures();
7569
7570 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007571 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 /* Explicitly disabled components */
7574 HashSet<String> disabledComponents = new HashSet<String>(0);
7575 /* Explicitly enabled components */
7576 HashSet<String> enabledComponents = new HashSet<String>(0);
7577 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7578 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007579
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007580 PackageSettingBase origPackage;
7581
Jacek Surazski65e13172009-04-28 15:26:38 +02007582 /* package name of the app that installed this package */
7583 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007585 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007586 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 super(pkgFlags);
7588 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007589 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007590 init(codePath, resourcePath, pVersionCode);
7591 }
7592
7593 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 this.codePath = codePath;
7595 this.codePathString = codePath.toString();
7596 this.resourcePath = resourcePath;
7597 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007598 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007600
Jacek Surazski65e13172009-04-28 15:26:38 +02007601 public void setInstallerPackageName(String packageName) {
7602 installerPackageName = packageName;
7603 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007604
Jacek Surazski65e13172009-04-28 15:26:38 +02007605 String getInstallerPackageName() {
7606 return installerPackageName;
7607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 public void setInstallStatus(int newStatus) {
7610 installStatus = newStatus;
7611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 public int getInstallStatus() {
7614 return installStatus;
7615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617 public void setTimeStamp(long newStamp) {
7618 if (newStamp != timeStamp) {
7619 timeStamp = newStamp;
7620 timeStampString = Long.toString(newStamp);
7621 }
7622 }
7623
7624 public void setTimeStamp(long newStamp, String newStampStr) {
7625 timeStamp = newStamp;
7626 timeStampString = newStampStr;
7627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 public long getTimeStamp() {
7630 return timeStamp;
7631 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 public String getTimeStampStr() {
7634 return timeStampString;
7635 }
7636
7637 public void copyFrom(PackageSettingBase base) {
7638 grantedPermissions = base.grantedPermissions;
7639 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 timeStamp = base.timeStamp;
7642 timeStampString = base.timeStampString;
7643 signatures = base.signatures;
7644 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007645 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646 disabledComponents = base.disabledComponents;
7647 enabledComponents = base.enabledComponents;
7648 enabled = base.enabled;
7649 installStatus = base.installStatus;
7650 }
7651
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007652 boolean enableComponentLP(String componentClassName) {
7653 boolean changed = disabledComponents.remove(componentClassName);
7654 changed |= enabledComponents.add(componentClassName);
7655 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 }
7657
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007658 boolean disableComponentLP(String componentClassName) {
7659 boolean changed = enabledComponents.remove(componentClassName);
7660 changed |= disabledComponents.add(componentClassName);
7661 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 }
7663
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007664 boolean restoreComponentLP(String componentClassName) {
7665 boolean changed = enabledComponents.remove(componentClassName);
7666 changed |= disabledComponents.remove(componentClassName);
7667 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 }
7669
7670 int currentEnabledStateLP(String componentName) {
7671 if (enabledComponents.contains(componentName)) {
7672 return COMPONENT_ENABLED_STATE_ENABLED;
7673 } else if (disabledComponents.contains(componentName)) {
7674 return COMPONENT_ENABLED_STATE_DISABLED;
7675 } else {
7676 return COMPONENT_ENABLED_STATE_DEFAULT;
7677 }
7678 }
7679 }
7680
7681 /**
7682 * Settings data for a particular package we know about.
7683 */
7684 static final class PackageSetting extends PackageSettingBase {
7685 int userId;
7686 PackageParser.Package pkg;
7687 SharedUserSetting sharedUser;
7688
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007689 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007690 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007691 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007694 @Override
7695 public String toString() {
7696 return "PackageSetting{"
7697 + Integer.toHexString(System.identityHashCode(this))
7698 + " " + name + "/" + userId + "}";
7699 }
7700 }
7701
7702 /**
7703 * Settings data for a particular shared user ID we know about.
7704 */
7705 static final class SharedUserSetting extends GrantedPermissions {
7706 final String name;
7707 int userId;
7708 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7709 final PackageSignatures signatures = new PackageSignatures();
7710
7711 SharedUserSetting(String _name, int _pkgFlags) {
7712 super(_pkgFlags);
7713 name = _name;
7714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 @Override
7717 public String toString() {
7718 return "SharedUserSetting{"
7719 + Integer.toHexString(System.identityHashCode(this))
7720 + " " + name + "/" + userId + "}";
7721 }
7722 }
7723
7724 /**
7725 * Holds information about dynamic settings.
7726 */
7727 private static final class Settings {
7728 private final File mSettingsFilename;
7729 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007730 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 private final HashMap<String, PackageSetting> mPackages =
7732 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007733 // List of replaced system applications
7734 final HashMap<String, PackageSetting> mDisabledSysPackages =
7735 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 // The user's preferred activities associated with particular intent
7738 // filters.
7739 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7740 new IntentResolver<PreferredActivity, PreferredActivity>() {
7741 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007742 protected String packageForFilter(PreferredActivity filter) {
7743 return filter.mActivity.getPackageName();
7744 }
7745 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007746 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007748 out.print(prefix); out.print(
7749 Integer.toHexString(System.identityHashCode(filter)));
7750 out.print(' ');
7751 out.print(filter.mActivity.flattenToShortString());
7752 out.print(" match=0x");
7753 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007755 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007757 out.print(prefix); out.print(" ");
7758 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007759 }
7760 }
7761 }
7762 };
7763 private final HashMap<String, SharedUserSetting> mSharedUsers =
7764 new HashMap<String, SharedUserSetting>();
7765 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7766 private final SparseArray<Object> mOtherUserIds =
7767 new SparseArray<Object>();
7768
7769 // For reading/writing settings file.
7770 private final ArrayList<Signature> mPastSignatures =
7771 new ArrayList<Signature>();
7772
7773 // Mapping from permission names to info about them.
7774 final HashMap<String, BasePermission> mPermissions =
7775 new HashMap<String, BasePermission>();
7776
7777 // Mapping from permission tree names to info about them.
7778 final HashMap<String, BasePermission> mPermissionTrees =
7779 new HashMap<String, BasePermission>();
7780
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007781 // Packages that have been uninstalled and still need their external
7782 // storage data deleted.
7783 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7784
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007785 // Packages that have been renamed since they were first installed.
7786 // Keys are the new names of the packages, values are the original
7787 // names. The packages appear everwhere else under their original
7788 // names.
7789 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 private final StringBuilder mReadMessages = new StringBuilder();
7792
7793 private static final class PendingPackage extends PackageSettingBase {
7794 final int sharedId;
7795
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007796 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007797 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007798 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007799 this.sharedId = sharedId;
7800 }
7801 }
7802 private final ArrayList<PendingPackage> mPendingPackages
7803 = new ArrayList<PendingPackage>();
7804
7805 Settings() {
7806 File dataDir = Environment.getDataDirectory();
7807 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007808 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7809 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007810 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007811 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812 FileUtils.setPermissions(systemDir.toString(),
7813 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7814 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7815 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007816 FileUtils.setPermissions(systemSecureDir.toString(),
7817 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7818 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7819 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 mSettingsFilename = new File(systemDir, "packages.xml");
7821 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007822 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 }
7824
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007825 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007826 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 int pkgFlags, boolean create, boolean add) {
7828 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007829 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007830 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831 return p;
7832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007833
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007834 PackageSetting peekPackageLP(String name) {
7835 return mPackages.get(name);
7836 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 PackageSetting p = mPackages.get(name);
7838 if (p != null && p.codePath.getPath().equals(codePath)) {
7839 return p;
7840 }
7841 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007842 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007845 void setInstallStatus(String pkgName, int status) {
7846 PackageSetting p = mPackages.get(pkgName);
7847 if(p != null) {
7848 if(p.getInstallStatus() != status) {
7849 p.setInstallStatus(status);
7850 }
7851 }
7852 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007853
Jacek Surazski65e13172009-04-28 15:26:38 +02007854 void setInstallerPackageName(String pkgName,
7855 String installerPkgName) {
7856 PackageSetting p = mPackages.get(pkgName);
7857 if(p != null) {
7858 p.setInstallerPackageName(installerPkgName);
7859 }
7860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007861
Jacek Surazski65e13172009-04-28 15:26:38 +02007862 String getInstallerPackageName(String pkgName) {
7863 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007864 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007865 }
7866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007867 int getInstallStatus(String pkgName) {
7868 PackageSetting p = mPackages.get(pkgName);
7869 if(p != null) {
7870 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 return -1;
7873 }
7874
7875 SharedUserSetting getSharedUserLP(String name,
7876 int pkgFlags, boolean create) {
7877 SharedUserSetting s = mSharedUsers.get(name);
7878 if (s == null) {
7879 if (!create) {
7880 return null;
7881 }
7882 s = new SharedUserSetting(name, pkgFlags);
7883 if (MULTIPLE_APPLICATION_UIDS) {
7884 s.userId = newUserIdLP(s);
7885 } else {
7886 s.userId = FIRST_APPLICATION_UID;
7887 }
7888 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7889 // < 0 means we couldn't assign a userid; fall out and return
7890 // s, which is currently null
7891 if (s.userId >= 0) {
7892 mSharedUsers.put(name, s);
7893 }
7894 }
7895
7896 return s;
7897 }
7898
7899 int disableSystemPackageLP(String name) {
7900 PackageSetting p = mPackages.get(name);
7901 if(p == null) {
7902 Log.w(TAG, "Package:"+name+" is not an installed package");
7903 return -1;
7904 }
7905 PackageSetting dp = mDisabledSysPackages.get(name);
7906 // always make sure the system package code and resource paths dont change
7907 if(dp == null) {
7908 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7909 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7910 }
7911 mDisabledSysPackages.put(name, p);
7912 }
7913 return removePackageLP(name);
7914 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 PackageSetting enableSystemPackageLP(String name) {
7917 PackageSetting p = mDisabledSysPackages.get(name);
7918 if(p == null) {
7919 Log.w(TAG, "Package:"+name+" is not disabled");
7920 return null;
7921 }
7922 // Reset flag in ApplicationInfo object
7923 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7924 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7925 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007926 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007927 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928 mDisabledSysPackages.remove(name);
7929 return ret;
7930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007931
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007932 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007933 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007934 PackageSetting p = mPackages.get(name);
7935 if (p != null) {
7936 if (p.userId == uid) {
7937 return p;
7938 }
7939 reportSettingsProblem(Log.ERROR,
7940 "Adding duplicate package, keeping first: " + name);
7941 return null;
7942 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007943 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 p.userId = uid;
7945 if (addUserIdLP(uid, p, name)) {
7946 mPackages.put(name, p);
7947 return p;
7948 }
7949 return null;
7950 }
7951
7952 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7953 SharedUserSetting s = mSharedUsers.get(name);
7954 if (s != null) {
7955 if (s.userId == uid) {
7956 return s;
7957 }
7958 reportSettingsProblem(Log.ERROR,
7959 "Adding duplicate shared user, keeping first: " + name);
7960 return null;
7961 }
7962 s = new SharedUserSetting(name, pkgFlags);
7963 s.userId = uid;
7964 if (addUserIdLP(uid, s, name)) {
7965 mSharedUsers.put(name, s);
7966 return s;
7967 }
7968 return null;
7969 }
7970
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007971 // Transfer ownership of permissions from one package to another.
7972 private void transferPermissions(String origPkg, String newPkg) {
7973 // Transfer ownership of permissions to the new package.
7974 for (int i=0; i<2; i++) {
7975 HashMap<String, BasePermission> permissions =
7976 i == 0 ? mPermissionTrees : mPermissions;
7977 for (BasePermission bp : permissions.values()) {
7978 if (origPkg.equals(bp.sourcePackage)) {
7979 if (DEBUG_UPGRADE) Log.v(TAG,
7980 "Moving permission " + bp.name
7981 + " from pkg " + bp.sourcePackage
7982 + " to " + newPkg);
7983 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007984 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007985 bp.perm = null;
7986 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007987 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007988 }
7989 bp.uid = 0;
7990 bp.gids = null;
7991 }
7992 }
7993 }
7994 }
7995
7996 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007997 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007998 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007999 PackageSetting p = mPackages.get(name);
8000 if (p != null) {
8001 if (!p.codePath.equals(codePath)) {
8002 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008003 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008004 // This is an updated system app with versions in both system
8005 // and data partition. Just let the most recent version
8006 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008007 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008008 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008009 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008010 // Just a change in the code path is not an issue, but
8011 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008012 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008013 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008015 }
8016 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 reportSettingsProblem(Log.WARN,
8018 "Package " + name + " shared user changed from "
8019 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8020 + " to "
8021 + (sharedUser != null ? sharedUser.name : "<nothing>")
8022 + "; replacing with new");
8023 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008024 } else {
8025 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8026 // If what we are scanning is a system package, then
8027 // make it so, regardless of whether it was previously
8028 // installed only in the data partition.
8029 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 }
8032 }
8033 if (p == null) {
8034 // Create a new PackageSettings entry. this can end up here because
8035 // of code path mismatch or user id mismatch of an updated system partition
8036 if (!create) {
8037 return null;
8038 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008039 if (origPackage != null) {
8040 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008041 p = new PackageSetting(origPackage.name, name, codePath,
8042 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008043 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8044 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008045 // Note that we will retain the new package's signature so
8046 // that we can keep its data.
8047 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008048 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008049 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008050 p.sharedUser = origPackage.sharedUser;
8051 p.userId = origPackage.userId;
8052 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008053 mRenamedPackages.put(name, origPackage.name);
8054 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008055 // Update new package state.
8056 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008058 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008059 p.setTimeStamp(codePath.lastModified());
8060 p.sharedUser = sharedUser;
8061 if (sharedUser != null) {
8062 p.userId = sharedUser.userId;
8063 } else if (MULTIPLE_APPLICATION_UIDS) {
8064 // Clone the setting here for disabled system packages
8065 PackageSetting dis = mDisabledSysPackages.get(name);
8066 if (dis != null) {
8067 // For disabled packages a new setting is created
8068 // from the existing user id. This still has to be
8069 // added to list of user id's
8070 // Copy signatures from previous setting
8071 if (dis.signatures.mSignatures != null) {
8072 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8073 }
8074 p.userId = dis.userId;
8075 // Clone permissions
8076 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008077 // Clone component info
8078 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8079 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8080 // Add new setting to list of user ids
8081 addUserIdLP(p.userId, p, name);
8082 } else {
8083 // Assign new user id
8084 p.userId = newUserIdLP(p);
8085 }
8086 } else {
8087 p.userId = FIRST_APPLICATION_UID;
8088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 }
8090 if (p.userId < 0) {
8091 reportSettingsProblem(Log.WARN,
8092 "Package " + name + " could not be assigned a valid uid");
8093 return null;
8094 }
8095 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008096 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008098 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 }
8100 }
8101 return p;
8102 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008103
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008104 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008105 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008106 String codePath = pkg.applicationInfo.sourceDir;
8107 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008108 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008109 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008110 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008111 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008112 p.codePath = new File(codePath);
8113 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008114 }
8115 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008116 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008117 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008118 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008119 p.resourcePath = new File(resourcePath);
8120 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008121 }
8122 // Update version code if needed
8123 if (pkg.mVersionCode != p.versionCode) {
8124 p.versionCode = pkg.mVersionCode;
8125 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008126 // Update signatures if needed.
8127 if (p.signatures.mSignatures == null) {
8128 p.signatures.assignSignatures(pkg.mSignatures);
8129 }
8130 // If this app defines a shared user id initialize
8131 // the shared user signatures as well.
8132 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8133 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8134 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008135 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8136 }
8137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 // Utility method that adds a PackageSetting to mPackages and
8139 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008140 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 SharedUserSetting sharedUser) {
8142 mPackages.put(name, p);
8143 if (sharedUser != null) {
8144 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8145 reportSettingsProblem(Log.ERROR,
8146 "Package " + p.name + " was user "
8147 + p.sharedUser + " but is now " + sharedUser
8148 + "; I am not changing its files so it will probably fail!");
8149 p.sharedUser.packages.remove(p);
8150 } else if (p.userId != sharedUser.userId) {
8151 reportSettingsProblem(Log.ERROR,
8152 "Package " + p.name + " was user id " + p.userId
8153 + " but is now user " + sharedUser
8154 + " with id " + sharedUser.userId
8155 + "; I am not changing its files so it will probably fail!");
8156 }
8157
8158 sharedUser.packages.add(p);
8159 p.sharedUser = sharedUser;
8160 p.userId = sharedUser.userId;
8161 }
8162 }
8163
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008164 /*
8165 * Update the shared user setting when a package using
8166 * specifying the shared user id is removed. The gids
8167 * associated with each permission of the deleted package
8168 * are removed from the shared user's gid list only if its
8169 * not in use by other permissions of packages in the
8170 * shared user setting.
8171 */
8172 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008174 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 return;
8176 }
8177 // No sharedUserId
8178 if (deletedPs.sharedUser == null) {
8179 return;
8180 }
8181 SharedUserSetting sus = deletedPs.sharedUser;
8182 // Update permissions
8183 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8184 boolean used = false;
8185 if (!sus.grantedPermissions.contains (eachPerm)) {
8186 continue;
8187 }
8188 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008189 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008190 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008191 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 used = true;
8193 break;
8194 }
8195 }
8196 if (!used) {
8197 // can safely delete this permission from list
8198 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 }
8200 }
8201 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008202 int newGids[] = globalGids;
8203 for (String eachPerm : sus.grantedPermissions) {
8204 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008205 if (bp != null) {
8206 newGids = appendInts(newGids, bp.gids);
8207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008208 }
8209 sus.gids = newGids;
8210 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008212 private int removePackageLP(String name) {
8213 PackageSetting p = mPackages.get(name);
8214 if (p != null) {
8215 mPackages.remove(name);
8216 if (p.sharedUser != null) {
8217 p.sharedUser.packages.remove(p);
8218 if (p.sharedUser.packages.size() == 0) {
8219 mSharedUsers.remove(p.sharedUser.name);
8220 removeUserIdLP(p.sharedUser.userId);
8221 return p.sharedUser.userId;
8222 }
8223 } else {
8224 removeUserIdLP(p.userId);
8225 return p.userId;
8226 }
8227 }
8228 return -1;
8229 }
8230
8231 private boolean addUserIdLP(int uid, Object obj, Object name) {
8232 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8233 return false;
8234 }
8235
8236 if (uid >= FIRST_APPLICATION_UID) {
8237 int N = mUserIds.size();
8238 final int index = uid - FIRST_APPLICATION_UID;
8239 while (index >= N) {
8240 mUserIds.add(null);
8241 N++;
8242 }
8243 if (mUserIds.get(index) != null) {
8244 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008245 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246 + " name=" + name);
8247 return false;
8248 }
8249 mUserIds.set(index, obj);
8250 } else {
8251 if (mOtherUserIds.get(uid) != null) {
8252 reportSettingsProblem(Log.ERROR,
8253 "Adding duplicate shared id: " + uid
8254 + " name=" + name);
8255 return false;
8256 }
8257 mOtherUserIds.put(uid, obj);
8258 }
8259 return true;
8260 }
8261
8262 public Object getUserIdLP(int uid) {
8263 if (uid >= FIRST_APPLICATION_UID) {
8264 int N = mUserIds.size();
8265 final int index = uid - FIRST_APPLICATION_UID;
8266 return index < N ? mUserIds.get(index) : null;
8267 } else {
8268 return mOtherUserIds.get(uid);
8269 }
8270 }
8271
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008272 private Set<String> findPackagesWithFlag(int flag) {
8273 Set<String> ret = new HashSet<String>();
8274 for (PackageSetting ps : mPackages.values()) {
8275 // Has to match atleast all the flag bits set on flag
8276 if ((ps.pkgFlags & flag) == flag) {
8277 ret.add(ps.name);
8278 }
8279 }
8280 return ret;
8281 }
8282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 private void removeUserIdLP(int uid) {
8284 if (uid >= FIRST_APPLICATION_UID) {
8285 int N = mUserIds.size();
8286 final int index = uid - FIRST_APPLICATION_UID;
8287 if (index < N) mUserIds.set(index, null);
8288 } else {
8289 mOtherUserIds.remove(uid);
8290 }
8291 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008293 void writeLP() {
8294 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8295
8296 // Keep the old settings around until we know the new ones have
8297 // been successfully written.
8298 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008299 // Presence of backup settings file indicates that we failed
8300 // to persist settings earlier. So preserve the older
8301 // backup for future reference since the current settings
8302 // might have been corrupted.
8303 if (!mBackupSettingsFilename.exists()) {
8304 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008305 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008306 return;
8307 }
8308 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008309 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008310 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 }
8313
8314 mPastSignatures.clear();
8315
8316 try {
8317 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8318
8319 //XmlSerializer serializer = XmlUtils.serializerInstance();
8320 XmlSerializer serializer = new FastXmlSerializer();
8321 serializer.setOutput(str, "utf-8");
8322 serializer.startDocument(null, true);
8323 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8324
8325 serializer.startTag(null, "packages");
8326
8327 serializer.startTag(null, "permission-trees");
8328 for (BasePermission bp : mPermissionTrees.values()) {
8329 writePermission(serializer, bp);
8330 }
8331 serializer.endTag(null, "permission-trees");
8332
8333 serializer.startTag(null, "permissions");
8334 for (BasePermission bp : mPermissions.values()) {
8335 writePermission(serializer, bp);
8336 }
8337 serializer.endTag(null, "permissions");
8338
8339 for (PackageSetting pkg : mPackages.values()) {
8340 writePackage(serializer, pkg);
8341 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008343 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8344 writeDisabledSysPackage(serializer, pkg);
8345 }
8346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008347 serializer.startTag(null, "preferred-activities");
8348 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8349 serializer.startTag(null, "item");
8350 pa.writeToXml(serializer);
8351 serializer.endTag(null, "item");
8352 }
8353 serializer.endTag(null, "preferred-activities");
8354
8355 for (SharedUserSetting usr : mSharedUsers.values()) {
8356 serializer.startTag(null, "shared-user");
8357 serializer.attribute(null, "name", usr.name);
8358 serializer.attribute(null, "userId",
8359 Integer.toString(usr.userId));
8360 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8361 serializer.startTag(null, "perms");
8362 for (String name : usr.grantedPermissions) {
8363 serializer.startTag(null, "item");
8364 serializer.attribute(null, "name", name);
8365 serializer.endTag(null, "item");
8366 }
8367 serializer.endTag(null, "perms");
8368 serializer.endTag(null, "shared-user");
8369 }
8370
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008371 if (mPackagesToBeCleaned.size() > 0) {
8372 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8373 serializer.startTag(null, "cleaning-package");
8374 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8375 serializer.endTag(null, "cleaning-package");
8376 }
8377 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008378
8379 if (mRenamedPackages.size() > 0) {
8380 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8381 serializer.startTag(null, "renamed-package");
8382 serializer.attribute(null, "new", e.getKey());
8383 serializer.attribute(null, "old", e.getValue());
8384 serializer.endTag(null, "renamed-package");
8385 }
8386 }
8387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008388 serializer.endTag(null, "packages");
8389
8390 serializer.endDocument();
8391
8392 str.flush();
8393 str.close();
8394
8395 // New settings successfully written, old ones are no longer
8396 // needed.
8397 mBackupSettingsFilename.delete();
8398 FileUtils.setPermissions(mSettingsFilename.toString(),
8399 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8400 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8401 |FileUtils.S_IROTH,
8402 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008403
8404 // Write package list file now, use a JournaledFile.
8405 //
8406 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8407 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8408
8409 str = new FileOutputStream(journal.chooseForWrite());
8410 try {
8411 StringBuilder sb = new StringBuilder();
8412 for (PackageSetting pkg : mPackages.values()) {
8413 ApplicationInfo ai = pkg.pkg.applicationInfo;
8414 String dataPath = ai.dataDir;
8415 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8416
8417 // Avoid any application that has a space in its path
8418 // or that is handled by the system.
8419 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8420 continue;
8421
8422 // we store on each line the following information for now:
8423 //
8424 // pkgName - package name
8425 // userId - application-specific user id
8426 // debugFlag - 0 or 1 if the package is debuggable.
8427 // dataPath - path to package's data path
8428 //
8429 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8430 //
8431 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8432 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8433 // system/core/run-as/run-as.c
8434 //
8435 sb.setLength(0);
8436 sb.append(ai.packageName);
8437 sb.append(" ");
8438 sb.append((int)ai.uid);
8439 sb.append(isDebug ? " 1 " : " 0 ");
8440 sb.append(dataPath);
8441 sb.append("\n");
8442 str.write(sb.toString().getBytes());
8443 }
8444 str.flush();
8445 str.close();
8446 journal.commit();
8447 }
8448 catch (Exception e) {
8449 journal.rollback();
8450 }
8451
8452 FileUtils.setPermissions(mPackageListFilename.toString(),
8453 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8454 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8455 |FileUtils.S_IROTH,
8456 -1, -1);
8457
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008458 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459
8460 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008461 Slog.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 -08008462 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008463 Slog.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 -08008464 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008465 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008466 if (mSettingsFilename.exists()) {
8467 if (!mSettingsFilename.delete()) {
8468 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8469 }
8470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008471 //Debug.stopMethodTracing();
8472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008473
8474 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008475 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 serializer.startTag(null, "updated-package");
8477 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008478 if (pkg.realName != null) {
8479 serializer.attribute(null, "realName", pkg.realName);
8480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 serializer.attribute(null, "codePath", pkg.codePathString);
8482 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008483 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008484 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8485 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8486 }
8487 if (pkg.sharedUser == null) {
8488 serializer.attribute(null, "userId",
8489 Integer.toString(pkg.userId));
8490 } else {
8491 serializer.attribute(null, "sharedUserId",
8492 Integer.toString(pkg.userId));
8493 }
8494 serializer.startTag(null, "perms");
8495 if (pkg.sharedUser == null) {
8496 // If this is a shared user, the permissions will
8497 // be written there. We still need to write an
8498 // empty permissions list so permissionsFixed will
8499 // be set.
8500 for (final String name : pkg.grantedPermissions) {
8501 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008502 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 // We only need to write signature or system permissions but this wont
8504 // match the semantics of grantedPermissions. So write all permissions.
8505 serializer.startTag(null, "item");
8506 serializer.attribute(null, "name", name);
8507 serializer.endTag(null, "item");
8508 }
8509 }
8510 }
8511 serializer.endTag(null, "perms");
8512 serializer.endTag(null, "updated-package");
8513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008514
8515 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008516 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 serializer.startTag(null, "package");
8518 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008519 if (pkg.realName != null) {
8520 serializer.attribute(null, "realName", pkg.realName);
8521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008522 serializer.attribute(null, "codePath", pkg.codePathString);
8523 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8524 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8525 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008526 serializer.attribute(null, "flags",
8527 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008529 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 if (pkg.sharedUser == null) {
8531 serializer.attribute(null, "userId",
8532 Integer.toString(pkg.userId));
8533 } else {
8534 serializer.attribute(null, "sharedUserId",
8535 Integer.toString(pkg.userId));
8536 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008537 if (pkg.uidError) {
8538 serializer.attribute(null, "uidError", "true");
8539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008540 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8541 serializer.attribute(null, "enabled",
8542 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8543 ? "true" : "false");
8544 }
8545 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8546 serializer.attribute(null, "installStatus", "false");
8547 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008548 if (pkg.installerPackageName != null) {
8549 serializer.attribute(null, "installer", pkg.installerPackageName);
8550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008551 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8552 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8553 serializer.startTag(null, "perms");
8554 if (pkg.sharedUser == null) {
8555 // If this is a shared user, the permissions will
8556 // be written there. We still need to write an
8557 // empty permissions list so permissionsFixed will
8558 // be set.
8559 for (final String name : pkg.grantedPermissions) {
8560 serializer.startTag(null, "item");
8561 serializer.attribute(null, "name", name);
8562 serializer.endTag(null, "item");
8563 }
8564 }
8565 serializer.endTag(null, "perms");
8566 }
8567 if (pkg.disabledComponents.size() > 0) {
8568 serializer.startTag(null, "disabled-components");
8569 for (final String name : pkg.disabledComponents) {
8570 serializer.startTag(null, "item");
8571 serializer.attribute(null, "name", name);
8572 serializer.endTag(null, "item");
8573 }
8574 serializer.endTag(null, "disabled-components");
8575 }
8576 if (pkg.enabledComponents.size() > 0) {
8577 serializer.startTag(null, "enabled-components");
8578 for (final String name : pkg.enabledComponents) {
8579 serializer.startTag(null, "item");
8580 serializer.attribute(null, "name", name);
8581 serializer.endTag(null, "item");
8582 }
8583 serializer.endTag(null, "enabled-components");
8584 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008586 serializer.endTag(null, "package");
8587 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589 void writePermission(XmlSerializer serializer, BasePermission bp)
8590 throws XmlPullParserException, java.io.IOException {
8591 if (bp.type != BasePermission.TYPE_BUILTIN
8592 && bp.sourcePackage != null) {
8593 serializer.startTag(null, "item");
8594 serializer.attribute(null, "name", bp.name);
8595 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008596 if (bp.protectionLevel !=
8597 PermissionInfo.PROTECTION_NORMAL) {
8598 serializer.attribute(null, "protection",
8599 Integer.toString(bp.protectionLevel));
8600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 if (DEBUG_SETTINGS) Log.v(TAG,
8602 "Writing perm: name=" + bp.name + " type=" + bp.type);
8603 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8604 PermissionInfo pi = bp.perm != null ? bp.perm.info
8605 : bp.pendingInfo;
8606 if (pi != null) {
8607 serializer.attribute(null, "type", "dynamic");
8608 if (pi.icon != 0) {
8609 serializer.attribute(null, "icon",
8610 Integer.toString(pi.icon));
8611 }
8612 if (pi.nonLocalizedLabel != null) {
8613 serializer.attribute(null, "label",
8614 pi.nonLocalizedLabel.toString());
8615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 }
8617 }
8618 serializer.endTag(null, "item");
8619 }
8620 }
8621
8622 String getReadMessagesLP() {
8623 return mReadMessages.toString();
8624 }
8625
Oscar Montemayora8529f62009-11-18 10:14:20 -08008626 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008627 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8628 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008629 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 while(its.hasNext()) {
8631 String key = its.next();
8632 PackageSetting ps = mPackages.get(key);
8633 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008634 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008635 }
8636 }
8637 return ret;
8638 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 boolean readLP() {
8641 FileInputStream str = null;
8642 if (mBackupSettingsFilename.exists()) {
8643 try {
8644 str = new FileInputStream(mBackupSettingsFilename);
8645 mReadMessages.append("Reading from backup settings file\n");
8646 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008647 if (mSettingsFilename.exists()) {
8648 // If both the backup and settings file exist, we
8649 // ignore the settings since it might have been
8650 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008651 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008652 mSettingsFilename.delete();
8653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654 } catch (java.io.IOException e) {
8655 // We'll try for the normal settings file.
8656 }
8657 }
8658
8659 mPastSignatures.clear();
8660
8661 try {
8662 if (str == null) {
8663 if (!mSettingsFilename.exists()) {
8664 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008665 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008666 return false;
8667 }
8668 str = new FileInputStream(mSettingsFilename);
8669 }
8670 XmlPullParser parser = Xml.newPullParser();
8671 parser.setInput(str, null);
8672
8673 int type;
8674 while ((type=parser.next()) != XmlPullParser.START_TAG
8675 && type != XmlPullParser.END_DOCUMENT) {
8676 ;
8677 }
8678
8679 if (type != XmlPullParser.START_TAG) {
8680 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008681 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008682 return false;
8683 }
8684
8685 int outerDepth = parser.getDepth();
8686 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8687 && (type != XmlPullParser.END_TAG
8688 || parser.getDepth() > outerDepth)) {
8689 if (type == XmlPullParser.END_TAG
8690 || type == XmlPullParser.TEXT) {
8691 continue;
8692 }
8693
8694 String tagName = parser.getName();
8695 if (tagName.equals("package")) {
8696 readPackageLP(parser);
8697 } else if (tagName.equals("permissions")) {
8698 readPermissionsLP(mPermissions, parser);
8699 } else if (tagName.equals("permission-trees")) {
8700 readPermissionsLP(mPermissionTrees, parser);
8701 } else if (tagName.equals("shared-user")) {
8702 readSharedUserLP(parser);
8703 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008704 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 } else if (tagName.equals("preferred-activities")) {
8706 readPreferredActivitiesLP(parser);
8707 } else if(tagName.equals("updated-package")) {
8708 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008709 } else if (tagName.equals("cleaning-package")) {
8710 String name = parser.getAttributeValue(null, "name");
8711 if (name != null) {
8712 mPackagesToBeCleaned.add(name);
8713 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008714 } else if (tagName.equals("renamed-package")) {
8715 String nname = parser.getAttributeValue(null, "new");
8716 String oname = parser.getAttributeValue(null, "old");
8717 if (nname != null && oname != null) {
8718 mRenamedPackages.put(nname, oname);
8719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008721 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008722 + parser.getName());
8723 XmlUtils.skipCurrentTag(parser);
8724 }
8725 }
8726
8727 str.close();
8728
8729 } catch(XmlPullParserException e) {
8730 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008731 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008732
8733 } catch(java.io.IOException e) {
8734 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008735 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008736
8737 }
8738
8739 int N = mPendingPackages.size();
8740 for (int i=0; i<N; i++) {
8741 final PendingPackage pp = mPendingPackages.get(i);
8742 Object idObj = getUserIdLP(pp.sharedId);
8743 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008744 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008746 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008747 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008748 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749 + pp.name);
8750 continue;
8751 }
8752 p.copyFrom(pp);
8753 } else if (idObj != null) {
8754 String msg = "Bad package setting: package " + pp.name
8755 + " has shared uid " + pp.sharedId
8756 + " that is not a shared uid\n";
8757 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008758 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 } else {
8760 String msg = "Bad package setting: package " + pp.name
8761 + " has shared uid " + pp.sharedId
8762 + " that is not defined\n";
8763 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008764 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008765 }
8766 }
8767 mPendingPackages.clear();
8768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 mReadMessages.append("Read completed successfully: "
8770 + mPackages.size() + " packages, "
8771 + mSharedUsers.size() + " shared uids\n");
8772
8773 return true;
8774 }
8775
8776 private int readInt(XmlPullParser parser, String ns, String name,
8777 int defValue) {
8778 String v = parser.getAttributeValue(ns, name);
8779 try {
8780 if (v == null) {
8781 return defValue;
8782 }
8783 return Integer.parseInt(v);
8784 } catch (NumberFormatException e) {
8785 reportSettingsProblem(Log.WARN,
8786 "Error in package manager settings: attribute " +
8787 name + " has bad integer value " + v + " at "
8788 + parser.getPositionDescription());
8789 }
8790 return defValue;
8791 }
8792
8793 private void readPermissionsLP(HashMap<String, BasePermission> out,
8794 XmlPullParser parser)
8795 throws IOException, XmlPullParserException {
8796 int outerDepth = parser.getDepth();
8797 int type;
8798 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8799 && (type != XmlPullParser.END_TAG
8800 || parser.getDepth() > outerDepth)) {
8801 if (type == XmlPullParser.END_TAG
8802 || type == XmlPullParser.TEXT) {
8803 continue;
8804 }
8805
8806 String tagName = parser.getName();
8807 if (tagName.equals("item")) {
8808 String name = parser.getAttributeValue(null, "name");
8809 String sourcePackage = parser.getAttributeValue(null, "package");
8810 String ptype = parser.getAttributeValue(null, "type");
8811 if (name != null && sourcePackage != null) {
8812 boolean dynamic = "dynamic".equals(ptype);
8813 BasePermission bp = new BasePermission(name, sourcePackage,
8814 dynamic
8815 ? BasePermission.TYPE_DYNAMIC
8816 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008817 bp.protectionLevel = readInt(parser, null, "protection",
8818 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008819 if (dynamic) {
8820 PermissionInfo pi = new PermissionInfo();
8821 pi.packageName = sourcePackage.intern();
8822 pi.name = name.intern();
8823 pi.icon = readInt(parser, null, "icon", 0);
8824 pi.nonLocalizedLabel = parser.getAttributeValue(
8825 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008826 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008827 bp.pendingInfo = pi;
8828 }
8829 out.put(bp.name, bp);
8830 } else {
8831 reportSettingsProblem(Log.WARN,
8832 "Error in package manager settings: permissions has"
8833 + " no name at " + parser.getPositionDescription());
8834 }
8835 } else {
8836 reportSettingsProblem(Log.WARN,
8837 "Unknown element reading permissions: "
8838 + parser.getName() + " at "
8839 + parser.getPositionDescription());
8840 }
8841 XmlUtils.skipCurrentTag(parser);
8842 }
8843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008846 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008847 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008848 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008849 String codePathStr = parser.getAttributeValue(null, "codePath");
8850 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008851 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008852 resourcePathStr = codePathStr;
8853 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008854 String version = parser.getAttributeValue(null, "version");
8855 int versionCode = 0;
8856 if (version != null) {
8857 try {
8858 versionCode = Integer.parseInt(version);
8859 } catch (NumberFormatException e) {
8860 }
8861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863 int pkgFlags = 0;
8864 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008865 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008866 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008867 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868 String timeStampStr = parser.getAttributeValue(null, "ts");
8869 if (timeStampStr != null) {
8870 try {
8871 long timeStamp = Long.parseLong(timeStampStr);
8872 ps.setTimeStamp(timeStamp, timeStampStr);
8873 } catch (NumberFormatException e) {
8874 }
8875 }
8876 String idStr = parser.getAttributeValue(null, "userId");
8877 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8878 if(ps.userId <= 0) {
8879 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8880 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8881 }
8882 int outerDepth = parser.getDepth();
8883 int type;
8884 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8885 && (type != XmlPullParser.END_TAG
8886 || parser.getDepth() > outerDepth)) {
8887 if (type == XmlPullParser.END_TAG
8888 || type == XmlPullParser.TEXT) {
8889 continue;
8890 }
8891
8892 String tagName = parser.getName();
8893 if (tagName.equals("perms")) {
8894 readGrantedPermissionsLP(parser,
8895 ps.grantedPermissions);
8896 } else {
8897 reportSettingsProblem(Log.WARN,
8898 "Unknown element under <updated-package>: "
8899 + parser.getName());
8900 XmlUtils.skipCurrentTag(parser);
8901 }
8902 }
8903 mDisabledSysPackages.put(name, ps);
8904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 private void readPackageLP(XmlPullParser parser)
8907 throws XmlPullParserException, IOException {
8908 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008909 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 String idStr = null;
8911 String sharedIdStr = null;
8912 String codePathStr = null;
8913 String resourcePathStr = null;
8914 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008915 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008916 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008917 int pkgFlags = 0;
8918 String timeStampStr;
8919 long timeStamp = 0;
8920 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008921 String version = null;
8922 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923 try {
8924 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008925 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008927 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8929 codePathStr = parser.getAttributeValue(null, "codePath");
8930 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008931 version = parser.getAttributeValue(null, "version");
8932 if (version != null) {
8933 try {
8934 versionCode = Integer.parseInt(version);
8935 } catch (NumberFormatException e) {
8936 }
8937 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008938 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008939
8940 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008942 try {
8943 pkgFlags = Integer.parseInt(systemStr);
8944 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 }
8946 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008947 // For backward compatibility
8948 systemStr = parser.getAttributeValue(null, "system");
8949 if (systemStr != null) {
8950 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8951 } else {
8952 // Old settings that don't specify system... just treat
8953 // them as system, good enough.
8954 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956 }
8957 timeStampStr = parser.getAttributeValue(null, "ts");
8958 if (timeStampStr != null) {
8959 try {
8960 timeStamp = Long.parseLong(timeStampStr);
8961 } catch (NumberFormatException e) {
8962 }
8963 }
8964 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8965 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8966 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8967 if (resourcePathStr == null) {
8968 resourcePathStr = codePathStr;
8969 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008970 if (realName != null) {
8971 realName = realName.intern();
8972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008973 if (name == null) {
8974 reportSettingsProblem(Log.WARN,
8975 "Error in package manager settings: <package> has no name at "
8976 + parser.getPositionDescription());
8977 } else if (codePathStr == null) {
8978 reportSettingsProblem(Log.WARN,
8979 "Error in package manager settings: <package> has no codePath at "
8980 + parser.getPositionDescription());
8981 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008982 packageSetting = addPackageLP(name.intern(), realName,
8983 new File(codePathStr), new File(resourcePathStr),
8984 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8986 + ": userId=" + userId + " pkg=" + packageSetting);
8987 if (packageSetting == null) {
8988 reportSettingsProblem(Log.ERROR,
8989 "Failure adding uid " + userId
8990 + " while parsing settings at "
8991 + parser.getPositionDescription());
8992 } else {
8993 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8994 }
8995 } else if (sharedIdStr != null) {
8996 userId = sharedIdStr != null
8997 ? Integer.parseInt(sharedIdStr) : 0;
8998 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008999 packageSetting = new PendingPackage(name.intern(), realName,
9000 new File(codePathStr), new File(resourcePathStr),
9001 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009002 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9003 mPendingPackages.add((PendingPackage) packageSetting);
9004 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9005 + ": sharedUserId=" + userId + " pkg="
9006 + packageSetting);
9007 } else {
9008 reportSettingsProblem(Log.WARN,
9009 "Error in package manager settings: package "
9010 + name + " has bad sharedId " + sharedIdStr
9011 + " at " + parser.getPositionDescription());
9012 }
9013 } else {
9014 reportSettingsProblem(Log.WARN,
9015 "Error in package manager settings: package "
9016 + name + " has bad userId " + idStr + " at "
9017 + parser.getPositionDescription());
9018 }
9019 } catch (NumberFormatException e) {
9020 reportSettingsProblem(Log.WARN,
9021 "Error in package manager settings: package "
9022 + name + " has bad userId " + idStr + " at "
9023 + parser.getPositionDescription());
9024 }
9025 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009026 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009027 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 final String enabledStr = parser.getAttributeValue(null, "enabled");
9029 if (enabledStr != null) {
9030 if (enabledStr.equalsIgnoreCase("true")) {
9031 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9032 } else if (enabledStr.equalsIgnoreCase("false")) {
9033 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9034 } else if (enabledStr.equalsIgnoreCase("default")) {
9035 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9036 } else {
9037 reportSettingsProblem(Log.WARN,
9038 "Error in package manager settings: package "
9039 + name + " has bad enabled value: " + idStr
9040 + " at " + parser.getPositionDescription());
9041 }
9042 } else {
9043 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9044 }
9045 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9046 if (installStatusStr != null) {
9047 if (installStatusStr.equalsIgnoreCase("false")) {
9048 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9049 } else {
9050 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9051 }
9052 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009054 int outerDepth = parser.getDepth();
9055 int type;
9056 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9057 && (type != XmlPullParser.END_TAG
9058 || parser.getDepth() > outerDepth)) {
9059 if (type == XmlPullParser.END_TAG
9060 || type == XmlPullParser.TEXT) {
9061 continue;
9062 }
9063
9064 String tagName = parser.getName();
9065 if (tagName.equals("disabled-components")) {
9066 readDisabledComponentsLP(packageSetting, parser);
9067 } else if (tagName.equals("enabled-components")) {
9068 readEnabledComponentsLP(packageSetting, parser);
9069 } else if (tagName.equals("sigs")) {
9070 packageSetting.signatures.readXml(parser, mPastSignatures);
9071 } else if (tagName.equals("perms")) {
9072 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009073 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 packageSetting.permissionsFixed = true;
9075 } else {
9076 reportSettingsProblem(Log.WARN,
9077 "Unknown element under <package>: "
9078 + parser.getName());
9079 XmlUtils.skipCurrentTag(parser);
9080 }
9081 }
9082 } else {
9083 XmlUtils.skipCurrentTag(parser);
9084 }
9085 }
9086
9087 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9088 XmlPullParser parser)
9089 throws IOException, XmlPullParserException {
9090 int outerDepth = parser.getDepth();
9091 int type;
9092 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9093 && (type != XmlPullParser.END_TAG
9094 || parser.getDepth() > outerDepth)) {
9095 if (type == XmlPullParser.END_TAG
9096 || type == XmlPullParser.TEXT) {
9097 continue;
9098 }
9099
9100 String tagName = parser.getName();
9101 if (tagName.equals("item")) {
9102 String name = parser.getAttributeValue(null, "name");
9103 if (name != null) {
9104 packageSetting.disabledComponents.add(name.intern());
9105 } else {
9106 reportSettingsProblem(Log.WARN,
9107 "Error in package manager settings: <disabled-components> has"
9108 + " no name at " + parser.getPositionDescription());
9109 }
9110 } else {
9111 reportSettingsProblem(Log.WARN,
9112 "Unknown element under <disabled-components>: "
9113 + parser.getName());
9114 }
9115 XmlUtils.skipCurrentTag(parser);
9116 }
9117 }
9118
9119 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9120 XmlPullParser parser)
9121 throws IOException, XmlPullParserException {
9122 int outerDepth = parser.getDepth();
9123 int type;
9124 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9125 && (type != XmlPullParser.END_TAG
9126 || parser.getDepth() > outerDepth)) {
9127 if (type == XmlPullParser.END_TAG
9128 || type == XmlPullParser.TEXT) {
9129 continue;
9130 }
9131
9132 String tagName = parser.getName();
9133 if (tagName.equals("item")) {
9134 String name = parser.getAttributeValue(null, "name");
9135 if (name != null) {
9136 packageSetting.enabledComponents.add(name.intern());
9137 } else {
9138 reportSettingsProblem(Log.WARN,
9139 "Error in package manager settings: <enabled-components> has"
9140 + " no name at " + parser.getPositionDescription());
9141 }
9142 } else {
9143 reportSettingsProblem(Log.WARN,
9144 "Unknown element under <enabled-components>: "
9145 + parser.getName());
9146 }
9147 XmlUtils.skipCurrentTag(parser);
9148 }
9149 }
9150
9151 private void readSharedUserLP(XmlPullParser parser)
9152 throws XmlPullParserException, IOException {
9153 String name = null;
9154 String idStr = null;
9155 int pkgFlags = 0;
9156 SharedUserSetting su = null;
9157 try {
9158 name = parser.getAttributeValue(null, "name");
9159 idStr = parser.getAttributeValue(null, "userId");
9160 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9161 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9162 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9163 }
9164 if (name == null) {
9165 reportSettingsProblem(Log.WARN,
9166 "Error in package manager settings: <shared-user> has no name at "
9167 + parser.getPositionDescription());
9168 } else if (userId == 0) {
9169 reportSettingsProblem(Log.WARN,
9170 "Error in package manager settings: shared-user "
9171 + name + " has bad userId " + idStr + " at "
9172 + parser.getPositionDescription());
9173 } else {
9174 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9175 reportSettingsProblem(Log.ERROR,
9176 "Occurred while parsing settings at "
9177 + parser.getPositionDescription());
9178 }
9179 }
9180 } catch (NumberFormatException e) {
9181 reportSettingsProblem(Log.WARN,
9182 "Error in package manager settings: package "
9183 + name + " has bad userId " + idStr + " at "
9184 + parser.getPositionDescription());
9185 };
9186
9187 if (su != null) {
9188 int outerDepth = parser.getDepth();
9189 int type;
9190 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9191 && (type != XmlPullParser.END_TAG
9192 || parser.getDepth() > outerDepth)) {
9193 if (type == XmlPullParser.END_TAG
9194 || type == XmlPullParser.TEXT) {
9195 continue;
9196 }
9197
9198 String tagName = parser.getName();
9199 if (tagName.equals("sigs")) {
9200 su.signatures.readXml(parser, mPastSignatures);
9201 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009202 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009203 } else {
9204 reportSettingsProblem(Log.WARN,
9205 "Unknown element under <shared-user>: "
9206 + parser.getName());
9207 XmlUtils.skipCurrentTag(parser);
9208 }
9209 }
9210
9211 } else {
9212 XmlUtils.skipCurrentTag(parser);
9213 }
9214 }
9215
9216 private void readGrantedPermissionsLP(XmlPullParser parser,
9217 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9218 int outerDepth = parser.getDepth();
9219 int type;
9220 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9221 && (type != XmlPullParser.END_TAG
9222 || parser.getDepth() > outerDepth)) {
9223 if (type == XmlPullParser.END_TAG
9224 || type == XmlPullParser.TEXT) {
9225 continue;
9226 }
9227
9228 String tagName = parser.getName();
9229 if (tagName.equals("item")) {
9230 String name = parser.getAttributeValue(null, "name");
9231 if (name != null) {
9232 outPerms.add(name.intern());
9233 } else {
9234 reportSettingsProblem(Log.WARN,
9235 "Error in package manager settings: <perms> has"
9236 + " no name at " + parser.getPositionDescription());
9237 }
9238 } else {
9239 reportSettingsProblem(Log.WARN,
9240 "Unknown element under <perms>: "
9241 + parser.getName());
9242 }
9243 XmlUtils.skipCurrentTag(parser);
9244 }
9245 }
9246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009247 private void readPreferredActivitiesLP(XmlPullParser parser)
9248 throws XmlPullParserException, IOException {
9249 int outerDepth = parser.getDepth();
9250 int type;
9251 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9252 && (type != XmlPullParser.END_TAG
9253 || parser.getDepth() > outerDepth)) {
9254 if (type == XmlPullParser.END_TAG
9255 || type == XmlPullParser.TEXT) {
9256 continue;
9257 }
9258
9259 String tagName = parser.getName();
9260 if (tagName.equals("item")) {
9261 PreferredActivity pa = new PreferredActivity(parser);
9262 if (pa.mParseError == null) {
9263 mPreferredActivities.addFilter(pa);
9264 } else {
9265 reportSettingsProblem(Log.WARN,
9266 "Error in package manager settings: <preferred-activity> "
9267 + pa.mParseError + " at "
9268 + parser.getPositionDescription());
9269 }
9270 } else {
9271 reportSettingsProblem(Log.WARN,
9272 "Unknown element under <preferred-activities>: "
9273 + parser.getName());
9274 XmlUtils.skipCurrentTag(parser);
9275 }
9276 }
9277 }
9278
9279 // Returns -1 if we could not find an available UserId to assign
9280 private int newUserIdLP(Object obj) {
9281 // Let's be stupidly inefficient for now...
9282 final int N = mUserIds.size();
9283 for (int i=0; i<N; i++) {
9284 if (mUserIds.get(i) == null) {
9285 mUserIds.set(i, obj);
9286 return FIRST_APPLICATION_UID + i;
9287 }
9288 }
9289
9290 // None left?
9291 if (N >= MAX_APPLICATION_UIDS) {
9292 return -1;
9293 }
9294
9295 mUserIds.add(obj);
9296 return FIRST_APPLICATION_UID + N;
9297 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009299 public PackageSetting getDisabledSystemPkg(String name) {
9300 synchronized(mPackages) {
9301 PackageSetting ps = mDisabledSysPackages.get(name);
9302 return ps;
9303 }
9304 }
9305
9306 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9307 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9308 if (Config.LOGV) {
9309 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9310 + " componentName = " + componentInfo.name);
9311 Log.v(TAG, "enabledComponents: "
9312 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9313 Log.v(TAG, "disabledComponents: "
9314 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9315 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009316 if (packageSettings == null) {
9317 if (false) {
9318 Log.w(TAG, "WAITING FOR DEBUGGER");
9319 Debug.waitForDebugger();
9320 Log.i(TAG, "We will crash!");
9321 }
9322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009323 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9324 || ((componentInfo.enabled
9325 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9326 || (componentInfo.applicationInfo.enabled
9327 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9328 && !packageSettings.disabledComponents.contains(componentInfo.name))
9329 || packageSettings.enabledComponents.contains(componentInfo.name));
9330 }
9331 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009332
9333 // ------- apps on sdcard specific code -------
9334 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009335 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009336 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009337 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009338 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009339
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009340 private String getEncryptKey() {
9341 try {
9342 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9343 if (sdEncKey == null) {
9344 sdEncKey = SystemKeyStore.getInstance().
9345 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9346 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009347 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009348 return null;
9349 }
9350 }
9351 return sdEncKey;
9352 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009353 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009354 return null;
9355 }
9356 }
9357
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009358 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009359 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009360 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009361 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009362 if (list != null) {
9363 int idx = 0;
9364 int idList[] = new int[MAX_CONTAINERS];
9365 boolean neverFound = true;
9366 for (String name : list) {
9367 // Ignore null entries
9368 if (name == null) {
9369 continue;
9370 }
9371 int sidx = name.indexOf(prefix);
9372 if (sidx == -1) {
9373 // Not a temp file. just ignore
9374 continue;
9375 }
9376 String subStr = name.substring(sidx + prefix.length());
9377 idList[idx] = -1;
9378 if (subStr != null) {
9379 try {
9380 int cid = Integer.parseInt(subStr);
9381 idList[idx++] = cid;
9382 neverFound = false;
9383 } catch (NumberFormatException e) {
9384 }
9385 }
9386 }
9387 if (!neverFound) {
9388 // Sort idList
9389 Arrays.sort(idList);
9390 for (int j = 1; j <= idList.length; j++) {
9391 if (idList[j-1] != j) {
9392 tmpIdx = j;
9393 break;
9394 }
9395 }
9396 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009397 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009398 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009399 }
9400
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009401 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009402 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009403 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009404 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9405 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9406 throw new SecurityException("Media status can only be updated by the system");
9407 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009408 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009409 Log.i(TAG, "Updating external media status from " +
9410 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9411 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009412 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9413 mediaStatus+", mMediaMounted=" + mMediaMounted);
9414 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009415 if (reportStatus) {
9416 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9417 }
9418 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009419 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009420 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009421 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009422 // Queue up an async operation since the package installation may take a little while.
9423 mHandler.post(new Runnable() {
9424 public void run() {
9425 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009426 try {
9427 updateExternalMediaStatusInner(mediaStatus);
9428 } finally {
9429 if (reportStatus) {
9430 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9431 }
9432 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009433 }
9434 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009435 }
9436
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009437 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009438 // If we are up here that means there are packages to be
9439 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009440 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009441 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009442 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009443 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009444 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009445
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009446 int uidList[] = new int[list.length];
9447 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009448 HashSet<String> removeCids = new HashSet<String>();
9449 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009450 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009451 for (String cid : list) {
9452 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009453 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9454 boolean failed = true;
9455 try {
9456 String pkgName = args.getPackageName();
9457 if (pkgName == null) {
9458 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009459 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009460 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9461 PackageSetting ps = mSettings.mPackages.get(pkgName);
9462 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009463 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009464 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9465 " corresponds to pkg : " + pkgName +
9466 " at code path: " + ps.codePathString);
9467 // We do have a valid package installed on sdcard
9468 processCids.put(args, ps.codePathString);
9469 failed = false;
9470 int uid = ps.userId;
9471 if (uid != -1) {
9472 uidList[num++] = uid;
9473 }
9474 }
9475 } finally {
9476 if (failed) {
9477 // Stale container on sdcard. Just delete
9478 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9479 removeCids.add(cid);
9480 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009481 }
9482 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009483 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009484 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009485 int uidArr[] = null;
9486 if (num > 0) {
9487 // Sort uid list
9488 Arrays.sort(uidList, 0, num);
9489 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009490 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009491 uidArr[0] = uidList[0];
9492 int di = 0;
9493 for (int i = 1; i < num; i++) {
9494 if (uidList[i-1] != uidList[i]) {
9495 uidArr[di++] = uidList[i];
9496 }
9497 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009498 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009499 // Process packages with valid entries.
9500 if (mediaStatus) {
9501 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009502 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009503 startCleaningPackages();
9504 } else {
9505 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009506 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009507 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009508 }
9509
9510 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9511 ArrayList<String> pkgList, int uidArr[]) {
9512 int size = pkgList.size();
9513 if (size > 0) {
9514 // Send broadcasts here
9515 Bundle extras = new Bundle();
9516 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9517 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009518 if (uidArr != null) {
9519 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9520 }
9521 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9522 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009523 sendPackageBroadcast(action, null, extras);
9524 }
9525 }
9526
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009527 /*
9528 * Look at potentially valid container ids from processCids
9529 * If package information doesn't match the one on record
9530 * or package scanning fails, the cid is added to list of
9531 * removeCids and cleaned up. Since cleaning up containers
9532 * involves destroying them, we do not want any parse
9533 * references to such stale containers. So force gc's
9534 * to avoid unnecessary crashes.
9535 */
9536 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009537 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009538 ArrayList<String> pkgList = new ArrayList<String>();
9539 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009540 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009541 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009542 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009543 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9544 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009545 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009546 try {
9547 // Make sure there are no container errors first.
9548 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9549 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009550 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009551 " when installing from sdcard");
9552 continue;
9553 }
9554 // Check code path here.
9555 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009556 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009557 " does not match one in settings " + codePath);
9558 continue;
9559 }
9560 // Parse package
9561 int parseFlags = PackageParser.PARSE_CHATTY |
Jeff Brown07330792010-03-30 19:57:08 -07009562 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009563 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009564 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009565 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9566 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009567 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009568 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009569 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009570 retCode = PackageManager.INSTALL_SUCCEEDED;
9571 pkgList.add(pkg.packageName);
9572 // Post process args
9573 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9574 }
9575 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009576 Slog.i(TAG, "Failed to install pkg from " +
9577 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009578 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009579 }
9580
9581 } finally {
9582 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9583 // Don't destroy container here. Wait till gc clears things up.
9584 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009585 }
9586 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009587 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009588 synchronized (mPackages) {
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009589 // Make sure group IDs have been assigned, and any permission
9590 // changes in other apps are accounted for
9591 updatePermissionsLP(null, null, true, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009592 // Persist settings
9593 mSettings.writeLP();
9594 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009595 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009596 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009597 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9598 }
9599 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009600 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009601 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009602 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009603 if (removeCids != null) {
9604 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009605 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009606 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009607 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009608 }
9609
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009610 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009611 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009612 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009613 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009614 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009615 Set<SdInstallArgs> keys = processCids.keySet();
9616 for (SdInstallArgs args : keys) {
9617 String cid = args.cid;
9618 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009619 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009620 // Delete package internally
9621 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9622 synchronized (mInstallLock) {
9623 boolean res = deletePackageLI(pkgName, false,
9624 PackageManager.DONT_DELETE_DATA, outInfo);
9625 if (res) {
9626 pkgList.add(pkgName);
9627 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009628 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009629 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009630 }
9631 }
9632 }
9633 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009634 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009635 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009636 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009637 // Force gc
9638 Runtime.getRuntime().gc();
9639 // Just unmount all valid containers.
9640 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009641 synchronized (mInstallLock) {
9642 args.doPostDeleteLI(false);
9643 }
9644 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009645 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009646
9647 public void movePackage(final String packageName,
9648 final IPackageMoveObserver observer, final int flags) {
9649 if (packageName == null) {
9650 return;
9651 }
9652 mContext.enforceCallingOrSelfPermission(
9653 android.Manifest.permission.MOVE_PACKAGE, null);
9654 int returnCode = PackageManager.MOVE_SUCCEEDED;
9655 int currFlags = 0;
9656 int newFlags = 0;
9657 synchronized (mPackages) {
9658 PackageParser.Package pkg = mPackages.get(packageName);
9659 if (pkg == null) {
9660 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9661 }
9662 // Disable moving fwd locked apps and system packages
9663 if (pkg.applicationInfo != null &&
9664 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009665 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009666 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9667 } else if (pkg.applicationInfo != null &&
9668 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009669 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009670 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9671 } else {
9672 // Find install location first
9673 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9674 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009675 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009676 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9677 } else {
9678 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9679 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009680 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009681 PackageManager.INSTALL_EXTERNAL : 0;
9682 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009683 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009684 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9685 }
9686 }
9687 }
9688 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9689 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9690 } else {
9691 Message msg = mHandler.obtainMessage(INIT_COPY);
9692 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9693 pkg.applicationInfo.publicSourceDir);
9694 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9695 packageName);
9696 msg.obj = mp;
9697 mHandler.sendMessage(msg);
9698 }
9699 }
9700 }
9701
9702 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9703 // Queue up an async operation since the package deletion may take a little while.
9704 mHandler.post(new Runnable() {
9705 public void run() {
9706 mHandler.removeCallbacks(this);
9707 int returnCode = currentStatus;
9708 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9709 if (moveSucceeded) {
9710 int uid = -1;
9711 synchronized (mPackages) {
9712 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9713 }
9714 ArrayList<String> pkgList = new ArrayList<String>();
9715 pkgList.add(mp.packageName);
9716 int uidArr[] = new int[] { uid };
9717 // Send resources unavailable broadcast
9718 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9719
9720 // Update package code and resource paths
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009721 synchronized (mInstallLock) {
9722 synchronized (mPackages) {
9723 PackageParser.Package pkg = mPackages.get(mp.packageName);
9724 if (pkg != null) {
9725 String oldCodePath = pkg.mPath;
9726 String newCodePath = mp.targetArgs.getCodePath();
9727 String newResPath = mp.targetArgs.getResourcePath();
9728 pkg.mPath = newCodePath;
9729 // Move dex files around
9730 if (moveDexFilesLI(pkg)
9731 != PackageManager.INSTALL_SUCCEEDED) {
9732 // Moving of dex files failed. Set
9733 // error code and abort move.
9734 pkg.mPath = pkg.mScanPath;
9735 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9736 moveSucceeded = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009737 } else {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009738 pkg.mScanPath = newCodePath;
9739 pkg.applicationInfo.sourceDir = newCodePath;
9740 pkg.applicationInfo.publicSourceDir = newResPath;
9741 PackageSetting ps = (PackageSetting) pkg.mExtras;
9742 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9743 ps.codePathString = ps.codePath.getPath();
9744 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9745 ps.resourcePathString = ps.resourcePath.getPath();
9746 // Set the application info flag correctly.
9747 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9748 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9749 } else {
9750 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9751 }
9752 ps.setFlags(pkg.applicationInfo.flags);
9753 mAppDirs.remove(oldCodePath);
9754 mAppDirs.put(newCodePath, pkg);
9755 // Persist settings
9756 mSettings.writeLP();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009757 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009758 }
9759 }
9760 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009761 // Send resources available broadcast
9762 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009763 }
9764 if (!moveSucceeded){
9765 // Clean up failed installation
9766 if (mp.targetArgs != null) {
9767 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009768 returnCode);
9769 }
9770 } else {
9771 // Force a gc to clear things up.
9772 Runtime.getRuntime().gc();
9773 // Delete older code
9774 synchronized (mInstallLock) {
9775 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009776 }
9777 }
9778 IPackageMoveObserver observer = mp.observer;
9779 if (observer != null) {
9780 try {
9781 observer.packageMoved(mp.packageName, returnCode);
9782 } catch (RemoteException e) {
9783 Log.i(TAG, "Observer no longer exists.");
9784 }
9785 }
9786 }
9787 });
9788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009789}