blob: 19667d4a1be677a77e43d72ef6e21b03f3f75afc [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;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
Jason parksa3cdaa52011-01-13 14:15:43 -060027import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
Jason parks1125d782011-01-12 09:47:26 -060035import android.content.Context;
Jason parksa3cdaa52011-01-13 14:15:43 -060036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Jason parks1125d782011-01-12 09:47:26 -060041import android.content.ServiceConnection;
Jason parksa3cdaa52011-01-13 14:15:43 -060042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060057import android.content.pm.PackageStats;
Jason parksa3cdaa52011-01-13 14:15:43 -060058import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
61import android.content.pm.PackageParser;
Jason parks1125d782011-01-12 09:47:26 -060062import android.content.pm.PermissionInfo;
Jason parksa3cdaa52011-01-13 14:15:43 -060063import android.content.pm.PermissionGroupInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
Jason parksa3cdaa52011-01-13 14:15:43 -060078import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Jason parksa3cdaa52011-01-13 14:15:43 -060088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
Jason parksa3cdaa52011-01-13 14:15:43 -060090import android.util.*;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.view.Display;
92import android.view.WindowManager;
93
Kenny Root9f306d72010-09-26 11:19:47 -070094import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.FileReader;
101import java.io.FilenameFilter;
102import java.io.IOException;
103import java.io.InputStream;
104import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800105import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
108import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700109import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Collections;
111import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800112import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.Enumeration;
114import java.util.HashMap;
115import java.util.HashSet;
116import java.util.Iterator;
Jason parksa3cdaa52011-01-13 14:15:43 -0600117import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.List;
119import java.util.Map;
120import java.util.Set;
121import java.util.zip.ZipEntry;
Jason parksa3cdaa52011-01-13 14:15:43 -0600122import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import java.util.zip.ZipFile;
124import java.util.zip.ZipOutputStream;
125
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700126/**
127 * Keep track of all those .apks everywhere.
128 *
129 * This is very central to the platform's security; please run the unit
130 * tests whenever making modifications here:
131 *
132mmm frameworks/base/tests/AndroidTests
133adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
134adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
135 *
136 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137class PackageManagerService extends IPackageManager.Stub {
138 private static final String TAG = "PackageManager";
139 private static final boolean DEBUG_SETTINGS = false;
140 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800141 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800142 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
145 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400146 private static final int LOG_UID = Process.LOG_UID;
Nick Pellycd0e8392010-10-13 17:25:24 -0700147 private static final int NFC_UID = Process.NFC_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private static final int FIRST_APPLICATION_UID =
149 Process.FIRST_APPLICATION_UID;
150 private static final int MAX_APPLICATION_UIDS = 1000;
151
152 private static final boolean SHOW_INFO = false;
153
154 private static final boolean GET_CERTIFICATES = true;
155
Oscar Montemayora8529f62009-11-18 10:14:20 -0800156 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private static final int REMOVE_EVENTS =
159 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
160 private static final int ADD_EVENTS =
161 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
162
163 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800164 // Suffix used during package installation when copying/moving
165 // package apks to install directory.
166 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800168 /**
169 * Indicates the state of installation. Used by PackageManager to
170 * figure out incomplete installations. Say a package is being installed
171 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
172 * the package installation is successful or unsuccesful lin which case
173 * the PackageManager will no longer maintain state information associated
174 * with the package. If some exception(like device freeze or battery being
175 * pulled out) occurs during installation of a package, the PackageManager
176 * needs this information to clean up the previously failed installation.
177 */
178 private static final int PKG_INSTALL_INCOMPLETE = 0;
179 private static final int PKG_INSTALL_COMPLETE = 1;
180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final int SCAN_MONITOR = 1<<0;
182 static final int SCAN_NO_DEX = 1<<1;
183 static final int SCAN_FORCE_DEX = 1<<2;
184 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800185 static final int SCAN_NEW_INSTALL = 1<<4;
186 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700187 static final int SCAN_UPDATE_TIME = 1<<6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700189 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700190
191 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
192
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800193 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700194 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800195 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700196
Kenny Root85387d72010-08-26 10:13:11 -0700197 private static final String LIB_DIR_NAME = "lib";
198
Kenny Rootc78a8072010-07-27 15:18:38 -0700199 static final String mTempContainerPrefix = "smdl2tmp";
200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
202 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700203 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Dianne Hackborn851a5412009-05-08 12:06:44 -0700205 final int mSdkVersion = Build.VERSION.SDK_INT;
206 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
207 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 final Context mContext;
210 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700211 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 final DisplayMetrics mMetrics;
213 final int mDefParseFlags;
214 final String[] mSeparateProcesses;
215
216 // This is where all application persistent data goes.
217 final File mAppDataDir;
218
Oscar Montemayora8529f62009-11-18 10:14:20 -0800219 // If Encrypted File System feature is enabled, all application persistent data
220 // should go here instead.
221 final File mSecureAppDataDir;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // This is the object monitoring the framework dir.
224 final FileObserver mFrameworkInstallObserver;
225
226 // This is the object monitoring the system app dir.
227 final FileObserver mSystemInstallObserver;
228
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700229 // This is the object monitoring the system app dir.
230 final FileObserver mVendorInstallObserver;
231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // This is the object monitoring mAppInstallDir.
233 final FileObserver mAppInstallObserver;
234
235 // This is the object monitoring mDrmAppPrivateInstallDir.
236 final FileObserver mDrmAppInstallObserver;
237
238 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
239 // LOCK HELD. Can be called with mInstallLock held.
240 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 final File mFrameworkDir;
243 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700244 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700246 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
249 // apps.
250 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // Lock for state used when installing and doing other long running
255 // operations. Methods that must be called with this lock held have
256 // the prefix "LI".
257 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 // These are the directories in the 3rd party applications installed dir
260 // that we have currently loaded packages from. Keys are the application's
261 // installed zip file (absolute codePath), and values are Package.
262 final HashMap<String, PackageParser.Package> mAppDirs =
263 new HashMap<String, PackageParser.Package>();
264
265 // Information for the parser to write more useful error messages.
266 File mScanningPath;
267 int mLastScanError;
268
269 final int[] mOutPermissions = new int[3];
270
271 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 // Keys are String (package name), values are Package. This also serves
274 // as the lock for the global state. Methods that must be called with
275 // this lock held have the prefix "LP".
276 final HashMap<String, PackageParser.Package> mPackages =
277 new HashMap<String, PackageParser.Package>();
278
279 final Settings mSettings;
280 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281
282 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
283 int[] mGlobalGids;
284
285 // These are the built-in uid -> permission mappings that were read from the
286 // etc/permissions.xml file.
287 final SparseArray<HashSet<String>> mSystemPermissions =
288 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 // These are the built-in shared libraries that were read from the
291 // etc/permissions.xml file.
292 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
Dianne Hackborn49237342009-08-27 20:08:01 -0700294 // Temporary for building the final shared libraries for an .apk.
295 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800296
Dianne Hackborn49237342009-08-27 20:08:01 -0700297 // These are the features this devices supports that were read from the
298 // etc/permissions.xml file.
299 final HashMap<String, FeatureInfo> mAvailableFeatures =
300 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 // All available activities, for your resolving pleasure.
303 final ActivityIntentResolver mActivities =
304 new ActivityIntentResolver();
305
306 // All available receivers, for your resolving pleasure.
307 final ActivityIntentResolver mReceivers =
308 new ActivityIntentResolver();
309
310 // All available services, for your resolving pleasure.
311 final ServiceIntentResolver mServices = new ServiceIntentResolver();
312
313 // Keys are String (provider class name), values are Provider.
314 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
315 new HashMap<ComponentName, PackageParser.Provider>();
316
317 // Mapping from provider base names (first directory in content URI codePath)
318 // to the provider information.
319 final HashMap<String, PackageParser.Provider> mProviders =
320 new HashMap<String, PackageParser.Provider>();
321
322 // Mapping from instrumentation class names to info about them.
323 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
324 new HashMap<ComponentName, PackageParser.Instrumentation>();
325
326 // Mapping from permission names to info about them.
327 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
328 new HashMap<String, PackageParser.PermissionGroup>();
329
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800330 // Packages whose data we have transfered into another package, thus
331 // should no longer exist.
332 final HashSet<String> mTransferedPackages = new HashSet<String>();
333
Dianne Hackborn854060af2009-07-09 18:14:31 -0700334 // Broadcast actions that are only available to the system.
335 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 boolean mSystemReady;
338 boolean mSafeMode;
339 boolean mHasSystemUidErrors;
340
341 ApplicationInfo mAndroidApplication;
342 final ActivityInfo mResolveActivity = new ActivityInfo();
343 final ResolveInfo mResolveInfo = new ResolveInfo();
344 ComponentName mResolveComponentName;
345 PackageParser.Package mPlatformPackage;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800348 final HashMap<String, ArrayList<String>> mPendingBroadcasts
349 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800350 // Service Connection to remote media container service to copy
351 // package uri's from external media onto secure containers
352 // or internal storage.
353 private IMediaContainerService mContainerService = null;
354
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700355 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800356 static final int MCS_BOUND = 3;
357 static final int END_COPY = 4;
358 static final int INIT_COPY = 5;
359 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800360 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800361 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800362 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800363 static final int MCS_RECONNECT = 10;
364 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700365 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700366 static final int WRITE_SETTINGS = 13;
367
368 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700370 // Delay time in millisecs
371 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372 final private DefaultContainerConnection mDefContainerConn =
373 new DefaultContainerConnection();
374 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800375 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800376 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800377 IMediaContainerService imcs =
378 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800379 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800380 }
381
382 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800383 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800384 }
385 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700386
Christopher Tate1bb69062010-02-19 17:02:12 -0800387 // Recordkeeping of restore-after-install operations that are currently in flight
388 // between the Package Manager and the Backup Manager
389 class PostInstallData {
390 public InstallArgs args;
391 public PackageInstalledInfo res;
392
393 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
394 args = _a;
395 res = _r;
396 }
397 };
398 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
399 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
400
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700401 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800403 final ArrayList<HandlerParams> mPendingInstalls =
404 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800405
406 private boolean connectToService() {
407 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
408 " DefaultContainerService");
409 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700410 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800411 if (mContext.bindService(service, mDefContainerConn,
412 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800414 mBound = true;
415 return true;
416 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700417 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800418 return false;
419 }
420
421 private void disconnectService() {
422 mContainerService = null;
423 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700424 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800425 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800427 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800428
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700429 PackageHandler(Looper looper) {
430 super(looper);
431 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700432
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700433 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700434 try {
435 doHandleMessage(msg);
436 } finally {
437 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
438 }
439 }
440
441 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700442 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800443 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800444 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800445 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800446 int idx = mPendingInstalls.size();
447 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
448 // If a bind was already initiated we dont really
449 // need to do anything. The pending install
450 // will be processed later on.
451 if (!mBound) {
452 // If this is the only one pending we might
453 // have to bind to the service again.
454 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800455 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800456 params.serviceError();
457 return;
458 } else {
459 // Once we bind to the service, the first
460 // pending request will be processed.
461 mPendingInstalls.add(idx, params);
462 }
463 } else {
464 mPendingInstalls.add(idx, params);
465 // Already bound to the service. Just make
466 // sure we trigger off processing the first request.
467 if (idx == 0) {
468 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800469 }
470 }
471 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800472 }
473 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800474 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800475 if (msg.obj != null) {
476 mContainerService = (IMediaContainerService) msg.obj;
477 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 if (mContainerService == null) {
479 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800480 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 for (HandlerParams params : mPendingInstalls) {
482 mPendingInstalls.remove(0);
483 // Indicate service bind error
484 params.serviceError();
485 }
486 mPendingInstalls.clear();
487 } else if (mPendingInstalls.size() > 0) {
488 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800489 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800490 params.startCopy();
491 }
492 } else {
493 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800494 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800495 }
496 break;
497 }
498 case MCS_RECONNECT : {
499 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
500 if (mPendingInstalls.size() > 0) {
501 if (mBound) {
502 disconnectService();
503 }
504 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800505 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800506 for (HandlerParams params : mPendingInstalls) {
507 mPendingInstalls.remove(0);
508 // Indicate service bind error
509 params.serviceError();
510 }
511 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800512 }
513 }
514 break;
515 }
516 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800517 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
518 // Delete pending install
519 if (mPendingInstalls.size() > 0) {
520 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800521 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800522 if (mPendingInstalls.size() == 0) {
523 if (mBound) {
524 disconnectService();
525 }
526 } else {
527 // There are more pending requests in queue.
528 // Just post MCS_BOUND message to trigger processing
529 // of next pending install.
530 mHandler.sendEmptyMessage(MCS_BOUND);
531 }
532 break;
533 }
534 case MCS_GIVE_UP: {
535 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
536 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800537 break;
538 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800540 String packages[];
541 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700543 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700544 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700545 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800546 if (mPendingBroadcasts == null) {
547 return;
548 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700549 size = mPendingBroadcasts.size();
550 if (size <= 0) {
551 // Nothing to be done. Just return
552 return;
553 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 packages = new String[size];
555 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700556 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800557 Iterator<HashMap.Entry<String, ArrayList<String>>>
558 it = mPendingBroadcasts.entrySet().iterator();
559 int i = 0;
560 while (it.hasNext() && i < size) {
561 HashMap.Entry<String, ArrayList<String>> ent = it.next();
562 packages[i] = ent.getKey();
563 components[i] = ent.getValue();
564 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700565 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800566 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700567 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800568 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700569 mPendingBroadcasts.clear();
570 }
571 // Send broadcasts
572 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800573 sendPackageChangedBroadcast(packages[i], true,
Jason parksa3cdaa52011-01-13 14:15:43 -0600574 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700575 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700577 break;
578 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800579 case START_CLEANING_PACKAGE: {
580 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700581 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800582 synchronized (mPackages) {
583 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
584 mSettings.mPackagesToBeCleaned.add(packageName);
585 }
586 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700587 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800588 startCleaningPackages();
589 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800590 case POST_INSTALL: {
591 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
592 PostInstallData data = mRunningInstalls.get(msg.arg1);
593 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700594 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800595
596 if (data != null) {
597 InstallArgs args = data.args;
598 PackageInstalledInfo res = data.res;
599
600 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700601 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800602 Bundle extras = new Bundle(1);
603 extras.putInt(Intent.EXTRA_UID, res.uid);
604 final boolean update = res.removedInfo.removedPackage != null;
605 if (update) {
606 extras.putBoolean(Intent.EXTRA_REPLACING, true);
607 }
608 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
609 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700610 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800611 if (update) {
612 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
613 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700614 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800615 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700616 if (res.removedInfo.args != null) {
617 // Remove the replaced package's older resources safely now
618 deleteOld = true;
619 }
620 }
621 // Force a gc to clear up things
622 Runtime.getRuntime().gc();
623 // We delete after a gc for applications on sdcard.
624 if (deleteOld) {
625 synchronized (mInstallLock) {
626 res.removedInfo.args.doPostDeleteLI(true);
627 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800628 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800629 if (args.observer != null) {
630 try {
631 args.observer.packageInstalled(res.name, res.returnCode);
632 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800633 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800634 }
635 }
636 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800637 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800638 }
639 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700640 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700641 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
642 boolean reportStatus = msg.arg1 == 1;
643 boolean doGc = msg.arg2 == 1;
644 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
645 if (doGc) {
646 // Force a gc to clear up stale containers.
647 Runtime.getRuntime().gc();
648 }
649 if (msg.obj != null) {
650 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
651 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
652 // Unload containers
653 unloadAllContainers(args);
654 }
655 if (reportStatus) {
656 try {
657 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
658 PackageHelper.getMountService().finishMediaUpdate();
659 } catch (RemoteException e) {
660 Log.e(TAG, "MountService not running?");
661 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700662 }
663 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700664 case WRITE_SETTINGS: {
665 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
666 synchronized (mPackages) {
667 removeMessages(WRITE_SETTINGS);
668 mSettings.writeLP();
669 }
670 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
671 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700672 }
673 }
674 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800675
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700676 void scheduleWriteSettingsLocked() {
677 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
678 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
679 }
680 }
681
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800682 static boolean installOnSd(int flags) {
683 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700684 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800685 return false;
686 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700687 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
688 return true;
689 }
690 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800691 }
692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 public static final IPackageManager main(Context context, boolean factoryTest) {
694 PackageManagerService m = new PackageManagerService(context, factoryTest);
695 ServiceManager.addService("package", m);
696 return m;
697 }
698
699 static String[] splitString(String str, char sep) {
700 int count = 1;
701 int i = 0;
702 while ((i=str.indexOf(sep, i)) >= 0) {
703 count++;
704 i++;
705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 String[] res = new String[count];
708 i=0;
709 count = 0;
710 int lastI=0;
711 while ((i=str.indexOf(sep, i)) >= 0) {
712 res[count] = str.substring(lastI, i);
713 count++;
714 i++;
715 lastI = i;
716 }
717 res[count] = str.substring(lastI, str.length());
718 return res;
719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800722 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800726 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 mContext = context;
730 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700731 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 mMetrics = new DisplayMetrics();
733 mSettings = new Settings();
734 mSettings.addSharedUserLP("android.uid.system",
735 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
736 mSettings.addSharedUserLP("android.uid.phone",
737 MULTIPLE_APPLICATION_UIDS
738 ? RADIO_UID : FIRST_APPLICATION_UID,
739 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400740 mSettings.addSharedUserLP("android.uid.log",
741 MULTIPLE_APPLICATION_UIDS
742 ? LOG_UID : FIRST_APPLICATION_UID,
743 ApplicationInfo.FLAG_SYSTEM);
Nick Pellycd0e8392010-10-13 17:25:24 -0700744 mSettings.addSharedUserLP("android.uid.nfc",
745 MULTIPLE_APPLICATION_UIDS
746 ? NFC_UID : FIRST_APPLICATION_UID,
747 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748
749 String separateProcesses = SystemProperties.get("debug.separate_processes");
750 if (separateProcesses != null && separateProcesses.length() > 0) {
751 if ("*".equals(separateProcesses)) {
752 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
753 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800754 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 } else {
756 mDefParseFlags = 0;
757 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800758 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 + separateProcesses);
760 }
761 } else {
762 mDefParseFlags = 0;
763 mSeparateProcesses = null;
764 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 Installer installer = new Installer();
767 // Little hacky thing to check if installd is here, to determine
768 // whether we are running on the simulator and thus need to take
769 // care of building the /data file structure ourself.
770 // (apparently the sim now has a working installer)
771 if (installer.ping() && Process.supportsProcesses()) {
772 mInstaller = installer;
773 } else {
774 mInstaller = null;
775 }
776
777 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
778 Display d = wm.getDefaultDisplay();
779 d.getMetrics(mMetrics);
780
781 synchronized (mInstallLock) {
782 synchronized (mPackages) {
783 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700784 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 File dataDir = Environment.getDataDirectory();
787 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800788 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
790
791 if (mInstaller == null) {
792 // Make sure these dirs exist, when we are running in
793 // the simulator.
794 // Make a wide-open directory for random misc stuff.
795 File miscDir = new File(dataDir, "misc");
796 miscDir.mkdirs();
797 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800798 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 mDrmAppPrivateInstallDir.mkdirs();
800 }
801
802 readPermissions();
803
804 mRestoredSettings = mSettings.readLP();
805 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806
807 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800809
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800810 // Set flag to monitor and not change apk file paths when
811 // scanning install directories.
812 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700813 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800814 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700821 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700824 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 /**
827 * Out of paranoia, ensure that everything in the boot class
828 * path has been dexed.
829 */
830 String bootClassPath = System.getProperty("java.boot.class.path");
831 if (bootClassPath != null) {
832 String[] paths = splitString(bootClassPath, ':');
833 for (int i=0; i<paths.length; i++) {
834 try {
835 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
836 libFiles.add(paths[i]);
837 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700838 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
840 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800841 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800843 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845 }
846 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800847 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 /**
851 * Also ensure all external libraries have had dexopt run on them.
852 */
853 if (mSharedLibraries.size() > 0) {
854 Iterator<String> libs = mSharedLibraries.values().iterator();
855 while (libs.hasNext()) {
856 String lib = libs.next();
857 try {
858 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
859 libFiles.add(lib);
860 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700861 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
863 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800864 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800866 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
868 }
869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 // Gross hack for now: we know this file doesn't contain any
872 // code, so don't dexopt it to avoid the resulting log spew.
873 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 /**
876 * And there are a number of commands implemented in Java, which
877 * we currently need to do the dexopt on so that they can be
878 * run from a non-root shell.
879 */
880 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700881 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 for (int i=0; i<frameworkFiles.length; i++) {
883 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
884 String path = libPath.getPath();
885 // Skip the file if we alrady did it.
886 if (libFiles.contains(path)) {
887 continue;
888 }
889 // Skip the file if it is not a type we want to dexopt.
890 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
891 continue;
892 }
893 try {
894 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
895 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700896 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 }
898 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800899 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800901 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
903 }
904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800905
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700906 if (didDexOpt) {
907 // If we had to do a dexopt of one of the previous
908 // things, then something on the system has changed.
909 // Consider this significant, and wipe away all other
910 // existing dexopt files to ensure we don't leave any
911 // dangling around.
912 String[] files = mDalvikCacheDir.list();
913 if (files != null) {
914 for (int i=0; i<files.length; i++) {
915 String fn = files[i];
916 if (fn.startsWith("data@app@")
917 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800918 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700919 (new File(mDalvikCacheDir, fn)).delete();
920 }
921 }
922 }
923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800925
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800926 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 mFrameworkInstallObserver = new AppDirObserver(
928 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
929 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700930 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
931 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700932 scanMode | SCAN_NO_DEX, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800933
934 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
936 mSystemInstallObserver = new AppDirObserver(
937 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
938 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700939 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700940 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800941
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700942 // Collect all vendor packages.
943 mVendorAppDir = new File("/vendor/app");
944 mVendorInstallObserver = new AppDirObserver(
945 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
946 mVendorInstallObserver.startWatching();
947 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700948 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700949
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800950 if (mInstaller != null) {
951 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
952 mInstaller.moveFiles();
953 }
954
955 // Prune any system packages that no longer exist.
956 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
957 while (psit.hasNext()) {
958 PackageSetting ps = psit.next();
959 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800960 && !mPackages.containsKey(ps.name)
961 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800962 psit.remove();
963 String msg = "System package " + ps.name
964 + " no longer exists; wiping its data";
965 reportSettingsProblem(Log.WARN, msg);
966 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -0600967 // XXX how to set useEncryptedFSDir for packages that
968 // are not encrypted?
969 mInstaller.remove(ps.name, true);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800970 }
971 }
972 }
973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 mAppInstallDir = new File(dataDir, "app");
975 if (mInstaller == null) {
976 // Make sure these dirs exist, when we are running in
977 // the simulator.
978 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
979 }
980 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800981 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 //clean up list
983 for(int i = 0; i < deletePkgsList.size(); i++) {
984 //clean up here
985 cleanupInstallFailedPackage(deletePkgsList.get(i));
986 }
987 //delete tmp files
988 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800989
990 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 SystemClock.uptimeMillis());
992 mAppInstallObserver = new AppDirObserver(
993 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
994 mAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700995 scanDirLI(mAppInstallDir, 0, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996
997 mDrmAppInstallObserver = new AppDirObserver(
998 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
999 mDrmAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001000 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1001 scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001003 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001005 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1007 + " seconds");
1008
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001009 // If the platform SDK has changed since the last time we booted,
1010 // we need to re-grant app permission to catch any new ones that
1011 // appear. This is really a hack, and means that apps can in some
1012 // cases get permissions that the user didn't initially explicitly
1013 // allow... it would be nice to have some better way to handle
1014 // this situation.
1015 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1016 != mSdkVersion;
1017 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1018 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1019 + "; regranting permissions for internal storage");
1020 mSettings.mInternalSdkPlatform = mSdkVersion;
1021
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001022 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023
1024 mSettings.writeLP();
1025
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001026 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 // Now after opening every single application zip, make sure they
1030 // are all flushed. Not really needed, but keeps things nice and
1031 // tidy.
1032 Runtime.getRuntime().gc();
1033 } // synchronized (mPackages)
1034 } // synchronized (mInstallLock)
1035 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 @Override
1038 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1039 throws RemoteException {
1040 try {
1041 return super.onTransact(code, data, reply, flags);
1042 } catch (RuntimeException e) {
1043 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001044 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046 throw e;
1047 }
1048 }
1049
Dianne Hackborne6620b22010-01-22 14:46:21 -08001050 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 if (mInstaller != null) {
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08001053 boolean useSecureFS = false;
Jason parksa3cdaa52011-01-13 14:15:43 -06001054 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001056 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001057 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
1059 } else {
1060 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001061 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 File dataDir = new File(pkg.applicationInfo.dataDir);
1063 dataDir.delete();
1064 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001065 if (ps.codePath != null) {
1066 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001067 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001068 }
1069 }
1070 if (ps.resourcePath != null) {
1071 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001072 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001073 }
1074 }
1075 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
1077
1078 void readPermissions() {
1079 // Read permissions from .../etc/permission directory.
1080 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1081 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001082 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 return;
1084 }
1085 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001086 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 return;
1088 }
1089
1090 // Iterate over the files in the directory and scan .xml files
1091 for (File f : libraryDir.listFiles()) {
1092 // We'll read platform.xml last
1093 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1094 continue;
1095 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001098 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 continue;
1100 }
1101 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001102 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 continue;
1104 }
1105
1106 readPermissionsFromXml(f);
1107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1110 final File permFile = new File(Environment.getRootDirectory(),
1111 "etc/permissions/platform.xml");
1112 readPermissionsFromXml(permFile);
1113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
1115 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 FileReader permReader = null;
1117 try {
1118 permReader = new FileReader(permFile);
1119 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001120 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 return;
1122 }
1123
1124 try {
1125 XmlPullParser parser = Xml.newPullParser();
1126 parser.setInput(permReader);
1127
1128 XmlUtils.beginDocument(parser, "permissions");
1129
1130 while (true) {
1131 XmlUtils.nextElement(parser);
1132 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1133 break;
1134 }
1135
1136 String name = parser.getName();
1137 if ("group".equals(name)) {
1138 String gidStr = parser.getAttributeValue(null, "gid");
1139 if (gidStr != null) {
1140 int gid = Integer.parseInt(gidStr);
1141 mGlobalGids = appendInt(mGlobalGids, gid);
1142 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + parser.getPositionDescription());
1145 }
1146
1147 XmlUtils.skipCurrentTag(parser);
1148 continue;
1149 } else if ("permission".equals(name)) {
1150 String perm = parser.getAttributeValue(null, "name");
1151 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 + parser.getPositionDescription());
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157 perm = perm.intern();
1158 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 } else if ("assign-permission".equals(name)) {
1161 String perm = parser.getAttributeValue(null, "name");
1162 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001163 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 + parser.getPositionDescription());
1165 XmlUtils.skipCurrentTag(parser);
1166 continue;
1167 }
1168 String uidStr = parser.getAttributeValue(null, "uid");
1169 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001170 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 + parser.getPositionDescription());
1172 XmlUtils.skipCurrentTag(parser);
1173 continue;
1174 }
1175 int uid = Process.getUidForName(uidStr);
1176 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 + uidStr + "\" at "
1179 + parser.getPositionDescription());
1180 XmlUtils.skipCurrentTag(parser);
1181 continue;
1182 }
1183 perm = perm.intern();
1184 HashSet<String> perms = mSystemPermissions.get(uid);
1185 if (perms == null) {
1186 perms = new HashSet<String>();
1187 mSystemPermissions.put(uid, perms);
1188 }
1189 perms.add(perm);
1190 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 } else if ("library".equals(name)) {
1193 String lname = parser.getAttributeValue(null, "name");
1194 String lfile = parser.getAttributeValue(null, "file");
1195 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001196 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 + parser.getPositionDescription());
1198 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 + parser.getPositionDescription());
1201 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001202 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 mSharedLibraries.put(lname, lfile);
1204 }
1205 XmlUtils.skipCurrentTag(parser);
1206 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001207
Dianne Hackborn49237342009-08-27 20:08:01 -07001208 } else if ("feature".equals(name)) {
1209 String fname = parser.getAttributeValue(null, "name");
1210 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001211 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001212 + parser.getPositionDescription());
1213 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001214 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 FeatureInfo fi = new FeatureInfo();
1216 fi.name = fname;
1217 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219 XmlUtils.skipCurrentTag(parser);
1220 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } else {
1223 XmlUtils.skipCurrentTag(parser);
1224 continue;
1225 }
1226
1227 }
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001228 permReader.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001230 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001232 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
1234 }
1235
1236 void readPermission(XmlPullParser parser, String name)
1237 throws IOException, XmlPullParserException {
1238
1239 name = name.intern();
1240
1241 BasePermission bp = mSettings.mPermissions.get(name);
1242 if (bp == null) {
1243 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1244 mSettings.mPermissions.put(name, bp);
1245 }
1246 int outerDepth = parser.getDepth();
1247 int type;
1248 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1249 && (type != XmlPullParser.END_TAG
1250 || parser.getDepth() > outerDepth)) {
1251 if (type == XmlPullParser.END_TAG
1252 || type == XmlPullParser.TEXT) {
1253 continue;
1254 }
1255
1256 String tagName = parser.getName();
1257 if ("group".equals(tagName)) {
1258 String gidStr = parser.getAttributeValue(null, "gid");
1259 if (gidStr != null) {
1260 int gid = Process.getGidForName(gidStr);
1261 bp.gids = appendInt(bp.gids, gid);
1262 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001263 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 + parser.getPositionDescription());
1265 }
1266 }
1267 XmlUtils.skipCurrentTag(parser);
1268 }
1269 }
1270
1271 static int[] appendInt(int[] cur, int val) {
1272 if (cur == null) {
1273 return new int[] { val };
1274 }
1275 final int N = cur.length;
1276 for (int i=0; i<N; i++) {
1277 if (cur[i] == val) {
1278 return cur;
1279 }
1280 }
1281 int[] ret = new int[N+1];
1282 System.arraycopy(cur, 0, ret, 0, N);
1283 ret[N] = val;
1284 return ret;
1285 }
1286
1287 static int[] appendInts(int[] cur, int[] add) {
1288 if (add == null) return cur;
1289 if (cur == null) return add;
1290 final int N = add.length;
1291 for (int i=0; i<N; i++) {
1292 cur = appendInt(cur, add[i]);
1293 }
1294 return cur;
1295 }
1296
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001297 static int[] removeInt(int[] cur, int val) {
1298 if (cur == null) {
1299 return null;
1300 }
1301 final int N = cur.length;
1302 for (int i=0; i<N; i++) {
1303 if (cur[i] == val) {
1304 int[] ret = new int[N-1];
1305 if (i > 0) {
1306 System.arraycopy(cur, 0, ret, 0, i);
1307 }
1308 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001309 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001310 }
1311 return ret;
1312 }
1313 }
1314 return cur;
1315 }
1316
1317 static int[] removeInts(int[] cur, int[] rem) {
1318 if (rem == null) return cur;
1319 if (cur == null) return cur;
1320 final int N = rem.length;
1321 for (int i=0; i<N; i++) {
1322 cur = removeInt(cur, rem[i]);
1323 }
1324 return cur;
1325 }
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001328 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1329 // The package has been uninstalled but has retained data and resources.
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001330 return PackageParser.generatePackageInfo(p, null, flags, 0, 0);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 final PackageSetting ps = (PackageSetting)p.mExtras;
1333 if (ps == null) {
1334 return null;
1335 }
1336 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001337 return PackageParser.generatePackageInfo(p, gp.gids, flags,
1338 ps.firstInstallTime, ps.lastUpdateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340
1341 public PackageInfo getPackageInfo(String packageName, int flags) {
1342 synchronized (mPackages) {
1343 PackageParser.Package p = mPackages.get(packageName);
1344 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001345 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 + ": " + p);
1347 if (p != null) {
1348 return generatePackageInfo(p, flags);
1349 }
1350 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1351 return generatePackageInfoFromSettingsLP(packageName, flags);
1352 }
1353 }
1354 return null;
1355 }
1356
Dianne Hackborn47096932010-02-11 15:57:09 -08001357 public String[] currentToCanonicalPackageNames(String[] names) {
1358 String[] out = new String[names.length];
1359 synchronized (mPackages) {
1360 for (int i=names.length-1; i>=0; i--) {
1361 PackageSetting ps = mSettings.mPackages.get(names[i]);
1362 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1363 }
1364 }
1365 return out;
1366 }
1367
1368 public String[] canonicalToCurrentPackageNames(String[] names) {
1369 String[] out = new String[names.length];
1370 synchronized (mPackages) {
1371 for (int i=names.length-1; i>=0; i--) {
1372 String cur = mSettings.mRenamedPackages.get(names[i]);
1373 out[i] = cur != null ? cur : names[i];
1374 }
1375 }
1376 return out;
1377 }
1378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 public int getPackageUid(String packageName) {
1380 synchronized (mPackages) {
1381 PackageParser.Package p = mPackages.get(packageName);
1382 if(p != null) {
1383 return p.applicationInfo.uid;
1384 }
1385 PackageSetting ps = mSettings.mPackages.get(packageName);
1386 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1387 return -1;
1388 }
1389 p = ps.pkg;
1390 return p != null ? p.applicationInfo.uid : -1;
1391 }
1392 }
1393
1394 public int[] getPackageGids(String packageName) {
1395 synchronized (mPackages) {
1396 PackageParser.Package p = mPackages.get(packageName);
1397 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001398 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 + ": " + p);
1400 if (p != null) {
1401 final PackageSetting ps = (PackageSetting)p.mExtras;
1402 final SharedUserSetting suid = ps.sharedUser;
1403 return suid != null ? suid.gids : ps.gids;
1404 }
1405 }
1406 // stupid thing to indicate an error.
1407 return new int[0];
1408 }
1409
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001410 static final PermissionInfo generatePermissionInfo(
1411 BasePermission bp, int flags) {
1412 if (bp.perm != null) {
1413 return PackageParser.generatePermissionInfo(bp.perm, flags);
1414 }
1415 PermissionInfo pi = new PermissionInfo();
1416 pi.name = bp.name;
1417 pi.packageName = bp.sourcePackage;
1418 pi.nonLocalizedLabel = bp.name;
1419 pi.protectionLevel = bp.protectionLevel;
1420 return pi;
1421 }
1422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 public PermissionInfo getPermissionInfo(String name, int flags) {
1424 synchronized (mPackages) {
1425 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001426 if (p != null) {
1427 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 return null;
1430 }
1431 }
1432
1433 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1434 synchronized (mPackages) {
1435 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1436 for (BasePermission p : mSettings.mPermissions.values()) {
1437 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001438 if (p.perm == null || p.perm.info.group == null) {
1439 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001442 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1444 }
1445 }
1446 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 if (out.size() > 0) {
1449 return out;
1450 }
1451 return mPermissionGroups.containsKey(group) ? out : null;
1452 }
1453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1456 synchronized (mPackages) {
1457 return PackageParser.generatePermissionGroupInfo(
1458 mPermissionGroups.get(name), flags);
1459 }
1460 }
1461
1462 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1463 synchronized (mPackages) {
1464 final int N = mPermissionGroups.size();
1465 ArrayList<PermissionGroupInfo> out
1466 = new ArrayList<PermissionGroupInfo>(N);
1467 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1468 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1469 }
1470 return out;
1471 }
1472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1475 PackageSetting ps = mSettings.mPackages.get(packageName);
1476 if(ps != null) {
1477 if(ps.pkg == null) {
1478 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1479 if(pInfo != null) {
1480 return pInfo.applicationInfo;
1481 }
1482 return null;
1483 }
1484 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1485 }
1486 return null;
1487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1490 PackageSetting ps = mSettings.mPackages.get(packageName);
1491 if(ps != null) {
1492 if(ps.pkg == null) {
1493 ps.pkg = new PackageParser.Package(packageName);
1494 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001495 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1496 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1497 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1498 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001499 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001500 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502 return generatePackageInfo(ps.pkg, flags);
1503 }
1504 return null;
1505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1508 synchronized (mPackages) {
1509 PackageParser.Package p = mPackages.get(packageName);
1510 if (Config.LOGV) Log.v(
1511 TAG, "getApplicationInfo " + packageName
1512 + ": " + p);
1513 if (p != null) {
1514 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001515 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517 if ("android".equals(packageName)||"system".equals(packageName)) {
1518 return mAndroidApplication;
1519 }
1520 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1521 return generateApplicationInfoFromSettingsLP(packageName, flags);
1522 }
1523 }
1524 return null;
1525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001526
1527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1529 mContext.enforceCallingOrSelfPermission(
1530 android.Manifest.permission.CLEAR_APP_CACHE, null);
1531 // Queue up an async operation since clearing cache may take a little while.
1532 mHandler.post(new Runnable() {
1533 public void run() {
1534 mHandler.removeCallbacks(this);
1535 int retCode = -1;
1536 if (mInstaller != null) {
1537 retCode = mInstaller.freeCache(freeStorageSize);
1538 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001539 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541 } //end if mInstaller
1542 if (observer != null) {
1543 try {
1544 observer.onRemoveCompleted(null, (retCode >= 0));
1545 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001546 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
1549 }
1550 });
1551 }
1552
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001553 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001554 mContext.enforceCallingOrSelfPermission(
1555 android.Manifest.permission.CLEAR_APP_CACHE, null);
1556 // Queue up an async operation since clearing cache may take a little while.
1557 mHandler.post(new Runnable() {
1558 public void run() {
1559 mHandler.removeCallbacks(this);
1560 int retCode = -1;
1561 if (mInstaller != null) {
1562 retCode = mInstaller.freeCache(freeStorageSize);
1563 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001564 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001565 }
1566 }
1567 if(pi != null) {
1568 try {
1569 // Callback via pending intent
1570 int code = (retCode >= 0) ? 1 : 0;
1571 pi.sendIntent(null, code, null,
1572 null, null);
1573 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001574 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001575 }
1576 }
1577 }
1578 });
1579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1582 synchronized (mPackages) {
1583 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001584
1585 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001587 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 }
1589 if (mResolveComponentName.equals(component)) {
1590 return mResolveActivity;
1591 }
1592 }
1593 return null;
1594 }
1595
1596 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1597 synchronized (mPackages) {
1598 PackageParser.Activity a = mReceivers.mActivities.get(component);
1599 if (Config.LOGV) Log.v(
1600 TAG, "getReceiverInfo " + component + ": " + a);
1601 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1602 return PackageParser.generateActivityInfo(a, flags);
1603 }
1604 }
1605 return null;
1606 }
1607
1608 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1609 synchronized (mPackages) {
1610 PackageParser.Service s = mServices.mServices.get(component);
1611 if (Config.LOGV) Log.v(
1612 TAG, "getServiceInfo " + component + ": " + s);
1613 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1614 return PackageParser.generateServiceInfo(s, flags);
1615 }
1616 }
1617 return null;
1618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001619
Dianne Hackborn361199b2010-08-30 17:42:07 -07001620 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1621 synchronized (mPackages) {
1622 PackageParser.Provider p = mProvidersByComponent.get(component);
1623 if (Config.LOGV) Log.v(
1624 TAG, "getProviderInfo " + component + ": " + p);
1625 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1626 return PackageParser.generateProviderInfo(p, flags);
1627 }
1628 }
1629 return null;
1630 }
1631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 public String[] getSystemSharedLibraryNames() {
1633 Set<String> libSet;
1634 synchronized (mPackages) {
1635 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001636 int size = libSet.size();
1637 if (size > 0) {
1638 String[] libs = new String[size];
1639 libSet.toArray(libs);
1640 return libs;
1641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001643 return null;
1644 }
1645
1646 public FeatureInfo[] getSystemAvailableFeatures() {
1647 Collection<FeatureInfo> featSet;
1648 synchronized (mPackages) {
1649 featSet = mAvailableFeatures.values();
1650 int size = featSet.size();
1651 if (size > 0) {
1652 FeatureInfo[] features = new FeatureInfo[size+1];
1653 featSet.toArray(features);
1654 FeatureInfo fi = new FeatureInfo();
1655 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1656 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1657 features[size] = fi;
1658 return features;
1659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 return null;
1662 }
1663
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001664 public boolean hasSystemFeature(String name) {
1665 synchronized (mPackages) {
1666 return mAvailableFeatures.containsKey(name);
1667 }
1668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 public int checkPermission(String permName, String pkgName) {
1671 synchronized (mPackages) {
1672 PackageParser.Package p = mPackages.get(pkgName);
1673 if (p != null && p.mExtras != null) {
1674 PackageSetting ps = (PackageSetting)p.mExtras;
1675 if (ps.sharedUser != null) {
1676 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1677 return PackageManager.PERMISSION_GRANTED;
1678 }
1679 } else if (ps.grantedPermissions.contains(permName)) {
1680 return PackageManager.PERMISSION_GRANTED;
1681 }
1682 }
1683 }
1684 return PackageManager.PERMISSION_DENIED;
1685 }
1686
1687 public int checkUidPermission(String permName, int uid) {
1688 synchronized (mPackages) {
1689 Object obj = mSettings.getUserIdLP(uid);
1690 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001691 GrantedPermissions gp = (GrantedPermissions)obj;
1692 if (gp.grantedPermissions.contains(permName)) {
1693 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695 } else {
1696 HashSet<String> perms = mSystemPermissions.get(uid);
1697 if (perms != null && perms.contains(permName)) {
1698 return PackageManager.PERMISSION_GRANTED;
1699 }
1700 }
1701 }
1702 return PackageManager.PERMISSION_DENIED;
1703 }
1704
1705 private BasePermission findPermissionTreeLP(String permName) {
1706 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1707 if (permName.startsWith(bp.name) &&
1708 permName.length() > bp.name.length() &&
1709 permName.charAt(bp.name.length()) == '.') {
1710 return bp;
1711 }
1712 }
1713 return null;
1714 }
1715
1716 private BasePermission checkPermissionTreeLP(String permName) {
1717 if (permName != null) {
1718 BasePermission bp = findPermissionTreeLP(permName);
1719 if (bp != null) {
1720 if (bp.uid == Binder.getCallingUid()) {
1721 return bp;
1722 }
1723 throw new SecurityException("Calling uid "
1724 + Binder.getCallingUid()
1725 + " is not allowed to add to permission tree "
1726 + bp.name + " owned by uid " + bp.uid);
1727 }
1728 }
1729 throw new SecurityException("No permission tree found for " + permName);
1730 }
1731
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001732 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1733 if (s1 == null) {
1734 return s2 == null;
1735 }
1736 if (s2 == null) {
1737 return false;
1738 }
1739 if (s1.getClass() != s2.getClass()) {
1740 return false;
1741 }
1742 return s1.equals(s2);
1743 }
1744
1745 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1746 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001747 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001748 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1749 if (!compareStrings(pi1.name, pi2.name)) return false;
1750 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1751 // We'll take care of setting this one.
1752 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1753 // These are not currently stored in settings.
1754 //if (!compareStrings(pi1.group, pi2.group)) return false;
1755 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1756 //if (pi1.labelRes != pi2.labelRes) return false;
1757 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1758 return true;
1759 }
1760
1761 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1762 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1763 throw new SecurityException("Label must be specified in permission");
1764 }
1765 BasePermission tree = checkPermissionTreeLP(info.name);
1766 BasePermission bp = mSettings.mPermissions.get(info.name);
1767 boolean added = bp == null;
1768 boolean changed = true;
1769 if (added) {
1770 bp = new BasePermission(info.name, tree.sourcePackage,
1771 BasePermission.TYPE_DYNAMIC);
1772 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1773 throw new SecurityException(
1774 "Not allowed to modify non-dynamic permission "
1775 + info.name);
1776 } else {
1777 if (bp.protectionLevel == info.protectionLevel
1778 && bp.perm.owner.equals(tree.perm.owner)
1779 && bp.uid == tree.uid
1780 && comparePermissionInfos(bp.perm.info, info)) {
1781 changed = false;
1782 }
1783 }
1784 bp.protectionLevel = info.protectionLevel;
1785 bp.perm = new PackageParser.Permission(tree.perm.owner,
1786 new PermissionInfo(info));
1787 bp.perm.info.packageName = tree.perm.info.packageName;
1788 bp.uid = tree.uid;
1789 if (added) {
1790 mSettings.mPermissions.put(info.name, bp);
1791 }
1792 if (changed) {
1793 if (!async) {
1794 mSettings.writeLP();
1795 } else {
1796 scheduleWriteSettingsLocked();
1797 }
1798 }
1799 return added;
1800 }
1801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 public boolean addPermission(PermissionInfo info) {
1803 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001804 return addPermissionLocked(info, false);
1805 }
1806 }
1807
1808 public boolean addPermissionAsync(PermissionInfo info) {
1809 synchronized (mPackages) {
1810 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
1812 }
1813
1814 public void removePermission(String name) {
1815 synchronized (mPackages) {
1816 checkPermissionTreeLP(name);
1817 BasePermission bp = mSettings.mPermissions.get(name);
1818 if (bp != null) {
1819 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1820 throw new SecurityException(
1821 "Not allowed to modify non-dynamic permission "
1822 + name);
1823 }
1824 mSettings.mPermissions.remove(name);
1825 mSettings.writeLP();
1826 }
1827 }
1828 }
1829
Dianne Hackborn854060af2009-07-09 18:14:31 -07001830 public boolean isProtectedBroadcast(String actionName) {
1831 synchronized (mPackages) {
1832 return mProtectedBroadcasts.contains(actionName);
1833 }
1834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 public int checkSignatures(String pkg1, String pkg2) {
1837 synchronized (mPackages) {
1838 PackageParser.Package p1 = mPackages.get(pkg1);
1839 PackageParser.Package p2 = mPackages.get(pkg2);
1840 if (p1 == null || p1.mExtras == null
1841 || p2 == null || p2.mExtras == null) {
1842 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1843 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001844 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846 }
1847
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001848 public int checkUidSignatures(int uid1, int uid2) {
1849 synchronized (mPackages) {
1850 Signature[] s1;
1851 Signature[] s2;
1852 Object obj = mSettings.getUserIdLP(uid1);
1853 if (obj != null) {
1854 if (obj instanceof SharedUserSetting) {
1855 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1856 } else if (obj instanceof PackageSetting) {
1857 s1 = ((PackageSetting)obj).signatures.mSignatures;
1858 } else {
1859 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1860 }
1861 } else {
1862 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1863 }
1864 obj = mSettings.getUserIdLP(uid2);
1865 if (obj != null) {
1866 if (obj instanceof SharedUserSetting) {
1867 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1868 } else if (obj instanceof PackageSetting) {
1869 s2 = ((PackageSetting)obj).signatures.mSignatures;
1870 } else {
1871 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1872 }
1873 } else {
1874 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1875 }
1876 return checkSignaturesLP(s1, s2);
1877 }
1878 }
1879
1880 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1881 if (s1 == null) {
1882 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1884 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1885 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001886 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1888 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001889 HashSet<Signature> set1 = new HashSet<Signature>();
1890 for (Signature sig : s1) {
1891 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001893 HashSet<Signature> set2 = new HashSet<Signature>();
1894 for (Signature sig : s2) {
1895 set2.add(sig);
1896 }
1897 // Make sure s2 contains all signatures in s1.
1898 if (set1.equals(set2)) {
1899 return PackageManager.SIGNATURE_MATCH;
1900 }
1901 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
1904 public String[] getPackagesForUid(int uid) {
1905 synchronized (mPackages) {
1906 Object obj = mSettings.getUserIdLP(uid);
1907 if (obj instanceof SharedUserSetting) {
1908 SharedUserSetting sus = (SharedUserSetting)obj;
1909 final int N = sus.packages.size();
1910 String[] res = new String[N];
1911 Iterator<PackageSetting> it = sus.packages.iterator();
1912 int i=0;
1913 while (it.hasNext()) {
1914 res[i++] = it.next().name;
1915 }
1916 return res;
1917 } else if (obj instanceof PackageSetting) {
1918 PackageSetting ps = (PackageSetting)obj;
1919 return new String[] { ps.name };
1920 }
1921 }
1922 return null;
1923 }
1924
1925 public String getNameForUid(int uid) {
1926 synchronized (mPackages) {
1927 Object obj = mSettings.getUserIdLP(uid);
1928 if (obj instanceof SharedUserSetting) {
1929 SharedUserSetting sus = (SharedUserSetting)obj;
1930 return sus.name + ":" + sus.userId;
1931 } else if (obj instanceof PackageSetting) {
1932 PackageSetting ps = (PackageSetting)obj;
1933 return ps.name;
1934 }
1935 }
1936 return null;
1937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 public int getUidForSharedUser(String sharedUserName) {
1940 if(sharedUserName == null) {
1941 return -1;
1942 }
1943 synchronized (mPackages) {
1944 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1945 if(suid == null) {
1946 return -1;
1947 }
1948 return suid.userId;
1949 }
1950 }
1951
1952 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1953 int flags) {
1954 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001955 return chooseBestActivity(intent, resolvedType, flags, query);
1956 }
1957
Mihai Predaeae850c2009-05-13 10:13:48 +02001958 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1959 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 if (query != null) {
1961 final int N = query.size();
1962 if (N == 1) {
1963 return query.get(0);
1964 } else if (N > 1) {
1965 // If there is more than one activity with the same priority,
1966 // then let the user decide between them.
1967 ResolveInfo r0 = query.get(0);
1968 ResolveInfo r1 = query.get(1);
1969 if (false) {
1970 System.out.println(r0.activityInfo.name +
1971 "=" + r0.priority + " vs " +
1972 r1.activityInfo.name +
1973 "=" + r1.priority);
1974 }
1975 // If the first activity has a higher priority, or a different
1976 // default, then it is always desireable to pick it.
1977 if (r0.priority != r1.priority
1978 || r0.preferredOrder != r1.preferredOrder
1979 || r0.isDefault != r1.isDefault) {
1980 return query.get(0);
1981 }
1982 // If we have saved a preference for a preferred activity for
1983 // this Intent, use that.
1984 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1985 flags, query, r0.priority);
1986 if (ri != null) {
1987 return ri;
1988 }
1989 return mResolveInfo;
1990 }
1991 }
1992 return null;
1993 }
1994
1995 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1996 int flags, List<ResolveInfo> query, int priority) {
1997 synchronized (mPackages) {
1998 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1999 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02002000 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2002 if (prefs != null && prefs.size() > 0) {
2003 // First figure out how good the original match set is.
2004 // We will only allow preferred activities that came
2005 // from the same match quality.
2006 int match = 0;
2007 final int N = query.size();
2008 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2009 for (int j=0; j<N; j++) {
2010 ResolveInfo ri = query.get(j);
2011 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2012 + ": 0x" + Integer.toHexString(match));
2013 if (ri.match > match) match = ri.match;
2014 }
2015 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2016 + Integer.toHexString(match));
2017 match &= IntentFilter.MATCH_CATEGORY_MASK;
2018 final int M = prefs.size();
2019 for (int i=0; i<M; i++) {
2020 PreferredActivity pa = prefs.get(i);
2021 if (pa.mMatch != match) {
2022 continue;
2023 }
2024 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2025 if (DEBUG_PREFERRED) {
2026 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002027 if (ai != null) {
2028 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2029 } else {
2030 Log.v(TAG, " null");
2031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033 if (ai != null) {
2034 for (int j=0; j<N; j++) {
2035 ResolveInfo ri = query.get(j);
2036 if (!ri.activityInfo.applicationInfo.packageName
2037 .equals(ai.applicationInfo.packageName)) {
2038 continue;
2039 }
2040 if (!ri.activityInfo.name.equals(ai.name)) {
2041 continue;
2042 }
2043
2044 // Okay we found a previously set preferred app.
2045 // If the result set is different from when this
2046 // was created, we need to clear it and re-ask the
2047 // user their preference.
2048 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002049 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 + intent + " type " + resolvedType);
2051 mSettings.mPreferredActivities.removeFilter(pa);
2052 return null;
2053 }
2054
2055 // Yay!
2056 return ri;
2057 }
2058 }
2059 }
2060 }
2061 }
2062 return null;
2063 }
2064
2065 public List<ResolveInfo> queryIntentActivities(Intent intent,
2066 String resolvedType, int flags) {
2067 ComponentName comp = intent.getComponent();
2068 if (comp != null) {
2069 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2070 ActivityInfo ai = getActivityInfo(comp, flags);
2071 if (ai != null) {
2072 ResolveInfo ri = new ResolveInfo();
2073 ri.activityInfo = ai;
2074 list.add(ri);
2075 }
2076 return list;
2077 }
2078
2079 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002080 String pkgName = intent.getPackage();
2081 if (pkgName == null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002082 return (List<ResolveInfo>)mActivities.queryIntent(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002083 resolvedType, flags);
2084 }
2085 PackageParser.Package pkg = mPackages.get(pkgName);
2086 if (pkg != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002087 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002088 resolvedType, flags, pkg.activities);
2089 }
2090 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
2093
2094 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2095 Intent[] specifics, String[] specificTypes, Intent intent,
2096 String resolvedType, int flags) {
2097 final String resultsAction = intent.getAction();
2098
2099 List<ResolveInfo> results = queryIntentActivities(
2100 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2101 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2102
2103 int specificsPos = 0;
2104 int N;
2105
2106 // todo: note that the algorithm used here is O(N^2). This
2107 // isn't a problem in our current environment, but if we start running
2108 // into situations where we have more than 5 or 10 matches then this
2109 // should probably be changed to something smarter...
2110
2111 // First we go through and resolve each of the specific items
2112 // that were supplied, taking care of removing any corresponding
2113 // duplicate items in the generic resolve list.
2114 if (specifics != null) {
2115 for (int i=0; i<specifics.length; i++) {
2116 final Intent sintent = specifics[i];
2117 if (sintent == null) {
2118 continue;
2119 }
2120
2121 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2122 String action = sintent.getAction();
2123 if (resultsAction != null && resultsAction.equals(action)) {
2124 // If this action was explicitly requested, then don't
2125 // remove things that have it.
2126 action = null;
2127 }
2128 ComponentName comp = sintent.getComponent();
2129 ResolveInfo ri = null;
2130 ActivityInfo ai = null;
2131 if (comp == null) {
2132 ri = resolveIntent(
2133 sintent,
2134 specificTypes != null ? specificTypes[i] : null,
2135 flags);
2136 if (ri == null) {
2137 continue;
2138 }
2139 if (ri == mResolveInfo) {
2140 // ACK! Must do something better with this.
2141 }
2142 ai = ri.activityInfo;
2143 comp = new ComponentName(ai.applicationInfo.packageName,
2144 ai.name);
2145 } else {
2146 ai = getActivityInfo(comp, flags);
2147 if (ai == null) {
2148 continue;
2149 }
2150 }
2151
2152 // Look for any generic query activities that are duplicates
2153 // of this specific one, and remove them from the results.
2154 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2155 N = results.size();
2156 int j;
2157 for (j=specificsPos; j<N; j++) {
2158 ResolveInfo sri = results.get(j);
2159 if ((sri.activityInfo.name.equals(comp.getClassName())
2160 && sri.activityInfo.applicationInfo.packageName.equals(
2161 comp.getPackageName()))
2162 || (action != null && sri.filter.matchAction(action))) {
2163 results.remove(j);
2164 if (Config.LOGV) Log.v(
2165 TAG, "Removing duplicate item from " + j
2166 + " due to specific " + specificsPos);
2167 if (ri == null) {
2168 ri = sri;
2169 }
2170 j--;
2171 N--;
2172 }
2173 }
2174
2175 // Add this specific item to its proper place.
2176 if (ri == null) {
2177 ri = new ResolveInfo();
2178 ri.activityInfo = ai;
2179 }
2180 results.add(specificsPos, ri);
2181 ri.specificIndex = i;
2182 specificsPos++;
2183 }
2184 }
2185
2186 // Now we go through the remaining generic results and remove any
2187 // duplicate actions that are found here.
2188 N = results.size();
2189 for (int i=specificsPos; i<N-1; i++) {
2190 final ResolveInfo rii = results.get(i);
2191 if (rii.filter == null) {
2192 continue;
2193 }
2194
2195 // Iterate over all of the actions of this result's intent
2196 // filter... typically this should be just one.
2197 final Iterator<String> it = rii.filter.actionsIterator();
2198 if (it == null) {
2199 continue;
2200 }
2201 while (it.hasNext()) {
2202 final String action = it.next();
2203 if (resultsAction != null && resultsAction.equals(action)) {
2204 // If this action was explicitly requested, then don't
2205 // remove things that have it.
2206 continue;
2207 }
2208 for (int j=i+1; j<N; j++) {
2209 final ResolveInfo rij = results.get(j);
2210 if (rij.filter != null && rij.filter.hasAction(action)) {
2211 results.remove(j);
2212 if (Config.LOGV) Log.v(
2213 TAG, "Removing duplicate item from " + j
2214 + " due to action " + action + " at " + i);
2215 j--;
2216 N--;
2217 }
2218 }
2219 }
2220
2221 // If the caller didn't request filter information, drop it now
2222 // so we don't have to marshall/unmarshall it.
2223 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2224 rii.filter = null;
2225 }
2226 }
2227
2228 // Filter out the caller activity if so requested.
2229 if (caller != null) {
2230 N = results.size();
2231 for (int i=0; i<N; i++) {
2232 ActivityInfo ainfo = results.get(i).activityInfo;
2233 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2234 && caller.getClassName().equals(ainfo.name)) {
2235 results.remove(i);
2236 break;
2237 }
2238 }
2239 }
2240
2241 // If the caller didn't request filter information,
2242 // drop them now so we don't have to
2243 // marshall/unmarshall it.
2244 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2245 N = results.size();
2246 for (int i=0; i<N; i++) {
2247 results.get(i).filter = null;
2248 }
2249 }
2250
2251 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2252 return results;
2253 }
2254
2255 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2256 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002257 ComponentName comp = intent.getComponent();
2258 if (comp != null) {
2259 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2260 ActivityInfo ai = getReceiverInfo(comp, flags);
2261 if (ai != null) {
2262 ResolveInfo ri = new ResolveInfo();
2263 ri.activityInfo = ai;
2264 list.add(ri);
2265 }
2266 return list;
2267 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002270 String pkgName = intent.getPackage();
2271 if (pkgName == null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002272 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002273 resolvedType, flags);
2274 }
2275 PackageParser.Package pkg = mPackages.get(pkgName);
2276 if (pkg != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002277 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002278 resolvedType, flags, pkg.receivers);
2279 }
2280 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
2282 }
2283
2284 public ResolveInfo resolveService(Intent intent, String resolvedType,
2285 int flags) {
2286 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2287 flags);
2288 if (query != null) {
2289 if (query.size() >= 1) {
2290 // If there is more than one service with the same priority,
2291 // just arbitrarily pick the first one.
2292 return query.get(0);
2293 }
2294 }
2295 return null;
2296 }
2297
2298 public List<ResolveInfo> queryIntentServices(Intent intent,
2299 String resolvedType, int flags) {
2300 ComponentName comp = intent.getComponent();
2301 if (comp != null) {
2302 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2303 ServiceInfo si = getServiceInfo(comp, flags);
2304 if (si != null) {
2305 ResolveInfo ri = new ResolveInfo();
2306 ri.serviceInfo = si;
2307 list.add(ri);
2308 }
2309 return list;
2310 }
2311
2312 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002313 String pkgName = intent.getPackage();
2314 if (pkgName == null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002315 return (List<ResolveInfo>)mServices.queryIntent(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002316 resolvedType, flags);
2317 }
2318 PackageParser.Package pkg = mPackages.get(pkgName);
2319 if (pkg != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002320 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002321 resolvedType, flags, pkg.services);
2322 }
2323 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 }
2325 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 public List<PackageInfo> getInstalledPackages(int flags) {
2328 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2329
2330 synchronized (mPackages) {
2331 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2332 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2333 while (i.hasNext()) {
2334 final PackageSetting ps = i.next();
2335 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2336 if(psPkg != null) {
2337 finalList.add(psPkg);
2338 }
2339 }
2340 }
2341 else {
2342 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2343 while (i.hasNext()) {
2344 final PackageParser.Package p = i.next();
2345 if (p.applicationInfo != null) {
2346 PackageInfo pi = generatePackageInfo(p, flags);
2347 if(pi != null) {
2348 finalList.add(pi);
2349 }
2350 }
2351 }
2352 }
2353 }
2354 return finalList;
2355 }
2356
2357 public List<ApplicationInfo> getInstalledApplications(int flags) {
2358 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2359 synchronized(mPackages) {
2360 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2361 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2362 while (i.hasNext()) {
2363 final PackageSetting ps = i.next();
2364 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2365 if(ai != null) {
2366 finalList.add(ai);
2367 }
2368 }
2369 }
2370 else {
2371 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2372 while (i.hasNext()) {
2373 final PackageParser.Package p = i.next();
2374 if (p.applicationInfo != null) {
2375 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2376 if(ai != null) {
2377 finalList.add(ai);
2378 }
2379 }
2380 }
2381 }
2382 }
2383 return finalList;
2384 }
2385
2386 public List<ApplicationInfo> getPersistentApplications(int flags) {
2387 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2388
2389 synchronized (mPackages) {
2390 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2391 while (i.hasNext()) {
2392 PackageParser.Package p = i.next();
2393 if (p.applicationInfo != null
2394 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002395 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002396 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
2398 }
2399 }
2400
2401 return finalList;
2402 }
2403
2404 public ProviderInfo resolveContentProvider(String name, int flags) {
2405 synchronized (mPackages) {
2406 final PackageParser.Provider provider = mProviders.get(name);
2407 return provider != null
2408 && mSettings.isEnabledLP(provider.info, flags)
2409 && (!mSafeMode || (provider.info.applicationInfo.flags
2410 &ApplicationInfo.FLAG_SYSTEM) != 0)
2411 ? PackageParser.generateProviderInfo(provider, flags)
2412 : null;
2413 }
2414 }
2415
Fred Quintana718d8a22009-04-29 17:53:20 -07002416 /**
2417 * @deprecated
2418 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 public void querySyncProviders(List outNames, List outInfo) {
2420 synchronized (mPackages) {
2421 Iterator<Map.Entry<String, PackageParser.Provider>> i
2422 = mProviders.entrySet().iterator();
2423
2424 while (i.hasNext()) {
2425 Map.Entry<String, PackageParser.Provider> entry = i.next();
2426 PackageParser.Provider p = entry.getValue();
2427
2428 if (p.syncable
2429 && (!mSafeMode || (p.info.applicationInfo.flags
2430 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2431 outNames.add(entry.getKey());
2432 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2433 }
2434 }
2435 }
2436 }
2437
2438 public List<ProviderInfo> queryContentProviders(String processName,
2439 int uid, int flags) {
2440 ArrayList<ProviderInfo> finalList = null;
2441
2442 synchronized (mPackages) {
2443 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2444 while (i.hasNext()) {
2445 PackageParser.Provider p = i.next();
2446 if (p.info.authority != null
2447 && (processName == null ||
2448 (p.info.processName.equals(processName)
2449 && p.info.applicationInfo.uid == uid))
2450 && mSettings.isEnabledLP(p.info, flags)
2451 && (!mSafeMode || (p.info.applicationInfo.flags
2452 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2453 if (finalList == null) {
2454 finalList = new ArrayList<ProviderInfo>(3);
2455 }
2456 finalList.add(PackageParser.generateProviderInfo(p,
2457 flags));
2458 }
2459 }
2460 }
2461
2462 if (finalList != null) {
2463 Collections.sort(finalList, mProviderInitOrderSorter);
2464 }
2465
2466 return finalList;
2467 }
2468
2469 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2470 int flags) {
2471 synchronized (mPackages) {
2472 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2473 return PackageParser.generateInstrumentationInfo(i, flags);
2474 }
2475 }
2476
2477 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2478 int flags) {
2479 ArrayList<InstrumentationInfo> finalList =
2480 new ArrayList<InstrumentationInfo>();
2481
2482 synchronized (mPackages) {
2483 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2484 while (i.hasNext()) {
2485 PackageParser.Instrumentation p = i.next();
2486 if (targetPackage == null
2487 || targetPackage.equals(p.info.targetPackage)) {
2488 finalList.add(PackageParser.generateInstrumentationInfo(p,
2489 flags));
2490 }
2491 }
2492 }
2493
2494 return finalList;
2495 }
2496
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002497 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002499 if (files == null) {
2500 Log.d(TAG, "No files in app dir " + dir);
2501 return;
2502 }
2503
Joe Onorato431bb222010-10-18 19:13:23 -04002504 if (false) {
2505 Log.d(TAG, "Scanning app dir " + dir);
2506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507
2508 int i;
2509 for (i=0; i<files.length; i++) {
2510 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002511 if (!isPackageFilename(files[i])) {
2512 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002513 continue;
2514 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002515 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002516 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002517 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002518 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2519 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002520 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002521 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002522 file.delete();
2523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 }
2525 }
2526
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002527 private static File getSettingsProblemFile() {
2528 File dataDir = Environment.getDataDirectory();
2529 File systemDir = new File(dataDir, "system");
2530 File fname = new File(systemDir, "uiderrors.txt");
2531 return fname;
2532 }
2533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 private static void reportSettingsProblem(int priority, String msg) {
2535 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002536 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 FileOutputStream out = new FileOutputStream(fname, true);
2538 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002539 SimpleDateFormat formatter = new SimpleDateFormat();
2540 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2541 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 pw.close();
2543 FileUtils.setPermissions(
2544 fname.toString(),
2545 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2546 -1, -1);
2547 } catch (java.io.IOException e) {
2548 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002549 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 }
2551
2552 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2553 PackageParser.Package pkg, File srcFile, int parseFlags) {
2554 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002555 if (ps != null
2556 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002557 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002558 if (ps.signatures.mSignatures != null
2559 && ps.signatures.mSignatures.length != 0) {
2560 // Optimization: reuse the existing cached certificates
2561 // if the package appears to be unchanged.
2562 pkg.mSignatures = ps.signatures.mSignatures;
2563 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
Jeff Browne7600722010-04-07 18:28:23 -07002565
2566 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002567 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002568 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2569 }
2570
2571 if (!pp.collectCertificates(pkg, parseFlags)) {
2572 mLastScanError = pp.getParseError();
2573 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 }
2576 return true;
2577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 /*
2580 * Scan a package and return the newly parsed package.
2581 * Returns null in case of errors and the error code is stored in mLastScanError
2582 */
2583 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002584 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002586 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002588 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 if (pkg == null) {
2593 mLastScanError = pp.getParseError();
2594 return null;
2595 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002596 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 PackageSetting updatedPkg;
2598 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002599 // Look to see if we already know about this package.
2600 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002601 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002602 // This package has been renamed to its original name. Let's
2603 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002604 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002605 }
2606 // If there was no original package, see one for the real package name.
2607 if (ps == null) {
2608 ps = mSettings.peekPackageLP(pkg.packageName);
2609 }
2610 // Check to see if this package could be hiding/updating a system
2611 // package. Must look for it either under the original or real
2612 // package name depending on our state.
2613 updatedPkg = mSettings.mDisabledSysPackages.get(
2614 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 // First check if this is a system package that may involve an update
2617 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002618 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 // The path has changed from what was last scanned... check the
2620 // version of the new path against what we have stored to determine
2621 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002622 if (pkg.mVersionCode < ps.versionCode) {
2623 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002624 // Ignore entry. Skip it.
2625 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002626 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002627 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002628 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2629 return null;
2630 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002631 // The current app on the system partion is better than
2632 // what we have updated to on the data partition; switch
2633 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002634 // At this point, its safely assumed that package installation for
2635 // apps in system partition will go through. If not there won't be a working
2636 // version of the app
2637 synchronized (mPackages) {
2638 // Just remove the loaded entries from package lists.
2639 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002640 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002641 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002642 + "reverting from " + ps.codePathString
2643 + ": new version " + pkg.mVersionCode
2644 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002645 InstallArgs args = new FileInstallArgs(ps.codePathString,
2646 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002647 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002648 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 }
2651 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002652 if (updatedPkg != null) {
2653 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2654 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2655 }
2656 // Verify certificates against what was last scanned
2657 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002658 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002659 return null;
2660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 // The apk is forward locked (not public) if its code and resources
2662 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002663 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002665 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002666 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002667
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002668 String codePath = null;
2669 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002670 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2671 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002672 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002673 } else {
2674 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002675 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002676 }
2677 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002678 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002679 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002680 codePath = pkg.mScanPath;
2681 // Set application objects path explicitly.
2682 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002684 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 }
2686
Kenny Root85387d72010-08-26 10:13:11 -07002687 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2688 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002689 pkg.mPath = pkg.mScanPath = destCodePath;
2690 pkg.applicationInfo.sourceDir = destCodePath;
2691 pkg.applicationInfo.publicSourceDir = destResPath;
2692 }
2693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 private static String fixProcessName(String defProcessName,
2695 String processName, int uid) {
2696 if (processName == null) {
2697 return defProcessName;
2698 }
2699 return processName;
2700 }
2701
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002702 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002703 PackageParser.Package pkg) {
2704 if (pkgSetting.signatures.mSignatures != null) {
2705 // Already existing package. Make sure signatures match
2706 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2707 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002708 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002709 + " signatures do not match the previously installed version; ignoring!");
2710 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 return false;
2712 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002713 }
2714 // Check for shared user signatures
2715 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2716 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2717 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2718 Slog.e(TAG, "Package " + pkg.packageName
2719 + " has no signatures that match those in shared user "
2720 + pkgSetting.sharedUser.name + "; ignoring!");
2721 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2722 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
2725 return true;
2726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002727
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002728 public boolean performDexOpt(String packageName) {
2729 if (!mNoDexOpt) {
2730 return false;
2731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002733 PackageParser.Package p;
2734 synchronized (mPackages) {
2735 p = mPackages.get(packageName);
2736 if (p == null || p.mDidDexOpt) {
2737 return false;
2738 }
2739 }
2740 synchronized (mInstallLock) {
2741 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2742 }
2743 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002744
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002745 static final int DEX_OPT_SKIPPED = 0;
2746 static final int DEX_OPT_PERFORMED = 1;
2747 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002748
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002749 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2750 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002751 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002752 String path = pkg.mScanPath;
2753 int ret = 0;
2754 try {
2755 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002756 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002757 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002758 pkg.mDidDexOpt = true;
2759 performed = true;
2760 }
2761 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002762 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002763 ret = -1;
2764 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002765 Slog.w(TAG, "IOException reading apk: " + path, e);
2766 ret = -1;
2767 } catch (dalvik.system.StaleDexCacheError e) {
2768 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2769 ret = -1;
2770 } catch (Exception e) {
2771 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002772 ret = -1;
2773 }
2774 if (ret < 0) {
2775 //error from installer
2776 return DEX_OPT_FAILED;
2777 }
2778 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002779
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002780 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2781 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002782
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002783 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2784 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002785 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002786 + " to " + newPkg.packageName
2787 + ": old package not in system partition");
2788 return false;
2789 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002790 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002791 + " to " + newPkg.packageName
2792 + ": old package still exists");
2793 return false;
2794 }
2795 return true;
2796 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002797
2798 private File getDataPathForPackage(PackageParser.Package pkg) {
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08002799 boolean useEncryptedFSDir = false;
Jason parksa3cdaa52011-01-13 14:15:43 -06002800 File dataPath;
2801 if (useEncryptedFSDir) {
2802 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2803 } else {
2804 dataPath = new File(mAppDataDir, pkg.packageName);
2805 }
2806 return dataPath;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002807 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002808
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002809 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002810 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002811 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002812 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2813 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002814 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002815 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002816 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2817 return null;
2818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 mScanningPath = scanFile;
2820 if (pkg == null) {
2821 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2822 return null;
2823 }
2824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2826 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2827 }
2828
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002829 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 synchronized (mPackages) {
2831 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002832 Slog.w(TAG, "*************************************************");
2833 Slog.w(TAG, "Core android package being redefined. Skipping.");
2834 Slog.w(TAG, " file=" + mScanningPath);
2835 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2837 return null;
2838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 // Set up information for our fall-back user intent resolution
2841 // activity.
2842 mPlatformPackage = pkg;
2843 pkg.mVersionCode = mSdkVersion;
2844 mAndroidApplication = pkg.applicationInfo;
2845 mResolveActivity.applicationInfo = mAndroidApplication;
2846 mResolveActivity.name = ResolverActivity.class.getName();
2847 mResolveActivity.packageName = mAndroidApplication.packageName;
2848 mResolveActivity.processName = mAndroidApplication.processName;
2849 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2850 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
Joe Onorato646f46e2010-11-08 15:08:56 -08002851 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 mResolveActivity.exported = true;
2853 mResolveActivity.enabled = true;
2854 mResolveInfo.activityInfo = mResolveActivity;
2855 mResolveInfo.priority = 0;
2856 mResolveInfo.preferredOrder = 0;
2857 mResolveInfo.match = 0;
2858 mResolveComponentName = new ComponentName(
2859 mAndroidApplication.packageName, mResolveActivity.name);
2860 }
2861 }
2862
2863 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002864 TAG, "Scanning package " + pkg.packageName);
2865 if (mPackages.containsKey(pkg.packageName)
2866 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002867 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2870 return null;
2871 }
2872
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002873 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002874 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2875 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 SharedUserSetting suid = null;
2878 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002879
Kenny Root502e9a42011-01-10 13:48:15 -08002880 if (!isSystemApp(pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002881 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002882 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002883 pkg.mRealPackage = null;
2884 pkg.mAdoptPermissions = null;
2885 }
Kenny Root502e9a42011-01-10 13:48:15 -08002886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 synchronized (mPackages) {
2888 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002889 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2890 if (mTmpSharedLibraries == null ||
2891 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2892 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2893 }
2894 int num = 0;
2895 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2896 for (int i=0; i<N; i++) {
2897 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002899 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002901 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2903 return null;
2904 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002905 mTmpSharedLibraries[num] = file;
2906 num++;
2907 }
2908 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2909 for (int i=0; i<N; i++) {
2910 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2911 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002912 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002913 + " desires unavailable shared library "
2914 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2915 } else {
2916 mTmpSharedLibraries[num] = file;
2917 num++;
2918 }
2919 }
2920 if (num > 0) {
2921 pkg.usesLibraryFiles = new String[num];
2922 System.arraycopy(mTmpSharedLibraries, 0,
2923 pkg.usesLibraryFiles, 0, num);
2924 }
Kenny Root1683afa2011-01-07 14:27:50 -08002925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002926
Kenny Root1683afa2011-01-07 14:27:50 -08002927 if (pkg.reqFeatures != null) {
2928 int N = pkg.reqFeatures.size();
2929 for (int i = 0; i < N; i++) {
2930 FeatureInfo fi = pkg.reqFeatures.get(i);
2931 if ((fi.flags & FeatureInfo.FLAG_REQUIRED) == 0) {
2932 // Don't care.
2933 continue;
2934 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002935
Kenny Root1683afa2011-01-07 14:27:50 -08002936 if (fi.name != null) {
2937 if (mAvailableFeatures.get(fi.name) == null) {
2938 Slog.e(TAG, "Package " + pkg.packageName
2939 + " requires unavailable feature " + fi.name + "; failing!");
2940 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2941 return null;
Dianne Hackborn49237342009-08-27 20:08:01 -07002942 }
2943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 }
2945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 if (pkg.mSharedUserId != null) {
2948 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2949 pkg.applicationInfo.flags, true);
2950 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002951 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 + " for shared user failed");
2953 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2954 return null;
2955 }
2956 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2957 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2958 + suid.userId + "): packages=" + suid.packages);
2959 }
2960 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002961
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002962 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002963 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002964 Log.w(TAG, "WAITING FOR DEBUGGER");
2965 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002966 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2967 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002968 }
2969 }
2970
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002971 // Check if we are renaming from an original package name.
2972 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002974 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 // This package may need to be renamed to a previously
2976 // installed name. Let's check on that...
2977 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002978 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002979 // This package had originally been installed as the
2980 // original name, and we have already taken care of
2981 // transitioning to the new one. Just update the new
2982 // one to continue using the old name.
2983 realName = pkg.mRealPackage;
2984 if (!pkg.packageName.equals(renamed)) {
2985 // Callers into this function may have already taken
2986 // care of renaming the package; only do it here if
2987 // it is not already done.
2988 pkg.setPackageName(renamed);
2989 }
2990
Dianne Hackbornc1552392010-03-03 16:19:01 -08002991 } else {
2992 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2993 if ((origPackage=mSettings.peekPackageLP(
2994 pkg.mOriginalPackages.get(i))) != null) {
2995 // We do have the package already installed under its
2996 // original name... should we use it?
2997 if (!verifyPackageUpdate(origPackage, pkg)) {
2998 // New package is not compatible with original.
2999 origPackage = null;
3000 continue;
3001 } else if (origPackage.sharedUser != null) {
3002 // Make sure uid is compatible between packages.
3003 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003004 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003005 + " to " + pkg.packageName + ": old uid "
3006 + origPackage.sharedUser.name
3007 + " differs from " + pkg.mSharedUserId);
3008 origPackage = null;
3009 continue;
3010 }
3011 } else {
3012 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3013 + pkg.packageName + " to old name " + origPackage.name);
3014 }
3015 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003016 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003017 }
3018 }
3019 }
3020
3021 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003022 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003023 + " was transferred to another, but its .apk remains");
3024 }
3025
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003026 // Just create the setting, don't add it yet. For already existing packages
3027 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003028 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003029 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3030 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003032 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3034 return null;
3035 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003036
3037 if (pkgSetting.origPackage != null) {
3038 // If we are first transitioning from an original package,
3039 // fix up the new package's name now. We need to do this after
3040 // looking up the package under its new name, so getPackageLP
3041 // can take care of fiddling things correctly.
3042 pkg.setPackageName(origPackage.name);
3043
3044 // File a report about this.
3045 String msg = "New package " + pkgSetting.realName
3046 + " renamed to replace old package " + pkgSetting.name;
3047 reportSettingsProblem(Log.WARN, msg);
3048
3049 // Make a note of it.
3050 mTransferedPackages.add(origPackage.name);
3051
3052 // No longer need to retain this.
3053 pkgSetting.origPackage = null;
3054 }
3055
3056 if (realName != null) {
3057 // Make a note of it.
3058 mTransferedPackages.add(pkg.packageName);
3059 }
3060
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003061 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 pkg.applicationInfo.uid = pkgSetting.userId;
3066 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003067
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003068 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003069 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 return null;
3071 }
3072 // The signature has changed, but this package is in the system
3073 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003074 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 // However... if this package is part of a shared user, but it
3076 // doesn't match the signature of the shared user, let's fail.
3077 // What this means is that you can't change the signatures
3078 // associated with an overall shared user, which doesn't seem all
3079 // that unreasonable.
3080 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003081 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3082 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3083 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3085 return null;
3086 }
3087 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003088 // File a report about this.
3089 String msg = "System package " + pkg.packageName
3090 + " signature changed; retaining data.";
3091 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003093
The Android Open Source Project10592532009-03-18 17:39:46 -07003094 // Verify that this new package doesn't have any content providers
3095 // that conflict with existing packages. Only do this if the
3096 // package isn't already installed, since we don't want to break
3097 // things that are installed.
3098 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3099 int N = pkg.providers.size();
3100 int i;
3101 for (i=0; i<N; i++) {
3102 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003103 if (p.info.authority != null) {
3104 String names[] = p.info.authority.split(";");
3105 for (int j = 0; j < names.length; j++) {
3106 if (mProviders.containsKey(names[j])) {
3107 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003108 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003109 " (in package " + pkg.applicationInfo.packageName +
3110 ") is already used by "
3111 + ((other != null && other.getComponentName() != null)
3112 ? other.getComponentName().getPackageName() : "?"));
3113 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3114 return null;
3115 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003116 }
3117 }
3118 }
3119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 }
3121
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003122 final String pkgName = pkg.packageName;
3123
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003124 if (pkg.mAdoptPermissions != null) {
3125 // This package wants to adopt ownership of permissions from
3126 // another package.
3127 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3128 String origName = pkg.mAdoptPermissions.get(i);
3129 PackageSetting orig = mSettings.peekPackageLP(origName);
3130 if (orig != null) {
3131 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003132 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003133 + origName + " to " + pkg.packageName);
3134 mSettings.transferPermissions(origName, pkg.packageName);
3135 }
3136 }
3137 }
3138 }
3139
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003140 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003142 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 pkg.applicationInfo.processName = fixProcessName(
3144 pkg.applicationInfo.packageName,
3145 pkg.applicationInfo.processName,
3146 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147
3148 File dataPath;
3149 if (mPlatformPackage == pkg) {
3150 // The system package is special.
3151 dataPath = new File (Environment.getDataDirectory(), "system");
3152 pkg.applicationInfo.dataDir = dataPath.getPath();
3153 } else {
3154 // This is a normal package, need to make its data directory.
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08003155 boolean useEncryptedFSDir = false;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003156 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003157
3158 boolean uidError = false;
3159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 if (dataPath.exists()) {
3161 mOutPermissions[1] = 0;
3162 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003163
3164 // If we have mismatched owners for the data path, we have a
3165 // problem (unless we're running in the simulator.)
3166 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 boolean recovered = false;
3168 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3169 // If this is a system app, we can at least delete its
3170 // current data so the application will still work.
3171 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06003172 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003173 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 // Old data gone!
3175 String msg = "System package " + pkg.packageName
3176 + " has changed from uid: "
3177 + mOutPermissions[1] + " to "
3178 + pkg.applicationInfo.uid + "; old data erased";
3179 reportSettingsProblem(Log.WARN, msg);
3180 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 // And now re-install the app.
Jason parksa3cdaa52011-01-13 14:15:43 -06003183 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 pkg.applicationInfo.uid);
3185 if (ret == -1) {
3186 // Ack should not happen!
3187 msg = "System package " + pkg.packageName
3188 + " could not have data directory re-created after delete.";
3189 reportSettingsProblem(Log.WARN, msg);
3190 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3191 return null;
3192 }
3193 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 if (!recovered) {
3196 mHasSystemUidErrors = true;
3197 }
3198 }
3199 if (!recovered) {
3200 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3201 + pkg.applicationInfo.uid + "/fs_"
3202 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003203 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 String msg = "Package " + pkg.packageName
3205 + " has mismatched uid: "
3206 + mOutPermissions[1] + " on disk, "
3207 + pkg.applicationInfo.uid + " in settings";
3208 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003209 mSettings.mReadMessages.append(msg);
3210 mSettings.mReadMessages.append('\n');
3211 uidError = true;
3212 if (!pkgSetting.uidError) {
3213 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 }
3216 }
3217 }
3218 pkg.applicationInfo.dataDir = dataPath.getPath();
3219 } else {
3220 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3221 Log.v(TAG, "Want this data dir: " + dataPath);
3222 //invoke installer to do the actual installation
3223 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06003224 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 pkg.applicationInfo.uid);
3226 if(ret < 0) {
3227 // Error from installer
3228 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3229 return null;
3230 }
3231 } else {
3232 dataPath.mkdirs();
3233 if (dataPath.exists()) {
3234 FileUtils.setPermissions(
3235 dataPath.toString(),
3236 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3237 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3238 }
3239 }
3240 if (dataPath.exists()) {
3241 pkg.applicationInfo.dataDir = dataPath.getPath();
3242 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003243 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 pkg.applicationInfo.dataDir = null;
3245 }
3246 }
Kenny Root85387d72010-08-26 10:13:11 -07003247
3248 /*
3249 * Set the data dir to the default "/data/data/<package name>/lib"
3250 * if we got here without anyone telling us different (e.g., apps
3251 * stored on SD card have their native libraries stored in the ASEC
3252 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003253 *
3254 * This happens during an upgrade from a package settings file that
3255 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003256 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003257 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3258 if (pkgSetting.nativeLibraryPathString == null) {
3259 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3260 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3261 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3262 } else {
3263 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3264 }
Kenny Root85387d72010-08-26 10:13:11 -07003265 }
3266
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003267 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 }
3269
Kenny Root85387d72010-08-26 10:13:11 -07003270 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 if (mInstaller != null) {
3272 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003273 /* Note: We don't want to unpack the native binaries for
3274 * system applications, unless they have been updated
3275 * (the binaries are already under /system/lib).
3276 * Also, don't unpack libs for apps on the external card
3277 * since they should have their libraries in the ASEC
3278 * container already.
3279 *
3280 * In other words, we're going to unpack the binaries
3281 * only for non-system apps and system app upgrades.
3282 */
Kenny Root831baa22010-10-05 12:29:25 -07003283 if (pkg.applicationInfo.nativeLibraryDir != null) {
Kenny Roote68d58a2010-10-18 16:08:54 -07003284 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3285 final String dataPathString = dataPath.getPath();
3286
Kenny Root831baa22010-10-05 12:29:25 -07003287 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3288 /*
3289 * Upgrading from a previous version of the OS sometimes
3290 * leaves native libraries in the /data/data/<app>/lib
3291 * directory for system apps even when they shouldn't be.
3292 * Recent changes in the JNI library search path
3293 * necessitates we remove those to match previous behavior.
3294 */
Kenny Roote68d58a2010-10-18 16:08:54 -07003295 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Kenny Root831baa22010-10-05 12:29:25 -07003296 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3297 }
Kenny Roote68d58a2010-10-18 16:08:54 -07003298 } else if (nativeLibraryDir.getParent().equals(dataPathString)) {
3299 /*
3300 * If this is an internal application or our
3301 * nativeLibraryPath points to our data directory, unpack
3302 * the libraries. The native library path pointing to the
3303 * data directory for an application in an ASEC container
3304 * can happen for older apps that existed before an OTA to
3305 * Gingerbread.
3306 */
3307 Slog.i(TAG, "Unpacking native libraries for " + path);
3308 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
3309 NativeLibraryHelper.copyNativeBinariesLI(scanFile, nativeLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003310 } else {
Kenny Roote68d58a2010-10-18 16:08:54 -07003311 Slog.i(TAG, "Linking native library dir for " + path);
3312 mInstaller.linkNativeLibraryDirectory(dataPathString,
Kenny Root6a6b0072010-10-07 16:46:10 -07003313 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003316 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003317
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003318 if ((scanMode&SCAN_NO_DEX) == 0) {
3319 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3321 return null;
3322 }
3323 }
3324 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 if (mFactoryTest && pkg.requestedPermissions.contains(
3327 android.Manifest.permission.FACTORY_TEST)) {
3328 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3329 }
3330
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003331 // Request the ActivityManager to kill the process(only for existing packages)
3332 // so that we do not end up in a confused state while the user is still using the older
3333 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003334 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003335 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003336 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003337 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003340 // We don't expect installation to fail beyond this point,
3341 if ((scanMode&SCAN_MONITOR) != 0) {
3342 mAppDirs.put(pkg.mPath, pkg);
3343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003345 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003347 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003348 // Make sure we don't accidentally delete its data.
3349 mSettings.mPackagesToBeCleaned.remove(pkgName);
3350
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003351 // Take care of first install / last update times.
3352 if (currentTime != 0) {
3353 if (pkgSetting.firstInstallTime == 0) {
3354 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3355 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3356 pkgSetting.lastUpdateTime = currentTime;
3357 }
3358 } else if (pkgSetting.firstInstallTime == 0) {
3359 // We need *something*. Take time time stamp of the file.
3360 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3361 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3362 if (scanFileTime != pkgSetting.timeStamp) {
3363 // A package on the system image has changed; consider this
3364 // to be an update.
3365 pkgSetting.lastUpdateTime = scanFileTime;
3366 }
3367 }
3368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 int N = pkg.providers.size();
3370 StringBuilder r = null;
3371 int i;
3372 for (i=0; i<N; i++) {
3373 PackageParser.Provider p = pkg.providers.get(i);
3374 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3375 p.info.processName, pkg.applicationInfo.uid);
3376 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3377 p.info.name), p);
3378 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003379 if (p.info.authority != null) {
3380 String names[] = p.info.authority.split(";");
3381 p.info.authority = null;
3382 for (int j = 0; j < names.length; j++) {
3383 if (j == 1 && p.syncable) {
3384 // We only want the first authority for a provider to possibly be
3385 // syncable, so if we already added this provider using a different
3386 // authority clear the syncable flag. We copy the provider before
3387 // changing it because the mProviders object contains a reference
3388 // to a provider that we don't want to change.
3389 // Only do this for the second authority since the resulting provider
3390 // object can be the same for all future authorities for this provider.
3391 p = new PackageParser.Provider(p);
3392 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003394 if (!mProviders.containsKey(names[j])) {
3395 mProviders.put(names[j], p);
3396 if (p.info.authority == null) {
3397 p.info.authority = names[j];
3398 } else {
3399 p.info.authority = p.info.authority + ";" + names[j];
3400 }
3401 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3402 Log.d(TAG, "Registered content provider: " + names[j] +
3403 ", className = " + p.info.name +
3404 ", isSyncable = " + p.info.isSyncable);
3405 } else {
3406 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003407 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003408 " (in package " + pkg.applicationInfo.packageName +
3409 "): name already used by "
3410 + ((other != null && other.getComponentName() != null)
3411 ? other.getComponentName().getPackageName() : "?"));
3412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 }
3414 }
3415 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3416 if (r == null) {
3417 r = new StringBuilder(256);
3418 } else {
3419 r.append(' ');
3420 }
3421 r.append(p.info.name);
3422 }
3423 }
3424 if (r != null) {
3425 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3426 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 N = pkg.services.size();
3429 r = null;
3430 for (i=0; i<N; i++) {
3431 PackageParser.Service s = pkg.services.get(i);
3432 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3433 s.info.processName, pkg.applicationInfo.uid);
3434 mServices.addService(s);
3435 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3436 if (r == null) {
3437 r = new StringBuilder(256);
3438 } else {
3439 r.append(' ');
3440 }
3441 r.append(s.info.name);
3442 }
3443 }
3444 if (r != null) {
3445 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3446 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 N = pkg.receivers.size();
3449 r = null;
3450 for (i=0; i<N; i++) {
3451 PackageParser.Activity a = pkg.receivers.get(i);
3452 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3453 a.info.processName, pkg.applicationInfo.uid);
3454 mReceivers.addActivity(a, "receiver");
3455 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3456 if (r == null) {
3457 r = new StringBuilder(256);
3458 } else {
3459 r.append(' ');
3460 }
3461 r.append(a.info.name);
3462 }
3463 }
3464 if (r != null) {
3465 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3466 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 N = pkg.activities.size();
3469 r = null;
3470 for (i=0; i<N; i++) {
3471 PackageParser.Activity a = pkg.activities.get(i);
3472 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3473 a.info.processName, pkg.applicationInfo.uid);
3474 mActivities.addActivity(a, "activity");
3475 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3476 if (r == null) {
3477 r = new StringBuilder(256);
3478 } else {
3479 r.append(' ');
3480 }
3481 r.append(a.info.name);
3482 }
3483 }
3484 if (r != null) {
3485 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3486 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 N = pkg.permissionGroups.size();
3489 r = null;
3490 for (i=0; i<N; i++) {
3491 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3492 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3493 if (cur == null) {
3494 mPermissionGroups.put(pg.info.name, pg);
3495 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3496 if (r == null) {
3497 r = new StringBuilder(256);
3498 } else {
3499 r.append(' ');
3500 }
3501 r.append(pg.info.name);
3502 }
3503 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003504 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 + pg.info.packageName + " ignored: original from "
3506 + cur.info.packageName);
3507 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3508 if (r == null) {
3509 r = new StringBuilder(256);
3510 } else {
3511 r.append(' ');
3512 }
3513 r.append("DUP:");
3514 r.append(pg.info.name);
3515 }
3516 }
3517 }
3518 if (r != null) {
3519 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3520 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 N = pkg.permissions.size();
3523 r = null;
3524 for (i=0; i<N; i++) {
3525 PackageParser.Permission p = pkg.permissions.get(i);
3526 HashMap<String, BasePermission> permissionMap =
3527 p.tree ? mSettings.mPermissionTrees
3528 : mSettings.mPermissions;
3529 p.group = mPermissionGroups.get(p.info.group);
3530 if (p.info.group == null || p.group != null) {
3531 BasePermission bp = permissionMap.get(p.info.name);
3532 if (bp == null) {
3533 bp = new BasePermission(p.info.name, p.info.packageName,
3534 BasePermission.TYPE_NORMAL);
3535 permissionMap.put(p.info.name, bp);
3536 }
3537 if (bp.perm == null) {
3538 if (bp.sourcePackage == null
3539 || bp.sourcePackage.equals(p.info.packageName)) {
3540 BasePermission tree = findPermissionTreeLP(p.info.name);
3541 if (tree == null
3542 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003543 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 bp.perm = p;
3545 bp.uid = pkg.applicationInfo.uid;
3546 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3547 if (r == null) {
3548 r = new StringBuilder(256);
3549 } else {
3550 r.append(' ');
3551 }
3552 r.append(p.info.name);
3553 }
3554 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003555 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 + p.info.packageName + " ignored: base tree "
3557 + tree.name + " is from package "
3558 + tree.sourcePackage);
3559 }
3560 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003561 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 + p.info.packageName + " ignored: original from "
3563 + bp.sourcePackage);
3564 }
3565 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3566 if (r == null) {
3567 r = new StringBuilder(256);
3568 } else {
3569 r.append(' ');
3570 }
3571 r.append("DUP:");
3572 r.append(p.info.name);
3573 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003574 if (bp.perm == p) {
3575 bp.protectionLevel = p.info.protectionLevel;
3576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003578 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 + p.info.packageName + " ignored: no group "
3580 + p.group);
3581 }
3582 }
3583 if (r != null) {
3584 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3585 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 N = pkg.instrumentation.size();
3588 r = null;
3589 for (i=0; i<N; i++) {
3590 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3591 a.info.packageName = pkg.applicationInfo.packageName;
3592 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3593 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3594 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003595 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003596 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3598 if (r == null) {
3599 r = new StringBuilder(256);
3600 } else {
3601 r.append(' ');
3602 }
3603 r.append(a.info.name);
3604 }
3605 }
3606 if (r != null) {
3607 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3608 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003609
Dianne Hackborn854060af2009-07-09 18:14:31 -07003610 if (pkg.protectedBroadcasts != null) {
3611 N = pkg.protectedBroadcasts.size();
3612 for (i=0; i<N; i++) {
3613 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3614 }
3615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 pkgSetting.setTimeStamp(scanFileTime);
3618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 return pkg;
3621 }
3622
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003623 private void killApplication(String pkgName, int uid) {
3624 // Request the ActivityManager to kill the process(only for existing packages)
3625 // so that we do not end up in a confused state while the user is still using the older
3626 // version of the application while the new one gets installed.
3627 IActivityManager am = ActivityManagerNative.getDefault();
3628 if (am != null) {
3629 try {
3630 am.killApplicationWithUid(pkgName, uid);
3631 } catch (RemoteException e) {
3632 }
3633 }
3634 }
3635
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003636 // Return the path of the directory that will contain the native binaries
3637 // of a given installed package. This is relative to the data path.
3638 //
Kenny Root85387d72010-08-26 10:13:11 -07003639 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3640 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3641 if (nativeLibraryDir != null) {
3642 return new File(nativeLibraryDir);
3643 } else {
3644 // Fall back for old packages
3645 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3646 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003647 }
3648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3650 if (chatty && Config.LOGD) Log.d(
3651 TAG, "Removing package " + pkg.applicationInfo.packageName );
3652
3653 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 mPackages.remove(pkg.applicationInfo.packageName);
3657 if (pkg.mPath != null) {
3658 mAppDirs.remove(pkg.mPath);
3659 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 int N = pkg.providers.size();
3662 StringBuilder r = null;
3663 int i;
3664 for (i=0; i<N; i++) {
3665 PackageParser.Provider p = pkg.providers.get(i);
3666 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3667 p.info.name));
3668 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 /* The is another ContentProvider with this authority when
3671 * this app was installed so this authority is null,
3672 * Ignore it as we don't have to unregister the provider.
3673 */
3674 continue;
3675 }
3676 String names[] = p.info.authority.split(";");
3677 for (int j = 0; j < names.length; j++) {
3678 if (mProviders.get(names[j]) == p) {
3679 mProviders.remove(names[j]);
3680 if (chatty && Config.LOGD) Log.d(
3681 TAG, "Unregistered content provider: " + names[j] +
3682 ", className = " + p.info.name +
3683 ", isSyncable = " + p.info.isSyncable);
3684 }
3685 }
3686 if (chatty) {
3687 if (r == null) {
3688 r = new StringBuilder(256);
3689 } else {
3690 r.append(' ');
3691 }
3692 r.append(p.info.name);
3693 }
3694 }
3695 if (r != null) {
3696 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 N = pkg.services.size();
3700 r = null;
3701 for (i=0; i<N; i++) {
3702 PackageParser.Service s = pkg.services.get(i);
3703 mServices.removeService(s);
3704 if (chatty) {
3705 if (r == null) {
3706 r = new StringBuilder(256);
3707 } else {
3708 r.append(' ');
3709 }
3710 r.append(s.info.name);
3711 }
3712 }
3713 if (r != null) {
3714 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 N = pkg.receivers.size();
3718 r = null;
3719 for (i=0; i<N; i++) {
3720 PackageParser.Activity a = pkg.receivers.get(i);
3721 mReceivers.removeActivity(a, "receiver");
3722 if (chatty) {
3723 if (r == null) {
3724 r = new StringBuilder(256);
3725 } else {
3726 r.append(' ');
3727 }
3728 r.append(a.info.name);
3729 }
3730 }
3731 if (r != null) {
3732 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 N = pkg.activities.size();
3736 r = null;
3737 for (i=0; i<N; i++) {
3738 PackageParser.Activity a = pkg.activities.get(i);
3739 mActivities.removeActivity(a, "activity");
3740 if (chatty) {
3741 if (r == null) {
3742 r = new StringBuilder(256);
3743 } else {
3744 r.append(' ');
3745 }
3746 r.append(a.info.name);
3747 }
3748 }
3749 if (r != null) {
3750 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 N = pkg.permissions.size();
3754 r = null;
3755 for (i=0; i<N; i++) {
3756 PackageParser.Permission p = pkg.permissions.get(i);
3757 boolean tree = false;
3758 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3759 if (bp == null) {
3760 tree = true;
3761 bp = mSettings.mPermissionTrees.get(p.info.name);
3762 }
3763 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003764 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 if (chatty) {
3766 if (r == null) {
3767 r = new StringBuilder(256);
3768 } else {
3769 r.append(' ');
3770 }
3771 r.append(p.info.name);
3772 }
3773 }
3774 }
3775 if (r != null) {
3776 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 N = pkg.instrumentation.size();
3780 r = null;
3781 for (i=0; i<N; i++) {
3782 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003783 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 if (chatty) {
3785 if (r == null) {
3786 r = new StringBuilder(256);
3787 } else {
3788 r.append(' ');
3789 }
3790 r.append(a.info.name);
3791 }
3792 }
3793 if (r != null) {
3794 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3795 }
3796 }
3797 }
3798
3799 private static final boolean isPackageFilename(String name) {
3800 return name != null && name.endsWith(".apk");
3801 }
3802
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003803 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3804 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3805 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3806 return true;
3807 }
3808 }
3809 return false;
3810 }
3811
3812 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003813 PackageParser.Package pkgInfo, boolean grantPermissions,
3814 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 // Make sure there are no dangling permission trees.
3816 Iterator<BasePermission> it = mSettings.mPermissionTrees
3817 .values().iterator();
3818 while (it.hasNext()) {
3819 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003820 if (bp.packageSetting == null) {
3821 // We may not yet have parsed the package, so just see if
3822 // we still know about its settings.
3823 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3824 }
3825 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003826 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 + " from package " + bp.sourcePackage);
3828 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003829 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3830 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3831 Slog.i(TAG, "Removing old permission tree: " + bp.name
3832 + " from package " + bp.sourcePackage);
3833 grantPermissions = true;
3834 it.remove();
3835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 }
3837 }
3838
3839 // Make sure all dynamic permissions have been assigned to a package,
3840 // and make sure there are no dangling permissions.
3841 it = mSettings.mPermissions.values().iterator();
3842 while (it.hasNext()) {
3843 BasePermission bp = it.next();
3844 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3845 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3846 + bp.name + " pkg=" + bp.sourcePackage
3847 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003848 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 BasePermission tree = findPermissionTreeLP(bp.name);
3850 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003851 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 bp.perm = new PackageParser.Permission(tree.perm.owner,
3853 new PermissionInfo(bp.pendingInfo));
3854 bp.perm.info.packageName = tree.perm.info.packageName;
3855 bp.perm.info.name = bp.name;
3856 bp.uid = tree.uid;
3857 }
3858 }
3859 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003860 if (bp.packageSetting == null) {
3861 // We may not yet have parsed the package, so just see if
3862 // we still know about its settings.
3863 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3864 }
3865 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003866 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 + " from package " + bp.sourcePackage);
3868 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003869 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3870 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3871 Slog.i(TAG, "Removing old permission: " + bp.name
3872 + " from package " + bp.sourcePackage);
3873 grantPermissions = true;
3874 it.remove();
3875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 }
3877 }
3878
3879 // Now update the permissions for all packages, in particular
3880 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003881 if (grantPermissions) {
3882 for (PackageParser.Package pkg : mPackages.values()) {
3883 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003884 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003885 }
3886 }
3887 }
3888
3889 if (pkgInfo != null) {
3890 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 }
3892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3895 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3896 if (ps == null) {
3897 return;
3898 }
3899 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003900 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 if (replace) {
3903 ps.permissionsFixed = false;
3904 if (gp == ps) {
3905 gp.grantedPermissions.clear();
3906 gp.gids = mGlobalGids;
3907 }
3908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 if (gp.gids == null) {
3911 gp.gids = mGlobalGids;
3912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 final int N = pkg.requestedPermissions.size();
3915 for (int i=0; i<N; i++) {
3916 String name = pkg.requestedPermissions.get(i);
3917 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 if (false) {
3919 if (gp != ps) {
3920 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003921 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 }
3923 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003924 if (bp != null && bp.packageSetting != null) {
3925 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003927 boolean allowedSig = false;
3928 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3929 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003931 } else if (bp.packageSetting == null) {
3932 // This permission is invalid; skip it.
3933 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003934 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3935 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003936 allowed = (checkSignaturesLP(
3937 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003939 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003941 if (!allowed && bp.protectionLevel
3942 == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003943 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 // For updated system applications, the signatureOrSystem permission
3945 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003946 if (isUpdatedSystemApp(pkg)) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003947 PackageSetting sysPs = mSettings.getDisabledSystemPkg(
3948 pkg.packageName);
3949 final GrantedPermissions origGp = sysPs.sharedUser != null
3950 ? sysPs.sharedUser : sysPs;
3951 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 allowed = true;
3953 } else {
3954 allowed = false;
3955 }
3956 } else {
3957 allowed = true;
3958 }
3959 }
3960 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003961 if (allowed) {
3962 allowedSig = true;
3963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 } else {
3965 allowed = false;
3966 }
3967 if (false) {
3968 if (gp != ps) {
3969 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3970 }
3971 }
3972 if (allowed) {
3973 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3974 && ps.permissionsFixed) {
3975 // If this is an existing, non-system package, then
3976 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003977 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003979 // Except... if this is a permission that was added
3980 // to the platform (note: need to only do this when
3981 // updating the platform).
3982 final int NP = PackageParser.NEW_PERMISSIONS.length;
3983 for (int ip=0; ip<NP; ip++) {
3984 final PackageParser.NewPermissionInfo npi
3985 = PackageParser.NEW_PERMISSIONS[ip];
3986 if (npi.name.equals(perm)
3987 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3988 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003989 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003990 + pkg.packageName);
3991 break;
3992 }
3993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 }
3995 }
3996 if (allowed) {
3997 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003998 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 gp.grantedPermissions.add(perm);
4000 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004001 } else if (!ps.haveGids) {
4002 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 }
4004 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004005 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 + " to package " + pkg.packageName
4007 + " because it was previously installed without");
4008 }
4009 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004010 if (gp.grantedPermissions.remove(perm)) {
4011 changedPermission = true;
4012 gp.gids = removeInts(gp.gids, bp.gids);
4013 Slog.i(TAG, "Un-granting permission " + perm
4014 + " from package " + pkg.packageName
4015 + " (protectionLevel=" + bp.protectionLevel
4016 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4017 + ")");
4018 } else {
4019 Slog.w(TAG, "Not granting permission " + perm
4020 + " to package " + pkg.packageName
4021 + " (protectionLevel=" + bp.protectionLevel
4022 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4023 + ")");
4024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 }
4026 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004027 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 + " in package " + pkg.packageName);
4029 }
4030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004031
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004032 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004033 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4034 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 // This is the first that we have heard about this package, so the
4036 // permissions we have now selected are fixed until explicitly
4037 // changed.
4038 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004040 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 private final class ActivityIntentResolver
4044 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004045 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004047 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 }
4049
Mihai Preda074edef2009-05-18 17:13:31 +02004050 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004052 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4054 }
4055
Mihai Predaeae850c2009-05-13 10:13:48 +02004056 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4057 ArrayList<PackageParser.Activity> packageActivities) {
4058 if (packageActivities == null) {
4059 return null;
4060 }
4061 mFlags = flags;
4062 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4063 int N = packageActivities.size();
4064 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4065 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004066
4067 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004068 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004069 intentFilters = packageActivities.get(i).intents;
4070 if (intentFilters != null && intentFilters.size() > 0) {
4071 listCut.add(intentFilters);
4072 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004073 }
4074 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4075 }
4076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 public final void addActivity(PackageParser.Activity a, String type) {
Kenny Root502e9a42011-01-10 13:48:15 -08004078 final boolean systemApp = isSystemApp(a.info.applicationInfo);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004079 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 if (SHOW_INFO || Config.LOGV) Log.v(
4081 TAG, " " + type + " " +
4082 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4083 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4084 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004085 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root502e9a42011-01-10 13:48:15 -08004087 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4088 intent.setPriority(0);
4089 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
4090 + a.className + " with priority > 0, forcing to 0");
4091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 if (SHOW_INFO || Config.LOGV) {
4093 Log.v(TAG, " IntentFilter:");
4094 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4095 }
4096 if (!intent.debugCheck()) {
4097 Log.w(TAG, "==> For Activity " + a.info.name);
4098 }
4099 addFilter(intent);
4100 }
4101 }
4102
4103 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004104 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 if (SHOW_INFO || Config.LOGV) Log.v(
4106 TAG, " " + type + " " +
4107 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4108 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4109 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004110 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4112 if (SHOW_INFO || Config.LOGV) {
4113 Log.v(TAG, " IntentFilter:");
4114 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4115 }
4116 removeFilter(intent);
4117 }
4118 }
4119
4120 @Override
4121 protected boolean allowFilterResult(
4122 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4123 ActivityInfo filterAi = filter.activity.info;
4124 for (int i=dest.size()-1; i>=0; i--) {
4125 ActivityInfo destAi = dest.get(i).activityInfo;
4126 if (destAi.name == filterAi.name
4127 && destAi.packageName == filterAi.packageName) {
4128 return false;
4129 }
4130 }
4131 return true;
4132 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004135 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4136 return info.activity.owner.packageName;
4137 }
4138
4139 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4141 int match) {
4142 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4143 return null;
4144 }
4145 final PackageParser.Activity activity = info.activity;
4146 if (mSafeMode && (activity.info.applicationInfo.flags
4147 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4148 return null;
4149 }
4150 final ResolveInfo res = new ResolveInfo();
4151 res.activityInfo = PackageParser.generateActivityInfo(activity,
4152 mFlags);
4153 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4154 res.filter = info;
4155 }
4156 res.priority = info.getPriority();
4157 res.preferredOrder = activity.owner.mPreferredOrder;
4158 //System.out.println("Result: " + res.activityInfo.className +
4159 // " = " + res.priority);
4160 res.match = match;
4161 res.isDefault = info.hasDefault;
4162 res.labelRes = info.labelRes;
4163 res.nonLocalizedLabel = info.nonLocalizedLabel;
4164 res.icon = info.icon;
4165 return res;
4166 }
4167
4168 @Override
4169 protected void sortResults(List<ResolveInfo> results) {
4170 Collections.sort(results, mResolvePrioritySorter);
4171 }
4172
4173 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004174 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004176 out.print(prefix); out.print(
4177 Integer.toHexString(System.identityHashCode(filter.activity)));
4178 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004179 out.print(filter.activity.getComponentShortName());
4180 out.print(" filter ");
4181 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 }
4183
4184// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4185// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4186// final List<ResolveInfo> retList = Lists.newArrayList();
4187// while (i.hasNext()) {
4188// final ResolveInfo resolveInfo = i.next();
4189// if (isEnabledLP(resolveInfo.activityInfo)) {
4190// retList.add(resolveInfo);
4191// }
4192// }
4193// return retList;
4194// }
4195
4196 // Keys are String (activity class name), values are Activity.
4197 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4198 = new HashMap<ComponentName, PackageParser.Activity>();
4199 private int mFlags;
4200 }
4201
4202 private final class ServiceIntentResolver
4203 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004204 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004206 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 }
4208
Mihai Preda074edef2009-05-18 17:13:31 +02004209 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004211 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4213 }
4214
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004215 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4216 ArrayList<PackageParser.Service> packageServices) {
4217 if (packageServices == null) {
4218 return null;
4219 }
4220 mFlags = flags;
4221 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4222 int N = packageServices.size();
4223 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4224 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4225
4226 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4227 for (int i = 0; i < N; ++i) {
4228 intentFilters = packageServices.get(i).intents;
4229 if (intentFilters != null && intentFilters.size() > 0) {
4230 listCut.add(intentFilters);
4231 }
4232 }
4233 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4234 }
4235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004236 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004237 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 if (SHOW_INFO || Config.LOGV) Log.v(
4239 TAG, " " + (s.info.nonLocalizedLabel != null
4240 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4241 if (SHOW_INFO || Config.LOGV) Log.v(
4242 TAG, " Class=" + s.info.name);
4243 int NI = s.intents.size();
4244 int j;
4245 for (j=0; j<NI; j++) {
4246 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4247 if (SHOW_INFO || Config.LOGV) {
4248 Log.v(TAG, " IntentFilter:");
4249 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4250 }
4251 if (!intent.debugCheck()) {
4252 Log.w(TAG, "==> For Service " + s.info.name);
4253 }
4254 addFilter(intent);
4255 }
4256 }
4257
4258 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004259 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 if (SHOW_INFO || Config.LOGV) Log.v(
4261 TAG, " " + (s.info.nonLocalizedLabel != null
4262 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4263 if (SHOW_INFO || Config.LOGV) Log.v(
4264 TAG, " Class=" + s.info.name);
4265 int NI = s.intents.size();
4266 int j;
4267 for (j=0; j<NI; j++) {
4268 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4269 if (SHOW_INFO || Config.LOGV) {
4270 Log.v(TAG, " IntentFilter:");
4271 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4272 }
4273 removeFilter(intent);
4274 }
4275 }
4276
4277 @Override
4278 protected boolean allowFilterResult(
4279 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4280 ServiceInfo filterSi = filter.service.info;
4281 for (int i=dest.size()-1; i>=0; i--) {
4282 ServiceInfo destAi = dest.get(i).serviceInfo;
4283 if (destAi.name == filterSi.name
4284 && destAi.packageName == filterSi.packageName) {
4285 return false;
4286 }
4287 }
4288 return true;
4289 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004292 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4293 return info.service.owner.packageName;
4294 }
4295
4296 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4298 int match) {
Jason parksa3cdaa52011-01-13 14:15:43 -06004299 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4301 return null;
4302 }
4303 final PackageParser.Service service = info.service;
4304 if (mSafeMode && (service.info.applicationInfo.flags
4305 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4306 return null;
4307 }
4308 final ResolveInfo res = new ResolveInfo();
4309 res.serviceInfo = PackageParser.generateServiceInfo(service,
4310 mFlags);
4311 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4312 res.filter = filter;
4313 }
4314 res.priority = info.getPriority();
4315 res.preferredOrder = service.owner.mPreferredOrder;
4316 //System.out.println("Result: " + res.activityInfo.className +
4317 // " = " + res.priority);
4318 res.match = match;
4319 res.isDefault = info.hasDefault;
4320 res.labelRes = info.labelRes;
4321 res.nonLocalizedLabel = info.nonLocalizedLabel;
4322 res.icon = info.icon;
4323 return res;
4324 }
4325
4326 @Override
4327 protected void sortResults(List<ResolveInfo> results) {
4328 Collections.sort(results, mResolvePrioritySorter);
4329 }
4330
4331 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004332 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004334 out.print(prefix); out.print(
4335 Integer.toHexString(System.identityHashCode(filter.service)));
4336 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004337 out.print(filter.service.getComponentShortName());
4338 out.print(" filter ");
4339 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 }
4341
4342// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4343// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4344// final List<ResolveInfo> retList = Lists.newArrayList();
4345// while (i.hasNext()) {
4346// final ResolveInfo resolveInfo = (ResolveInfo) i;
4347// if (isEnabledLP(resolveInfo.serviceInfo)) {
4348// retList.add(resolveInfo);
4349// }
4350// }
4351// return retList;
4352// }
4353
4354 // Keys are String (activity class name), values are Activity.
4355 private final HashMap<ComponentName, PackageParser.Service> mServices
4356 = new HashMap<ComponentName, PackageParser.Service>();
4357 private int mFlags;
4358 };
4359
4360 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4361 new Comparator<ResolveInfo>() {
4362 public int compare(ResolveInfo r1, ResolveInfo r2) {
4363 int v1 = r1.priority;
4364 int v2 = r2.priority;
4365 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4366 if (v1 != v2) {
4367 return (v1 > v2) ? -1 : 1;
4368 }
4369 v1 = r1.preferredOrder;
4370 v2 = r2.preferredOrder;
4371 if (v1 != v2) {
4372 return (v1 > v2) ? -1 : 1;
4373 }
4374 if (r1.isDefault != r2.isDefault) {
4375 return r1.isDefault ? -1 : 1;
4376 }
4377 v1 = r1.match;
4378 v2 = r2.match;
4379 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4380 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4381 }
4382 };
4383
4384 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4385 new Comparator<ProviderInfo>() {
4386 public int compare(ProviderInfo p1, ProviderInfo p2) {
4387 final int v1 = p1.initOrder;
4388 final int v2 = p2.initOrder;
4389 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4390 }
4391 };
4392
Kenny Root93565c4b2010-06-18 15:46:06 -07004393 private static final boolean DEBUG_OBB = false;
4394
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004395 private static final void sendPackageBroadcast(String action, String pkg,
4396 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 IActivityManager am = ActivityManagerNative.getDefault();
4398 if (am != null) {
4399 try {
4400 final Intent intent = new Intent(action,
4401 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4402 if (extras != null) {
4403 intent.putExtras(extras);
4404 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004405 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004406 am.broadcastIntent(null, intent, null, finishedReceiver,
4407 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004408 } catch (RemoteException ex) {
4409 }
4410 }
4411 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004412
4413 public String nextPackageToClean(String lastPackage) {
4414 synchronized (mPackages) {
4415 if (!mMediaMounted) {
4416 // If the external storage is no longer mounted at this point,
4417 // the caller may not have been able to delete all of this
4418 // packages files and can not delete any more. Bail.
4419 return null;
4420 }
4421 if (lastPackage != null) {
4422 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4423 }
4424 return mSettings.mPackagesToBeCleaned.size() > 0
4425 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4426 }
4427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004429 void schedulePackageCleaning(String packageName) {
4430 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4431 }
4432
4433 void startCleaningPackages() {
4434 synchronized (mPackages) {
4435 if (!mMediaMounted) {
4436 return;
4437 }
4438 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4439 return;
4440 }
4441 }
4442 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4443 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4444 IActivityManager am = ActivityManagerNative.getDefault();
4445 if (am != null) {
4446 try {
4447 am.startService(null, intent, null);
4448 } catch (RemoteException e) {
4449 }
4450 }
4451 }
4452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 private final class AppDirObserver extends FileObserver {
4454 public AppDirObserver(String path, int mask, boolean isrom) {
4455 super(path, mask);
4456 mRootDir = path;
4457 mIsRom = isrom;
4458 }
4459
4460 public void onEvent(int event, String path) {
4461 String removedPackage = null;
4462 int removedUid = -1;
4463 String addedPackage = null;
4464 int addedUid = -1;
4465
4466 synchronized (mInstallLock) {
4467 String fullPathStr = null;
4468 File fullPath = null;
4469 if (path != null) {
4470 fullPath = new File(mRootDir, path);
4471 fullPathStr = fullPath.getPath();
4472 }
4473
4474 if (Config.LOGV) Log.v(
4475 TAG, "File " + fullPathStr + " changed: "
4476 + Integer.toHexString(event));
4477
4478 if (!isPackageFilename(path)) {
4479 if (Config.LOGV) Log.v(
4480 TAG, "Ignoring change of non-package file: " + fullPathStr);
4481 return;
4482 }
4483
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004484 // Ignore packages that are being installed or
4485 // have just been installed.
4486 if (ignoreCodePath(fullPathStr)) {
4487 return;
4488 }
4489 PackageParser.Package p = null;
4490 synchronized (mPackages) {
4491 p = mAppDirs.get(fullPathStr);
4492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004494 if (p != null) {
4495 removePackageLI(p, true);
4496 removedPackage = p.applicationInfo.packageName;
4497 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 }
4499 }
4500
4501 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004503 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004504 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4505 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 PackageParser.PARSE_CHATTY |
4507 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004508 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4509 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 if (p != null) {
4511 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004512 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004513 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 }
4515 addedPackage = p.applicationInfo.packageName;
4516 addedUid = p.applicationInfo.uid;
4517 }
4518 }
4519 }
4520
4521 synchronized (mPackages) {
4522 mSettings.writeLP();
4523 }
4524 }
4525
4526 if (removedPackage != null) {
4527 Bundle extras = new Bundle(1);
4528 extras.putInt(Intent.EXTRA_UID, removedUid);
4529 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004530 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4531 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 }
4533 if (addedPackage != null) {
4534 Bundle extras = new Bundle(1);
4535 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004536 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4537 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 }
4539 }
4540
4541 private final String mRootDir;
4542 private final boolean mIsRom;
4543 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 /* Called when a downloaded package installation has been confirmed by the user */
4546 public void installPackage(
4547 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004548 installPackage(packageURI, observer, flags, null);
4549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004550
Jacek Surazski65e13172009-04-28 15:26:38 +02004551 /* Called when a downloaded package installation has been confirmed by the user */
4552 public void installPackage(
4553 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4554 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004555 mContext.enforceCallingOrSelfPermission(
4556 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004557
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004558 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004559 msg.obj = new InstallParams(packageURI, observer, flags,
4560 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004561 mHandler.sendMessage(msg);
4562 }
4563
Christopher Tate1bb69062010-02-19 17:02:12 -08004564 public void finishPackageInstall(int token) {
4565 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4566 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4567 mHandler.sendMessage(msg);
4568 }
4569
Dianne Hackborn880119b2010-11-18 22:26:40 -08004570 public void setInstallerPackageName(String targetPackage,
4571 String installerPackageName) {
4572 PackageSetting pkgSetting;
4573 final int uid = Binder.getCallingUid();
4574 final int permission = mContext.checkCallingPermission(
4575 android.Manifest.permission.INSTALL_PACKAGES);
4576 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4577 synchronized (mPackages) {
4578 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
4579 if (targetPackageSetting == null) {
4580 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
4581 }
4582
4583 PackageSetting installerPackageSetting;
4584 if (installerPackageName != null) {
4585 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
4586 if (installerPackageSetting == null) {
4587 throw new IllegalArgumentException("Unknown installer package: "
4588 + installerPackageName);
4589 }
4590 } else {
4591 installerPackageSetting = null;
4592 }
4593
4594 Signature[] callerSignature;
4595 Object obj = mSettings.getUserIdLP(uid);
4596 if (obj != null) {
4597 if (obj instanceof SharedUserSetting) {
4598 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
4599 } else if (obj instanceof PackageSetting) {
4600 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
4601 } else {
4602 throw new SecurityException("Bad object " + obj + " for uid " + uid);
4603 }
4604 } else {
4605 throw new SecurityException("Unknown calling uid " + uid);
4606 }
4607
4608 // Verify: can't set installerPackageName to a package that is
4609 // not signed with the same cert as the caller.
4610 if (installerPackageSetting != null) {
4611 if (checkSignaturesLP(callerSignature,
4612 installerPackageSetting.signatures.mSignatures)
4613 != PackageManager.SIGNATURE_MATCH) {
4614 throw new SecurityException(
4615 "Caller does not have same cert as new installer package "
4616 + installerPackageName);
4617 }
4618 }
4619
4620 // Verify: if target already has an installer package, it must
4621 // be signed with the same cert as the caller.
4622 if (targetPackageSetting.installerPackageName != null) {
4623 PackageSetting setting = mSettings.mPackages.get(
4624 targetPackageSetting.installerPackageName);
4625 // If the currently set package isn't valid, then it's always
4626 // okay to change it.
4627 if (setting != null) {
4628 if (checkSignaturesLP(callerSignature,
4629 setting.signatures.mSignatures)
4630 != PackageManager.SIGNATURE_MATCH) {
4631 throw new SecurityException(
4632 "Caller does not have same cert as old installer package "
4633 + targetPackageSetting.installerPackageName);
4634 }
4635 }
4636 }
4637
4638 // Okay!
4639 targetPackageSetting.installerPackageName = installerPackageName;
4640 scheduleWriteSettingsLocked();
4641 }
4642 }
4643
Kenny Root5d40fe92011-01-14 10:54:46 -08004644 public void setPackageObbPaths(String packageName, String[] paths) {
Kenny Root93565c4b2010-06-18 15:46:06 -07004645 if (DEBUG_OBB)
Kenny Root5d40fe92011-01-14 10:54:46 -08004646 Log.v(TAG, "Setting .obb paths for " + packageName + " to: " + Arrays.toString(paths));
4647 final int uid = Binder.getCallingUid();
4648 final int permission = mContext.checkCallingPermission(
4649 android.Manifest.permission.INSTALL_PACKAGES);
4650 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4651 if (!allowedByPermission) {
4652 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4653 + Binder.getCallingPid());
4654 }
4655 synchronized (mPackages) {
4656 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
4657 if (pkgSetting == null) {
4658 throw new IllegalArgumentException("Unknown package: " + packageName);
4659 }
4660
4661 if (paths != null) {
4662 if (paths.length == 0) {
4663 // Don't bother storing an empty array.
4664 paths = null;
4665 } else {
4666 // Don't allow the caller to manipulate our copy of the
4667 // list.
4668 paths = paths.clone();
4669 }
4670 }
4671
4672 // Only write settings file if the new and old settings are not the
4673 // same.
4674 if (!Arrays.equals(paths, pkgSetting.obbPathStrings)) {
4675 pkgSetting.obbPathStrings = paths;
4676 mSettings.writeLP();
4677 }
4678 }
4679 }
4680
4681 public String[] getPackageObbPaths(String packageName) {
4682 if (DEBUG_OBB)
4683 Log.v(TAG, "Getting .obb paths for " + packageName);
Kenny Root93565c4b2010-06-18 15:46:06 -07004684 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004685 final int permission = mContext.checkCallingPermission(
4686 android.Manifest.permission.INSTALL_PACKAGES);
4687 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004688 synchronized (mPackages) {
Kenny Root5d40fe92011-01-14 10:54:46 -08004689 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
Kenny Root93565c4b2010-06-18 15:46:06 -07004690 if (pkgSetting == null) {
4691 throw new IllegalArgumentException("Unknown package: " + packageName);
4692 }
4693 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4694 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4695 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4696 + pkgSetting.userId);
4697 }
Kenny Root5d40fe92011-01-14 10:54:46 -08004698 return pkgSetting.obbPathStrings;
Kenny Root93565c4b2010-06-18 15:46:06 -07004699 }
4700 }
4701
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004702 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 // Queue up an async operation since the package installation may take a little while.
4704 mHandler.post(new Runnable() {
4705 public void run() {
4706 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004707 // Result object to be returned
4708 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004709 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004710 res.uid = -1;
4711 res.pkg = null;
4712 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004713 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004714 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004715 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004716 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004717 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004718 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004720
4721 // A restore should be performed at this point if (a) the install
4722 // succeeded, (b) the operation is not an update, and (c) the new
4723 // package has a backupAgent defined.
4724 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004725 boolean doRestore = (!update
4726 && res.pkg != null
4727 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004728
4729 // Set up the post-install work request bookkeeping. This will be used
4730 // and cleaned up by the post-install event handling regardless of whether
4731 // there's a restore pass performed. Token values are >= 1.
4732 int token;
4733 if (mNextInstallToken < 0) mNextInstallToken = 1;
4734 token = mNextInstallToken++;
4735
4736 PostInstallData data = new PostInstallData(args, res);
4737 mRunningInstalls.put(token, data);
4738 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4739
4740 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4741 // Pass responsibility to the Backup Manager. It will perform a
4742 // restore if appropriate, then pass responsibility back to the
4743 // Package Manager to run the post-install observer callbacks
4744 // and broadcasts.
4745 IBackupManager bm = IBackupManager.Stub.asInterface(
4746 ServiceManager.getService(Context.BACKUP_SERVICE));
4747 if (bm != null) {
4748 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4749 + " to BM for possible restore");
4750 try {
4751 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4752 } catch (RemoteException e) {
4753 // can't happen; the backup manager is local
4754 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004755 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004756 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004757 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004758 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004759 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004760 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004762 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004763
4764 if (!doRestore) {
4765 // No restore possible, or the Backup Manager was mysteriously not
4766 // available -- just fire the post-install work request directly.
4767 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4768 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4769 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004771 }
4772 });
4773 }
4774
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004775 abstract class HandlerParams {
4776 final static int MAX_RETRIES = 4;
4777 int retry = 0;
4778 final void startCopy() {
4779 try {
4780 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4781 retry++;
4782 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004783 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004784 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4785 handleServiceError();
4786 return;
4787 } else {
4788 handleStartCopy();
4789 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4790 mHandler.sendEmptyMessage(MCS_UNBIND);
4791 }
4792 } catch (RemoteException e) {
4793 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4794 mHandler.sendEmptyMessage(MCS_RECONNECT);
4795 }
4796 handleReturnCode();
4797 }
4798
4799 final void serviceError() {
4800 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4801 handleServiceError();
4802 handleReturnCode();
4803 }
4804 abstract void handleStartCopy() throws RemoteException;
4805 abstract void handleServiceError();
4806 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004807 }
4808
Kenny Root366949c2011-01-14 17:18:14 -08004809 class MeasureParams extends HandlerParams {
4810 private final PackageStats mStats;
4811 private boolean mSuccess;
4812
4813 private final IPackageStatsObserver mObserver;
4814
4815 public MeasureParams(PackageStats stats, boolean success,
4816 IPackageStatsObserver observer) {
4817 mObserver = observer;
4818 mStats = stats;
4819 mSuccess = success;
4820 }
4821
4822 @Override
4823 void handleStartCopy() throws RemoteException {
4824 final boolean mounted;
4825
4826 if (Environment.isExternalStorageEmulated()) {
4827 mounted = true;
4828 } else {
4829 final String status = Environment.getExternalStorageState();
4830
4831 mounted = status.equals(Environment.MEDIA_MOUNTED)
4832 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
4833 }
4834
4835 if (mounted) {
4836 final File externalCacheDir = Environment
4837 .getExternalStorageAppCacheDirectory(mStats.packageName);
4838 final long externalCacheSize = mContainerService
4839 .calculateDirectorySize(externalCacheDir.getPath());
4840 mStats.externalCacheSize = externalCacheSize;
4841
4842 final File externalDataDir = Environment
4843 .getExternalStorageAppDataDirectory(mStats.packageName);
4844 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
4845 .getPath());
4846
4847 if (externalCacheDir.getParentFile().equals(externalDataDir)) {
4848 externalDataSize -= externalCacheSize;
4849 }
4850 mStats.externalDataSize = externalDataSize;
4851
4852 final File externalMediaDir = Environment
4853 .getExternalStorageAppMediaDirectory(mStats.packageName);
4854 mStats.externalMediaSize = mContainerService
4855 .calculateDirectorySize(externalCacheDir.getPath());
4856 }
4857 }
4858
4859 @Override
4860 void handleReturnCode() {
4861 if (mObserver != null) {
4862 try {
4863 mObserver.onGetStatsCompleted(mStats, mSuccess);
4864 } catch (RemoteException e) {
4865 Slog.i(TAG, "Observer no longer exists.");
4866 }
4867 }
4868 }
4869
4870 @Override
4871 void handleServiceError() {
4872 Slog.e(TAG, "Could not measure application " + mStats.packageName
4873 + " external storage");
4874 }
4875 }
4876
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004877 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004878 final IPackageInstallObserver observer;
4879 int flags;
4880 final Uri packageURI;
4881 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004882 private InstallArgs mArgs;
4883 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004884 InstallParams(Uri packageURI,
4885 IPackageInstallObserver observer, int flags,
4886 String installerPackageName) {
4887 this.packageURI = packageURI;
4888 this.flags = flags;
4889 this.observer = observer;
4890 this.installerPackageName = installerPackageName;
4891 }
4892
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004893 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4894 String packageName = pkgLite.packageName;
4895 int installLocation = pkgLite.installLocation;
4896 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4897 synchronized (mPackages) {
4898 PackageParser.Package pkg = mPackages.get(packageName);
4899 if (pkg != null) {
4900 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4901 // Check for updated system application.
4902 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4903 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004904 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004905 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4906 }
4907 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4908 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004909 if (onSd) {
4910 // Install flag overrides everything.
4911 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4912 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004913 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004914 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4915 // Application explicitly specified internal.
4916 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4917 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4918 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004919 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004920 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004921 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004922 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4923 }
4924 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004925 }
4926 }
4927 } else {
4928 // Invalid install. Return error code
4929 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4930 }
4931 }
4932 }
4933 // All the special cases have been taken care of.
4934 // Return result based on recommended install location.
4935 if (onSd) {
4936 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4937 }
4938 return pkgLite.recommendedInstallLocation;
4939 }
4940
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004941 /*
4942 * Invoke remote method to get package information and install
4943 * location values. Override install location based on default
4944 * policy if needed and then create install arguments based
4945 * on the install location.
4946 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004947 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004948 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004949 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4950 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004951 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4952 if (onInt && onSd) {
4953 // Check if both bits are set.
4954 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4955 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4956 } else if (fwdLocked && onSd) {
4957 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004958 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004959 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004960 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07004962 final PackageInfoLite pkgLite;
4963 try {
4964 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4965 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4966 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
4967 } finally {
4968 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4969 }
4970
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004971 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004972 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4973 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4974 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4975 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4976 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004977 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4978 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4979 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004980 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4981 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004982 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004983 // Override with defaults if needed.
4984 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004985 if (!onSd && !onInt) {
4986 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004987 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4988 // Set the flag to install on external media.
4989 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004990 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004991 } else {
4992 // Make sure the flag for installing on external
4993 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004994 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004995 flags &= ~PackageManager.INSTALL_EXTERNAL;
4996 }
4997 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004998 }
4999 }
5000 // Create the file args now.
5001 mArgs = createInstallArgs(this);
5002 if (ret == PackageManager.INSTALL_SUCCEEDED) {
5003 // Create copy only if we are not in an erroneous state.
5004 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005005 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005006 }
5007 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005008 }
5009
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005010 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005011 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07005012 // If mArgs is null, then MCS couldn't be reached. When it
5013 // reconnects, it will try again to install. At that point, this
5014 // will succeed.
5015 if (mArgs != null) {
5016 processPendingInstall(mArgs, mRet);
5017 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005018 }
5019
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005020 @Override
5021 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005022 mArgs = createInstallArgs(this);
5023 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005024 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005025 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005026
5027 /*
5028 * Utility class used in movePackage api.
5029 * srcArgs and targetArgs are not set for invalid flags and make
5030 * sure to do null checks when invoking methods on them.
5031 * We probably want to return ErrorPrams for both failed installs
5032 * and moves.
5033 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005034 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005035 final IPackageMoveObserver observer;
5036 final int flags;
5037 final String packageName;
5038 final InstallArgs srcArgs;
5039 final InstallArgs targetArgs;
5040 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07005041
5042 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
5043 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005044 this.srcArgs = srcArgs;
5045 this.observer = observer;
5046 this.flags = flags;
5047 this.packageName = packageName;
5048 if (srcArgs != null) {
5049 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07005050 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005051 } else {
5052 targetArgs = null;
5053 }
5054 }
5055
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005056 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005057 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5058 // Check for storage space on target medium
5059 if (!targetArgs.checkFreeStorage(mContainerService)) {
5060 Log.w(TAG, "Insufficient storage to install");
5061 return;
5062 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005063 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005064 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005065 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005066 if (DEBUG_SD_INSTALL) {
5067 StringBuilder builder = new StringBuilder();
5068 if (srcArgs != null) {
5069 builder.append("src: ");
5070 builder.append(srcArgs.getCodePath());
5071 }
5072 if (targetArgs != null) {
5073 builder.append(" target : ");
5074 builder.append(targetArgs.getCodePath());
5075 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005076 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005077 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005078 }
5079
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005080 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005081 void handleReturnCode() {
5082 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005083 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5084 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5085 currentStatus = PackageManager.MOVE_SUCCEEDED;
5086 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5087 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5088 }
5089 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005090 }
5091
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005092 @Override
5093 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005094 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005095 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005096 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005097
5098 private InstallArgs createInstallArgs(InstallParams params) {
5099 if (installOnSd(params.flags)) {
5100 return new SdInstallArgs(params);
5101 } else {
5102 return new FileInstallArgs(params);
5103 }
5104 }
5105
Kenny Root85387d72010-08-26 10:13:11 -07005106 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
5107 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005108 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07005109 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005110 } else {
Kenny Root85387d72010-08-26 10:13:11 -07005111 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005112 }
5113 }
5114
Kenny Root85387d72010-08-26 10:13:11 -07005115 // Used by package mover
5116 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005117 if (installOnSd(flags)) {
5118 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5119 return new SdInstallArgs(packageURI, cid);
5120 } else {
Kenny Root85387d72010-08-26 10:13:11 -07005121 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005122 }
5123 }
5124
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005125 static abstract class InstallArgs {
5126 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005127 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005128 final int flags;
5129 final Uri packageURI;
5130 final String installerPackageName;
5131
5132 InstallArgs(Uri packageURI,
5133 IPackageInstallObserver observer, int flags,
5134 String installerPackageName) {
5135 this.packageURI = packageURI;
5136 this.flags = flags;
5137 this.observer = observer;
5138 this.installerPackageName = installerPackageName;
5139 }
5140
5141 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005142 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005143 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005144 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005145 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005146 abstract String getCodePath();
5147 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07005148 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005149 // Need installer lock especially for dex file removal.
5150 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005151 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005152 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005153 }
5154
5155 class FileInstallArgs extends InstallArgs {
5156 File installDir;
5157 String codeFileName;
5158 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07005159 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005160 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005161
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005162 FileInstallArgs(InstallParams params) {
5163 super(params.packageURI, params.observer,
5164 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005165 }
5166
Kenny Root85387d72010-08-26 10:13:11 -07005167 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005168 super(null, null, 0, null);
5169 File codeFile = new File(fullCodePath);
5170 installDir = codeFile.getParentFile();
5171 codeFileName = fullCodePath;
5172 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07005173 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005174 }
5175
Kenny Root85387d72010-08-26 10:13:11 -07005176 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005177 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07005178 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005179 String apkName = getNextCodePath(null, pkgName, ".apk");
5180 codeFileName = new File(installDir, apkName + ".apk").getPath();
5181 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07005182 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005183 }
5184
Kenny Root11128572010-10-11 10:51:32 -07005185 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5186 try {
5187 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5188 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5189 return imcs.checkFreeStorage(false, packageURI);
5190 } finally {
5191 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5192 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005193 }
5194
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005195 String getCodePath() {
5196 return codeFileName;
5197 }
5198
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005199 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005200 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005201 codeFileName = createTempPackageFile(installDir).getPath();
5202 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005203 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005204 }
5205
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005206 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005207 if (temp) {
5208 // Generate temp file name
5209 createCopyFile();
5210 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005211 // Get a ParcelFileDescriptor to write to the output file
5212 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005213 if (!created) {
5214 try {
5215 codeFile.createNewFile();
5216 // Set permissions
5217 if (!setPermissions()) {
5218 // Failed setting permissions.
5219 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5220 }
5221 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005222 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005223 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5224 }
5225 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005226 ParcelFileDescriptor out = null;
5227 try {
Kenny Root85387d72010-08-26 10:13:11 -07005228 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005229 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005230 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005231 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5232 }
5233 // Copy the resource now
5234 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5235 try {
Kenny Root11128572010-10-11 10:51:32 -07005236 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5237 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005238 if (imcs.copyResource(packageURI, out)) {
5239 ret = PackageManager.INSTALL_SUCCEEDED;
5240 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 } finally {
5242 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005243 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005244 }
Kenny Root85387d72010-08-26 10:13:11 -07005245
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005246 return ret;
5247 }
5248
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005249 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005250 if (status != PackageManager.INSTALL_SUCCEEDED) {
5251 cleanUp();
5252 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005253 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005254 }
5255
5256 boolean doRename(int status, final String pkgName, String oldCodePath) {
5257 if (status != PackageManager.INSTALL_SUCCEEDED) {
5258 cleanUp();
5259 return false;
5260 } else {
5261 // Rename based on packageName
5262 File codeFile = new File(getCodePath());
5263 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5264 File desFile = new File(installDir, apkName + ".apk");
5265 if (!codeFile.renameTo(desFile)) {
5266 return false;
5267 }
5268 // Reset paths since the file has been renamed.
5269 codeFileName = desFile.getPath();
5270 resourceFileName = getResourcePathFromCodePath();
5271 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005272 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005273 // Failed setting permissions.
5274 return false;
5275 }
5276 return true;
5277 }
5278 }
5279
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005280 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005281 if (status != PackageManager.INSTALL_SUCCEEDED) {
5282 cleanUp();
5283 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005284 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005285 }
5286
5287 String getResourcePath() {
5288 return resourceFileName;
5289 }
5290
5291 String getResourcePathFromCodePath() {
5292 String codePath = getCodePath();
5293 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5294 String apkNameOnly = getApkName(codePath);
5295 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5296 } else {
5297 return codePath;
5298 }
5299 }
5300
Kenny Root85387d72010-08-26 10:13:11 -07005301 @Override
5302 String getNativeLibraryPath() {
5303 return libraryPath;
5304 }
5305
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005306 private boolean cleanUp() {
5307 boolean ret = true;
5308 String sourceDir = getCodePath();
5309 String publicSourceDir = getResourcePath();
5310 if (sourceDir != null) {
5311 File sourceFile = new File(sourceDir);
5312 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005313 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005314 ret = false;
5315 }
5316 // Delete application's code and resources
5317 sourceFile.delete();
5318 }
5319 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5320 final File publicSourceFile = new File(publicSourceDir);
5321 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005322 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005323 }
5324 if (publicSourceFile.exists()) {
5325 publicSourceFile.delete();
5326 }
5327 }
5328 return ret;
5329 }
5330
5331 void cleanUpResourcesLI() {
5332 String sourceDir = getCodePath();
5333 if (cleanUp() && mInstaller != null) {
5334 int retCode = mInstaller.rmdex(sourceDir);
5335 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005336 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005337 + " at location "
5338 + sourceDir + ", retcode=" + retCode);
5339 // we don't consider this to be a failure of the core package deletion
5340 }
5341 }
5342 }
5343
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005344 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005345 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005346 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005347 final int filePermissions =
5348 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5349 |FileUtils.S_IROTH;
5350 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5351 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005352 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005353 getCodePath()
5354 + ". The return code was: " + retCode);
5355 // TODO Define new internal error
5356 return false;
5357 }
5358 return true;
5359 }
5360 return true;
5361 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005362
5363 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005364 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005365 cleanUpResourcesLI();
5366 return true;
5367 }
Kenny Root85387d72010-08-26 10:13:11 -07005368
5369 private boolean isFwdLocked() {
5370 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5371 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005372 }
5373
5374 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005375 static final String RES_FILE_NAME = "pkg.apk";
5376
Kenny Root85387d72010-08-26 10:13:11 -07005377 String cid;
5378 String packagePath;
5379 String libraryPath;
5380
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005381 SdInstallArgs(InstallParams params) {
5382 super(params.packageURI, params.observer,
5383 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005384 }
5385
Kenny Root85387d72010-08-26 10:13:11 -07005386 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005387 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005388 // Extract cid from fullCodePath
5389 int eidx = fullCodePath.lastIndexOf("/");
5390 String subStr1 = fullCodePath.substring(0, eidx);
5391 int sidx = subStr1.lastIndexOf("/");
5392 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005393 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005394 }
5395
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005396 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005397 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5398 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005399 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005400 }
5401
5402 SdInstallArgs(Uri packageURI, String cid) {
5403 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005404 this.cid = cid;
5405 }
5406
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005407 void createCopyFile() {
5408 cid = getTempContainerId();
5409 }
5410
Kenny Root11128572010-10-11 10:51:32 -07005411 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5412 try {
5413 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5414 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5415 return imcs.checkFreeStorage(true, packageURI);
5416 } finally {
5417 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5418 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005419 }
5420
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005421 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005422 if (temp) {
5423 createCopyFile();
5424 }
Kenny Root11128572010-10-11 10:51:32 -07005425
5426 final String newCachePath;
5427 try {
5428 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5429 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5430 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5431 getEncryptKey(), RES_FILE_NAME);
5432 } finally {
5433 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5434 }
5435
Kenny Root85387d72010-08-26 10:13:11 -07005436 if (newCachePath != null) {
5437 setCachePath(newCachePath);
5438 return PackageManager.INSTALL_SUCCEEDED;
5439 } else {
5440 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5441 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005442 }
5443
5444 @Override
5445 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005446 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005447 }
5448
5449 @Override
5450 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005451 return packagePath;
5452 }
5453
5454 @Override
5455 String getNativeLibraryPath() {
5456 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005457 }
5458
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005459 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005460 if (status != PackageManager.INSTALL_SUCCEEDED) {
5461 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005462 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005463 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005464 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005465 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005466 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5467 Process.SYSTEM_UID);
5468 if (newCachePath != null) {
5469 setCachePath(newCachePath);
5470 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005471 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5472 }
5473 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005474 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005475 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005476 }
5477
5478 boolean doRename(int status, final String pkgName,
5479 String oldCodePath) {
5480 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005481 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005482 if (PackageHelper.isContainerMounted(cid)) {
5483 // Unmount the container
5484 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005485 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005486 return false;
5487 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005488 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005489 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005490 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5491 " which might be stale. Will try to clean up.");
5492 // Clean up the stale container and proceed to recreate.
5493 if (!PackageHelper.destroySdDir(newCacheId)) {
5494 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5495 return false;
5496 }
5497 // Successfully cleaned up stale container. Try to rename again.
5498 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5499 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5500 + " inspite of cleaning it up.");
5501 return false;
5502 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005503 }
5504 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005505 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005506 newCachePath = PackageHelper.mountSdDir(newCacheId,
5507 getEncryptKey(), Process.SYSTEM_UID);
5508 } else {
5509 newCachePath = PackageHelper.getSdDir(newCacheId);
5510 }
5511 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005512 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005513 return false;
5514 }
5515 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005516 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005517 " at new path: " + newCachePath);
5518 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005519 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005520 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005521 }
5522
Kenny Root85387d72010-08-26 10:13:11 -07005523 private void setCachePath(String newCachePath) {
5524 File cachePath = new File(newCachePath);
5525 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5526 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5527 }
5528
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005529 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005530 if (status != PackageManager.INSTALL_SUCCEEDED) {
5531 cleanUp();
5532 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005533 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005534 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005535 PackageHelper.mountSdDir(cid,
5536 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005537 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005538 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005539 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005540 }
5541
5542 private void cleanUp() {
5543 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005544 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005545 }
5546
5547 void cleanUpResourcesLI() {
5548 String sourceFile = getCodePath();
5549 // Remove dex file
5550 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005551 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005552 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005553 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005554 + " at location "
5555 + sourceFile.toString() + ", retcode=" + retCode);
5556 // we don't consider this to be a failure of the core package deletion
5557 }
5558 }
5559 cleanUp();
5560 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005561
5562 boolean matchContainer(String app) {
5563 if (cid.startsWith(app)) {
5564 return true;
5565 }
5566 return false;
5567 }
5568
5569 String getPackageName() {
5570 int idx = cid.lastIndexOf("-");
5571 if (idx == -1) {
5572 return cid;
5573 }
5574 return cid.substring(0, idx);
5575 }
5576
5577 boolean doPostDeleteLI(boolean delete) {
5578 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005579 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005580 if (mounted) {
5581 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005582 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005583 }
5584 if (ret && delete) {
5585 cleanUpResourcesLI();
5586 }
5587 return ret;
5588 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005589 };
5590
5591 // Utility method used to create code paths based on package name and available index.
5592 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5593 String idxStr = "";
5594 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005595 // Fall back to default value of idx=1 if prefix is not
5596 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005597 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005598 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005599 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005600 if (subStr.endsWith(suffix)) {
5601 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005602 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005603 // If oldCodePath already contains prefix find out the
5604 // ending index to either increment or decrement.
5605 int sidx = subStr.lastIndexOf(prefix);
5606 if (sidx != -1) {
5607 subStr = subStr.substring(sidx + prefix.length());
5608 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005609 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5610 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005611 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005612 try {
5613 idx = Integer.parseInt(subStr);
5614 if (idx <= 1) {
5615 idx++;
5616 } else {
5617 idx--;
5618 }
5619 } catch(NumberFormatException e) {
5620 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005621 }
5622 }
5623 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005624 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005625 return prefix + idxStr;
5626 }
5627
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005628 // Utility method used to ignore ADD/REMOVE events
5629 // by directory observer.
5630 private static boolean ignoreCodePath(String fullPathStr) {
5631 String apkName = getApkName(fullPathStr);
5632 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5633 if (idx != -1 && ((idx+1) < apkName.length())) {
5634 // Make sure the package ends with a numeral
5635 String version = apkName.substring(idx+1);
5636 try {
5637 Integer.parseInt(version);
5638 return true;
5639 } catch (NumberFormatException e) {}
5640 }
5641 return false;
5642 }
5643
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005644 // Utility method that returns the relative package path with respect
5645 // to the installation directory. Like say for /data/data/com.test-1.apk
5646 // string com.test-1 is returned.
5647 static String getApkName(String codePath) {
5648 if (codePath == null) {
5649 return null;
5650 }
5651 int sidx = codePath.lastIndexOf("/");
5652 int eidx = codePath.lastIndexOf(".");
5653 if (eidx == -1) {
5654 eidx = codePath.length();
5655 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005656 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005657 return null;
5658 }
5659 return codePath.substring(sidx+1, eidx);
5660 }
5661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 class PackageInstalledInfo {
5663 String name;
5664 int uid;
5665 PackageParser.Package pkg;
5666 int returnCode;
5667 PackageRemovedInfo removedInfo;
5668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 /*
5671 * Install a non-existing package.
5672 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005673 private void installNewPackageLI(PackageParser.Package pkg,
5674 int parseFlags,
5675 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005676 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005678 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005679
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005680 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 res.name = pkgName;
5682 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005683 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5684 // A package with the same name is already installed, though
5685 // it has been renamed to an older name. The package we
5686 // are trying to install should be installed as an update to
5687 // the existing one, but that has not been requested, so bail.
5688 Slog.w(TAG, "Attempt to re-install " + pkgName
5689 + " without first uninstalling package running as "
5690 + mSettings.mRenamedPackages.get(pkgName));
5691 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5692 return;
5693 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005694 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005696 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 + " without first uninstalling.");
5698 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5699 return;
5700 }
5701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005703 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5704 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005706 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5708 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5709 }
5710 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005711 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005712 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 res);
5714 // delete the partially installed application. the data directory will have to be
5715 // restored if it was already existing
5716 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5717 // remove package from internal structures. Note that we want deletePackageX to
5718 // delete the package data and cache directories that it created in
5719 // scanPackageLocked, unless those directories existed before we even tried to
5720 // install.
5721 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005722 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005724 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 }
5726 }
5727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005728
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005729 private void replacePackageLI(PackageParser.Package pkg,
5730 int parseFlags,
5731 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005732 String installerPackageName, PackageInstalledInfo res) {
5733
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005734 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005735 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 // First find the old package info and check signatures
5737 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005738 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005739 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005740 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5742 return;
5743 }
5744 }
Kenny Root85387d72010-08-26 10:13:11 -07005745 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005746 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005747 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005749 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 }
5751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005753 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005754 PackageParser.Package pkg,
5755 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005756 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 PackageParser.Package newPackage = null;
5758 String pkgName = deletedPackage.packageName;
5759 boolean deletedPkg = true;
5760 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005761
Jacek Surazski65e13172009-04-28 15:26:38 +02005762 String oldInstallerPackageName = null;
5763 synchronized (mPackages) {
5764 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005766
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005767 long origUpdateTime;
5768 if (pkg.mExtras != null) {
5769 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5770 } else {
5771 origUpdateTime = 0;
5772 }
5773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005775 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005776 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005777 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5779 deletedPkg = false;
5780 } else {
5781 // Successfully deleted the old package. Now proceed with re-installation
5782 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005783 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5784 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005786 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5788 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005789 }
5790 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005791 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005792 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793 res);
5794 updatedSettings = true;
5795 }
5796 }
5797
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005798 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 // remove package from internal structures. Note that we want deletePackageX to
5800 // delete the package data and cache directories that it created in
5801 // scanPackageLocked, unless those directories existed before we even tried to
5802 // install.
5803 if(updatedSettings) {
5804 deletePackageLI(
5805 pkgName, true,
5806 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005807 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 }
5809 // Since we failed to install the new package we need to restore the old
5810 // package that we deleted.
5811 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005812 File restoreFile = new File(deletedPackage.mPath);
5813 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005814 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005815 return;
5816 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005817 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005818 boolean oldOnSd = isExternal(deletedPackage);
5819 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5820 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5821 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005822 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5823 | SCAN_UPDATE_TIME;
5824 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5825 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005826 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5827 return;
5828 }
5829 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005830 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005831 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005832 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005833 mSettings.writeLP();
5834 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005835 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 }
5837 }
5838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005841 PackageParser.Package pkg,
5842 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005843 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 PackageParser.Package newPackage = null;
5845 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005846 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 PackageParser.PARSE_IS_SYSTEM;
5848 String packageName = deletedPackage.packageName;
5849 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5850 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005851 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 return;
5853 }
5854 PackageParser.Package oldPkg;
5855 PackageSetting oldPkgSetting;
5856 synchronized (mPackages) {
5857 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005858 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5860 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005861 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 return;
5863 }
5864 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005865
5866 killApplication(packageName, oldPkg.applicationInfo.uid);
5867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5869 res.removedInfo.removedPackage = packageName;
5870 // Remove existing system package
5871 removePackageLI(oldPkg, true);
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005872 synchronized (mPackages) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005873 if (!mSettings.disableSystemPackageLP(packageName) && deletedPackage != null) {
5874 // We didn't need to disable the .apk as a current system package,
5875 // which means we are replacing another update that is already
5876 // installed. We need to make sure to delete the older one's .apk.
5877 res.removedInfo.args = createInstallArgs(isExternal(pkg)
5878 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL,
5879 deletedPackage.applicationInfo.sourceDir,
5880 deletedPackage.applicationInfo.publicSourceDir,
5881 deletedPackage.applicationInfo.nativeLibraryDir);
5882 } else {
5883 res.removedInfo.args = null;
5884 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005885 }
5886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 // Successfully disabled the old package. Now proceed with re-installation
5888 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5889 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005890 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005891 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005892 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5894 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5895 }
5896 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005897 if (newPackage.mExtras != null) {
5898 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5899 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5900 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5901 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005902 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 updatedSettings = true;
5904 }
5905
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005906 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 // Re installation failed. Restore old information
5908 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005909 if (newPackage != null) {
5910 removePackageLI(newPackage, true);
5911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005913 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005914 // Restore the old system information in Settings
5915 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005916 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005918 mSettings.setInstallerPackageName(packageName,
5919 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005920 }
5921 mSettings.writeLP();
5922 }
5923 }
5924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005925
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005926 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005927 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005928 int retCode;
5929 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5930 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5931 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005932 if (mNoDexOpt) {
5933 /*
5934 * If we're in an engineering build, programs are lazily run
5935 * through dexopt. If the .dex file doesn't exist yet, it
5936 * will be created when the program is run next.
5937 */
5938 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5939 } else {
5940 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5941 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5942 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005943 }
5944 }
5945 return PackageManager.INSTALL_SUCCEEDED;
5946 }
5947
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005948 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005949 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005950 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 synchronized (mPackages) {
5952 //write settings. the installStatus will be incomplete at this stage.
5953 //note that the new package setting would have already been
5954 //added to mPackages. It hasn't been persisted yet.
5955 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5956 mSettings.writeLP();
5957 }
5958
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005959 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005960 != PackageManager.INSTALL_SUCCEEDED) {
5961 // Discontinue if moving dex files failed.
5962 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005964 if((res.returnCode = setPermissionsLI(newPackage))
5965 != PackageManager.INSTALL_SUCCEEDED) {
5966 if (mInstaller != null) {
5967 mInstaller.rmdex(newPackage.mScanPath);
5968 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005969 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005971 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005974 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005975 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 res.name = pkgName;
5977 res.uid = newPackage.applicationInfo.uid;
5978 res.pkg = newPackage;
5979 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005980 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5982 //to update install status
5983 mSettings.writeLP();
5984 }
5985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005986
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005987 private void installPackageLI(InstallArgs args,
5988 boolean newInstall, PackageInstalledInfo res) {
5989 int pFlags = args.flags;
5990 String installerPackageName = args.installerPackageName;
5991 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005992 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005993 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005994 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005995 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005996 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005997 // Result object to be returned
5998 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5999
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006000 // Retrieve PackageSettings and parse package
6001 int parseFlags = PackageParser.PARSE_CHATTY |
6002 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
6003 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
6004 parseFlags |= mDefParseFlags;
6005 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
6006 pp.setSeparateProcesses(mSeparateProcesses);
6007 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
6008 null, mMetrics, parseFlags);
6009 if (pkg == null) {
6010 res.returnCode = pp.getParseError();
6011 return;
6012 }
6013 String pkgName = res.name = pkg.packageName;
6014 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
6015 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
6016 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
6017 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006018 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006019 }
6020 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
6021 res.returnCode = pp.getParseError();
6022 return;
6023 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006024 // Get rid of all references to package scan path via parser.
6025 pp = null;
6026 String oldCodePath = null;
6027 boolean systemApp = false;
6028 synchronized (mPackages) {
6029 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006030 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
6031 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08006032 if (pkg.mOriginalPackages != null
6033 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006034 && mPackages.containsKey(oldName)) {
6035 // This package is derived from an original package,
6036 // and this device has been updating from that original
6037 // name. We must continue using the original name, so
6038 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08006039 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006040 pkgName = pkg.packageName;
6041 replace = true;
6042 } else if (mPackages.containsKey(pkgName)) {
6043 // This package, under its official name, already exists
6044 // on the device; we should replace it.
6045 replace = true;
6046 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006047 }
6048 PackageSetting ps = mSettings.mPackages.get(pkgName);
6049 if (ps != null) {
6050 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
6051 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6052 systemApp = (ps.pkg.applicationInfo.flags &
6053 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07006054 }
6055 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006056 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006057
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006058 if (systemApp && onSd) {
6059 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006060 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006061 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
6062 return;
6063 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08006064
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006065 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
6066 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6067 return;
6068 }
6069 // Set application objects path explicitly after the rename
6070 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07006071 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006072 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006073 replacePackageLI(pkg, parseFlags, scanMode,
6074 installerPackageName, res);
6075 } else {
6076 installNewPackageLI(pkg, parseFlags, scanMode,
6077 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 }
6079 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006080
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006081 private int setPermissionsLI(PackageParser.Package newPackage) {
6082 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006083 int retCode = 0;
6084 // TODO Gross hack but fix later. Ideally move this to be a post installation
6085 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07006086 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006087 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 try {
6089 extractPublicFiles(newPackage, destResourceFile);
6090 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006091 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 -08006092 " forward-locked app.");
6093 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6094 } finally {
6095 //TODO clean up the extracted public files
6096 }
6097 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006098 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 newPackage.applicationInfo.uid);
6100 } else {
6101 final int filePermissions =
6102 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006103 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 newPackage.applicationInfo.uid);
6105 }
6106 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006107 // The permissions on the resource file was set when it was copied for
6108 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006112 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006113 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006115 // TODO Define new internal error
6116 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 }
6118 return PackageManager.INSTALL_SUCCEEDED;
6119 }
6120
Kenny Root85387d72010-08-26 10:13:11 -07006121 private static boolean isForwardLocked(PackageParser.Package pkg) {
6122 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 }
6124
Kenny Root85387d72010-08-26 10:13:11 -07006125 private static boolean isExternal(PackageParser.Package pkg) {
6126 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
6127 }
6128
6129 private static boolean isSystemApp(PackageParser.Package pkg) {
6130 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6131 }
6132
Kenny Root502e9a42011-01-10 13:48:15 -08006133 private static boolean isSystemApp(ApplicationInfo info) {
6134 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6135 }
6136
Kenny Root85387d72010-08-26 10:13:11 -07006137 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
6138 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006139 }
6140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 private void extractPublicFiles(PackageParser.Package newPackage,
6142 File publicZipFile) throws IOException {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006143 final FileOutputStream fstr = new FileOutputStream(publicZipFile);
6144 final ZipOutputStream publicZipOutStream = new ZipOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6146
6147 // Copy manifest, resources.arsc and res directory to public zip
6148
6149 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6150 while (privateZipEntries.hasMoreElements()) {
6151 final ZipEntry zipEntry = privateZipEntries.nextElement();
6152 final String zipEntryName = zipEntry.getName();
6153 if ("AndroidManifest.xml".equals(zipEntryName)
6154 || "resources.arsc".equals(zipEntryName)
6155 || zipEntryName.startsWith("res/")) {
6156 try {
6157 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6158 } catch (IOException e) {
6159 try {
6160 publicZipOutStream.close();
6161 throw e;
6162 } finally {
6163 publicZipFile.delete();
6164 }
6165 }
6166 }
6167 }
6168
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006169 publicZipOutStream.finish();
6170 publicZipOutStream.flush();
6171 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 publicZipOutStream.close();
6173 FileUtils.setPermissions(
6174 publicZipFile.getAbsolutePath(),
6175 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6176 -1, -1);
6177 }
6178
6179 private static void copyZipEntry(ZipEntry zipEntry,
6180 ZipFile inZipFile,
6181 ZipOutputStream outZipStream) throws IOException {
6182 byte[] buffer = new byte[4096];
6183 int num;
6184
6185 ZipEntry newEntry;
6186 if (zipEntry.getMethod() == ZipEntry.STORED) {
6187 // Preserve the STORED method of the input entry.
6188 newEntry = new ZipEntry(zipEntry);
6189 } else {
6190 // Create a new entry so that the compressed len is recomputed.
6191 newEntry = new ZipEntry(zipEntry.getName());
6192 }
6193 outZipStream.putNextEntry(newEntry);
6194
6195 InputStream data = inZipFile.getInputStream(zipEntry);
6196 while ((num = data.read(buffer)) > 0) {
6197 outZipStream.write(buffer, 0, num);
6198 }
6199 outZipStream.flush();
6200 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 private void deleteTempPackageFiles() {
6203 FilenameFilter filter = new FilenameFilter() {
6204 public boolean accept(File dir, String name) {
6205 return name.startsWith("vmdl") && name.endsWith(".tmp");
6206 }
6207 };
6208 String tmpFilesList[] = mAppInstallDir.list(filter);
6209 if(tmpFilesList == null) {
6210 return;
6211 }
6212 for(int i = 0; i < tmpFilesList.length; i++) {
6213 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6214 tmpFile.delete();
6215 }
6216 }
6217
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006218 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 File tmpPackageFile;
6220 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006221 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006223 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 return null;
6225 }
6226 try {
6227 FileUtils.setPermissions(
6228 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6229 -1, -1);
6230 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006231 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 return null;
6233 }
6234 return tmpPackageFile;
6235 }
6236
6237 public void deletePackage(final String packageName,
6238 final IPackageDeleteObserver observer,
6239 final int flags) {
6240 mContext.enforceCallingOrSelfPermission(
6241 android.Manifest.permission.DELETE_PACKAGES, null);
6242 // Queue up an async operation since the package deletion may take a little while.
6243 mHandler.post(new Runnable() {
6244 public void run() {
6245 mHandler.removeCallbacks(this);
6246 final boolean succeded = deletePackageX(packageName, true, true, flags);
6247 if (observer != null) {
6248 try {
6249 observer.packageDeleted(succeded);
6250 } catch (RemoteException e) {
6251 Log.i(TAG, "Observer no longer exists.");
6252 } //end catch
6253 } //end if
6254 } //end run
6255 });
6256 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 /**
6259 * This method is an internal method that could be get invoked either
6260 * to delete an installed package or to clean up a failed installation.
6261 * After deleting an installed package, a broadcast is sent to notify any
6262 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006263 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 * installation wouldn't have sent the initial broadcast either
6265 * The key steps in deleting a package are
6266 * deleting the package information in internal structures like mPackages,
6267 * deleting the packages base directories through installd
6268 * updating mSettings to reflect current status
6269 * persisting settings for later use
6270 * sending a broadcast if necessary
6271 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6273 boolean deleteCodeAndResources, int flags) {
6274 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006275 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006277 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6278 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6279 try {
6280 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006281 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006282 return false;
6283 }
6284 } catch (RemoteException e) {
6285 }
6286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006287 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006288 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006289 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006293 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006294 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006295
6296 // If the removed package was a system update, the old system packaged
6297 // was re-enabled; we need to broadcast this information
6298 if (systemUpdate) {
6299 Bundle extras = new Bundle(1);
6300 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6301 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6302
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006303 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6304 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006307 // Force a gc here.
6308 Runtime.getRuntime().gc();
6309 // Delete the resources here after sending the broadcast to let
6310 // other processes clean up before deleting resources.
6311 if (info.args != null) {
6312 synchronized (mInstallLock) {
6313 info.args.doPostDeleteLI(deleteCodeAndResources);
6314 }
6315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 return res;
6317 }
6318
6319 static class PackageRemovedInfo {
6320 String removedPackage;
6321 int uid = -1;
6322 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006323 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006324 // Clean up resources deleted packages.
6325 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006326
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006327 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 Bundle extras = new Bundle(1);
6329 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6330 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6331 if (replacing) {
6332 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6333 }
6334 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006335 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 }
6337 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006338 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 }
6340 }
6341 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 /*
6344 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6345 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006346 * 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 -08006347 * delete a partially installed application.
6348 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006349 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006350 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006352 if (outInfo != null) {
6353 outInfo.removedPackage = packageName;
6354 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006355 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 // Retrieve object to delete permissions for shared user later on
6357 PackageSetting deletedPs;
6358 synchronized (mPackages) {
6359 deletedPs = mSettings.mPackages.get(packageName);
6360 }
6361 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006362 boolean useEncryptedFSDir = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06006364 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006366 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 + packageName + ", retcode=" + retCode);
6368 // we don't consider this to be a failure of the core package deletion
6369 }
6370 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006371 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 PackageParser.Package pkg = mPackages.get(packageName);
6373 File dataDir = new File(pkg.applicationInfo.dataDir);
6374 dataDir.delete();
6375 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006376 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 }
6378 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006379 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006380 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6381 if (outInfo != null) {
6382 outInfo.removedUid = mSettings.removePackageLP(packageName);
6383 }
6384 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006385 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006386 if (deletedPs.sharedUser != null) {
6387 // remove permissions associated with package
6388 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6389 }
6390 }
6391 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006392 // remove from preferred activities.
6393 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6394 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6395 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6396 removed.add(pa);
6397 }
6398 }
6399 for (PreferredActivity pa : removed) {
6400 mSettings.mPreferredActivities.removeFilter(pa);
6401 }
6402 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006403 if (writeSettings) {
6404 // Save settings now
6405 mSettings.writeLP();
6406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 }
6408 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 /*
6411 * Tries to delete system package.
6412 */
6413 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006414 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 ApplicationInfo applicationInfo = p.applicationInfo;
6416 //applicable for non-partially installed applications only
6417 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006418 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 return false;
6420 }
6421 PackageSetting ps = null;
6422 // Confirm if the system package has been updated
6423 // An updated system app can be deleted. This will also have to restore
6424 // the system pkg from system partition
6425 synchronized (mPackages) {
6426 ps = mSettings.getDisabledSystemPkg(p.packageName);
6427 }
6428 if (ps == null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006429 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 return false;
6431 } else {
6432 Log.i(TAG, "Deleting system pkg from data partition");
6433 }
6434 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006435 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006436 if (ps.versionCode < p.mVersionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006437 // Delete data for downgrades
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006438 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006439 } else {
6440 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006441 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006442 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006443 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006444 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 if (!ret) {
6446 return false;
6447 }
6448 synchronized (mPackages) {
6449 // Reinstate the old system package
6450 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006451 // Remove any native libraries from the upgraded package.
6452 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 }
6454 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006455 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006457 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006460 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 return false;
6462 }
6463 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006464 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006465 if (writeSettings) {
6466 mSettings.writeLP();
6467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 }
6469 return true;
6470 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006473 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6474 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 ApplicationInfo applicationInfo = p.applicationInfo;
6476 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006477 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 return false;
6479 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006480 if (outInfo != null) {
6481 outInfo.uid = applicationInfo.uid;
6482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483
6484 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006485 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486
6487 // Delete application code and resources
6488 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006489 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006490 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6491 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6492 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6493 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 }
6495 return true;
6496 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 /*
6499 * This method handles package deletion in general
6500 */
6501 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006502 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6503 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006505 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 return false;
6507 }
6508 PackageParser.Package p;
6509 boolean dataOnly = false;
6510 synchronized (mPackages) {
6511 p = mPackages.get(packageName);
6512 if (p == null) {
6513 //this retrieves partially installed apps
6514 dataOnly = true;
6515 PackageSetting ps = mSettings.mPackages.get(packageName);
6516 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006517 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 return false;
6519 }
6520 p = ps.pkg;
6521 }
6522 }
6523 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006524 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 return false;
6526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 if (dataOnly) {
6529 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006530 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 return true;
6532 }
6533 // At this point the package should have ApplicationInfo associated with it
6534 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006535 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 return false;
6537 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006538 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006539 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 Log.i(TAG, "Removing system package:"+p.packageName);
6541 // When an updated system application is deleted we delete the existing resources as well and
6542 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006543 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006544 } else {
6545 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006546 // Kill application pre-emptively especially for apps on sd.
6547 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006548 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6549 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006551 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006554 public void clearApplicationUserData(final String packageName,
6555 final IPackageDataObserver observer) {
6556 mContext.enforceCallingOrSelfPermission(
6557 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6558 // Queue up an async operation since the package deletion may take a little while.
6559 mHandler.post(new Runnable() {
6560 public void run() {
6561 mHandler.removeCallbacks(this);
6562 final boolean succeeded;
6563 synchronized (mInstallLock) {
6564 succeeded = clearApplicationUserDataLI(packageName);
6565 }
6566 if (succeeded) {
6567 // invoke DeviceStorageMonitor's update method to clear any notifications
6568 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6569 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6570 if (dsm != null) {
6571 dsm.updateMemory();
6572 }
6573 }
6574 if(observer != null) {
6575 try {
6576 observer.onRemoveCompleted(packageName, succeeded);
6577 } catch (RemoteException e) {
6578 Log.i(TAG, "Observer no longer exists.");
6579 }
6580 } //end if observer
6581 } //end run
6582 });
6583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 private boolean clearApplicationUserDataLI(String packageName) {
6586 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006587 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 return false;
6589 }
6590 PackageParser.Package p;
6591 boolean dataOnly = false;
6592 synchronized (mPackages) {
6593 p = mPackages.get(packageName);
6594 if(p == null) {
6595 dataOnly = true;
6596 PackageSetting ps = mSettings.mPackages.get(packageName);
6597 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006598 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 return false;
6600 }
6601 p = ps.pkg;
6602 }
6603 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006604 boolean useEncryptedFSDir = false;
6605
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006606 if (!dataOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 //need to check this only for fully installed applications
6608 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006609 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 return false;
6611 }
6612 final ApplicationInfo applicationInfo = p.applicationInfo;
6613 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006614 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 return false;
6616 }
6617 }
6618 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06006619 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006621 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006622 + packageName);
6623 return false;
6624 }
6625 }
6626 return true;
6627 }
6628
6629 public void deleteApplicationCacheFiles(final String packageName,
6630 final IPackageDataObserver observer) {
6631 mContext.enforceCallingOrSelfPermission(
6632 android.Manifest.permission.DELETE_CACHE_FILES, null);
6633 // Queue up an async operation since the package deletion may take a little while.
6634 mHandler.post(new Runnable() {
6635 public void run() {
6636 mHandler.removeCallbacks(this);
6637 final boolean succeded;
6638 synchronized (mInstallLock) {
6639 succeded = deleteApplicationCacheFilesLI(packageName);
6640 }
6641 if(observer != null) {
6642 try {
6643 observer.onRemoveCompleted(packageName, succeded);
6644 } catch (RemoteException e) {
6645 Log.i(TAG, "Observer no longer exists.");
6646 }
6647 } //end if observer
6648 } //end run
6649 });
6650 }
6651
6652 private boolean deleteApplicationCacheFilesLI(String packageName) {
6653 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006654 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 return false;
6656 }
6657 PackageParser.Package p;
6658 synchronized (mPackages) {
6659 p = mPackages.get(packageName);
6660 }
6661 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006662 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 return false;
6664 }
6665 final ApplicationInfo applicationInfo = p.applicationInfo;
6666 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006667 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 return false;
6669 }
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006670 boolean useEncryptedFSDir = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06006672 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006674 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 + packageName);
6676 return false;
6677 }
6678 }
6679 return true;
6680 }
6681
6682 public void getPackageSizeInfo(final String packageName,
6683 final IPackageStatsObserver observer) {
6684 mContext.enforceCallingOrSelfPermission(
6685 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6686 // Queue up an async operation since the package deletion may take a little while.
6687 mHandler.post(new Runnable() {
6688 public void run() {
6689 mHandler.removeCallbacks(this);
Kenny Root366949c2011-01-14 17:18:14 -08006690 PackageStats stats = new PackageStats(packageName);
6691
6692 final boolean success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 synchronized (mInstallLock) {
Kenny Root366949c2011-01-14 17:18:14 -08006694 success = getPackageSizeInfoLI(packageName, stats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 }
Kenny Root366949c2011-01-14 17:18:14 -08006696
6697 Message msg = mHandler.obtainMessage(INIT_COPY);
6698 msg.obj = new MeasureParams(stats, success, observer);
6699 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006700 } //end run
6701 });
6702 }
6703
6704 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6705 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006706 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 return false;
6708 }
6709 PackageParser.Package p;
6710 boolean dataOnly = false;
6711 synchronized (mPackages) {
6712 p = mPackages.get(packageName);
6713 if(p == null) {
6714 dataOnly = true;
6715 PackageSetting ps = mSettings.mPackages.get(packageName);
6716 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006717 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 return false;
6719 }
6720 p = ps.pkg;
6721 }
6722 }
6723 String publicSrcDir = null;
6724 if(!dataOnly) {
6725 final ApplicationInfo applicationInfo = p.applicationInfo;
6726 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006727 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 return false;
6729 }
6730 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6731 }
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006732 boolean useEncryptedFSDir = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06006734 int res = mInstaller.getSizeInfo(packageName, p.mPath,
6735 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 if (res < 0) {
6737 return false;
6738 } else {
6739 return true;
6740 }
6741 }
6742 return true;
6743 }
6744
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006747 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006748 }
6749
6750 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006751 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 }
6753
6754 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006755 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006756 }
6757
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006758 int getUidTargetSdkVersionLockedLP(int uid) {
6759 Object obj = mSettings.getUserIdLP(uid);
6760 if (obj instanceof SharedUserSetting) {
6761 SharedUserSetting sus = (SharedUserSetting)obj;
6762 final int N = sus.packages.size();
6763 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6764 Iterator<PackageSetting> it = sus.packages.iterator();
6765 int i=0;
6766 while (it.hasNext()) {
6767 PackageSetting ps = it.next();
6768 if (ps.pkg != null) {
6769 int v = ps.pkg.applicationInfo.targetSdkVersion;
6770 if (v < vers) vers = v;
6771 }
6772 }
6773 return vers;
6774 } else if (obj instanceof PackageSetting) {
6775 PackageSetting ps = (PackageSetting)obj;
6776 if (ps.pkg != null) {
6777 return ps.pkg.applicationInfo.targetSdkVersion;
6778 }
6779 }
6780 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6781 }
6782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 public void addPreferredActivity(IntentFilter filter, int match,
6784 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006785 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006786 if (mContext.checkCallingOrSelfPermission(
6787 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6788 != PackageManager.PERMISSION_GRANTED) {
6789 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6790 < Build.VERSION_CODES.FROYO) {
6791 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6792 + Binder.getCallingUid());
6793 return;
6794 }
6795 mContext.enforceCallingOrSelfPermission(
6796 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6797 }
6798
6799 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6801 mSettings.mPreferredActivities.addFilter(
6802 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006803 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006804 }
6805 }
6806
Satish Sampath8dbe6122009-06-02 23:35:54 +01006807 public void replacePreferredActivity(IntentFilter filter, int match,
6808 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006809 if (filter.countActions() != 1) {
6810 throw new IllegalArgumentException(
6811 "replacePreferredActivity expects filter to have only 1 action.");
6812 }
6813 if (filter.countCategories() != 1) {
6814 throw new IllegalArgumentException(
6815 "replacePreferredActivity expects filter to have only 1 category.");
6816 }
6817 if (filter.countDataAuthorities() != 0
6818 || filter.countDataPaths() != 0
6819 || filter.countDataSchemes() != 0
6820 || filter.countDataTypes() != 0) {
6821 throw new IllegalArgumentException(
6822 "replacePreferredActivity expects filter to have no data authorities, " +
6823 "paths, schemes or types.");
6824 }
6825 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006826 if (mContext.checkCallingOrSelfPermission(
6827 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6828 != PackageManager.PERMISSION_GRANTED) {
6829 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6830 < Build.VERSION_CODES.FROYO) {
6831 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6832 + Binder.getCallingUid());
6833 return;
6834 }
6835 mContext.enforceCallingOrSelfPermission(
6836 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6837 }
6838
Satish Sampath8dbe6122009-06-02 23:35:54 +01006839 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6840 String action = filter.getAction(0);
6841 String category = filter.getCategory(0);
6842 while (it.hasNext()) {
6843 PreferredActivity pa = it.next();
6844 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6845 it.remove();
6846 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6847 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6848 }
6849 }
6850 addPreferredActivity(filter, match, set, activity);
6851 }
6852 }
6853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006854 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006855 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006856 int uid = Binder.getCallingUid();
6857 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006858 if (pkg == null || pkg.applicationInfo.uid != uid) {
6859 if (mContext.checkCallingOrSelfPermission(
6860 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6861 != PackageManager.PERMISSION_GRANTED) {
6862 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6863 < Build.VERSION_CODES.FROYO) {
6864 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6865 + Binder.getCallingUid());
6866 return;
6867 }
6868 mContext.enforceCallingOrSelfPermission(
6869 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6870 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006871 }
6872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006873 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006874 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006875 }
6876 }
6877 }
6878
6879 boolean clearPackagePreferredActivitiesLP(String packageName) {
6880 boolean changed = false;
6881 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6882 while (it.hasNext()) {
6883 PreferredActivity pa = it.next();
6884 if (pa.mActivity.getPackageName().equals(packageName)) {
6885 it.remove();
6886 changed = true;
6887 }
6888 }
6889 return changed;
6890 }
6891
6892 public int getPreferredActivities(List<IntentFilter> outFilters,
6893 List<ComponentName> outActivities, String packageName) {
6894
6895 int num = 0;
6896 synchronized (mPackages) {
6897 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6898 while (it.hasNext()) {
6899 PreferredActivity pa = it.next();
6900 if (packageName == null
6901 || pa.mActivity.getPackageName().equals(packageName)) {
6902 if (outFilters != null) {
6903 outFilters.add(new IntentFilter(pa));
6904 }
6905 if (outActivities != null) {
6906 outActivities.add(pa.mActivity);
6907 }
6908 }
6909 }
6910 }
6911
6912 return num;
6913 }
6914
6915 public void setApplicationEnabledSetting(String appPackageName,
6916 int newState, int flags) {
6917 setEnabledSetting(appPackageName, null, newState, flags);
6918 }
6919
6920 public void setComponentEnabledSetting(ComponentName componentName,
6921 int newState, int flags) {
6922 setEnabledSetting(componentName.getPackageName(),
6923 componentName.getClassName(), newState, flags);
6924 }
6925
6926 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006927 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006928 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6929 || newState == COMPONENT_ENABLED_STATE_ENABLED
6930 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6931 throw new IllegalArgumentException("Invalid new component state: "
6932 + newState);
6933 }
6934 PackageSetting pkgSetting;
6935 final int uid = Binder.getCallingUid();
6936 final int permission = mContext.checkCallingPermission(
6937 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6938 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006939 boolean sendNow = false;
6940 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006941 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006943 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006945 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006947 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006949 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 }
6951 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006952 "Unknown component: " + packageName
6953 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 }
6955 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6956 throw new SecurityException(
6957 "Permission Denial: attempt to change component state from pid="
6958 + Binder.getCallingPid()
6959 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6960 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006961 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006963 if (pkgSetting.enabled == newState) {
6964 // Nothing to do
6965 return;
6966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006968 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 } else {
6970 // We're dealing with a component level state change
6971 switch (newState) {
6972 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006973 if (!pkgSetting.enableComponentLP(className)) {
6974 return;
6975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006976 break;
6977 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006978 if (!pkgSetting.disableComponentLP(className)) {
6979 return;
6980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006981 break;
6982 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006983 if (!pkgSetting.restoreComponentLP(className)) {
6984 return;
6985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006986 break;
6987 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006988 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006989 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006990 }
6991 }
6992 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006993 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006994 components = mPendingBroadcasts.get(packageName);
6995 boolean newPackage = components == null;
6996 if (newPackage) {
6997 components = new ArrayList<String>();
6998 }
6999 if (!components.contains(componentName)) {
7000 components.add(componentName);
7001 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007002 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
7003 sendNow = true;
7004 // Purge entry from pending broadcast list if another one exists already
7005 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007006 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007007 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007008 if (newPackage) {
7009 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007010 }
7011 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
7012 // Schedule a message
7013 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
7014 }
7015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007016 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 long callingId = Binder.clearCallingIdentity();
7019 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007020 if (sendNow) {
7021 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007022 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 } finally {
7025 Binder.restoreCallingIdentity(callingId);
7026 }
7027 }
7028
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007029 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08007030 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
7031 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
7032 + " components=" + componentNames);
7033 Bundle extras = new Bundle(4);
7034 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
7035 String nameList[] = new String[componentNames.size()];
7036 componentNames.toArray(nameList);
7037 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007038 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
7039 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07007040 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07007041 }
7042
Jacek Surazski65e13172009-04-28 15:26:38 +02007043 public String getInstallerPackageName(String packageName) {
7044 synchronized (mPackages) {
7045 PackageSetting pkg = mSettings.mPackages.get(packageName);
7046 if (pkg == null) {
7047 throw new IllegalArgumentException("Unknown package: " + packageName);
7048 }
7049 return pkg.installerPackageName;
7050 }
7051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 public int getApplicationEnabledSetting(String appPackageName) {
7054 synchronized (mPackages) {
7055 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
7056 if (pkg == null) {
7057 throw new IllegalArgumentException("Unknown package: " + appPackageName);
7058 }
7059 return pkg.enabled;
7060 }
7061 }
7062
7063 public int getComponentEnabledSetting(ComponentName componentName) {
7064 synchronized (mPackages) {
7065 final String packageNameStr = componentName.getPackageName();
7066 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
7067 if (pkg == null) {
7068 throw new IllegalArgumentException("Unknown component: " + componentName);
7069 }
7070 final String classNameStr = componentName.getClassName();
7071 return pkg.currentEnabledStateLP(classNameStr);
7072 }
7073 }
7074
7075 public void enterSafeMode() {
7076 if (!mSystemReady) {
7077 mSafeMode = true;
7078 }
7079 }
7080
7081 public void systemReady() {
7082 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007083
7084 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007085 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007086 mContext.getContentResolver(),
7087 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007088 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007089 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007090 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 }
7093
7094 public boolean isSafeMode() {
7095 return mSafeMode;
7096 }
7097
7098 public boolean hasSystemUidErrors() {
7099 return mHasSystemUidErrors;
7100 }
7101
7102 static String arrayToString(int[] array) {
7103 StringBuffer buf = new StringBuffer(128);
7104 buf.append('[');
7105 if (array != null) {
7106 for (int i=0; i<array.length; i++) {
7107 if (i > 0) buf.append(", ");
7108 buf.append(array[i]);
7109 }
7110 }
7111 buf.append(']');
7112 return buf.toString();
7113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007115 @Override
7116 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7117 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7118 != PackageManager.PERMISSION_GRANTED) {
7119 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7120 + Binder.getCallingPid()
7121 + ", uid=" + Binder.getCallingUid()
7122 + " without permission "
7123 + android.Manifest.permission.DUMP);
7124 return;
7125 }
7126
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007127 boolean dumpStar = true;
7128 boolean dumpLibs = false;
7129 boolean dumpFeatures = false;
7130 boolean dumpResolvers = false;
7131 boolean dumpPermissions = false;
7132 boolean dumpPackages = false;
7133 boolean dumpSharedUsers = false;
7134 boolean dumpMessages = false;
7135 boolean dumpProviders = false;
7136
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007137 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007138 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007139
7140 int opti = 0;
7141 while (opti < args.length) {
7142 String opt = args[opti];
7143 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7144 break;
7145 }
7146 opti++;
7147 if ("-a".equals(opt)) {
7148 // Right now we only know how to print all.
7149 } else if ("-h".equals(opt)) {
7150 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007151 pw.println(" [-h] [-f] [cmd] ...");
7152 pw.println(" -f: print details of intent filters");
7153 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007154 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007155 pw.println(" l[ibraries]: list known shared libraries");
7156 pw.println(" f[ibraries]: list device features");
7157 pw.println(" r[esolvers]: dump intent resolvers");
7158 pw.println(" perm[issions]: dump permissions");
7159 pw.println(" prov[iders]: dump content providers");
7160 pw.println(" p[ackages]: dump installed packages");
7161 pw.println(" s[hared-users]: dump shared user IDs");
7162 pw.println(" m[essages]: print collected runtime messages");
7163 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007164 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007165 } else if ("-f".equals(opt)) {
7166 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007167 } else {
7168 pw.println("Unknown argument: " + opt + "; use -h for help");
7169 }
7170 }
7171
7172 // Is the caller requesting to dump a particular piece of data?
7173 if (opti < args.length) {
7174 String cmd = args[opti];
7175 opti++;
7176 // Is this a package name?
7177 if ("android".equals(cmd) || cmd.contains(".")) {
7178 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007179 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
7180 dumpStar = false;
7181 dumpLibs = true;
7182 } else if ("f".equals(cmd) || "features".equals(cmd)) {
7183 dumpStar = false;
7184 dumpFeatures = true;
7185 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
7186 dumpStar = false;
7187 dumpResolvers = true;
7188 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
7189 dumpStar = false;
7190 dumpPermissions = true;
7191 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
7192 dumpStar = false;
7193 dumpPackages = true;
7194 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
7195 dumpStar = false;
7196 dumpSharedUsers = true;
7197 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
7198 dumpStar = false;
7199 dumpProviders = true;
7200 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
7201 dumpStar = false;
7202 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007203 }
7204 }
7205
7206 boolean printedTitle = false;
7207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007209 if ((dumpStar || dumpLibs) && packageName == null) {
7210 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007211 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007212 pw.println("Libraries:");
7213 Iterator<String> it = mSharedLibraries.keySet().iterator();
7214 while (it.hasNext()) {
7215 String name = it.next();
7216 pw.print(" ");
7217 pw.print(name);
7218 pw.print(" -> ");
7219 pw.println(mSharedLibraries.get(name));
7220 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007221 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007222
7223 if ((dumpStar || dumpFeatures) && packageName == null) {
7224 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007225 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007226 pw.println("Features:");
7227 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7228 while (it.hasNext()) {
7229 String name = it.next();
7230 pw.print(" ");
7231 pw.println(name);
7232 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007233 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007234
7235 if (dumpStar || dumpResolvers) {
7236 if (mActivities.dump(pw, printedTitle
7237 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7238 " ", packageName, showFilters)) {
7239 printedTitle = true;
7240 }
7241 if (mReceivers.dump(pw, printedTitle
7242 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7243 " ", packageName, showFilters)) {
7244 printedTitle = true;
7245 }
7246 if (mServices.dump(pw, printedTitle
7247 ? "\nService Resolver Table:" : "Service Resolver Table:",
7248 " ", packageName, showFilters)) {
7249 printedTitle = true;
7250 }
7251 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7252 ? "\nPreferred Activities:" : "Preferred Activities:",
7253 " ", packageName, showFilters)) {
7254 printedTitle = true;
7255 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007256 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007257
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007258 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007259 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007260 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007261 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7262 continue;
7263 }
7264 if (!printedSomething) {
7265 if (printedTitle) pw.println(" ");
7266 pw.println("Permissions:");
7267 printedSomething = true;
7268 printedTitle = true;
7269 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007270 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7271 pw.print(Integer.toHexString(System.identityHashCode(p)));
7272 pw.println("):");
7273 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7274 pw.print(" uid="); pw.print(p.uid);
7275 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007276 pw.print(" type="); pw.print(p.type);
7277 pw.print(" prot="); pw.println(p.protectionLevel);
7278 if (p.packageSetting != null) {
7279 pw.print(" packageSetting="); pw.println(p.packageSetting);
7280 }
7281 if (p.perm != null) {
7282 pw.print(" perm="); pw.println(p.perm);
7283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 }
7285 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007286
7287 if (dumpStar || dumpProviders) {
7288 printedSomething = false;
7289 for (PackageParser.Provider p : mProviders.values()) {
7290 if (packageName != null && !packageName.equals(p.info.packageName)) {
7291 continue;
7292 }
7293 if (!printedSomething) {
7294 if (printedTitle) pw.println(" ");
7295 pw.println("Registered ContentProviders:");
7296 printedSomething = true;
7297 printedTitle = true;
7298 }
7299 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7300 pw.println(p.toString());
7301 }
7302 }
7303
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007304 printedSomething = false;
7305 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007306 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007307 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7308 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007310 if (packageName != null && !packageName.equals(ps.realName)
7311 && !packageName.equals(ps.name)) {
7312 continue;
7313 }
7314 if (!printedSomething) {
7315 if (printedTitle) pw.println(" ");
7316 pw.println("Packages:");
7317 printedSomething = true;
7318 printedTitle = true;
7319 }
7320 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007321 pw.print(" Package [");
7322 pw.print(ps.realName != null ? ps.realName : ps.name);
7323 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007324 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7325 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007326 if (ps.realName != null) {
7327 pw.print(" compat name="); pw.println(ps.name);
7328 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007329 pw.print(" userId="); pw.print(ps.userId);
7330 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7331 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7332 pw.print(" pkg="); pw.println(ps.pkg);
7333 pw.print(" codePath="); pw.println(ps.codePathString);
7334 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007335 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root5d40fe92011-01-14 10:54:46 -08007336 pw.print(" obbPaths="); pw.println(Arrays.toString(ps.obbPathStrings));
Kenny Root1174f712010-10-22 10:07:11 -07007337 pw.print(" versionCode="); pw.println(ps.versionCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 if (ps.pkg != null) {
Kenny Root1174f712010-10-22 10:07:11 -07007339 pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007340 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007341 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007342 if (ps.pkg.mOperationPending) {
7343 pw.println(" mOperationPending=true");
7344 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007345 pw.print(" supportsScreens=[");
7346 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007347 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007348 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7349 if (!first) pw.print(", ");
7350 first = false;
7351 pw.print("small");
7352 }
7353 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007354 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007355 if (!first) pw.print(", ");
7356 first = false;
7357 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007358 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007359 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007360 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007361 if (!first) pw.print(", ");
7362 first = false;
7363 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007364 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007365 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007366 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007367 if (!first) pw.print(", ");
7368 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007369 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007370 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007371 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007372 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007373 if (!first) pw.print(", ");
7374 first = false;
7375 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007376 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007377 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007378 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7379 if (!first) pw.print(", ");
7380 first = false;
7381 pw.print("anyDensity");
7382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007383 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007384 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007385 pw.print(" timeStamp=");
7386 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7387 pw.print(" firstInstallTime=");
7388 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7389 pw.print(" lastUpdateTime=");
7390 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007391 pw.print(" signatures="); pw.println(ps.signatures);
7392 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007393 pw.print(" haveGids="); pw.println(ps.haveGids);
7394 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007395 pw.print(" installStatus="); pw.print(ps.installStatus);
7396 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 if (ps.disabledComponents.size() > 0) {
7398 pw.println(" disabledComponents:");
7399 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007400 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007401 }
7402 }
7403 if (ps.enabledComponents.size() > 0) {
7404 pw.println(" enabledComponents:");
7405 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007406 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 }
7408 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007409 if (ps.grantedPermissions.size() > 0) {
7410 pw.println(" grantedPermissions:");
7411 for (String s : ps.grantedPermissions) {
7412 pw.print(" "); pw.println(s);
7413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 }
7416 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007417 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007418 if (dumpStar || dumpPackages) {
7419 if (mSettings.mRenamedPackages.size() > 0) {
7420 for (HashMap.Entry<String, String> e
7421 : mSettings.mRenamedPackages.entrySet()) {
7422 if (packageName != null && !packageName.equals(e.getKey())
7423 && !packageName.equals(e.getValue())) {
7424 continue;
7425 }
7426 if (!printedSomething) {
7427 if (printedTitle) pw.println(" ");
7428 pw.println("Renamed packages:");
7429 printedSomething = true;
7430 printedTitle = true;
7431 }
7432 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7433 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007434 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007435 }
7436 printedSomething = false;
7437 if (mSettings.mDisabledSysPackages.size() > 0) {
7438 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7439 if (packageName != null && !packageName.equals(ps.realName)
7440 && !packageName.equals(ps.name)) {
7441 continue;
7442 }
7443 if (!printedSomething) {
7444 if (printedTitle) pw.println(" ");
7445 pw.println("Hidden system packages:");
7446 printedSomething = true;
7447 printedTitle = true;
7448 }
7449 pw.print(" Package [");
7450 pw.print(ps.realName != null ? ps.realName : ps.name);
7451 pw.print("] (");
7452 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7453 pw.println("):");
7454 if (ps.realName != null) {
7455 pw.print(" compat name="); pw.println(ps.name);
7456 }
7457 pw.print(" userId="); pw.println(ps.userId);
7458 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7459 pw.print(" codePath="); pw.println(ps.codePathString);
7460 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007461 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007462 }
7463 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007464 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007465 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007466 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007467 if (packageName != null && su != packageSharedUser) {
7468 continue;
7469 }
7470 if (!printedSomething) {
7471 if (printedTitle) pw.println(" ");
7472 pw.println("Shared users:");
7473 printedSomething = true;
7474 printedTitle = true;
7475 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007476 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7477 pw.print(Integer.toHexString(System.identityHashCode(su)));
7478 pw.println("):");
7479 pw.print(" userId="); pw.print(su.userId);
7480 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007481 pw.println(" grantedPermissions:");
7482 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007483 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007485 }
7486 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007487
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007488 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007489 if (printedTitle) pw.println(" ");
7490 printedTitle = true;
7491 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007492 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007493
7494 pw.println(" ");
7495 pw.println("Package warning messages:");
7496 File fname = getSettingsProblemFile();
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08007497 FileInputStream in = null;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007498 try {
7499 in = new FileInputStream(fname);
7500 int avail = in.available();
7501 byte[] data = new byte[avail];
7502 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007503 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007504 } catch (FileNotFoundException e) {
7505 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08007506 } finally {
7507 if (in != null) {
7508 try {
7509 in.close();
7510 } catch (IOException e) {
7511 }
7512 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007513 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007515 }
7516 }
7517
7518 static final class BasePermission {
7519 final static int TYPE_NORMAL = 0;
7520 final static int TYPE_BUILTIN = 1;
7521 final static int TYPE_DYNAMIC = 2;
7522
7523 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007524 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007525 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007526 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007527 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007528 PackageParser.Permission perm;
7529 PermissionInfo pendingInfo;
7530 int uid;
7531 int[] gids;
7532
7533 BasePermission(String _name, String _sourcePackage, int _type) {
7534 name = _name;
7535 sourcePackage = _sourcePackage;
7536 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007537 // Default to most conservative protection level.
7538 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7539 }
7540
7541 public String toString() {
7542 return "BasePermission{"
7543 + Integer.toHexString(System.identityHashCode(this))
7544 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545 }
7546 }
7547
7548 static class PackageSignatures {
7549 private Signature[] mSignatures;
7550
Kenny Root291e78c2011-01-13 14:53:17 -08007551 PackageSignatures(PackageSignatures orig) {
Kenny Rootbd392c52011-01-14 10:34:56 -08007552 if (orig != null && orig.mSignatures != null) {
7553 mSignatures = orig.mSignatures.clone();
7554 }
Kenny Root291e78c2011-01-13 14:53:17 -08007555 }
7556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557 PackageSignatures(Signature[] sigs) {
7558 assignSignatures(sigs);
7559 }
7560
7561 PackageSignatures() {
7562 }
7563
7564 void writeXml(XmlSerializer serializer, String tagName,
7565 ArrayList<Signature> pastSignatures) throws IOException {
7566 if (mSignatures == null) {
7567 return;
7568 }
7569 serializer.startTag(null, tagName);
7570 serializer.attribute(null, "count",
7571 Integer.toString(mSignatures.length));
7572 for (int i=0; i<mSignatures.length; i++) {
7573 serializer.startTag(null, "cert");
7574 final Signature sig = mSignatures[i];
7575 final int sigHash = sig.hashCode();
7576 final int numPast = pastSignatures.size();
7577 int j;
7578 for (j=0; j<numPast; j++) {
7579 Signature pastSig = pastSignatures.get(j);
7580 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7581 serializer.attribute(null, "index", Integer.toString(j));
7582 break;
7583 }
7584 }
7585 if (j >= numPast) {
7586 pastSignatures.add(sig);
7587 serializer.attribute(null, "index", Integer.toString(numPast));
7588 serializer.attribute(null, "key", sig.toCharsString());
7589 }
7590 serializer.endTag(null, "cert");
7591 }
7592 serializer.endTag(null, tagName);
7593 }
7594
7595 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7596 throws IOException, XmlPullParserException {
7597 String countStr = parser.getAttributeValue(null, "count");
7598 if (countStr == null) {
7599 reportSettingsProblem(Log.WARN,
7600 "Error in package manager settings: <signatures> has"
7601 + " no count at " + parser.getPositionDescription());
7602 XmlUtils.skipCurrentTag(parser);
7603 }
7604 final int count = Integer.parseInt(countStr);
7605 mSignatures = new Signature[count];
7606 int pos = 0;
7607
7608 int outerDepth = parser.getDepth();
7609 int type;
7610 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7611 && (type != XmlPullParser.END_TAG
7612 || parser.getDepth() > outerDepth)) {
7613 if (type == XmlPullParser.END_TAG
7614 || type == XmlPullParser.TEXT) {
7615 continue;
7616 }
7617
7618 String tagName = parser.getName();
7619 if (tagName.equals("cert")) {
7620 if (pos < count) {
7621 String index = parser.getAttributeValue(null, "index");
7622 if (index != null) {
7623 try {
7624 int idx = Integer.parseInt(index);
7625 String key = parser.getAttributeValue(null, "key");
7626 if (key == null) {
7627 if (idx >= 0 && idx < pastSignatures.size()) {
7628 Signature sig = pastSignatures.get(idx);
7629 if (sig != null) {
7630 mSignatures[pos] = pastSignatures.get(idx);
7631 pos++;
7632 } else {
7633 reportSettingsProblem(Log.WARN,
7634 "Error in package manager settings: <cert> "
7635 + "index " + index + " is not defined at "
7636 + parser.getPositionDescription());
7637 }
7638 } else {
7639 reportSettingsProblem(Log.WARN,
7640 "Error in package manager settings: <cert> "
7641 + "index " + index + " is out of bounds at "
7642 + parser.getPositionDescription());
7643 }
7644 } else {
7645 while (pastSignatures.size() <= idx) {
7646 pastSignatures.add(null);
7647 }
7648 Signature sig = new Signature(key);
7649 pastSignatures.set(idx, sig);
7650 mSignatures[pos] = sig;
7651 pos++;
7652 }
7653 } catch (NumberFormatException e) {
7654 reportSettingsProblem(Log.WARN,
7655 "Error in package manager settings: <cert> "
7656 + "index " + index + " is not a number at "
7657 + parser.getPositionDescription());
7658 }
7659 } else {
7660 reportSettingsProblem(Log.WARN,
7661 "Error in package manager settings: <cert> has"
7662 + " no index at " + parser.getPositionDescription());
7663 }
7664 } else {
7665 reportSettingsProblem(Log.WARN,
7666 "Error in package manager settings: too "
7667 + "many <cert> tags, expected " + count
7668 + " at " + parser.getPositionDescription());
7669 }
7670 } else {
7671 reportSettingsProblem(Log.WARN,
7672 "Unknown element under <cert>: "
7673 + parser.getName());
7674 }
7675 XmlUtils.skipCurrentTag(parser);
7676 }
7677
7678 if (pos < count) {
7679 // Should never happen -- there is an error in the written
7680 // settings -- but if it does we don't want to generate
7681 // a bad array.
7682 Signature[] newSigs = new Signature[pos];
7683 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7684 mSignatures = newSigs;
7685 }
7686 }
7687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 private void assignSignatures(Signature[] sigs) {
7689 if (sigs == null) {
7690 mSignatures = null;
7691 return;
7692 }
7693 mSignatures = new Signature[sigs.length];
7694 for (int i=0; i<sigs.length; i++) {
7695 mSignatures[i] = sigs[i];
7696 }
7697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007699 @Override
7700 public String toString() {
7701 StringBuffer buf = new StringBuffer(128);
7702 buf.append("PackageSignatures{");
7703 buf.append(Integer.toHexString(System.identityHashCode(this)));
7704 buf.append(" [");
7705 if (mSignatures != null) {
7706 for (int i=0; i<mSignatures.length; i++) {
7707 if (i > 0) buf.append(", ");
7708 buf.append(Integer.toHexString(
7709 System.identityHashCode(mSignatures[i])));
7710 }
7711 }
7712 buf.append("]}");
7713 return buf.toString();
7714 }
7715 }
7716
7717 static class PreferredActivity extends IntentFilter {
7718 final int mMatch;
7719 final String[] mSetPackages;
7720 final String[] mSetClasses;
7721 final String[] mSetComponents;
7722 final ComponentName mActivity;
7723 final String mShortActivity;
7724 String mParseError;
7725
7726 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7727 ComponentName activity) {
7728 super(filter);
7729 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7730 mActivity = activity;
7731 mShortActivity = activity.flattenToShortString();
7732 mParseError = null;
7733 if (set != null) {
7734 final int N = set.length;
7735 String[] myPackages = new String[N];
7736 String[] myClasses = new String[N];
7737 String[] myComponents = new String[N];
7738 for (int i=0; i<N; i++) {
7739 ComponentName cn = set[i];
7740 if (cn == null) {
7741 mSetPackages = null;
7742 mSetClasses = null;
7743 mSetComponents = null;
7744 return;
7745 }
7746 myPackages[i] = cn.getPackageName().intern();
7747 myClasses[i] = cn.getClassName().intern();
7748 myComponents[i] = cn.flattenToShortString().intern();
7749 }
7750 mSetPackages = myPackages;
7751 mSetClasses = myClasses;
7752 mSetComponents = myComponents;
7753 } else {
7754 mSetPackages = null;
7755 mSetClasses = null;
7756 mSetComponents = null;
7757 }
7758 }
7759
7760 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7761 IOException {
7762 mShortActivity = parser.getAttributeValue(null, "name");
7763 mActivity = ComponentName.unflattenFromString(mShortActivity);
7764 if (mActivity == null) {
7765 mParseError = "Bad activity name " + mShortActivity;
7766 }
7767 String matchStr = parser.getAttributeValue(null, "match");
7768 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7769 String setCountStr = parser.getAttributeValue(null, "set");
7770 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7771
7772 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7773 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7774 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7775
7776 int setPos = 0;
7777
7778 int outerDepth = parser.getDepth();
7779 int type;
7780 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7781 && (type != XmlPullParser.END_TAG
7782 || parser.getDepth() > outerDepth)) {
7783 if (type == XmlPullParser.END_TAG
7784 || type == XmlPullParser.TEXT) {
7785 continue;
7786 }
7787
7788 String tagName = parser.getName();
7789 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7790 // + parser.getDepth() + " tag=" + tagName);
7791 if (tagName.equals("set")) {
7792 String name = parser.getAttributeValue(null, "name");
7793 if (name == null) {
7794 if (mParseError == null) {
7795 mParseError = "No name in set tag in preferred activity "
7796 + mShortActivity;
7797 }
7798 } else if (setPos >= setCount) {
7799 if (mParseError == null) {
7800 mParseError = "Too many set tags in preferred activity "
7801 + mShortActivity;
7802 }
7803 } else {
7804 ComponentName cn = ComponentName.unflattenFromString(name);
7805 if (cn == null) {
7806 if (mParseError == null) {
7807 mParseError = "Bad set name " + name + " in preferred activity "
7808 + mShortActivity;
7809 }
7810 } else {
7811 myPackages[setPos] = cn.getPackageName();
7812 myClasses[setPos] = cn.getClassName();
7813 myComponents[setPos] = name;
7814 setPos++;
7815 }
7816 }
7817 XmlUtils.skipCurrentTag(parser);
7818 } else if (tagName.equals("filter")) {
7819 //Log.i(TAG, "Starting to parse filter...");
7820 readFromXml(parser);
7821 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7822 // + parser.getDepth() + " tag=" + parser.getName());
7823 } else {
7824 reportSettingsProblem(Log.WARN,
7825 "Unknown element under <preferred-activities>: "
7826 + parser.getName());
7827 XmlUtils.skipCurrentTag(parser);
7828 }
7829 }
7830
7831 if (setPos != setCount) {
7832 if (mParseError == null) {
7833 mParseError = "Not enough set tags (expected " + setCount
7834 + " but found " + setPos + ") in " + mShortActivity;
7835 }
7836 }
7837
7838 mSetPackages = myPackages;
7839 mSetClasses = myClasses;
7840 mSetComponents = myComponents;
7841 }
7842
7843 public void writeToXml(XmlSerializer serializer) throws IOException {
7844 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7845 serializer.attribute(null, "name", mShortActivity);
7846 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7847 serializer.attribute(null, "set", Integer.toString(NS));
7848 for (int s=0; s<NS; s++) {
7849 serializer.startTag(null, "set");
7850 serializer.attribute(null, "name", mSetComponents[s]);
7851 serializer.endTag(null, "set");
7852 }
7853 serializer.startTag(null, "filter");
7854 super.writeToXml(serializer);
7855 serializer.endTag(null, "filter");
7856 }
7857
7858 boolean sameSet(List<ResolveInfo> query, int priority) {
7859 if (mSetPackages == null) return false;
7860 final int NQ = query.size();
7861 final int NS = mSetPackages.length;
7862 int numMatch = 0;
7863 for (int i=0; i<NQ; i++) {
7864 ResolveInfo ri = query.get(i);
7865 if (ri.priority != priority) continue;
7866 ActivityInfo ai = ri.activityInfo;
7867 boolean good = false;
7868 for (int j=0; j<NS; j++) {
7869 if (mSetPackages[j].equals(ai.packageName)
7870 && mSetClasses[j].equals(ai.name)) {
7871 numMatch++;
7872 good = true;
7873 break;
7874 }
7875 }
7876 if (!good) return false;
7877 }
7878 return numMatch == NS;
7879 }
7880 }
7881
7882 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007883 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007885 HashSet<String> grantedPermissions = new HashSet<String>();
7886 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007888 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007889 setFlags(pkgFlags);
7890 }
7891
Kenny Root291e78c2011-01-13 14:53:17 -08007892 GrantedPermissions(GrantedPermissions base) {
7893 pkgFlags = base.pkgFlags;
7894 grantedPermissions = (HashSet<String>) base.grantedPermissions.clone();
Kenny Rootbd392c52011-01-14 10:34:56 -08007895
7896 if (base.gids != null) {
7897 gids = base.gids.clone();
7898 }
Kenny Root291e78c2011-01-13 14:53:17 -08007899 }
7900
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007901 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007902 this.pkgFlags = pkgFlags & (
7903 ApplicationInfo.FLAG_SYSTEM |
7904 ApplicationInfo.FLAG_FORWARD_LOCK |
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08007905 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 }
7907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 /**
7910 * Settings base class for pending and resolved classes.
7911 */
7912 static class PackageSettingBase extends GrantedPermissions {
7913 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007914 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007915 File codePath;
7916 String codePathString;
7917 File resourcePath;
7918 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007919 String nativeLibraryPathString;
Kenny Root5d40fe92011-01-14 10:54:46 -08007920 String[] obbPathStrings;
Kenny Root7d794fb2010-09-13 16:29:49 -07007921 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007922 long firstInstallTime;
7923 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007924 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007926 boolean uidError;
Kenny Root291e78c2011-01-13 14:53:17 -08007927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928 PackageSignatures signatures = new PackageSignatures();
7929
7930 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007931 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 /* Explicitly disabled components */
7934 HashSet<String> disabledComponents = new HashSet<String>(0);
7935 /* Explicitly enabled components */
7936 HashSet<String> enabledComponents = new HashSet<String>(0);
7937 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7938 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007939
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007940 PackageSettingBase origPackage;
7941
Jacek Surazski65e13172009-04-28 15:26:38 +02007942 /* package name of the app that installed this package */
7943 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007945 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007946 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007947 super(pkgFlags);
7948 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007949 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007950 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007951 }
7952
Kenny Root291e78c2011-01-13 14:53:17 -08007953 /**
7954 * New instance of PackageSetting with one-level-deep cloning.
7955 */
7956 PackageSettingBase(PackageSettingBase base) {
7957 super(base);
7958
7959 name = base.name;
7960 realName = base.realName;
7961 codePath = base.codePath;
7962 codePathString = base.codePathString;
7963 resourcePath = base.resourcePath;
7964 resourcePathString = base.resourcePathString;
7965 nativeLibraryPathString = base.nativeLibraryPathString;
Kenny Root5d40fe92011-01-14 10:54:46 -08007966
7967 if (base.obbPathStrings != null) {
7968 obbPathStrings = base.obbPathStrings.clone();
7969 }
7970
Kenny Root291e78c2011-01-13 14:53:17 -08007971 timeStamp = base.timeStamp;
7972 firstInstallTime = base.firstInstallTime;
7973 lastUpdateTime = base.lastUpdateTime;
7974 versionCode = base.versionCode;
7975
7976 uidError = base.uidError;
7977
7978 signatures = new PackageSignatures(base.signatures);
7979
7980 permissionsFixed = base.permissionsFixed;
7981 haveGids = base.haveGids;
7982
7983 disabledComponents = (HashSet<String>) base.disabledComponents.clone();
7984
7985 enabledComponents = (HashSet<String>) base.enabledComponents.clone();
7986
7987 enabled = base.enabled;
7988 installStatus = base.installStatus;
7989
7990 origPackage = base.origPackage;
7991
7992 installerPackageName = base.installerPackageName;
7993 }
7994
Kenny Root806cc132010-09-12 08:34:19 -07007995 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7996 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 this.codePath = codePath;
7998 this.codePathString = codePath.toString();
7999 this.resourcePath = resourcePath;
8000 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07008001 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008002 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008003 }
Kenny Root85387d72010-08-26 10:13:11 -07008004
Jacek Surazski65e13172009-04-28 15:26:38 +02008005 public void setInstallerPackageName(String packageName) {
8006 installerPackageName = packageName;
8007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008008
Jacek Surazski65e13172009-04-28 15:26:38 +02008009 String getInstallerPackageName() {
8010 return installerPackageName;
8011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008013 public void setInstallStatus(int newStatus) {
8014 installStatus = newStatus;
8015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 public int getInstallStatus() {
8018 return installStatus;
8019 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008022 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 }
8024
Kenny Root291e78c2011-01-13 14:53:17 -08008025 /**
8026 * Make a shallow copy of this package settings.
8027 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008028 public void copyFrom(PackageSettingBase base) {
8029 grantedPermissions = base.grantedPermissions;
8030 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008033 firstInstallTime = base.firstInstallTime;
8034 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 signatures = base.signatures;
8036 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07008037 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 disabledComponents = base.disabledComponents;
8039 enabledComponents = base.enabledComponents;
8040 enabled = base.enabled;
8041 installStatus = base.installStatus;
8042 }
8043
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008044 boolean enableComponentLP(String componentClassName) {
8045 boolean changed = disabledComponents.remove(componentClassName);
8046 changed |= enabledComponents.add(componentClassName);
8047 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 }
8049
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008050 boolean disableComponentLP(String componentClassName) {
8051 boolean changed = enabledComponents.remove(componentClassName);
8052 changed |= disabledComponents.add(componentClassName);
8053 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008054 }
8055
Dianne Hackbornd7c09682010-03-30 10:42:20 -07008056 boolean restoreComponentLP(String componentClassName) {
8057 boolean changed = enabledComponents.remove(componentClassName);
8058 changed |= disabledComponents.remove(componentClassName);
8059 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 }
8061
8062 int currentEnabledStateLP(String componentName) {
8063 if (enabledComponents.contains(componentName)) {
8064 return COMPONENT_ENABLED_STATE_ENABLED;
8065 } else if (disabledComponents.contains(componentName)) {
8066 return COMPONENT_ENABLED_STATE_DISABLED;
8067 } else {
8068 return COMPONENT_ENABLED_STATE_DEFAULT;
8069 }
8070 }
8071 }
8072
8073 /**
8074 * Settings data for a particular package we know about.
8075 */
8076 static final class PackageSetting extends PackageSettingBase {
8077 int userId;
8078 PackageParser.Package pkg;
8079 SharedUserSetting sharedUser;
8080
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008081 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008082 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
8083 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
8084 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008086
Kenny Root291e78c2011-01-13 14:53:17 -08008087 /**
8088 * New instance of PackageSetting replicating the original settings.
8089 * Note that it keeps the same PackageParser.Package instance.
8090 */
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008091 PackageSetting(PackageSetting orig) {
Kenny Root291e78c2011-01-13 14:53:17 -08008092 super(orig);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008093
Kenny Root291e78c2011-01-13 14:53:17 -08008094 userId = orig.userId;
8095 pkg = orig.pkg;
8096 sharedUser = orig.sharedUser;
Kenny Root97ef63b2011-01-11 11:15:35 -08008097 }
8098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 @Override
8100 public String toString() {
8101 return "PackageSetting{"
8102 + Integer.toHexString(System.identityHashCode(this))
8103 + " " + name + "/" + userId + "}";
8104 }
8105 }
8106
8107 /**
8108 * Settings data for a particular shared user ID we know about.
8109 */
8110 static final class SharedUserSetting extends GrantedPermissions {
8111 final String name;
8112 int userId;
8113 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
8114 final PackageSignatures signatures = new PackageSignatures();
8115
8116 SharedUserSetting(String _name, int _pkgFlags) {
8117 super(_pkgFlags);
8118 name = _name;
8119 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008121 @Override
8122 public String toString() {
8123 return "SharedUserSetting{"
8124 + Integer.toHexString(System.identityHashCode(this))
8125 + " " + name + "/" + userId + "}";
8126 }
8127 }
8128
8129 /**
8130 * Holds information about dynamic settings.
8131 */
8132 private static final class Settings {
8133 private final File mSettingsFilename;
8134 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008135 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008136 private final HashMap<String, PackageSetting> mPackages =
8137 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 // List of replaced system applications
8139 final HashMap<String, PackageSetting> mDisabledSysPackages =
8140 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008141
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008142 // These are the last platform API version we were using for
8143 // the apps installed on internal and external storage. It is
8144 // used to grant newer permissions one time during a system upgrade.
8145 int mInternalSdkPlatform;
8146 int mExternalSdkPlatform;
8147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 // The user's preferred activities associated with particular intent
8149 // filters.
8150 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
8151 new IntentResolver<PreferredActivity, PreferredActivity>() {
8152 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008153 protected String packageForFilter(PreferredActivity filter) {
8154 return filter.mActivity.getPackageName();
8155 }
8156 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008157 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008159 out.print(prefix); out.print(
8160 Integer.toHexString(System.identityHashCode(filter)));
8161 out.print(' ');
8162 out.print(filter.mActivity.flattenToShortString());
8163 out.print(" match=0x");
8164 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008166 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008167 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008168 out.print(prefix); out.print(" ");
8169 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 }
8171 }
8172 }
8173 };
8174 private final HashMap<String, SharedUserSetting> mSharedUsers =
8175 new HashMap<String, SharedUserSetting>();
8176 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
8177 private final SparseArray<Object> mOtherUserIds =
8178 new SparseArray<Object>();
8179
8180 // For reading/writing settings file.
8181 private final ArrayList<Signature> mPastSignatures =
8182 new ArrayList<Signature>();
8183
8184 // Mapping from permission names to info about them.
8185 final HashMap<String, BasePermission> mPermissions =
8186 new HashMap<String, BasePermission>();
8187
8188 // Mapping from permission tree names to info about them.
8189 final HashMap<String, BasePermission> mPermissionTrees =
8190 new HashMap<String, BasePermission>();
8191
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008192 // Packages that have been uninstalled and still need their external
8193 // storage data deleted.
8194 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
8195
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008196 // Packages that have been renamed since they were first installed.
8197 // Keys are the new names of the packages, values are the original
8198 // names. The packages appear everwhere else under their original
8199 // names.
8200 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
8201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008202 private final StringBuilder mReadMessages = new StringBuilder();
8203
8204 private static final class PendingPackage extends PackageSettingBase {
8205 final int sharedId;
8206
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008207 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008208 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
8209 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
8210 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008211 this.sharedId = sharedId;
8212 }
8213 }
8214 private final ArrayList<PendingPackage> mPendingPackages
8215 = new ArrayList<PendingPackage>();
8216
8217 Settings() {
8218 File dataDir = Environment.getDataDirectory();
8219 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08008220 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
8221 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008223 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008224 FileUtils.setPermissions(systemDir.toString(),
8225 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8226 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8227 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08008228 FileUtils.setPermissions(systemSecureDir.toString(),
8229 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8230 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8231 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232 mSettingsFilename = new File(systemDir, "packages.xml");
8233 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008234 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008235 }
8236
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008237 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008238 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008239 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008241 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07008242 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243 return p;
8244 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008245
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008246 PackageSetting peekPackageLP(String name) {
8247 return mPackages.get(name);
8248 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008249 PackageSetting p = mPackages.get(name);
8250 if (p != null && p.codePath.getPath().equals(codePath)) {
8251 return p;
8252 }
8253 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008254 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257 void setInstallStatus(String pkgName, int status) {
8258 PackageSetting p = mPackages.get(pkgName);
8259 if(p != null) {
8260 if(p.getInstallStatus() != status) {
8261 p.setInstallStatus(status);
8262 }
8263 }
8264 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008265
Jacek Surazski65e13172009-04-28 15:26:38 +02008266 void setInstallerPackageName(String pkgName,
8267 String installerPkgName) {
8268 PackageSetting p = mPackages.get(pkgName);
8269 if(p != null) {
8270 p.setInstallerPackageName(installerPkgName);
8271 }
8272 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008273
Jacek Surazski65e13172009-04-28 15:26:38 +02008274 String getInstallerPackageName(String pkgName) {
8275 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008276 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008277 }
8278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 int getInstallStatus(String pkgName) {
8280 PackageSetting p = mPackages.get(pkgName);
8281 if(p != null) {
8282 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 return -1;
8285 }
8286
8287 SharedUserSetting getSharedUserLP(String name,
8288 int pkgFlags, boolean create) {
8289 SharedUserSetting s = mSharedUsers.get(name);
8290 if (s == null) {
8291 if (!create) {
8292 return null;
8293 }
8294 s = new SharedUserSetting(name, pkgFlags);
8295 if (MULTIPLE_APPLICATION_UIDS) {
8296 s.userId = newUserIdLP(s);
8297 } else {
8298 s.userId = FIRST_APPLICATION_UID;
8299 }
8300 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8301 // < 0 means we couldn't assign a userid; fall out and return
8302 // s, which is currently null
8303 if (s.userId >= 0) {
8304 mSharedUsers.put(name, s);
8305 }
8306 }
8307
8308 return s;
8309 }
8310
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008311 boolean disableSystemPackageLP(String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 PackageSetting p = mPackages.get(name);
8313 if(p == null) {
8314 Log.w(TAG, "Package:"+name+" is not an installed package");
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008315 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008316 }
8317 PackageSetting dp = mDisabledSysPackages.get(name);
8318 // always make sure the system package code and resource paths dont change
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008319 if (dp == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8321 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8322 }
8323 mDisabledSysPackages.put(name, p);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008324
8325 // a little trick... when we install the new package, we don't
8326 // want to modify the existing PackageSetting for the built-in
8327 // version. so at this point we need a new PackageSetting that
Kenny Root291e78c2011-01-13 14:53:17 -08008328 // is okay to muck with.
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008329 PackageSetting newp = new PackageSetting(p);
8330 replacePackageLP(name, newp);
8331 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008332 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008333 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008334 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 PackageSetting enableSystemPackageLP(String name) {
8337 PackageSetting p = mDisabledSysPackages.get(name);
8338 if(p == null) {
8339 Log.w(TAG, "Package:"+name+" is not disabled");
8340 return null;
8341 }
8342 // Reset flag in ApplicationInfo object
8343 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8344 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8345 }
Kenny Root806cc132010-09-12 08:34:19 -07008346 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8347 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008348 mDisabledSysPackages.remove(name);
8349 return ret;
8350 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008351
Kenny Root806cc132010-09-12 08:34:19 -07008352 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8353 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 PackageSetting p = mPackages.get(name);
8355 if (p != null) {
8356 if (p.userId == uid) {
8357 return p;
8358 }
8359 reportSettingsProblem(Log.ERROR,
8360 "Adding duplicate package, keeping first: " + name);
8361 return null;
8362 }
Kenny Root806cc132010-09-12 08:34:19 -07008363 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8364 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008365 p.userId = uid;
8366 if (addUserIdLP(uid, p, name)) {
8367 mPackages.put(name, p);
8368 return p;
8369 }
8370 return null;
8371 }
8372
8373 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8374 SharedUserSetting s = mSharedUsers.get(name);
8375 if (s != null) {
8376 if (s.userId == uid) {
8377 return s;
8378 }
8379 reportSettingsProblem(Log.ERROR,
8380 "Adding duplicate shared user, keeping first: " + name);
8381 return null;
8382 }
8383 s = new SharedUserSetting(name, pkgFlags);
8384 s.userId = uid;
8385 if (addUserIdLP(uid, s, name)) {
8386 mSharedUsers.put(name, s);
8387 return s;
8388 }
8389 return null;
8390 }
8391
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008392 // Transfer ownership of permissions from one package to another.
8393 private void transferPermissions(String origPkg, String newPkg) {
8394 // Transfer ownership of permissions to the new package.
8395 for (int i=0; i<2; i++) {
8396 HashMap<String, BasePermission> permissions =
8397 i == 0 ? mPermissionTrees : mPermissions;
8398 for (BasePermission bp : permissions.values()) {
8399 if (origPkg.equals(bp.sourcePackage)) {
8400 if (DEBUG_UPGRADE) Log.v(TAG,
8401 "Moving permission " + bp.name
8402 + " from pkg " + bp.sourcePackage
8403 + " to " + newPkg);
8404 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008405 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008406 bp.perm = null;
8407 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008408 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008409 }
8410 bp.uid = 0;
8411 bp.gids = null;
8412 }
8413 }
8414 }
8415 }
8416
8417 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008418 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008419 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008420 PackageSetting p = mPackages.get(name);
8421 if (p != null) {
8422 if (!p.codePath.equals(codePath)) {
8423 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008424 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008425 // This is an updated system app with versions in both system
8426 // and data partition. Just let the most recent version
8427 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008428 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008429 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008430 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008431 // Just a change in the code path is not an issue, but
8432 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008433 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008434 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008435 /*
8436 * Since we've changed paths, we need to prefer the new
8437 * native library path over the one stored in the
8438 * package settings since we might have moved from
8439 * internal to external storage or vice versa.
8440 */
8441 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008442 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008443 }
8444 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008445 reportSettingsProblem(Log.WARN,
8446 "Package " + name + " shared user changed from "
8447 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8448 + " to "
8449 + (sharedUser != null ? sharedUser.name : "<nothing>")
8450 + "; replacing with new");
8451 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008452 } else {
8453 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8454 // If what we are scanning is a system package, then
8455 // make it so, regardless of whether it was previously
8456 // installed only in the data partition.
8457 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459 }
8460 }
8461 if (p == null) {
8462 // Create a new PackageSettings entry. this can end up here because
8463 // of code path mismatch or user id mismatch of an updated system partition
8464 if (!create) {
8465 return null;
8466 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008467 if (origPackage != null) {
8468 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008469 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8470 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008471 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8472 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008473 // Note that we will retain the new package's signature so
8474 // that we can keep its data.
8475 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008476 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008477 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008478 p.sharedUser = origPackage.sharedUser;
8479 p.userId = origPackage.userId;
8480 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008481 mRenamedPackages.put(name, origPackage.name);
8482 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008483 // Update new package state.
8484 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008485 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008486 p = new PackageSetting(name, realName, codePath, resourcePath,
8487 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008488 p.setTimeStamp(codePath.lastModified());
8489 p.sharedUser = sharedUser;
8490 if (sharedUser != null) {
8491 p.userId = sharedUser.userId;
8492 } else if (MULTIPLE_APPLICATION_UIDS) {
8493 // Clone the setting here for disabled system packages
8494 PackageSetting dis = mDisabledSysPackages.get(name);
8495 if (dis != null) {
8496 // For disabled packages a new setting is created
8497 // from the existing user id. This still has to be
8498 // added to list of user id's
8499 // Copy signatures from previous setting
8500 if (dis.signatures.mSignatures != null) {
8501 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8502 }
8503 p.userId = dis.userId;
8504 // Clone permissions
8505 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008506 // Clone component info
8507 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8508 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8509 // Add new setting to list of user ids
8510 addUserIdLP(p.userId, p, name);
8511 } else {
8512 // Assign new user id
8513 p.userId = newUserIdLP(p);
8514 }
8515 } else {
8516 p.userId = FIRST_APPLICATION_UID;
8517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 }
8519 if (p.userId < 0) {
8520 reportSettingsProblem(Log.WARN,
8521 "Package " + name + " could not be assigned a valid uid");
8522 return null;
8523 }
8524 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008525 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008526 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008527 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 }
8529 }
8530 return p;
8531 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008532
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008533 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008534 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008535 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008536 final String codePath = pkg.applicationInfo.sourceDir;
8537 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008538 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008539 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008540 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008541 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008542 p.codePath = new File(codePath);
8543 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008544 }
8545 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008546 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008547 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008548 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008549 p.resourcePath = new File(resourcePath);
8550 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008551 }
Kenny Root85387d72010-08-26 10:13:11 -07008552 // Update the native library path if needed
8553 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8554 if (nativeLibraryPath != null
8555 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8556 p.nativeLibraryPathString = nativeLibraryPath;
8557 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008558 // Update version code if needed
8559 if (pkg.mVersionCode != p.versionCode) {
8560 p.versionCode = pkg.mVersionCode;
8561 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008562 // Update signatures if needed.
8563 if (p.signatures.mSignatures == null) {
8564 p.signatures.assignSignatures(pkg.mSignatures);
8565 }
8566 // If this app defines a shared user id initialize
8567 // the shared user signatures as well.
8568 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8569 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8570 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008571 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8572 }
8573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 // Utility method that adds a PackageSetting to mPackages and
8575 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008576 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 SharedUserSetting sharedUser) {
8578 mPackages.put(name, p);
8579 if (sharedUser != null) {
8580 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8581 reportSettingsProblem(Log.ERROR,
8582 "Package " + p.name + " was user "
8583 + p.sharedUser + " but is now " + sharedUser
8584 + "; I am not changing its files so it will probably fail!");
8585 p.sharedUser.packages.remove(p);
8586 } else if (p.userId != sharedUser.userId) {
8587 reportSettingsProblem(Log.ERROR,
8588 "Package " + p.name + " was user id " + p.userId
8589 + " but is now user " + sharedUser
8590 + " with id " + sharedUser.userId
8591 + "; I am not changing its files so it will probably fail!");
8592 }
8593
8594 sharedUser.packages.add(p);
8595 p.sharedUser = sharedUser;
8596 p.userId = sharedUser.userId;
8597 }
8598 }
8599
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008600 /*
8601 * Update the shared user setting when a package using
8602 * specifying the shared user id is removed. The gids
8603 * associated with each permission of the deleted package
8604 * are removed from the shared user's gid list only if its
8605 * not in use by other permissions of packages in the
8606 * shared user setting.
8607 */
8608 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008609 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008610 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 return;
8612 }
8613 // No sharedUserId
8614 if (deletedPs.sharedUser == null) {
8615 return;
8616 }
8617 SharedUserSetting sus = deletedPs.sharedUser;
8618 // Update permissions
8619 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8620 boolean used = false;
8621 if (!sus.grantedPermissions.contains (eachPerm)) {
8622 continue;
8623 }
8624 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008625 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008626 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008627 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 used = true;
8629 break;
8630 }
8631 }
8632 if (!used) {
8633 // can safely delete this permission from list
8634 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008635 }
8636 }
8637 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008638 int newGids[] = globalGids;
8639 for (String eachPerm : sus.grantedPermissions) {
8640 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008641 if (bp != null) {
8642 newGids = appendInts(newGids, bp.gids);
8643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 }
8645 sus.gids = newGids;
8646 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008648 private int removePackageLP(String name) {
8649 PackageSetting p = mPackages.get(name);
8650 if (p != null) {
8651 mPackages.remove(name);
8652 if (p.sharedUser != null) {
8653 p.sharedUser.packages.remove(p);
8654 if (p.sharedUser.packages.size() == 0) {
8655 mSharedUsers.remove(p.sharedUser.name);
8656 removeUserIdLP(p.sharedUser.userId);
8657 return p.sharedUser.userId;
8658 }
8659 } else {
8660 removeUserIdLP(p.userId);
8661 return p.userId;
8662 }
8663 }
8664 return -1;
8665 }
8666
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008667 private void replacePackageLP(String name, PackageSetting newp) {
8668 PackageSetting p = mPackages.get(name);
8669 if (p != null) {
8670 if (p.sharedUser != null) {
8671 p.sharedUser.packages.remove(p);
8672 p.sharedUser.packages.add(newp);
8673 } else {
8674 replaceUserIdLP(p.userId, newp);
8675 }
8676 }
8677 mPackages.put(name, newp);
8678 }
8679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 private boolean addUserIdLP(int uid, Object obj, Object name) {
8681 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8682 return false;
8683 }
8684
8685 if (uid >= FIRST_APPLICATION_UID) {
8686 int N = mUserIds.size();
8687 final int index = uid - FIRST_APPLICATION_UID;
8688 while (index >= N) {
8689 mUserIds.add(null);
8690 N++;
8691 }
8692 if (mUserIds.get(index) != null) {
8693 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008694 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008695 + " name=" + name);
8696 return false;
8697 }
8698 mUserIds.set(index, obj);
8699 } else {
8700 if (mOtherUserIds.get(uid) != null) {
8701 reportSettingsProblem(Log.ERROR,
8702 "Adding duplicate shared id: " + uid
8703 + " name=" + name);
8704 return false;
8705 }
8706 mOtherUserIds.put(uid, obj);
8707 }
8708 return true;
8709 }
8710
8711 public Object getUserIdLP(int uid) {
8712 if (uid >= FIRST_APPLICATION_UID) {
8713 int N = mUserIds.size();
8714 final int index = uid - FIRST_APPLICATION_UID;
8715 return index < N ? mUserIds.get(index) : null;
8716 } else {
8717 return mOtherUserIds.get(uid);
8718 }
8719 }
8720
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008721 private Set<String> findPackagesWithFlag(int flag) {
8722 Set<String> ret = new HashSet<String>();
8723 for (PackageSetting ps : mPackages.values()) {
8724 // Has to match atleast all the flag bits set on flag
8725 if ((ps.pkgFlags & flag) == flag) {
8726 ret.add(ps.name);
8727 }
8728 }
8729 return ret;
8730 }
8731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008732 private void removeUserIdLP(int uid) {
8733 if (uid >= FIRST_APPLICATION_UID) {
8734 int N = mUserIds.size();
8735 final int index = uid - FIRST_APPLICATION_UID;
8736 if (index < N) mUserIds.set(index, null);
8737 } else {
8738 mOtherUserIds.remove(uid);
8739 }
8740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008741
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008742 private void replaceUserIdLP(int uid, Object obj) {
8743 if (uid >= FIRST_APPLICATION_UID) {
8744 int N = mUserIds.size();
8745 final int index = uid - FIRST_APPLICATION_UID;
8746 if (index < N) mUserIds.set(index, obj);
8747 } else {
8748 mOtherUserIds.put(uid, obj);
8749 }
8750 }
8751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 void writeLP() {
8753 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8754
8755 // Keep the old settings around until we know the new ones have
8756 // been successfully written.
8757 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008758 // Presence of backup settings file indicates that we failed
8759 // to persist settings earlier. So preserve the older
8760 // backup for future reference since the current settings
8761 // might have been corrupted.
8762 if (!mBackupSettingsFilename.exists()) {
8763 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008764 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008765 return;
8766 }
8767 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008768 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008769 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 }
8772
8773 mPastSignatures.clear();
8774
8775 try {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008776 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
8777 BufferedOutputStream str = new BufferedOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778
8779 //XmlSerializer serializer = XmlUtils.serializerInstance();
8780 XmlSerializer serializer = new FastXmlSerializer();
8781 serializer.setOutput(str, "utf-8");
8782 serializer.startDocument(null, true);
8783 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8784
8785 serializer.startTag(null, "packages");
8786
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008787 serializer.startTag(null, "last-platform-version");
8788 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8789 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8790 serializer.endTag(null, "last-platform-version");
8791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008792 serializer.startTag(null, "permission-trees");
8793 for (BasePermission bp : mPermissionTrees.values()) {
8794 writePermission(serializer, bp);
8795 }
8796 serializer.endTag(null, "permission-trees");
8797
8798 serializer.startTag(null, "permissions");
8799 for (BasePermission bp : mPermissions.values()) {
8800 writePermission(serializer, bp);
8801 }
8802 serializer.endTag(null, "permissions");
8803
8804 for (PackageSetting pkg : mPackages.values()) {
8805 writePackage(serializer, pkg);
8806 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8809 writeDisabledSysPackage(serializer, pkg);
8810 }
8811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008812 serializer.startTag(null, "preferred-activities");
8813 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8814 serializer.startTag(null, "item");
8815 pa.writeToXml(serializer);
8816 serializer.endTag(null, "item");
8817 }
8818 serializer.endTag(null, "preferred-activities");
8819
8820 for (SharedUserSetting usr : mSharedUsers.values()) {
8821 serializer.startTag(null, "shared-user");
8822 serializer.attribute(null, "name", usr.name);
8823 serializer.attribute(null, "userId",
8824 Integer.toString(usr.userId));
8825 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8826 serializer.startTag(null, "perms");
8827 for (String name : usr.grantedPermissions) {
8828 serializer.startTag(null, "item");
8829 serializer.attribute(null, "name", name);
8830 serializer.endTag(null, "item");
8831 }
8832 serializer.endTag(null, "perms");
8833 serializer.endTag(null, "shared-user");
8834 }
8835
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008836 if (mPackagesToBeCleaned.size() > 0) {
8837 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8838 serializer.startTag(null, "cleaning-package");
8839 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8840 serializer.endTag(null, "cleaning-package");
8841 }
8842 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008843
8844 if (mRenamedPackages.size() > 0) {
8845 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8846 serializer.startTag(null, "renamed-package");
8847 serializer.attribute(null, "new", e.getKey());
8848 serializer.attribute(null, "old", e.getValue());
8849 serializer.endTag(null, "renamed-package");
8850 }
8851 }
8852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 serializer.endTag(null, "packages");
8854
8855 serializer.endDocument();
8856
8857 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008858 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008859 str.close();
8860
8861 // New settings successfully written, old ones are no longer
8862 // needed.
8863 mBackupSettingsFilename.delete();
8864 FileUtils.setPermissions(mSettingsFilename.toString(),
8865 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8866 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8867 |FileUtils.S_IROTH,
8868 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008869
8870 // Write package list file now, use a JournaledFile.
8871 //
8872 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8873 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8874
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008875 fstr = new FileOutputStream(journal.chooseForWrite());
8876 str = new BufferedOutputStream(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008877 try {
8878 StringBuilder sb = new StringBuilder();
8879 for (PackageSetting pkg : mPackages.values()) {
8880 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008881 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008882 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8883
8884 // Avoid any application that has a space in its path
8885 // or that is handled by the system.
8886 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8887 continue;
8888
8889 // we store on each line the following information for now:
8890 //
8891 // pkgName - package name
8892 // userId - application-specific user id
8893 // debugFlag - 0 or 1 if the package is debuggable.
8894 // dataPath - path to package's data path
8895 //
8896 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8897 //
8898 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8899 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8900 // system/core/run-as/run-as.c
8901 //
8902 sb.setLength(0);
8903 sb.append(ai.packageName);
8904 sb.append(" ");
Jason parksa3cdaa52011-01-13 14:15:43 -06008905 sb.append((int)ai.uid);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008906 sb.append(isDebug ? " 1 " : " 0 ");
8907 sb.append(dataPath);
8908 sb.append("\n");
8909 str.write(sb.toString().getBytes());
8910 }
8911 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008912 FileUtils.sync(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008913 str.close();
8914 journal.commit();
8915 }
8916 catch (Exception e) {
8917 journal.rollback();
8918 }
8919
8920 FileUtils.setPermissions(mPackageListFilename.toString(),
8921 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8922 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8923 |FileUtils.S_IROTH,
8924 -1, -1);
8925
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008926 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927
8928 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008929 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 -08008930 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008931 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 -08008932 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008933 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008934 if (mSettingsFilename.exists()) {
8935 if (!mSettingsFilename.delete()) {
8936 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8937 }
8938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 //Debug.stopMethodTracing();
8940 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008941
8942 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008943 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 serializer.startTag(null, "updated-package");
8945 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008946 if (pkg.realName != null) {
8947 serializer.attribute(null, "realName", pkg.realName);
8948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008950 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8951 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8952 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008953 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008954 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8955 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8956 }
Kenny Root85387d72010-08-26 10:13:11 -07008957 if (pkg.nativeLibraryPathString != null) {
8958 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 if (pkg.sharedUser == null) {
8961 serializer.attribute(null, "userId",
8962 Integer.toString(pkg.userId));
8963 } else {
8964 serializer.attribute(null, "sharedUserId",
8965 Integer.toString(pkg.userId));
8966 }
8967 serializer.startTag(null, "perms");
8968 if (pkg.sharedUser == null) {
8969 // If this is a shared user, the permissions will
8970 // be written there. We still need to write an
8971 // empty permissions list so permissionsFixed will
8972 // be set.
8973 for (final String name : pkg.grantedPermissions) {
8974 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008975 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008976 // We only need to write signature or system permissions but this wont
8977 // match the semantics of grantedPermissions. So write all permissions.
8978 serializer.startTag(null, "item");
8979 serializer.attribute(null, "name", name);
8980 serializer.endTag(null, "item");
8981 }
8982 }
8983 }
8984 serializer.endTag(null, "perms");
8985 serializer.endTag(null, "updated-package");
8986 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008987
8988 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008989 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008990 serializer.startTag(null, "package");
8991 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008992 if (pkg.realName != null) {
8993 serializer.attribute(null, "realName", pkg.realName);
8994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008995 serializer.attribute(null, "codePath", pkg.codePathString);
8996 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8997 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8998 }
Kenny Root85387d72010-08-26 10:13:11 -07008999 if (pkg.nativeLibraryPathString != null) {
9000 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
9001 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009002 serializer.attribute(null, "flags",
9003 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009004 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
9005 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
9006 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009007 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008 if (pkg.sharedUser == null) {
9009 serializer.attribute(null, "userId",
9010 Integer.toString(pkg.userId));
9011 } else {
9012 serializer.attribute(null, "sharedUserId",
9013 Integer.toString(pkg.userId));
9014 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009015 if (pkg.uidError) {
9016 serializer.attribute(null, "uidError", "true");
9017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009018 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
9019 serializer.attribute(null, "enabled",
9020 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
9021 ? "true" : "false");
9022 }
9023 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
9024 serializer.attribute(null, "installStatus", "false");
9025 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009026 if (pkg.installerPackageName != null) {
9027 serializer.attribute(null, "installer", pkg.installerPackageName);
9028 }
Kenny Root5d40fe92011-01-14 10:54:46 -08009029 if (pkg.obbPathStrings != null && pkg.obbPathStrings.length > 0) {
9030 int N = pkg.obbPathStrings.length;
9031 serializer.startTag(null, "obbs");
9032 for (int i = 0; i < N; i++) {
9033 serializer.startTag(null, "obb");
9034 serializer.attribute(null, "path", pkg.obbPathStrings[i]);
9035 serializer.endTag(null, "obb");
9036 }
9037 serializer.endTag(null, "obbs");
Kenny Root93565c4b2010-06-18 15:46:06 -07009038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009039 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
9040 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9041 serializer.startTag(null, "perms");
9042 if (pkg.sharedUser == null) {
9043 // If this is a shared user, the permissions will
9044 // be written there. We still need to write an
9045 // empty permissions list so permissionsFixed will
9046 // be set.
9047 for (final String name : pkg.grantedPermissions) {
9048 serializer.startTag(null, "item");
9049 serializer.attribute(null, "name", name);
9050 serializer.endTag(null, "item");
9051 }
9052 }
9053 serializer.endTag(null, "perms");
9054 }
9055 if (pkg.disabledComponents.size() > 0) {
9056 serializer.startTag(null, "disabled-components");
9057 for (final String name : pkg.disabledComponents) {
9058 serializer.startTag(null, "item");
9059 serializer.attribute(null, "name", name);
9060 serializer.endTag(null, "item");
9061 }
9062 serializer.endTag(null, "disabled-components");
9063 }
9064 if (pkg.enabledComponents.size() > 0) {
9065 serializer.startTag(null, "enabled-components");
9066 for (final String name : pkg.enabledComponents) {
9067 serializer.startTag(null, "item");
9068 serializer.attribute(null, "name", name);
9069 serializer.endTag(null, "item");
9070 }
9071 serializer.endTag(null, "enabled-components");
9072 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 serializer.endTag(null, "package");
9075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009077 void writePermission(XmlSerializer serializer, BasePermission bp)
9078 throws XmlPullParserException, java.io.IOException {
9079 if (bp.type != BasePermission.TYPE_BUILTIN
9080 && bp.sourcePackage != null) {
9081 serializer.startTag(null, "item");
9082 serializer.attribute(null, "name", bp.name);
9083 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009084 if (bp.protectionLevel !=
9085 PermissionInfo.PROTECTION_NORMAL) {
9086 serializer.attribute(null, "protection",
9087 Integer.toString(bp.protectionLevel));
9088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009089 if (DEBUG_SETTINGS) Log.v(TAG,
9090 "Writing perm: name=" + bp.name + " type=" + bp.type);
9091 if (bp.type == BasePermission.TYPE_DYNAMIC) {
9092 PermissionInfo pi = bp.perm != null ? bp.perm.info
9093 : bp.pendingInfo;
9094 if (pi != null) {
9095 serializer.attribute(null, "type", "dynamic");
9096 if (pi.icon != 0) {
9097 serializer.attribute(null, "icon",
9098 Integer.toString(pi.icon));
9099 }
9100 if (pi.nonLocalizedLabel != null) {
9101 serializer.attribute(null, "label",
9102 pi.nonLocalizedLabel.toString());
9103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009104 }
9105 }
9106 serializer.endTag(null, "item");
9107 }
9108 }
9109
9110 String getReadMessagesLP() {
9111 return mReadMessages.toString();
9112 }
9113
Oscar Montemayora8529f62009-11-18 10:14:20 -08009114 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009115 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
9116 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08009117 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009118 while(its.hasNext()) {
9119 String key = its.next();
9120 PackageSetting ps = mPackages.get(key);
9121 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08009122 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009123 }
9124 }
9125 return ret;
9126 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009128 boolean readLP() {
9129 FileInputStream str = null;
9130 if (mBackupSettingsFilename.exists()) {
9131 try {
9132 str = new FileInputStream(mBackupSettingsFilename);
9133 mReadMessages.append("Reading from backup settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009134 reportSettingsProblem(Log.INFO, "Need to read from backup settings file");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07009135 if (mSettingsFilename.exists()) {
9136 // If both the backup and settings file exist, we
9137 // ignore the settings since it might have been
9138 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009139 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07009140 mSettingsFilename.delete();
9141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 } catch (java.io.IOException e) {
9143 // We'll try for the normal settings file.
9144 }
9145 }
9146
9147 mPastSignatures.clear();
9148
9149 try {
9150 if (str == null) {
9151 if (!mSettingsFilename.exists()) {
9152 mReadMessages.append("No settings file found\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009153 reportSettingsProblem(Log.INFO, "No settings file; creating initial state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009154 return false;
9155 }
9156 str = new FileInputStream(mSettingsFilename);
9157 }
9158 XmlPullParser parser = Xml.newPullParser();
9159 parser.setInput(str, null);
9160
9161 int type;
9162 while ((type=parser.next()) != XmlPullParser.START_TAG
9163 && type != XmlPullParser.END_DOCUMENT) {
9164 ;
9165 }
9166
9167 if (type != XmlPullParser.START_TAG) {
9168 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009169 reportSettingsProblem(Log.WARN, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009170 return false;
9171 }
9172
9173 int outerDepth = parser.getDepth();
9174 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9175 && (type != XmlPullParser.END_TAG
9176 || parser.getDepth() > outerDepth)) {
9177 if (type == XmlPullParser.END_TAG
9178 || type == XmlPullParser.TEXT) {
9179 continue;
9180 }
9181
9182 String tagName = parser.getName();
9183 if (tagName.equals("package")) {
9184 readPackageLP(parser);
9185 } else if (tagName.equals("permissions")) {
9186 readPermissionsLP(mPermissions, parser);
9187 } else if (tagName.equals("permission-trees")) {
9188 readPermissionsLP(mPermissionTrees, parser);
9189 } else if (tagName.equals("shared-user")) {
9190 readSharedUserLP(parser);
9191 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08009192 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 } else if (tagName.equals("preferred-activities")) {
9194 readPreferredActivitiesLP(parser);
9195 } else if(tagName.equals("updated-package")) {
9196 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009197 } else if (tagName.equals("cleaning-package")) {
9198 String name = parser.getAttributeValue(null, "name");
9199 if (name != null) {
9200 mPackagesToBeCleaned.add(name);
9201 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009202 } else if (tagName.equals("renamed-package")) {
9203 String nname = parser.getAttributeValue(null, "new");
9204 String oname = parser.getAttributeValue(null, "old");
9205 if (nname != null && oname != null) {
9206 mRenamedPackages.put(nname, oname);
9207 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009208 } else if (tagName.equals("last-platform-version")) {
9209 mInternalSdkPlatform = mExternalSdkPlatform = 0;
9210 try {
9211 String internal = parser.getAttributeValue(null, "internal");
9212 if (internal != null) {
9213 mInternalSdkPlatform = Integer.parseInt(internal);
9214 }
9215 String external = parser.getAttributeValue(null, "external");
9216 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01009217 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009218 }
9219 } catch (NumberFormatException e) {
9220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009221 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009222 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009223 + parser.getName());
9224 XmlUtils.skipCurrentTag(parser);
9225 }
9226 }
9227
9228 str.close();
9229
9230 } catch(XmlPullParserException e) {
9231 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07009232 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009233 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009234
9235 } catch(java.io.IOException e) {
9236 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07009237 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009238 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009239
9240 }
9241
9242 int N = mPendingPackages.size();
9243 for (int i=0; i<N; i++) {
9244 final PendingPackage pp = mPendingPackages.get(i);
9245 Object idObj = getUserIdLP(pp.sharedId);
9246 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009247 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07009248 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
9249 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009250 if (p == null) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07009251 reportSettingsProblem(Log.WARN, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009252 + pp.name);
9253 continue;
9254 }
9255 p.copyFrom(pp);
9256 } else if (idObj != null) {
9257 String msg = "Bad package setting: package " + pp.name
9258 + " has shared uid " + pp.sharedId
9259 + " that is not a shared uid\n";
9260 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009261 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009262 } else {
9263 String msg = "Bad package setting: package " + pp.name
9264 + " has shared uid " + pp.sharedId
9265 + " that is not defined\n";
9266 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009267 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009268 }
9269 }
9270 mPendingPackages.clear();
9271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009272 mReadMessages.append("Read completed successfully: "
9273 + mPackages.size() + " packages, "
9274 + mSharedUsers.size() + " shared uids\n");
9275
9276 return true;
9277 }
9278
9279 private int readInt(XmlPullParser parser, String ns, String name,
9280 int defValue) {
9281 String v = parser.getAttributeValue(ns, name);
9282 try {
9283 if (v == null) {
9284 return defValue;
9285 }
9286 return Integer.parseInt(v);
9287 } catch (NumberFormatException e) {
9288 reportSettingsProblem(Log.WARN,
9289 "Error in package manager settings: attribute " +
9290 name + " has bad integer value " + v + " at "
9291 + parser.getPositionDescription());
9292 }
9293 return defValue;
9294 }
9295
9296 private void readPermissionsLP(HashMap<String, BasePermission> out,
9297 XmlPullParser parser)
9298 throws IOException, XmlPullParserException {
9299 int outerDepth = parser.getDepth();
9300 int type;
9301 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9302 && (type != XmlPullParser.END_TAG
9303 || parser.getDepth() > outerDepth)) {
9304 if (type == XmlPullParser.END_TAG
9305 || type == XmlPullParser.TEXT) {
9306 continue;
9307 }
9308
9309 String tagName = parser.getName();
9310 if (tagName.equals("item")) {
9311 String name = parser.getAttributeValue(null, "name");
9312 String sourcePackage = parser.getAttributeValue(null, "package");
9313 String ptype = parser.getAttributeValue(null, "type");
9314 if (name != null && sourcePackage != null) {
9315 boolean dynamic = "dynamic".equals(ptype);
9316 BasePermission bp = new BasePermission(name, sourcePackage,
9317 dynamic
9318 ? BasePermission.TYPE_DYNAMIC
9319 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009320 bp.protectionLevel = readInt(parser, null, "protection",
9321 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009322 if (dynamic) {
9323 PermissionInfo pi = new PermissionInfo();
9324 pi.packageName = sourcePackage.intern();
9325 pi.name = name.intern();
9326 pi.icon = readInt(parser, null, "icon", 0);
9327 pi.nonLocalizedLabel = parser.getAttributeValue(
9328 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009329 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330 bp.pendingInfo = pi;
9331 }
9332 out.put(bp.name, bp);
9333 } else {
9334 reportSettingsProblem(Log.WARN,
9335 "Error in package manager settings: permissions has"
9336 + " no name at " + parser.getPositionDescription());
9337 }
9338 } else {
9339 reportSettingsProblem(Log.WARN,
9340 "Unknown element reading permissions: "
9341 + parser.getName() + " at "
9342 + parser.getPositionDescription());
9343 }
9344 XmlUtils.skipCurrentTag(parser);
9345 }
9346 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009349 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009350 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009351 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 String codePathStr = parser.getAttributeValue(null, "codePath");
9353 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009354 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009355 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009356 resourcePathStr = codePathStr;
9357 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009358 String version = parser.getAttributeValue(null, "version");
9359 int versionCode = 0;
9360 if (version != null) {
9361 try {
9362 versionCode = Integer.parseInt(version);
9363 } catch (NumberFormatException e) {
9364 }
9365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009367 int pkgFlags = 0;
9368 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009369 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9370 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009371 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009372 if (timeStampStr != null) {
9373 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009374 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009375 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 } catch (NumberFormatException e) {
9377 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009378 } else {
9379 timeStampStr = parser.getAttributeValue(null, "ts");
9380 if (timeStampStr != null) {
9381 try {
9382 long timeStamp = Long.parseLong(timeStampStr);
9383 ps.setTimeStamp(timeStamp);
9384 } catch (NumberFormatException e) {
9385 }
9386 }
9387 }
9388 timeStampStr = parser.getAttributeValue(null, "it");
9389 if (timeStampStr != null) {
9390 try {
9391 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9392 } catch (NumberFormatException e) {
9393 }
9394 }
9395 timeStampStr = parser.getAttributeValue(null, "ut");
9396 if (timeStampStr != null) {
9397 try {
9398 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9399 } catch (NumberFormatException e) {
9400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 }
9402 String idStr = parser.getAttributeValue(null, "userId");
9403 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9404 if(ps.userId <= 0) {
9405 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9406 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9407 }
9408 int outerDepth = parser.getDepth();
9409 int type;
9410 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9411 && (type != XmlPullParser.END_TAG
9412 || parser.getDepth() > outerDepth)) {
9413 if (type == XmlPullParser.END_TAG
9414 || type == XmlPullParser.TEXT) {
9415 continue;
9416 }
9417
9418 String tagName = parser.getName();
9419 if (tagName.equals("perms")) {
9420 readGrantedPermissionsLP(parser,
9421 ps.grantedPermissions);
9422 } else {
9423 reportSettingsProblem(Log.WARN,
9424 "Unknown element under <updated-package>: "
9425 + parser.getName());
9426 XmlUtils.skipCurrentTag(parser);
9427 }
9428 }
9429 mDisabledSysPackages.put(name, ps);
9430 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009432 private void readPackageLP(XmlPullParser parser)
9433 throws XmlPullParserException, IOException {
9434 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009435 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436 String idStr = null;
9437 String sharedIdStr = null;
9438 String codePathStr = null;
9439 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009440 String nativeLibraryPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009441 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009442 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009443 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009444 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009445 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009446 long firstInstallTime = 0;
9447 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009449 String version = null;
9450 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009451 try {
9452 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009453 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009455 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009456 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9457 codePathStr = parser.getAttributeValue(null, "codePath");
9458 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009459 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009460 version = parser.getAttributeValue(null, "version");
9461 if (version != null) {
9462 try {
9463 versionCode = Integer.parseInt(version);
9464 } catch (NumberFormatException e) {
9465 }
9466 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009467 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009468
9469 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009470 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009471 try {
9472 pkgFlags = Integer.parseInt(systemStr);
9473 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009474 }
9475 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009476 // For backward compatibility
9477 systemStr = parser.getAttributeValue(null, "system");
9478 if (systemStr != null) {
9479 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9480 } else {
9481 // Old settings that don't specify system... just treat
9482 // them as system, good enough.
9483 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009485 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009486 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487 if (timeStampStr != null) {
9488 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009489 timeStamp = Long.parseLong(timeStampStr, 16);
9490 } catch (NumberFormatException e) {
9491 }
9492 } else {
9493 timeStampStr = parser.getAttributeValue(null, "ts");
9494 if (timeStampStr != null) {
9495 try {
9496 timeStamp = Long.parseLong(timeStampStr);
9497 } catch (NumberFormatException e) {
9498 }
9499 }
9500 }
9501 timeStampStr = parser.getAttributeValue(null, "it");
9502 if (timeStampStr != null) {
9503 try {
9504 firstInstallTime = Long.parseLong(timeStampStr, 16);
9505 } catch (NumberFormatException e) {
9506 }
9507 }
9508 timeStampStr = parser.getAttributeValue(null, "ut");
9509 if (timeStampStr != null) {
9510 try {
9511 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009512 } catch (NumberFormatException e) {
9513 }
9514 }
9515 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9516 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9517 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9518 if (resourcePathStr == null) {
9519 resourcePathStr = codePathStr;
9520 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009521 if (realName != null) {
9522 realName = realName.intern();
9523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009524 if (name == null) {
9525 reportSettingsProblem(Log.WARN,
9526 "Error in package manager settings: <package> has no name at "
9527 + parser.getPositionDescription());
9528 } else if (codePathStr == null) {
9529 reportSettingsProblem(Log.WARN,
9530 "Error in package manager settings: <package> has no codePath at "
9531 + parser.getPositionDescription());
9532 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009533 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9534 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9535 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009536 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9537 + ": userId=" + userId + " pkg=" + packageSetting);
9538 if (packageSetting == null) {
9539 reportSettingsProblem(Log.ERROR,
9540 "Failure adding uid " + userId
9541 + " while parsing settings at "
9542 + parser.getPositionDescription());
9543 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009544 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009545 packageSetting.firstInstallTime = firstInstallTime;
9546 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009547 }
9548 } else if (sharedIdStr != null) {
9549 userId = sharedIdStr != null
9550 ? Integer.parseInt(sharedIdStr) : 0;
9551 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009552 packageSetting = new PendingPackage(name.intern(), realName,
9553 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009554 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009555 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009556 packageSetting.firstInstallTime = firstInstallTime;
9557 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009558 mPendingPackages.add((PendingPackage) packageSetting);
9559 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9560 + ": sharedUserId=" + userId + " pkg="
9561 + packageSetting);
9562 } else {
9563 reportSettingsProblem(Log.WARN,
9564 "Error in package manager settings: package "
9565 + name + " has bad sharedId " + sharedIdStr
9566 + " at " + parser.getPositionDescription());
9567 }
9568 } else {
9569 reportSettingsProblem(Log.WARN,
9570 "Error in package manager settings: package "
9571 + name + " has bad userId " + idStr + " at "
9572 + parser.getPositionDescription());
9573 }
9574 } catch (NumberFormatException e) {
9575 reportSettingsProblem(Log.WARN,
9576 "Error in package manager settings: package "
9577 + name + " has bad userId " + idStr + " at "
9578 + parser.getPositionDescription());
9579 }
9580 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009581 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009582 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009583 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009584 final String enabledStr = parser.getAttributeValue(null, "enabled");
9585 if (enabledStr != null) {
9586 if (enabledStr.equalsIgnoreCase("true")) {
9587 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9588 } else if (enabledStr.equalsIgnoreCase("false")) {
9589 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9590 } else if (enabledStr.equalsIgnoreCase("default")) {
9591 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9592 } else {
9593 reportSettingsProblem(Log.WARN,
9594 "Error in package manager settings: package "
9595 + name + " has bad enabled value: " + idStr
9596 + " at " + parser.getPositionDescription());
9597 }
9598 } else {
9599 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9600 }
9601 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9602 if (installStatusStr != null) {
9603 if (installStatusStr.equalsIgnoreCase("false")) {
9604 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9605 } else {
9606 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9607 }
9608 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009610 int outerDepth = parser.getDepth();
9611 int type;
9612 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9613 && (type != XmlPullParser.END_TAG
9614 || parser.getDepth() > outerDepth)) {
9615 if (type == XmlPullParser.END_TAG
9616 || type == XmlPullParser.TEXT) {
9617 continue;
9618 }
9619
9620 String tagName = parser.getName();
9621 if (tagName.equals("disabled-components")) {
9622 readDisabledComponentsLP(packageSetting, parser);
9623 } else if (tagName.equals("enabled-components")) {
9624 readEnabledComponentsLP(packageSetting, parser);
9625 } else if (tagName.equals("sigs")) {
9626 packageSetting.signatures.readXml(parser, mPastSignatures);
9627 } else if (tagName.equals("perms")) {
9628 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009629 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009630 packageSetting.permissionsFixed = true;
Kenny Root5d40fe92011-01-14 10:54:46 -08009631 } else if (tagName.equals("obbs")) {
9632 readObbPathsLP(packageSetting, parser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009633 } else {
9634 reportSettingsProblem(Log.WARN,
9635 "Unknown element under <package>: "
9636 + parser.getName());
9637 XmlUtils.skipCurrentTag(parser);
9638 }
9639 }
9640 } else {
9641 XmlUtils.skipCurrentTag(parser);
9642 }
9643 }
9644
9645 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9646 XmlPullParser parser)
9647 throws IOException, XmlPullParserException {
9648 int outerDepth = parser.getDepth();
9649 int type;
9650 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9651 && (type != XmlPullParser.END_TAG
9652 || parser.getDepth() > outerDepth)) {
9653 if (type == XmlPullParser.END_TAG
9654 || type == XmlPullParser.TEXT) {
9655 continue;
9656 }
9657
9658 String tagName = parser.getName();
9659 if (tagName.equals("item")) {
9660 String name = parser.getAttributeValue(null, "name");
9661 if (name != null) {
9662 packageSetting.disabledComponents.add(name.intern());
9663 } else {
9664 reportSettingsProblem(Log.WARN,
9665 "Error in package manager settings: <disabled-components> has"
9666 + " no name at " + parser.getPositionDescription());
9667 }
9668 } else {
9669 reportSettingsProblem(Log.WARN,
9670 "Unknown element under <disabled-components>: "
9671 + parser.getName());
9672 }
9673 XmlUtils.skipCurrentTag(parser);
9674 }
9675 }
9676
9677 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9678 XmlPullParser parser)
9679 throws IOException, XmlPullParserException {
9680 int outerDepth = parser.getDepth();
9681 int type;
9682 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9683 && (type != XmlPullParser.END_TAG
9684 || parser.getDepth() > outerDepth)) {
9685 if (type == XmlPullParser.END_TAG
9686 || type == XmlPullParser.TEXT) {
9687 continue;
9688 }
9689
9690 String tagName = parser.getName();
9691 if (tagName.equals("item")) {
9692 String name = parser.getAttributeValue(null, "name");
9693 if (name != null) {
9694 packageSetting.enabledComponents.add(name.intern());
9695 } else {
9696 reportSettingsProblem(Log.WARN,
9697 "Error in package manager settings: <enabled-components> has"
9698 + " no name at " + parser.getPositionDescription());
9699 }
9700 } else {
9701 reportSettingsProblem(Log.WARN,
9702 "Unknown element under <enabled-components>: "
9703 + parser.getName());
9704 }
9705 XmlUtils.skipCurrentTag(parser);
9706 }
9707 }
9708
9709 private void readSharedUserLP(XmlPullParser parser)
9710 throws XmlPullParserException, IOException {
9711 String name = null;
9712 String idStr = null;
9713 int pkgFlags = 0;
9714 SharedUserSetting su = null;
9715 try {
9716 name = parser.getAttributeValue(null, "name");
9717 idStr = parser.getAttributeValue(null, "userId");
9718 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9719 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9720 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9721 }
9722 if (name == null) {
9723 reportSettingsProblem(Log.WARN,
9724 "Error in package manager settings: <shared-user> has no name at "
9725 + parser.getPositionDescription());
9726 } else if (userId == 0) {
9727 reportSettingsProblem(Log.WARN,
9728 "Error in package manager settings: shared-user "
9729 + name + " has bad userId " + idStr + " at "
9730 + parser.getPositionDescription());
9731 } else {
9732 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9733 reportSettingsProblem(Log.ERROR,
9734 "Occurred while parsing settings at "
9735 + parser.getPositionDescription());
9736 }
9737 }
9738 } catch (NumberFormatException e) {
9739 reportSettingsProblem(Log.WARN,
9740 "Error in package manager settings: package "
9741 + name + " has bad userId " + idStr + " at "
9742 + parser.getPositionDescription());
9743 };
9744
9745 if (su != null) {
9746 int outerDepth = parser.getDepth();
9747 int type;
9748 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9749 && (type != XmlPullParser.END_TAG
9750 || parser.getDepth() > outerDepth)) {
9751 if (type == XmlPullParser.END_TAG
9752 || type == XmlPullParser.TEXT) {
9753 continue;
9754 }
9755
9756 String tagName = parser.getName();
9757 if (tagName.equals("sigs")) {
9758 su.signatures.readXml(parser, mPastSignatures);
9759 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009760 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009761 } else {
9762 reportSettingsProblem(Log.WARN,
9763 "Unknown element under <shared-user>: "
9764 + parser.getName());
9765 XmlUtils.skipCurrentTag(parser);
9766 }
9767 }
9768
9769 } else {
9770 XmlUtils.skipCurrentTag(parser);
9771 }
9772 }
9773
9774 private void readGrantedPermissionsLP(XmlPullParser parser,
9775 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9776 int outerDepth = parser.getDepth();
9777 int type;
9778 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9779 && (type != XmlPullParser.END_TAG
9780 || parser.getDepth() > outerDepth)) {
9781 if (type == XmlPullParser.END_TAG
9782 || type == XmlPullParser.TEXT) {
9783 continue;
9784 }
9785
9786 String tagName = parser.getName();
9787 if (tagName.equals("item")) {
9788 String name = parser.getAttributeValue(null, "name");
9789 if (name != null) {
9790 outPerms.add(name.intern());
9791 } else {
9792 reportSettingsProblem(Log.WARN,
9793 "Error in package manager settings: <perms> has"
9794 + " no name at " + parser.getPositionDescription());
9795 }
9796 } else {
9797 reportSettingsProblem(Log.WARN,
9798 "Unknown element under <perms>: "
9799 + parser.getName());
9800 }
9801 XmlUtils.skipCurrentTag(parser);
9802 }
9803 }
9804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009805 private void readPreferredActivitiesLP(XmlPullParser parser)
9806 throws XmlPullParserException, IOException {
9807 int outerDepth = parser.getDepth();
9808 int type;
9809 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9810 && (type != XmlPullParser.END_TAG
9811 || parser.getDepth() > outerDepth)) {
9812 if (type == XmlPullParser.END_TAG
9813 || type == XmlPullParser.TEXT) {
9814 continue;
9815 }
9816
9817 String tagName = parser.getName();
9818 if (tagName.equals("item")) {
9819 PreferredActivity pa = new PreferredActivity(parser);
9820 if (pa.mParseError == null) {
9821 mPreferredActivities.addFilter(pa);
9822 } else {
9823 reportSettingsProblem(Log.WARN,
9824 "Error in package manager settings: <preferred-activity> "
9825 + pa.mParseError + " at "
9826 + parser.getPositionDescription());
9827 }
9828 } else {
9829 reportSettingsProblem(Log.WARN,
9830 "Unknown element under <preferred-activities>: "
9831 + parser.getName());
9832 XmlUtils.skipCurrentTag(parser);
9833 }
9834 }
9835 }
9836
Kenny Root5d40fe92011-01-14 10:54:46 -08009837 private void readObbPathsLP(PackageSettingBase packageSetting, XmlPullParser parser)
9838 throws XmlPullParserException, IOException {
9839 final List<String> obbPaths = new ArrayList<String>();
9840 final int outerDepth = parser.getDepth();
9841 int type;
9842 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9843 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9844 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9845 continue;
9846 }
9847
9848 final String tagName = parser.getName();
9849 if (tagName.equals("obb")) {
9850 final String path = parser.getAttributeValue(null, "path");
9851 obbPaths.add(path);
9852 } else {
9853 reportSettingsProblem(Log.WARN, "Unknown element under <obbs>: "
9854 + parser.getName());
9855 }
9856 XmlUtils.skipCurrentTag(parser);
9857 }
9858 if (obbPaths.size() == 0) {
9859 return;
9860 } else {
9861 packageSetting.obbPathStrings = obbPaths.toArray(new String[obbPaths.size()]);
9862 }
9863 }
9864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009865 // Returns -1 if we could not find an available UserId to assign
9866 private int newUserIdLP(Object obj) {
9867 // Let's be stupidly inefficient for now...
9868 final int N = mUserIds.size();
9869 for (int i=0; i<N; i++) {
9870 if (mUserIds.get(i) == null) {
9871 mUserIds.set(i, obj);
9872 return FIRST_APPLICATION_UID + i;
9873 }
9874 }
9875
9876 // None left?
9877 if (N >= MAX_APPLICATION_UIDS) {
9878 return -1;
9879 }
9880
9881 mUserIds.add(obj);
9882 return FIRST_APPLICATION_UID + N;
9883 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009885 public PackageSetting getDisabledSystemPkg(String name) {
9886 synchronized(mPackages) {
9887 PackageSetting ps = mDisabledSysPackages.get(name);
9888 return ps;
9889 }
9890 }
9891
9892 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009893 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9894 return true;
9895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009896 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9897 if (Config.LOGV) {
9898 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9899 + " componentName = " + componentInfo.name);
9900 Log.v(TAG, "enabledComponents: "
9901 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9902 Log.v(TAG, "disabledComponents: "
9903 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9904 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009905 if (packageSettings == null) {
9906 if (false) {
9907 Log.w(TAG, "WAITING FOR DEBUGGER");
9908 Debug.waitForDebugger();
9909 Log.i(TAG, "We will crash!");
9910 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009911 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009912 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009913 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9914 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9915 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9916 return false;
9917 }
9918 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9919 return true;
9920 }
9921 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9922 return false;
9923 }
9924 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009925 }
9926 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009927
9928 // ------- apps on sdcard specific code -------
9929 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009930 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9931 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9932 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009933 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009934
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009935 private String getEncryptKey() {
9936 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009937 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9938 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009939 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009940 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9941 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009942 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009943 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009944 return null;
9945 }
9946 }
9947 return sdEncKey;
9948 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009949 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009950 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009951 } catch (IOException ioe) {
9952 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9953 + ioe);
9954 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009955 }
Rich Cannings8d578832010-09-09 15:12:40 -07009956
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009957 }
9958
Kenny Rootc78a8072010-07-27 15:18:38 -07009959 /* package */ static String getTempContainerId() {
9960 int tmpIdx = 1;
9961 String list[] = PackageHelper.getSecureContainerList();
9962 if (list != null) {
9963 for (final String name : list) {
9964 // Ignore null and non-temporary container entries
9965 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9966 continue;
9967 }
9968
9969 String subStr = name.substring(mTempContainerPrefix.length());
9970 try {
9971 int cid = Integer.parseInt(subStr);
9972 if (cid >= tmpIdx) {
9973 tmpIdx = cid + 1;
9974 }
9975 } catch (NumberFormatException e) {
9976 }
9977 }
9978 }
9979 return mTempContainerPrefix + tmpIdx;
9980 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009981
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009982 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009983 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009984 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009985 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
Marco Nelissen584f1372010-05-24 16:34:30 -07009986 int callingUid = Binder.getCallingUid();
9987 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009988 throw new SecurityException("Media status can only be updated by the system");
9989 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009990 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009991 Log.i(TAG, "Updating external media status from " +
9992 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9993 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009994 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9995 mediaStatus+", mMediaMounted=" + mMediaMounted);
9996 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009997 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9998 reportStatus ? 1 : 0, -1);
9999 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010000 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010001 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -080010002 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -080010003 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010004 // Queue up an async operation since the package installation may take a little while.
10005 mHandler.post(new Runnable() {
10006 public void run() {
10007 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010008 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010009 }
10010 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010011 }
10012
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010013 /*
10014 * Collect information of applications on external media, map them
10015 * against existing containers and update information based on current
10016 * mount status. Please note that we always have to report status
10017 * if reportStatus has been set to true especially when unloading packages.
10018 */
10019 private void updateExternalMediaStatusInner(boolean mediaStatus,
10020 boolean reportStatus) {
10021 // Collection of uids
10022 int uidArr[] = null;
10023 // Collection of stale containers
10024 HashSet<String> removeCids = new HashSet<String>();
10025 // Collection of packages on external media with valid containers.
10026 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
10027 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -080010028 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010029 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080010030 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010031 } else {
10032 // Process list of secure containers and categorize them
10033 // as active or stale based on their package internal state.
10034 int uidList[] = new int[list.length];
10035 int num = 0;
10036 synchronized (mPackages) {
10037 for (String cid : list) {
10038 SdInstallArgs args = new SdInstallArgs(cid);
10039 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010040 String pkgName = args.getPackageName();
10041 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010042 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
10043 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010044 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010045 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010046 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
10047 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -070010048 // The package status is changed only if the code path
10049 // matches between settings and the container id.
10050 if (ps != null && ps.codePathString != null &&
10051 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010052 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
10053 " corresponds to pkg : " + pkgName +
10054 " at code path: " + ps.codePathString);
10055 // We do have a valid package installed on sdcard
10056 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010057 int uid = ps.userId;
10058 if (uid != -1) {
10059 uidList[num++] = uid;
10060 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010061 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010062 // Stale container on sdcard. Just delete
10063 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
10064 removeCids.add(cid);
10065 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080010066 }
10067 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010068
10069 if (num > 0) {
10070 // Sort uid list
10071 Arrays.sort(uidList, 0, num);
10072 // Throw away duplicates
10073 uidArr = new int[num];
10074 uidArr[0] = uidList[0];
10075 int di = 0;
10076 for (int i = 1; i < num; i++) {
10077 if (uidList[i-1] != uidList[i]) {
10078 uidArr[di++] = uidList[i];
10079 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010080 }
10081 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010082 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010083 // Process packages with valid entries.
10084 if (mediaStatus) {
10085 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010086 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010087 startCleaningPackages();
10088 } else {
10089 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010090 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010091 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010092 }
10093
10094 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010095 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010096 int size = pkgList.size();
10097 if (size > 0) {
10098 // Send broadcasts here
10099 Bundle extras = new Bundle();
10100 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
10101 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010102 if (uidArr != null) {
10103 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
10104 }
10105 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
10106 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010107 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010108 }
10109 }
10110
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010111 /*
10112 * Look at potentially valid container ids from processCids
10113 * If package information doesn't match the one on record
10114 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010115 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010116 */
10117 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010118 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010119 ArrayList<String> pkgList = new ArrayList<String>();
10120 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010121 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010122 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010123 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010124 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
10125 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010126 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010127 try {
10128 // Make sure there are no container errors first.
10129 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
10130 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -080010131 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010132 " when installing from sdcard");
10133 continue;
10134 }
10135 // Check code path here.
10136 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -080010137 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010138 " does not match one in settings " + codePath);
10139 continue;
10140 }
10141 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -070010142 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010143 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010144 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010145 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -070010146 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010147 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010148 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010149 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010150 retCode = PackageManager.INSTALL_SUCCEEDED;
10151 pkgList.add(pkg.packageName);
10152 // Post process args
10153 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
10154 }
10155 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010156 Slog.i(TAG, "Failed to install pkg from " +
10157 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010158 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010159 }
10160
10161 } finally {
10162 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
10163 // Don't destroy container here. Wait till gc clears things up.
10164 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010165 }
10166 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010167 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010168 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -070010169 // If the platform SDK has changed since the last time we booted,
10170 // we need to re-grant app permission to catch any new ones that
10171 // appear. This is really a hack, and means that apps can in some
10172 // cases get permissions that the user didn't initially explicitly
10173 // allow... it would be nice to have some better way to handle
10174 // this situation.
10175 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
10176 != mSdkVersion;
10177 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
10178 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
10179 + "; regranting permissions for external storage");
10180 mSettings.mExternalSdkPlatform = mSdkVersion;
10181
Dianne Hackbornaf7cea32010-03-24 12:59:52 -070010182 // Make sure group IDs have been assigned, and any permission
10183 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -070010184 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010185 // Persist settings
10186 mSettings.writeLP();
10187 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080010188 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010189 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010190 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010191 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010192 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010193 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010194 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010195 }
Kenny Rootf369a9b2010-07-28 14:47:01 -070010196 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010197 if (removeCids != null) {
10198 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -070010199 if (cid.startsWith(mTempContainerPrefix)) {
10200 Log.i(TAG, "Destroying stale temporary container " + cid);
10201 PackageHelper.destroySdDir(cid);
10202 } else {
10203 Log.w(TAG, "Container " + cid + " is stale");
10204 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010205 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010206 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010207 }
10208
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010209 /*
10210 * Utility method to unload a list of specified containers
10211 */
10212 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
10213 // Just unmount all valid containers.
10214 for (SdInstallArgs arg : cidArgs) {
10215 synchronized (mInstallLock) {
10216 arg.doPostDeleteLI(false);
10217 }
10218 }
10219 }
10220
10221 /*
10222 * Unload packages mounted on external media. This involves deleting
10223 * package data from internal structures, sending broadcasts about
10224 * diabled packages, gc'ing to free up references, unmounting all
10225 * secure containers corresponding to packages on external media, and
10226 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
10227 * Please note that we always have to post this message if status has
10228 * been requested no matter what.
10229 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010230 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010231 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010232 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010233 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010234 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010235 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010236 for (SdInstallArgs args : keys) {
10237 String cid = args.cid;
10238 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010239 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010240 // Delete package internally
10241 PackageRemovedInfo outInfo = new PackageRemovedInfo();
10242 synchronized (mInstallLock) {
10243 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010244 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010245 if (res) {
10246 pkgList.add(pkgName);
10247 } else {
Jeff Brown07330792010-03-30 19:57:08 -070010248 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010249 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010250 }
10251 }
10252 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010253
10254 synchronized (mPackages) {
10255 // We didn't update the settings after removing each package;
10256 // write them now for all packages.
10257 mSettings.writeLP();
10258 }
10259
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010260 // We have to absolutely send UPDATED_MEDIA_STATUS only
10261 // after confirming that all the receivers processed the ordered
10262 // broadcast when packages get disabled, force a gc to clean things up.
10263 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010264 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010265 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
10266 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
10267 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010268 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10269 reportStatus ? 1 : 0, 1, keys);
10270 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010271 }
10272 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010273 } else {
10274 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10275 reportStatus ? 1 : 0, -1, keys);
10276 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010277 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -080010278 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010279
10280 public void movePackage(final String packageName,
10281 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010282 mContext.enforceCallingOrSelfPermission(
10283 android.Manifest.permission.MOVE_PACKAGE, null);
10284 int returnCode = PackageManager.MOVE_SUCCEEDED;
10285 int currFlags = 0;
10286 int newFlags = 0;
10287 synchronized (mPackages) {
10288 PackageParser.Package pkg = mPackages.get(packageName);
10289 if (pkg == null) {
10290 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010291 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010292 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -070010293 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010294 Slog.w(TAG, "Cannot move system application");
10295 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -070010296 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010297 Slog.w(TAG, "Cannot move forward locked app.");
10298 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -070010299 } else if (pkg.mOperationPending) {
10300 Slog.w(TAG, "Attempt to move package which has pending operations");
10301 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010302 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010303 // Find install location first
10304 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
10305 (flags & PackageManager.MOVE_INTERNAL) != 0) {
10306 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010307 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010308 } else {
10309 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
10310 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -070010311 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
10312 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010313 if (newFlags == currFlags) {
10314 Slog.w(TAG, "No move required. Trying to move to same location");
10315 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
10316 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010317 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010318 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10319 pkg.mOperationPending = true;
10320 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010321 }
10322 }
10323 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -070010324 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010325 } else {
10326 Message msg = mHandler.obtainMessage(INIT_COPY);
10327 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -070010328 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
10329 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
10330 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010331 msg.obj = mp;
10332 mHandler.sendMessage(msg);
10333 }
10334 }
10335 }
10336
10337 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10338 // Queue up an async operation since the package deletion may take a little while.
10339 mHandler.post(new Runnable() {
10340 public void run() {
10341 mHandler.removeCallbacks(this);
10342 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010343 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10344 int uidArr[] = null;
10345 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010346 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010347 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010348 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010349 Slog.w(TAG, " Package " + mp.packageName +
10350 " doesn't exist. Aborting move");
10351 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10352 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10353 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10354 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10355 " Aborting move and returning error");
10356 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10357 } else {
10358 uidArr = new int[] { pkg.applicationInfo.uid };
10359 pkgList = new ArrayList<String>();
10360 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010361 }
10362 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010363 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10364 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010365 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010366 // Update package code and resource paths
10367 synchronized (mInstallLock) {
10368 synchronized (mPackages) {
10369 PackageParser.Package pkg = mPackages.get(mp.packageName);
10370 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010371 if (pkg == null) {
10372 Slog.w(TAG, " Package " + mp.packageName
10373 + " doesn't exist. Aborting move");
10374 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010375 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10376 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10377 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10378 " Aborting move and returning error");
10379 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10380 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010381 final String oldCodePath = pkg.mPath;
10382 final String newCodePath = mp.targetArgs.getCodePath();
10383 final String newResPath = mp.targetArgs.getResourcePath();
10384 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010385
10386 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10387 if (mInstaller
10388 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10389 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10390 } else {
10391 NativeLibraryHelper.copyNativeBinariesLI(
10392 new File(newCodePath), new File(newNativePath));
10393 }
10394 } else {
10395 if (mInstaller.linkNativeLibraryDirectory(
10396 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10397 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10398 }
10399 }
10400
10401 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10402 pkg.mPath = newCodePath;
10403 // Move dex files around
10404 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10405 // Moving of dex files failed. Set
10406 // error code and abort move.
10407 pkg.mPath = pkg.mScanPath;
10408 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10409 }
10410 }
10411
10412 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010413 pkg.mScanPath = newCodePath;
10414 pkg.applicationInfo.sourceDir = newCodePath;
10415 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010416 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010417 PackageSetting ps = (PackageSetting) pkg.mExtras;
10418 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10419 ps.codePathString = ps.codePath.getPath();
10420 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10421 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010422 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010423 // Set the application info flag correctly.
10424 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10425 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10426 } else {
10427 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10428 }
10429 ps.setFlags(pkg.applicationInfo.flags);
10430 mAppDirs.remove(oldCodePath);
10431 mAppDirs.put(newCodePath, pkg);
10432 // Persist settings
10433 mSettings.writeLP();
10434 }
10435 }
10436 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010437 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010438 // Send resources available broadcast
10439 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010440 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010441 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010442 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010443 // Clean up failed installation
10444 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010445 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010446 }
10447 } else {
10448 // Force a gc to clear things up.
10449 Runtime.getRuntime().gc();
10450 // Delete older code
10451 synchronized (mInstallLock) {
10452 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010453 }
10454 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010455
10456 // Allow more operations on this file if we didn't fail because
10457 // an operation was already pending for this package.
10458 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10459 synchronized (mPackages) {
10460 PackageParser.Package pkg = mPackages.get(mp.packageName);
10461 if (pkg != null) {
10462 pkg.mOperationPending = false;
10463 }
10464 }
10465 }
10466
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010467 IPackageMoveObserver observer = mp.observer;
10468 if (observer != null) {
10469 try {
10470 observer.packageMoved(mp.packageName, returnCode);
10471 } catch (RemoteException e) {
10472 Log.i(TAG, "Observer no longer exists.");
10473 }
10474 }
10475 }
10476 });
10477 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010478
10479 public boolean setInstallLocation(int loc) {
10480 mContext.enforceCallingOrSelfPermission(
10481 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10482 if (getInstallLocation() == loc) {
10483 return true;
10484 }
10485 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10486 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10487 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10488 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10489 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10490 return true;
10491 }
10492 return false;
10493 }
10494
10495 public int getInstallLocation() {
10496 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10497 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010499}