blob: 18371662b72b9b45e2ac5f3b1f32d279b45cf3fd [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) {
Jason parksa3cdaa52011-01-13 14:15:43 -06001053 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1054 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
Jason parksa3cdaa52011-01-13 14:15:43 -06002783 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2784 return Environment.isEncryptedFilesystemEnabled() &&
2785 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2786 }
2787
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002788 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2789 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
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 not in system partition");
2793 return false;
2794 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002795 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002796 + " to " + newPkg.packageName
2797 + ": old package still exists");
2798 return false;
2799 }
2800 return true;
2801 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002802
2803 private File getDataPathForPackage(PackageParser.Package pkg) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002804 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2805 File dataPath;
2806 if (useEncryptedFSDir) {
2807 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2808 } else {
2809 dataPath = new File(mAppDataDir, pkg.packageName);
2810 }
2811 return dataPath;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002812 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002813
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002814 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002815 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002816 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002817 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2818 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002819 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002820 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002821 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2822 return null;
2823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 mScanningPath = scanFile;
2825 if (pkg == null) {
2826 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2827 return null;
2828 }
2829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2831 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2832 }
2833
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002834 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 synchronized (mPackages) {
2836 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002837 Slog.w(TAG, "*************************************************");
2838 Slog.w(TAG, "Core android package being redefined. Skipping.");
2839 Slog.w(TAG, " file=" + mScanningPath);
2840 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2842 return null;
2843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 // Set up information for our fall-back user intent resolution
2846 // activity.
2847 mPlatformPackage = pkg;
2848 pkg.mVersionCode = mSdkVersion;
2849 mAndroidApplication = pkg.applicationInfo;
2850 mResolveActivity.applicationInfo = mAndroidApplication;
2851 mResolveActivity.name = ResolverActivity.class.getName();
2852 mResolveActivity.packageName = mAndroidApplication.packageName;
2853 mResolveActivity.processName = mAndroidApplication.processName;
2854 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2855 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
Joe Onorato646f46e2010-11-08 15:08:56 -08002856 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 mResolveActivity.exported = true;
2858 mResolveActivity.enabled = true;
2859 mResolveInfo.activityInfo = mResolveActivity;
2860 mResolveInfo.priority = 0;
2861 mResolveInfo.preferredOrder = 0;
2862 mResolveInfo.match = 0;
2863 mResolveComponentName = new ComponentName(
2864 mAndroidApplication.packageName, mResolveActivity.name);
2865 }
2866 }
2867
2868 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002869 TAG, "Scanning package " + pkg.packageName);
2870 if (mPackages.containsKey(pkg.packageName)
2871 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002872 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2875 return null;
2876 }
2877
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002878 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002879 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2880 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 SharedUserSetting suid = null;
2883 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002884
Kenny Root502e9a42011-01-10 13:48:15 -08002885 if (!isSystemApp(pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002886 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002887 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002888 pkg.mRealPackage = null;
2889 pkg.mAdoptPermissions = null;
2890 }
Kenny Root502e9a42011-01-10 13:48:15 -08002891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 synchronized (mPackages) {
2893 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002894 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2895 if (mTmpSharedLibraries == null ||
2896 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2897 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2898 }
2899 int num = 0;
2900 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2901 for (int i=0; i<N; i++) {
2902 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002904 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002906 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2908 return null;
2909 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002910 mTmpSharedLibraries[num] = file;
2911 num++;
2912 }
2913 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2914 for (int i=0; i<N; i++) {
2915 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2916 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002917 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002918 + " desires unavailable shared library "
2919 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2920 } else {
2921 mTmpSharedLibraries[num] = file;
2922 num++;
2923 }
2924 }
2925 if (num > 0) {
2926 pkg.usesLibraryFiles = new String[num];
2927 System.arraycopy(mTmpSharedLibraries, 0,
2928 pkg.usesLibraryFiles, 0, num);
2929 }
Kenny Root1683afa2011-01-07 14:27:50 -08002930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002931
Kenny Root1683afa2011-01-07 14:27:50 -08002932 if (pkg.reqFeatures != null) {
2933 int N = pkg.reqFeatures.size();
2934 for (int i = 0; i < N; i++) {
2935 FeatureInfo fi = pkg.reqFeatures.get(i);
2936 if ((fi.flags & FeatureInfo.FLAG_REQUIRED) == 0) {
2937 // Don't care.
2938 continue;
2939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002940
Kenny Root1683afa2011-01-07 14:27:50 -08002941 if (fi.name != null) {
2942 if (mAvailableFeatures.get(fi.name) == null) {
2943 Slog.e(TAG, "Package " + pkg.packageName
2944 + " requires unavailable feature " + fi.name + "; failing!");
2945 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2946 return null;
Dianne Hackborn49237342009-08-27 20:08:01 -07002947 }
2948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 }
2950 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 if (pkg.mSharedUserId != null) {
2953 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2954 pkg.applicationInfo.flags, true);
2955 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002956 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 + " for shared user failed");
2958 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2959 return null;
2960 }
2961 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2962 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2963 + suid.userId + "): packages=" + suid.packages);
2964 }
2965 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002966
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002967 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002968 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002969 Log.w(TAG, "WAITING FOR DEBUGGER");
2970 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002971 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2972 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973 }
2974 }
2975
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002976 // Check if we are renaming from an original package name.
2977 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002978 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002979 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002980 // This package may need to be renamed to a previously
2981 // installed name. Let's check on that...
2982 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002983 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002984 // This package had originally been installed as the
2985 // original name, and we have already taken care of
2986 // transitioning to the new one. Just update the new
2987 // one to continue using the old name.
2988 realName = pkg.mRealPackage;
2989 if (!pkg.packageName.equals(renamed)) {
2990 // Callers into this function may have already taken
2991 // care of renaming the package; only do it here if
2992 // it is not already done.
2993 pkg.setPackageName(renamed);
2994 }
2995
Dianne Hackbornc1552392010-03-03 16:19:01 -08002996 } else {
2997 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2998 if ((origPackage=mSettings.peekPackageLP(
2999 pkg.mOriginalPackages.get(i))) != null) {
3000 // We do have the package already installed under its
3001 // original name... should we use it?
3002 if (!verifyPackageUpdate(origPackage, pkg)) {
3003 // New package is not compatible with original.
3004 origPackage = null;
3005 continue;
3006 } else if (origPackage.sharedUser != null) {
3007 // Make sure uid is compatible between packages.
3008 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003009 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003010 + " to " + pkg.packageName + ": old uid "
3011 + origPackage.sharedUser.name
3012 + " differs from " + pkg.mSharedUserId);
3013 origPackage = null;
3014 continue;
3015 }
3016 } else {
3017 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3018 + pkg.packageName + " to old name " + origPackage.name);
3019 }
3020 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003021 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003022 }
3023 }
3024 }
3025
3026 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003027 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003028 + " was transferred to another, but its .apk remains");
3029 }
3030
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003031 // Just create the setting, don't add it yet. For already existing packages
3032 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003033 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003034 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3035 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003037 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3039 return null;
3040 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003041
3042 if (pkgSetting.origPackage != null) {
3043 // If we are first transitioning from an original package,
3044 // fix up the new package's name now. We need to do this after
3045 // looking up the package under its new name, so getPackageLP
3046 // can take care of fiddling things correctly.
3047 pkg.setPackageName(origPackage.name);
3048
3049 // File a report about this.
3050 String msg = "New package " + pkgSetting.realName
3051 + " renamed to replace old package " + pkgSetting.name;
3052 reportSettingsProblem(Log.WARN, msg);
3053
3054 // Make a note of it.
3055 mTransferedPackages.add(origPackage.name);
3056
3057 // No longer need to retain this.
3058 pkgSetting.origPackage = null;
3059 }
3060
3061 if (realName != null) {
3062 // Make a note of it.
3063 mTransferedPackages.add(pkg.packageName);
3064 }
3065
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003066 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3068 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 pkg.applicationInfo.uid = pkgSetting.userId;
3071 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003072
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003073 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003074 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 return null;
3076 }
3077 // The signature has changed, but this package is in the system
3078 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003079 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 // However... if this package is part of a shared user, but it
3081 // doesn't match the signature of the shared user, let's fail.
3082 // What this means is that you can't change the signatures
3083 // associated with an overall shared user, which doesn't seem all
3084 // that unreasonable.
3085 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003086 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3087 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3088 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3090 return null;
3091 }
3092 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003093 // File a report about this.
3094 String msg = "System package " + pkg.packageName
3095 + " signature changed; retaining data.";
3096 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003098
The Android Open Source Project10592532009-03-18 17:39:46 -07003099 // Verify that this new package doesn't have any content providers
3100 // that conflict with existing packages. Only do this if the
3101 // package isn't already installed, since we don't want to break
3102 // things that are installed.
3103 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3104 int N = pkg.providers.size();
3105 int i;
3106 for (i=0; i<N; i++) {
3107 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003108 if (p.info.authority != null) {
3109 String names[] = p.info.authority.split(";");
3110 for (int j = 0; j < names.length; j++) {
3111 if (mProviders.containsKey(names[j])) {
3112 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003113 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003114 " (in package " + pkg.applicationInfo.packageName +
3115 ") is already used by "
3116 + ((other != null && other.getComponentName() != null)
3117 ? other.getComponentName().getPackageName() : "?"));
3118 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3119 return null;
3120 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003121 }
3122 }
3123 }
3124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 }
3126
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003127 final String pkgName = pkg.packageName;
3128
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003129 if (pkg.mAdoptPermissions != null) {
3130 // This package wants to adopt ownership of permissions from
3131 // another package.
3132 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3133 String origName = pkg.mAdoptPermissions.get(i);
3134 PackageSetting orig = mSettings.peekPackageLP(origName);
3135 if (orig != null) {
3136 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003137 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003138 + origName + " to " + pkg.packageName);
3139 mSettings.transferPermissions(origName, pkg.packageName);
3140 }
3141 }
3142 }
3143 }
3144
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003145 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003147 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 pkg.applicationInfo.processName = fixProcessName(
3149 pkg.applicationInfo.packageName,
3150 pkg.applicationInfo.processName,
3151 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152
3153 File dataPath;
3154 if (mPlatformPackage == pkg) {
3155 // The system package is special.
3156 dataPath = new File (Environment.getDataDirectory(), "system");
3157 pkg.applicationInfo.dataDir = dataPath.getPath();
3158 } else {
3159 // This is a normal package, need to make its data directory.
Jason parksa3cdaa52011-01-13 14:15:43 -06003160 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003161 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003162
3163 boolean uidError = false;
3164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 if (dataPath.exists()) {
3166 mOutPermissions[1] = 0;
3167 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003168
3169 // If we have mismatched owners for the data path, we have a
3170 // problem (unless we're running in the simulator.)
3171 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 boolean recovered = false;
3173 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3174 // If this is a system app, we can at least delete its
3175 // current data so the application will still work.
3176 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06003177 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003178 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 // Old data gone!
3180 String msg = "System package " + pkg.packageName
3181 + " has changed from uid: "
3182 + mOutPermissions[1] + " to "
3183 + pkg.applicationInfo.uid + "; old data erased";
3184 reportSettingsProblem(Log.WARN, msg);
3185 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 // And now re-install the app.
Jason parksa3cdaa52011-01-13 14:15:43 -06003188 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 pkg.applicationInfo.uid);
3190 if (ret == -1) {
3191 // Ack should not happen!
3192 msg = "System package " + pkg.packageName
3193 + " could not have data directory re-created after delete.";
3194 reportSettingsProblem(Log.WARN, msg);
3195 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3196 return null;
3197 }
3198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 if (!recovered) {
3201 mHasSystemUidErrors = true;
3202 }
3203 }
3204 if (!recovered) {
3205 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3206 + pkg.applicationInfo.uid + "/fs_"
3207 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003208 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 String msg = "Package " + pkg.packageName
3210 + " has mismatched uid: "
3211 + mOutPermissions[1] + " on disk, "
3212 + pkg.applicationInfo.uid + " in settings";
3213 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003214 mSettings.mReadMessages.append(msg);
3215 mSettings.mReadMessages.append('\n');
3216 uidError = true;
3217 if (!pkgSetting.uidError) {
3218 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 }
3221 }
3222 }
3223 pkg.applicationInfo.dataDir = dataPath.getPath();
3224 } else {
3225 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3226 Log.v(TAG, "Want this data dir: " + dataPath);
3227 //invoke installer to do the actual installation
3228 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06003229 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 pkg.applicationInfo.uid);
3231 if(ret < 0) {
3232 // Error from installer
3233 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3234 return null;
3235 }
3236 } else {
3237 dataPath.mkdirs();
3238 if (dataPath.exists()) {
3239 FileUtils.setPermissions(
3240 dataPath.toString(),
3241 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3242 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3243 }
3244 }
3245 if (dataPath.exists()) {
3246 pkg.applicationInfo.dataDir = dataPath.getPath();
3247 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003248 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 pkg.applicationInfo.dataDir = null;
3250 }
3251 }
Kenny Root85387d72010-08-26 10:13:11 -07003252
3253 /*
3254 * Set the data dir to the default "/data/data/<package name>/lib"
3255 * if we got here without anyone telling us different (e.g., apps
3256 * stored on SD card have their native libraries stored in the ASEC
3257 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003258 *
3259 * This happens during an upgrade from a package settings file that
3260 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003261 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003262 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3263 if (pkgSetting.nativeLibraryPathString == null) {
3264 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3265 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3266 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3267 } else {
3268 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3269 }
Kenny Root85387d72010-08-26 10:13:11 -07003270 }
3271
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003272 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 }
3274
Kenny Root85387d72010-08-26 10:13:11 -07003275 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 if (mInstaller != null) {
3277 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003278 /* Note: We don't want to unpack the native binaries for
3279 * system applications, unless they have been updated
3280 * (the binaries are already under /system/lib).
3281 * Also, don't unpack libs for apps on the external card
3282 * since they should have their libraries in the ASEC
3283 * container already.
3284 *
3285 * In other words, we're going to unpack the binaries
3286 * only for non-system apps and system app upgrades.
3287 */
Kenny Root831baa22010-10-05 12:29:25 -07003288 if (pkg.applicationInfo.nativeLibraryDir != null) {
Kenny Roote68d58a2010-10-18 16:08:54 -07003289 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3290 final String dataPathString = dataPath.getPath();
3291
Kenny Root831baa22010-10-05 12:29:25 -07003292 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3293 /*
3294 * Upgrading from a previous version of the OS sometimes
3295 * leaves native libraries in the /data/data/<app>/lib
3296 * directory for system apps even when they shouldn't be.
3297 * Recent changes in the JNI library search path
3298 * necessitates we remove those to match previous behavior.
3299 */
Kenny Roote68d58a2010-10-18 16:08:54 -07003300 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Kenny Root831baa22010-10-05 12:29:25 -07003301 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3302 }
Kenny Roote68d58a2010-10-18 16:08:54 -07003303 } else if (nativeLibraryDir.getParent().equals(dataPathString)) {
3304 /*
3305 * If this is an internal application or our
3306 * nativeLibraryPath points to our data directory, unpack
3307 * the libraries. The native library path pointing to the
3308 * data directory for an application in an ASEC container
3309 * can happen for older apps that existed before an OTA to
3310 * Gingerbread.
3311 */
3312 Slog.i(TAG, "Unpacking native libraries for " + path);
3313 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
3314 NativeLibraryHelper.copyNativeBinariesLI(scanFile, nativeLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003315 } else {
Kenny Roote68d58a2010-10-18 16:08:54 -07003316 Slog.i(TAG, "Linking native library dir for " + path);
3317 mInstaller.linkNativeLibraryDirectory(dataPathString,
Kenny Root6a6b0072010-10-07 16:46:10 -07003318 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003321 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003322
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003323 if ((scanMode&SCAN_NO_DEX) == 0) {
3324 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3326 return null;
3327 }
3328 }
3329 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 if (mFactoryTest && pkg.requestedPermissions.contains(
3332 android.Manifest.permission.FACTORY_TEST)) {
3333 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3334 }
3335
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003336 // Request the ActivityManager to kill the process(only for existing packages)
3337 // so that we do not end up in a confused state while the user is still using the older
3338 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003339 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003340 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003341 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003342 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003345 // We don't expect installation to fail beyond this point,
3346 if ((scanMode&SCAN_MONITOR) != 0) {
3347 mAppDirs.put(pkg.mPath, pkg);
3348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003350 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003352 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003353 // Make sure we don't accidentally delete its data.
3354 mSettings.mPackagesToBeCleaned.remove(pkgName);
3355
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003356 // Take care of first install / last update times.
3357 if (currentTime != 0) {
3358 if (pkgSetting.firstInstallTime == 0) {
3359 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3360 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3361 pkgSetting.lastUpdateTime = currentTime;
3362 }
3363 } else if (pkgSetting.firstInstallTime == 0) {
3364 // We need *something*. Take time time stamp of the file.
3365 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3366 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3367 if (scanFileTime != pkgSetting.timeStamp) {
3368 // A package on the system image has changed; consider this
3369 // to be an update.
3370 pkgSetting.lastUpdateTime = scanFileTime;
3371 }
3372 }
3373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 int N = pkg.providers.size();
3375 StringBuilder r = null;
3376 int i;
3377 for (i=0; i<N; i++) {
3378 PackageParser.Provider p = pkg.providers.get(i);
3379 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3380 p.info.processName, pkg.applicationInfo.uid);
3381 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3382 p.info.name), p);
3383 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003384 if (p.info.authority != null) {
3385 String names[] = p.info.authority.split(";");
3386 p.info.authority = null;
3387 for (int j = 0; j < names.length; j++) {
3388 if (j == 1 && p.syncable) {
3389 // We only want the first authority for a provider to possibly be
3390 // syncable, so if we already added this provider using a different
3391 // authority clear the syncable flag. We copy the provider before
3392 // changing it because the mProviders object contains a reference
3393 // to a provider that we don't want to change.
3394 // Only do this for the second authority since the resulting provider
3395 // object can be the same for all future authorities for this provider.
3396 p = new PackageParser.Provider(p);
3397 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003399 if (!mProviders.containsKey(names[j])) {
3400 mProviders.put(names[j], p);
3401 if (p.info.authority == null) {
3402 p.info.authority = names[j];
3403 } else {
3404 p.info.authority = p.info.authority + ";" + names[j];
3405 }
3406 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3407 Log.d(TAG, "Registered content provider: " + names[j] +
3408 ", className = " + p.info.name +
3409 ", isSyncable = " + p.info.isSyncable);
3410 } else {
3411 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003412 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003413 " (in package " + pkg.applicationInfo.packageName +
3414 "): name already used by "
3415 + ((other != null && other.getComponentName() != null)
3416 ? other.getComponentName().getPackageName() : "?"));
3417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 }
3419 }
3420 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3421 if (r == null) {
3422 r = new StringBuilder(256);
3423 } else {
3424 r.append(' ');
3425 }
3426 r.append(p.info.name);
3427 }
3428 }
3429 if (r != null) {
3430 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 N = pkg.services.size();
3434 r = null;
3435 for (i=0; i<N; i++) {
3436 PackageParser.Service s = pkg.services.get(i);
3437 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3438 s.info.processName, pkg.applicationInfo.uid);
3439 mServices.addService(s);
3440 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3441 if (r == null) {
3442 r = new StringBuilder(256);
3443 } else {
3444 r.append(' ');
3445 }
3446 r.append(s.info.name);
3447 }
3448 }
3449 if (r != null) {
3450 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 N = pkg.receivers.size();
3454 r = null;
3455 for (i=0; i<N; i++) {
3456 PackageParser.Activity a = pkg.receivers.get(i);
3457 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3458 a.info.processName, pkg.applicationInfo.uid);
3459 mReceivers.addActivity(a, "receiver");
3460 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3461 if (r == null) {
3462 r = new StringBuilder(256);
3463 } else {
3464 r.append(' ');
3465 }
3466 r.append(a.info.name);
3467 }
3468 }
3469 if (r != null) {
3470 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 N = pkg.activities.size();
3474 r = null;
3475 for (i=0; i<N; i++) {
3476 PackageParser.Activity a = pkg.activities.get(i);
3477 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3478 a.info.processName, pkg.applicationInfo.uid);
3479 mActivities.addActivity(a, "activity");
3480 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3481 if (r == null) {
3482 r = new StringBuilder(256);
3483 } else {
3484 r.append(' ');
3485 }
3486 r.append(a.info.name);
3487 }
3488 }
3489 if (r != null) {
3490 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3491 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 N = pkg.permissionGroups.size();
3494 r = null;
3495 for (i=0; i<N; i++) {
3496 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3497 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3498 if (cur == null) {
3499 mPermissionGroups.put(pg.info.name, pg);
3500 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3501 if (r == null) {
3502 r = new StringBuilder(256);
3503 } else {
3504 r.append(' ');
3505 }
3506 r.append(pg.info.name);
3507 }
3508 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003509 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 + pg.info.packageName + " ignored: original from "
3511 + cur.info.packageName);
3512 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3513 if (r == null) {
3514 r = new StringBuilder(256);
3515 } else {
3516 r.append(' ');
3517 }
3518 r.append("DUP:");
3519 r.append(pg.info.name);
3520 }
3521 }
3522 }
3523 if (r != null) {
3524 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 N = pkg.permissions.size();
3528 r = null;
3529 for (i=0; i<N; i++) {
3530 PackageParser.Permission p = pkg.permissions.get(i);
3531 HashMap<String, BasePermission> permissionMap =
3532 p.tree ? mSettings.mPermissionTrees
3533 : mSettings.mPermissions;
3534 p.group = mPermissionGroups.get(p.info.group);
3535 if (p.info.group == null || p.group != null) {
3536 BasePermission bp = permissionMap.get(p.info.name);
3537 if (bp == null) {
3538 bp = new BasePermission(p.info.name, p.info.packageName,
3539 BasePermission.TYPE_NORMAL);
3540 permissionMap.put(p.info.name, bp);
3541 }
3542 if (bp.perm == null) {
3543 if (bp.sourcePackage == null
3544 || bp.sourcePackage.equals(p.info.packageName)) {
3545 BasePermission tree = findPermissionTreeLP(p.info.name);
3546 if (tree == null
3547 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003548 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 bp.perm = p;
3550 bp.uid = pkg.applicationInfo.uid;
3551 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3552 if (r == null) {
3553 r = new StringBuilder(256);
3554 } else {
3555 r.append(' ');
3556 }
3557 r.append(p.info.name);
3558 }
3559 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003560 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 + p.info.packageName + " ignored: base tree "
3562 + tree.name + " is from package "
3563 + tree.sourcePackage);
3564 }
3565 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003566 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 + p.info.packageName + " ignored: original from "
3568 + bp.sourcePackage);
3569 }
3570 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3571 if (r == null) {
3572 r = new StringBuilder(256);
3573 } else {
3574 r.append(' ');
3575 }
3576 r.append("DUP:");
3577 r.append(p.info.name);
3578 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003579 if (bp.perm == p) {
3580 bp.protectionLevel = p.info.protectionLevel;
3581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003583 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 + p.info.packageName + " ignored: no group "
3585 + p.group);
3586 }
3587 }
3588 if (r != null) {
3589 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 N = pkg.instrumentation.size();
3593 r = null;
3594 for (i=0; i<N; i++) {
3595 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3596 a.info.packageName = pkg.applicationInfo.packageName;
3597 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3598 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3599 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003600 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003601 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3603 if (r == null) {
3604 r = new StringBuilder(256);
3605 } else {
3606 r.append(' ');
3607 }
3608 r.append(a.info.name);
3609 }
3610 }
3611 if (r != null) {
3612 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003614
Dianne Hackborn854060af2009-07-09 18:14:31 -07003615 if (pkg.protectedBroadcasts != null) {
3616 N = pkg.protectedBroadcasts.size();
3617 for (i=0; i<N; i++) {
3618 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3619 }
3620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 pkgSetting.setTimeStamp(scanFileTime);
3623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 return pkg;
3626 }
3627
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003628 private void killApplication(String pkgName, int uid) {
3629 // Request the ActivityManager to kill the process(only for existing packages)
3630 // so that we do not end up in a confused state while the user is still using the older
3631 // version of the application while the new one gets installed.
3632 IActivityManager am = ActivityManagerNative.getDefault();
3633 if (am != null) {
3634 try {
3635 am.killApplicationWithUid(pkgName, uid);
3636 } catch (RemoteException e) {
3637 }
3638 }
3639 }
3640
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003641 // Return the path of the directory that will contain the native binaries
3642 // of a given installed package. This is relative to the data path.
3643 //
Kenny Root85387d72010-08-26 10:13:11 -07003644 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3645 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3646 if (nativeLibraryDir != null) {
3647 return new File(nativeLibraryDir);
3648 } else {
3649 // Fall back for old packages
3650 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3651 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003652 }
3653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3655 if (chatty && Config.LOGD) Log.d(
3656 TAG, "Removing package " + pkg.applicationInfo.packageName );
3657
3658 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 mPackages.remove(pkg.applicationInfo.packageName);
3662 if (pkg.mPath != null) {
3663 mAppDirs.remove(pkg.mPath);
3664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 int N = pkg.providers.size();
3667 StringBuilder r = null;
3668 int i;
3669 for (i=0; i<N; i++) {
3670 PackageParser.Provider p = pkg.providers.get(i);
3671 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3672 p.info.name));
3673 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 /* The is another ContentProvider with this authority when
3676 * this app was installed so this authority is null,
3677 * Ignore it as we don't have to unregister the provider.
3678 */
3679 continue;
3680 }
3681 String names[] = p.info.authority.split(";");
3682 for (int j = 0; j < names.length; j++) {
3683 if (mProviders.get(names[j]) == p) {
3684 mProviders.remove(names[j]);
3685 if (chatty && Config.LOGD) Log.d(
3686 TAG, "Unregistered content provider: " + names[j] +
3687 ", className = " + p.info.name +
3688 ", isSyncable = " + p.info.isSyncable);
3689 }
3690 }
3691 if (chatty) {
3692 if (r == null) {
3693 r = new StringBuilder(256);
3694 } else {
3695 r.append(' ');
3696 }
3697 r.append(p.info.name);
3698 }
3699 }
3700 if (r != null) {
3701 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 N = pkg.services.size();
3705 r = null;
3706 for (i=0; i<N; i++) {
3707 PackageParser.Service s = pkg.services.get(i);
3708 mServices.removeService(s);
3709 if (chatty) {
3710 if (r == null) {
3711 r = new StringBuilder(256);
3712 } else {
3713 r.append(' ');
3714 }
3715 r.append(s.info.name);
3716 }
3717 }
3718 if (r != null) {
3719 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 N = pkg.receivers.size();
3723 r = null;
3724 for (i=0; i<N; i++) {
3725 PackageParser.Activity a = pkg.receivers.get(i);
3726 mReceivers.removeActivity(a, "receiver");
3727 if (chatty) {
3728 if (r == null) {
3729 r = new StringBuilder(256);
3730 } else {
3731 r.append(' ');
3732 }
3733 r.append(a.info.name);
3734 }
3735 }
3736 if (r != null) {
3737 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 N = pkg.activities.size();
3741 r = null;
3742 for (i=0; i<N; i++) {
3743 PackageParser.Activity a = pkg.activities.get(i);
3744 mActivities.removeActivity(a, "activity");
3745 if (chatty) {
3746 if (r == null) {
3747 r = new StringBuilder(256);
3748 } else {
3749 r.append(' ');
3750 }
3751 r.append(a.info.name);
3752 }
3753 }
3754 if (r != null) {
3755 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 N = pkg.permissions.size();
3759 r = null;
3760 for (i=0; i<N; i++) {
3761 PackageParser.Permission p = pkg.permissions.get(i);
3762 boolean tree = false;
3763 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3764 if (bp == null) {
3765 tree = true;
3766 bp = mSettings.mPermissionTrees.get(p.info.name);
3767 }
3768 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003769 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 if (chatty) {
3771 if (r == null) {
3772 r = new StringBuilder(256);
3773 } else {
3774 r.append(' ');
3775 }
3776 r.append(p.info.name);
3777 }
3778 }
3779 }
3780 if (r != null) {
3781 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3782 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 N = pkg.instrumentation.size();
3785 r = null;
3786 for (i=0; i<N; i++) {
3787 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003788 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 if (chatty) {
3790 if (r == null) {
3791 r = new StringBuilder(256);
3792 } else {
3793 r.append(' ');
3794 }
3795 r.append(a.info.name);
3796 }
3797 }
3798 if (r != null) {
3799 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3800 }
3801 }
3802 }
3803
3804 private static final boolean isPackageFilename(String name) {
3805 return name != null && name.endsWith(".apk");
3806 }
3807
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003808 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3809 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3810 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3811 return true;
3812 }
3813 }
3814 return false;
3815 }
3816
3817 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003818 PackageParser.Package pkgInfo, boolean grantPermissions,
3819 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 // Make sure there are no dangling permission trees.
3821 Iterator<BasePermission> it = mSettings.mPermissionTrees
3822 .values().iterator();
3823 while (it.hasNext()) {
3824 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003825 if (bp.packageSetting == null) {
3826 // We may not yet have parsed the package, so just see if
3827 // we still know about its settings.
3828 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3829 }
3830 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003831 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 + " from package " + bp.sourcePackage);
3833 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003834 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3835 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3836 Slog.i(TAG, "Removing old permission tree: " + bp.name
3837 + " from package " + bp.sourcePackage);
3838 grantPermissions = true;
3839 it.remove();
3840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 }
3842 }
3843
3844 // Make sure all dynamic permissions have been assigned to a package,
3845 // and make sure there are no dangling permissions.
3846 it = mSettings.mPermissions.values().iterator();
3847 while (it.hasNext()) {
3848 BasePermission bp = it.next();
3849 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3850 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3851 + bp.name + " pkg=" + bp.sourcePackage
3852 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003853 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 BasePermission tree = findPermissionTreeLP(bp.name);
3855 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003856 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 bp.perm = new PackageParser.Permission(tree.perm.owner,
3858 new PermissionInfo(bp.pendingInfo));
3859 bp.perm.info.packageName = tree.perm.info.packageName;
3860 bp.perm.info.name = bp.name;
3861 bp.uid = tree.uid;
3862 }
3863 }
3864 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003865 if (bp.packageSetting == null) {
3866 // We may not yet have parsed the package, so just see if
3867 // we still know about its settings.
3868 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3869 }
3870 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003871 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 + " from package " + bp.sourcePackage);
3873 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003874 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3875 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3876 Slog.i(TAG, "Removing old permission: " + bp.name
3877 + " from package " + bp.sourcePackage);
3878 grantPermissions = true;
3879 it.remove();
3880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 }
3882 }
3883
3884 // Now update the permissions for all packages, in particular
3885 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003886 if (grantPermissions) {
3887 for (PackageParser.Package pkg : mPackages.values()) {
3888 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003889 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003890 }
3891 }
3892 }
3893
3894 if (pkgInfo != null) {
3895 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 }
3897 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3900 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3901 if (ps == null) {
3902 return;
3903 }
3904 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003905 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 if (replace) {
3908 ps.permissionsFixed = false;
3909 if (gp == ps) {
3910 gp.grantedPermissions.clear();
3911 gp.gids = mGlobalGids;
3912 }
3913 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 if (gp.gids == null) {
3916 gp.gids = mGlobalGids;
3917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 final int N = pkg.requestedPermissions.size();
3920 for (int i=0; i<N; i++) {
3921 String name = pkg.requestedPermissions.get(i);
3922 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923 if (false) {
3924 if (gp != ps) {
3925 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003926 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 }
3928 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003929 if (bp != null && bp.packageSetting != null) {
3930 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003932 boolean allowedSig = false;
3933 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3934 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003936 } else if (bp.packageSetting == null) {
3937 // This permission is invalid; skip it.
3938 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003939 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3940 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003941 allowed = (checkSignaturesLP(
3942 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003944 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003946 if (!allowed && bp.protectionLevel
3947 == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003948 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 // For updated system applications, the signatureOrSystem permission
3950 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003951 if (isUpdatedSystemApp(pkg)) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003952 PackageSetting sysPs = mSettings.getDisabledSystemPkg(
3953 pkg.packageName);
3954 final GrantedPermissions origGp = sysPs.sharedUser != null
3955 ? sysPs.sharedUser : sysPs;
3956 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 allowed = true;
3958 } else {
3959 allowed = false;
3960 }
3961 } else {
3962 allowed = true;
3963 }
3964 }
3965 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003966 if (allowed) {
3967 allowedSig = true;
3968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 } else {
3970 allowed = false;
3971 }
3972 if (false) {
3973 if (gp != ps) {
3974 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3975 }
3976 }
3977 if (allowed) {
3978 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3979 && ps.permissionsFixed) {
3980 // If this is an existing, non-system package, then
3981 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003982 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003984 // Except... if this is a permission that was added
3985 // to the platform (note: need to only do this when
3986 // updating the platform).
3987 final int NP = PackageParser.NEW_PERMISSIONS.length;
3988 for (int ip=0; ip<NP; ip++) {
3989 final PackageParser.NewPermissionInfo npi
3990 = PackageParser.NEW_PERMISSIONS[ip];
3991 if (npi.name.equals(perm)
3992 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3993 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003994 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003995 + pkg.packageName);
3996 break;
3997 }
3998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 }
4000 }
4001 if (allowed) {
4002 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004003 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 gp.grantedPermissions.add(perm);
4005 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004006 } else if (!ps.haveGids) {
4007 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 }
4009 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004010 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 + " to package " + pkg.packageName
4012 + " because it was previously installed without");
4013 }
4014 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004015 if (gp.grantedPermissions.remove(perm)) {
4016 changedPermission = true;
4017 gp.gids = removeInts(gp.gids, bp.gids);
4018 Slog.i(TAG, "Un-granting permission " + perm
4019 + " from package " + pkg.packageName
4020 + " (protectionLevel=" + bp.protectionLevel
4021 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4022 + ")");
4023 } else {
4024 Slog.w(TAG, "Not granting permission " + perm
4025 + " to package " + pkg.packageName
4026 + " (protectionLevel=" + bp.protectionLevel
4027 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4028 + ")");
4029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 }
4031 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004032 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 + " in package " + pkg.packageName);
4034 }
4035 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004036
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004037 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004038 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4039 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 // This is the first that we have heard about this package, so the
4041 // permissions we have now selected are fixed until explicitly
4042 // changed.
4043 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004045 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 private final class ActivityIntentResolver
4049 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004050 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004052 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 }
4054
Mihai Preda074edef2009-05-18 17:13:31 +02004055 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004057 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4059 }
4060
Mihai Predaeae850c2009-05-13 10:13:48 +02004061 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4062 ArrayList<PackageParser.Activity> packageActivities) {
4063 if (packageActivities == null) {
4064 return null;
4065 }
4066 mFlags = flags;
4067 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4068 int N = packageActivities.size();
4069 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4070 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004071
4072 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004073 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004074 intentFilters = packageActivities.get(i).intents;
4075 if (intentFilters != null && intentFilters.size() > 0) {
4076 listCut.add(intentFilters);
4077 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004078 }
4079 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4080 }
4081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 public final void addActivity(PackageParser.Activity a, String type) {
Kenny Root502e9a42011-01-10 13:48:15 -08004083 final boolean systemApp = isSystemApp(a.info.applicationInfo);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004084 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 if (SHOW_INFO || Config.LOGV) Log.v(
4086 TAG, " " + type + " " +
4087 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4088 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4089 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004090 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root502e9a42011-01-10 13:48:15 -08004092 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4093 intent.setPriority(0);
4094 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
4095 + a.className + " with priority > 0, forcing to 0");
4096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 if (SHOW_INFO || Config.LOGV) {
4098 Log.v(TAG, " IntentFilter:");
4099 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4100 }
4101 if (!intent.debugCheck()) {
4102 Log.w(TAG, "==> For Activity " + a.info.name);
4103 }
4104 addFilter(intent);
4105 }
4106 }
4107
4108 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004109 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 if (SHOW_INFO || Config.LOGV) Log.v(
4111 TAG, " " + type + " " +
4112 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4113 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4114 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004115 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4117 if (SHOW_INFO || Config.LOGV) {
4118 Log.v(TAG, " IntentFilter:");
4119 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4120 }
4121 removeFilter(intent);
4122 }
4123 }
4124
4125 @Override
4126 protected boolean allowFilterResult(
4127 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4128 ActivityInfo filterAi = filter.activity.info;
4129 for (int i=dest.size()-1; i>=0; i--) {
4130 ActivityInfo destAi = dest.get(i).activityInfo;
4131 if (destAi.name == filterAi.name
4132 && destAi.packageName == filterAi.packageName) {
4133 return false;
4134 }
4135 }
4136 return true;
4137 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004140 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4141 return info.activity.owner.packageName;
4142 }
4143
4144 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4146 int match) {
4147 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4148 return null;
4149 }
4150 final PackageParser.Activity activity = info.activity;
4151 if (mSafeMode && (activity.info.applicationInfo.flags
4152 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4153 return null;
4154 }
4155 final ResolveInfo res = new ResolveInfo();
4156 res.activityInfo = PackageParser.generateActivityInfo(activity,
4157 mFlags);
4158 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4159 res.filter = info;
4160 }
4161 res.priority = info.getPriority();
4162 res.preferredOrder = activity.owner.mPreferredOrder;
4163 //System.out.println("Result: " + res.activityInfo.className +
4164 // " = " + res.priority);
4165 res.match = match;
4166 res.isDefault = info.hasDefault;
4167 res.labelRes = info.labelRes;
4168 res.nonLocalizedLabel = info.nonLocalizedLabel;
4169 res.icon = info.icon;
4170 return res;
4171 }
4172
4173 @Override
4174 protected void sortResults(List<ResolveInfo> results) {
4175 Collections.sort(results, mResolvePrioritySorter);
4176 }
4177
4178 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004179 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004181 out.print(prefix); out.print(
4182 Integer.toHexString(System.identityHashCode(filter.activity)));
4183 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004184 out.print(filter.activity.getComponentShortName());
4185 out.print(" filter ");
4186 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 }
4188
4189// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4190// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4191// final List<ResolveInfo> retList = Lists.newArrayList();
4192// while (i.hasNext()) {
4193// final ResolveInfo resolveInfo = i.next();
4194// if (isEnabledLP(resolveInfo.activityInfo)) {
4195// retList.add(resolveInfo);
4196// }
4197// }
4198// return retList;
4199// }
4200
4201 // Keys are String (activity class name), values are Activity.
4202 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4203 = new HashMap<ComponentName, PackageParser.Activity>();
4204 private int mFlags;
4205 }
4206
4207 private final class ServiceIntentResolver
4208 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004209 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004211 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 }
4213
Mihai Preda074edef2009-05-18 17:13:31 +02004214 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004216 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4218 }
4219
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004220 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4221 ArrayList<PackageParser.Service> packageServices) {
4222 if (packageServices == null) {
4223 return null;
4224 }
4225 mFlags = flags;
4226 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4227 int N = packageServices.size();
4228 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4229 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4230
4231 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4232 for (int i = 0; i < N; ++i) {
4233 intentFilters = packageServices.get(i).intents;
4234 if (intentFilters != null && intentFilters.size() > 0) {
4235 listCut.add(intentFilters);
4236 }
4237 }
4238 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4239 }
4240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004242 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 if (SHOW_INFO || Config.LOGV) Log.v(
4244 TAG, " " + (s.info.nonLocalizedLabel != null
4245 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4246 if (SHOW_INFO || Config.LOGV) Log.v(
4247 TAG, " Class=" + s.info.name);
4248 int NI = s.intents.size();
4249 int j;
4250 for (j=0; j<NI; j++) {
4251 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4252 if (SHOW_INFO || Config.LOGV) {
4253 Log.v(TAG, " IntentFilter:");
4254 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4255 }
4256 if (!intent.debugCheck()) {
4257 Log.w(TAG, "==> For Service " + s.info.name);
4258 }
4259 addFilter(intent);
4260 }
4261 }
4262
4263 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004264 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 if (SHOW_INFO || Config.LOGV) Log.v(
4266 TAG, " " + (s.info.nonLocalizedLabel != null
4267 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4268 if (SHOW_INFO || Config.LOGV) Log.v(
4269 TAG, " Class=" + s.info.name);
4270 int NI = s.intents.size();
4271 int j;
4272 for (j=0; j<NI; j++) {
4273 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4274 if (SHOW_INFO || Config.LOGV) {
4275 Log.v(TAG, " IntentFilter:");
4276 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4277 }
4278 removeFilter(intent);
4279 }
4280 }
4281
4282 @Override
4283 protected boolean allowFilterResult(
4284 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4285 ServiceInfo filterSi = filter.service.info;
4286 for (int i=dest.size()-1; i>=0; i--) {
4287 ServiceInfo destAi = dest.get(i).serviceInfo;
4288 if (destAi.name == filterSi.name
4289 && destAi.packageName == filterSi.packageName) {
4290 return false;
4291 }
4292 }
4293 return true;
4294 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004297 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4298 return info.service.owner.packageName;
4299 }
4300
4301 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4303 int match) {
Jason parksa3cdaa52011-01-13 14:15:43 -06004304 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4306 return null;
4307 }
4308 final PackageParser.Service service = info.service;
4309 if (mSafeMode && (service.info.applicationInfo.flags
4310 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4311 return null;
4312 }
4313 final ResolveInfo res = new ResolveInfo();
4314 res.serviceInfo = PackageParser.generateServiceInfo(service,
4315 mFlags);
4316 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4317 res.filter = filter;
4318 }
4319 res.priority = info.getPriority();
4320 res.preferredOrder = service.owner.mPreferredOrder;
4321 //System.out.println("Result: " + res.activityInfo.className +
4322 // " = " + res.priority);
4323 res.match = match;
4324 res.isDefault = info.hasDefault;
4325 res.labelRes = info.labelRes;
4326 res.nonLocalizedLabel = info.nonLocalizedLabel;
4327 res.icon = info.icon;
4328 return res;
4329 }
4330
4331 @Override
4332 protected void sortResults(List<ResolveInfo> results) {
4333 Collections.sort(results, mResolvePrioritySorter);
4334 }
4335
4336 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004337 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004339 out.print(prefix); out.print(
4340 Integer.toHexString(System.identityHashCode(filter.service)));
4341 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004342 out.print(filter.service.getComponentShortName());
4343 out.print(" filter ");
4344 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 }
4346
4347// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4348// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4349// final List<ResolveInfo> retList = Lists.newArrayList();
4350// while (i.hasNext()) {
4351// final ResolveInfo resolveInfo = (ResolveInfo) i;
4352// if (isEnabledLP(resolveInfo.serviceInfo)) {
4353// retList.add(resolveInfo);
4354// }
4355// }
4356// return retList;
4357// }
4358
4359 // Keys are String (activity class name), values are Activity.
4360 private final HashMap<ComponentName, PackageParser.Service> mServices
4361 = new HashMap<ComponentName, PackageParser.Service>();
4362 private int mFlags;
4363 };
4364
4365 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4366 new Comparator<ResolveInfo>() {
4367 public int compare(ResolveInfo r1, ResolveInfo r2) {
4368 int v1 = r1.priority;
4369 int v2 = r2.priority;
4370 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4371 if (v1 != v2) {
4372 return (v1 > v2) ? -1 : 1;
4373 }
4374 v1 = r1.preferredOrder;
4375 v2 = r2.preferredOrder;
4376 if (v1 != v2) {
4377 return (v1 > v2) ? -1 : 1;
4378 }
4379 if (r1.isDefault != r2.isDefault) {
4380 return r1.isDefault ? -1 : 1;
4381 }
4382 v1 = r1.match;
4383 v2 = r2.match;
4384 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4385 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4386 }
4387 };
4388
4389 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4390 new Comparator<ProviderInfo>() {
4391 public int compare(ProviderInfo p1, ProviderInfo p2) {
4392 final int v1 = p1.initOrder;
4393 final int v2 = p2.initOrder;
4394 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4395 }
4396 };
4397
Kenny Root93565c4b2010-06-18 15:46:06 -07004398 private static final boolean DEBUG_OBB = false;
4399
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004400 private static final void sendPackageBroadcast(String action, String pkg,
4401 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 IActivityManager am = ActivityManagerNative.getDefault();
4403 if (am != null) {
4404 try {
4405 final Intent intent = new Intent(action,
4406 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4407 if (extras != null) {
4408 intent.putExtras(extras);
4409 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004410 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004411 am.broadcastIntent(null, intent, null, finishedReceiver,
4412 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004413 } catch (RemoteException ex) {
4414 }
4415 }
4416 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004417
4418 public String nextPackageToClean(String lastPackage) {
4419 synchronized (mPackages) {
4420 if (!mMediaMounted) {
4421 // If the external storage is no longer mounted at this point,
4422 // the caller may not have been able to delete all of this
4423 // packages files and can not delete any more. Bail.
4424 return null;
4425 }
4426 if (lastPackage != null) {
4427 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4428 }
4429 return mSettings.mPackagesToBeCleaned.size() > 0
4430 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4431 }
4432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004434 void schedulePackageCleaning(String packageName) {
4435 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4436 }
4437
4438 void startCleaningPackages() {
4439 synchronized (mPackages) {
4440 if (!mMediaMounted) {
4441 return;
4442 }
4443 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4444 return;
4445 }
4446 }
4447 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4448 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4449 IActivityManager am = ActivityManagerNative.getDefault();
4450 if (am != null) {
4451 try {
4452 am.startService(null, intent, null);
4453 } catch (RemoteException e) {
4454 }
4455 }
4456 }
4457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004458 private final class AppDirObserver extends FileObserver {
4459 public AppDirObserver(String path, int mask, boolean isrom) {
4460 super(path, mask);
4461 mRootDir = path;
4462 mIsRom = isrom;
4463 }
4464
4465 public void onEvent(int event, String path) {
4466 String removedPackage = null;
4467 int removedUid = -1;
4468 String addedPackage = null;
4469 int addedUid = -1;
4470
4471 synchronized (mInstallLock) {
4472 String fullPathStr = null;
4473 File fullPath = null;
4474 if (path != null) {
4475 fullPath = new File(mRootDir, path);
4476 fullPathStr = fullPath.getPath();
4477 }
4478
4479 if (Config.LOGV) Log.v(
4480 TAG, "File " + fullPathStr + " changed: "
4481 + Integer.toHexString(event));
4482
4483 if (!isPackageFilename(path)) {
4484 if (Config.LOGV) Log.v(
4485 TAG, "Ignoring change of non-package file: " + fullPathStr);
4486 return;
4487 }
4488
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004489 // Ignore packages that are being installed or
4490 // have just been installed.
4491 if (ignoreCodePath(fullPathStr)) {
4492 return;
4493 }
4494 PackageParser.Package p = null;
4495 synchronized (mPackages) {
4496 p = mAppDirs.get(fullPathStr);
4497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004499 if (p != null) {
4500 removePackageLI(p, true);
4501 removedPackage = p.applicationInfo.packageName;
4502 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 }
4504 }
4505
4506 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004508 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004509 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4510 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 PackageParser.PARSE_CHATTY |
4512 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004513 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4514 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515 if (p != null) {
4516 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004517 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004518 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 }
4520 addedPackage = p.applicationInfo.packageName;
4521 addedUid = p.applicationInfo.uid;
4522 }
4523 }
4524 }
4525
4526 synchronized (mPackages) {
4527 mSettings.writeLP();
4528 }
4529 }
4530
4531 if (removedPackage != null) {
4532 Bundle extras = new Bundle(1);
4533 extras.putInt(Intent.EXTRA_UID, removedUid);
4534 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004535 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4536 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 }
4538 if (addedPackage != null) {
4539 Bundle extras = new Bundle(1);
4540 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004541 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4542 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 }
4544 }
4545
4546 private final String mRootDir;
4547 private final boolean mIsRom;
4548 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 /* Called when a downloaded package installation has been confirmed by the user */
4551 public void installPackage(
4552 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004553 installPackage(packageURI, observer, flags, null);
4554 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004555
Jacek Surazski65e13172009-04-28 15:26:38 +02004556 /* Called when a downloaded package installation has been confirmed by the user */
4557 public void installPackage(
4558 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4559 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 mContext.enforceCallingOrSelfPermission(
4561 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004562
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004563 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004564 msg.obj = new InstallParams(packageURI, observer, flags,
4565 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004566 mHandler.sendMessage(msg);
4567 }
4568
Christopher Tate1bb69062010-02-19 17:02:12 -08004569 public void finishPackageInstall(int token) {
4570 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4571 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4572 mHandler.sendMessage(msg);
4573 }
4574
Dianne Hackborn880119b2010-11-18 22:26:40 -08004575 public void setInstallerPackageName(String targetPackage,
4576 String installerPackageName) {
4577 PackageSetting pkgSetting;
4578 final int uid = Binder.getCallingUid();
4579 final int permission = mContext.checkCallingPermission(
4580 android.Manifest.permission.INSTALL_PACKAGES);
4581 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4582 synchronized (mPackages) {
4583 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
4584 if (targetPackageSetting == null) {
4585 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
4586 }
4587
4588 PackageSetting installerPackageSetting;
4589 if (installerPackageName != null) {
4590 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
4591 if (installerPackageSetting == null) {
4592 throw new IllegalArgumentException("Unknown installer package: "
4593 + installerPackageName);
4594 }
4595 } else {
4596 installerPackageSetting = null;
4597 }
4598
4599 Signature[] callerSignature;
4600 Object obj = mSettings.getUserIdLP(uid);
4601 if (obj != null) {
4602 if (obj instanceof SharedUserSetting) {
4603 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
4604 } else if (obj instanceof PackageSetting) {
4605 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
4606 } else {
4607 throw new SecurityException("Bad object " + obj + " for uid " + uid);
4608 }
4609 } else {
4610 throw new SecurityException("Unknown calling uid " + uid);
4611 }
4612
4613 // Verify: can't set installerPackageName to a package that is
4614 // not signed with the same cert as the caller.
4615 if (installerPackageSetting != null) {
4616 if (checkSignaturesLP(callerSignature,
4617 installerPackageSetting.signatures.mSignatures)
4618 != PackageManager.SIGNATURE_MATCH) {
4619 throw new SecurityException(
4620 "Caller does not have same cert as new installer package "
4621 + installerPackageName);
4622 }
4623 }
4624
4625 // Verify: if target already has an installer package, it must
4626 // be signed with the same cert as the caller.
4627 if (targetPackageSetting.installerPackageName != null) {
4628 PackageSetting setting = mSettings.mPackages.get(
4629 targetPackageSetting.installerPackageName);
4630 // If the currently set package isn't valid, then it's always
4631 // okay to change it.
4632 if (setting != null) {
4633 if (checkSignaturesLP(callerSignature,
4634 setting.signatures.mSignatures)
4635 != PackageManager.SIGNATURE_MATCH) {
4636 throw new SecurityException(
4637 "Caller does not have same cert as old installer package "
4638 + targetPackageSetting.installerPackageName);
4639 }
4640 }
4641 }
4642
4643 // Okay!
4644 targetPackageSetting.installerPackageName = installerPackageName;
4645 scheduleWriteSettingsLocked();
4646 }
4647 }
4648
Kenny Root5d40fe92011-01-14 10:54:46 -08004649 public void setPackageObbPaths(String packageName, String[] paths) {
Kenny Root93565c4b2010-06-18 15:46:06 -07004650 if (DEBUG_OBB)
Kenny Root5d40fe92011-01-14 10:54:46 -08004651 Log.v(TAG, "Setting .obb paths for " + packageName + " to: " + Arrays.toString(paths));
4652 final int uid = Binder.getCallingUid();
4653 final int permission = mContext.checkCallingPermission(
4654 android.Manifest.permission.INSTALL_PACKAGES);
4655 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4656 if (!allowedByPermission) {
4657 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4658 + Binder.getCallingPid());
4659 }
4660 synchronized (mPackages) {
4661 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
4662 if (pkgSetting == null) {
4663 throw new IllegalArgumentException("Unknown package: " + packageName);
4664 }
4665
4666 if (paths != null) {
4667 if (paths.length == 0) {
4668 // Don't bother storing an empty array.
4669 paths = null;
4670 } else {
4671 // Don't allow the caller to manipulate our copy of the
4672 // list.
4673 paths = paths.clone();
4674 }
4675 }
4676
4677 // Only write settings file if the new and old settings are not the
4678 // same.
4679 if (!Arrays.equals(paths, pkgSetting.obbPathStrings)) {
4680 pkgSetting.obbPathStrings = paths;
4681 mSettings.writeLP();
4682 }
4683 }
4684 }
4685
4686 public String[] getPackageObbPaths(String packageName) {
4687 if (DEBUG_OBB)
4688 Log.v(TAG, "Getting .obb paths for " + packageName);
Kenny Root93565c4b2010-06-18 15:46:06 -07004689 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004690 final int permission = mContext.checkCallingPermission(
4691 android.Manifest.permission.INSTALL_PACKAGES);
4692 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004693 synchronized (mPackages) {
Kenny Root5d40fe92011-01-14 10:54:46 -08004694 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
Kenny Root93565c4b2010-06-18 15:46:06 -07004695 if (pkgSetting == null) {
4696 throw new IllegalArgumentException("Unknown package: " + packageName);
4697 }
4698 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4699 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4700 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4701 + pkgSetting.userId);
4702 }
Kenny Root5d40fe92011-01-14 10:54:46 -08004703 return pkgSetting.obbPathStrings;
Kenny Root93565c4b2010-06-18 15:46:06 -07004704 }
4705 }
4706
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004707 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004708 // Queue up an async operation since the package installation may take a little while.
4709 mHandler.post(new Runnable() {
4710 public void run() {
4711 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004712 // Result object to be returned
4713 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004714 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004715 res.uid = -1;
4716 res.pkg = null;
4717 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004718 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004719 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004720 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004721 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004722 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004723 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004724 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004725
4726 // A restore should be performed at this point if (a) the install
4727 // succeeded, (b) the operation is not an update, and (c) the new
4728 // package has a backupAgent defined.
4729 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004730 boolean doRestore = (!update
4731 && res.pkg != null
4732 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004733
4734 // Set up the post-install work request bookkeeping. This will be used
4735 // and cleaned up by the post-install event handling regardless of whether
4736 // there's a restore pass performed. Token values are >= 1.
4737 int token;
4738 if (mNextInstallToken < 0) mNextInstallToken = 1;
4739 token = mNextInstallToken++;
4740
4741 PostInstallData data = new PostInstallData(args, res);
4742 mRunningInstalls.put(token, data);
4743 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4744
4745 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4746 // Pass responsibility to the Backup Manager. It will perform a
4747 // restore if appropriate, then pass responsibility back to the
4748 // Package Manager to run the post-install observer callbacks
4749 // and broadcasts.
4750 IBackupManager bm = IBackupManager.Stub.asInterface(
4751 ServiceManager.getService(Context.BACKUP_SERVICE));
4752 if (bm != null) {
4753 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4754 + " to BM for possible restore");
4755 try {
4756 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4757 } catch (RemoteException e) {
4758 // can't happen; the backup manager is local
4759 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004760 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004761 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004762 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004763 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004764 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004765 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004767 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004768
4769 if (!doRestore) {
4770 // No restore possible, or the Backup Manager was mysteriously not
4771 // available -- just fire the post-install work request directly.
4772 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4773 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4774 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 }
4777 });
4778 }
4779
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004780 abstract class HandlerParams {
4781 final static int MAX_RETRIES = 4;
4782 int retry = 0;
4783 final void startCopy() {
4784 try {
4785 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4786 retry++;
4787 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004788 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004789 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4790 handleServiceError();
4791 return;
4792 } else {
4793 handleStartCopy();
4794 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4795 mHandler.sendEmptyMessage(MCS_UNBIND);
4796 }
4797 } catch (RemoteException e) {
4798 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4799 mHandler.sendEmptyMessage(MCS_RECONNECT);
4800 }
4801 handleReturnCode();
4802 }
4803
4804 final void serviceError() {
4805 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4806 handleServiceError();
4807 handleReturnCode();
4808 }
4809 abstract void handleStartCopy() throws RemoteException;
4810 abstract void handleServiceError();
4811 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004812 }
4813
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004814 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004815 final IPackageInstallObserver observer;
4816 int flags;
4817 final Uri packageURI;
4818 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004819 private InstallArgs mArgs;
4820 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004821 InstallParams(Uri packageURI,
4822 IPackageInstallObserver observer, int flags,
4823 String installerPackageName) {
4824 this.packageURI = packageURI;
4825 this.flags = flags;
4826 this.observer = observer;
4827 this.installerPackageName = installerPackageName;
4828 }
4829
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004830 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4831 String packageName = pkgLite.packageName;
4832 int installLocation = pkgLite.installLocation;
4833 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4834 synchronized (mPackages) {
4835 PackageParser.Package pkg = mPackages.get(packageName);
4836 if (pkg != null) {
4837 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4838 // Check for updated system application.
4839 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4840 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004841 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004842 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4843 }
4844 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4845 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004846 if (onSd) {
4847 // Install flag overrides everything.
4848 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4849 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004850 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004851 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4852 // Application explicitly specified internal.
4853 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4854 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4855 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004856 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004857 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004858 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004859 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4860 }
4861 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004862 }
4863 }
4864 } else {
4865 // Invalid install. Return error code
4866 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4867 }
4868 }
4869 }
4870 // All the special cases have been taken care of.
4871 // Return result based on recommended install location.
4872 if (onSd) {
4873 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4874 }
4875 return pkgLite.recommendedInstallLocation;
4876 }
4877
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004878 /*
4879 * Invoke remote method to get package information and install
4880 * location values. Override install location based on default
4881 * policy if needed and then create install arguments based
4882 * on the install location.
4883 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004884 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004885 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004886 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4887 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004888 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4889 if (onInt && onSd) {
4890 // Check if both bits are set.
4891 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4892 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4893 } else if (fwdLocked && onSd) {
4894 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004895 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004896 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004897 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004898 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07004899 final PackageInfoLite pkgLite;
4900 try {
4901 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4902 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4903 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
4904 } finally {
4905 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4906 }
4907
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004908 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004909 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4910 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4911 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4912 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4913 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004914 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4915 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4916 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004917 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4918 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004919 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004920 // Override with defaults if needed.
4921 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004922 if (!onSd && !onInt) {
4923 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004924 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4925 // Set the flag to install on external media.
4926 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004927 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004928 } else {
4929 // Make sure the flag for installing on external
4930 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004931 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004932 flags &= ~PackageManager.INSTALL_EXTERNAL;
4933 }
4934 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004935 }
4936 }
4937 // Create the file args now.
4938 mArgs = createInstallArgs(this);
4939 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4940 // Create copy only if we are not in an erroneous state.
4941 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004942 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004943 }
4944 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004945 }
4946
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004947 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004948 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004949 // If mArgs is null, then MCS couldn't be reached. When it
4950 // reconnects, it will try again to install. At that point, this
4951 // will succeed.
4952 if (mArgs != null) {
4953 processPendingInstall(mArgs, mRet);
4954 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004955 }
4956
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004957 @Override
4958 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004959 mArgs = createInstallArgs(this);
4960 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004962 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004963
4964 /*
4965 * Utility class used in movePackage api.
4966 * srcArgs and targetArgs are not set for invalid flags and make
4967 * sure to do null checks when invoking methods on them.
4968 * We probably want to return ErrorPrams for both failed installs
4969 * and moves.
4970 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004971 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004972 final IPackageMoveObserver observer;
4973 final int flags;
4974 final String packageName;
4975 final InstallArgs srcArgs;
4976 final InstallArgs targetArgs;
4977 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004978
4979 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4980 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004981 this.srcArgs = srcArgs;
4982 this.observer = observer;
4983 this.flags = flags;
4984 this.packageName = packageName;
4985 if (srcArgs != null) {
4986 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004987 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004988 } else {
4989 targetArgs = null;
4990 }
4991 }
4992
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004993 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004994 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4995 // Check for storage space on target medium
4996 if (!targetArgs.checkFreeStorage(mContainerService)) {
4997 Log.w(TAG, "Insufficient storage to install");
4998 return;
4999 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005000 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005001 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005002 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005003 if (DEBUG_SD_INSTALL) {
5004 StringBuilder builder = new StringBuilder();
5005 if (srcArgs != null) {
5006 builder.append("src: ");
5007 builder.append(srcArgs.getCodePath());
5008 }
5009 if (targetArgs != null) {
5010 builder.append(" target : ");
5011 builder.append(targetArgs.getCodePath());
5012 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005013 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005014 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005015 }
5016
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005017 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005018 void handleReturnCode() {
5019 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005020 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5021 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5022 currentStatus = PackageManager.MOVE_SUCCEEDED;
5023 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5024 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5025 }
5026 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005027 }
5028
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005029 @Override
5030 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005031 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005032 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005033 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005034
5035 private InstallArgs createInstallArgs(InstallParams params) {
5036 if (installOnSd(params.flags)) {
5037 return new SdInstallArgs(params);
5038 } else {
5039 return new FileInstallArgs(params);
5040 }
5041 }
5042
Kenny Root85387d72010-08-26 10:13:11 -07005043 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
5044 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005045 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07005046 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005047 } else {
Kenny Root85387d72010-08-26 10:13:11 -07005048 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005049 }
5050 }
5051
Kenny Root85387d72010-08-26 10:13:11 -07005052 // Used by package mover
5053 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005054 if (installOnSd(flags)) {
5055 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5056 return new SdInstallArgs(packageURI, cid);
5057 } else {
Kenny Root85387d72010-08-26 10:13:11 -07005058 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005059 }
5060 }
5061
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005062 static abstract class InstallArgs {
5063 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005064 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005065 final int flags;
5066 final Uri packageURI;
5067 final String installerPackageName;
5068
5069 InstallArgs(Uri packageURI,
5070 IPackageInstallObserver observer, int flags,
5071 String installerPackageName) {
5072 this.packageURI = packageURI;
5073 this.flags = flags;
5074 this.observer = observer;
5075 this.installerPackageName = installerPackageName;
5076 }
5077
5078 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005079 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005080 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005081 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005082 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005083 abstract String getCodePath();
5084 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07005085 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005086 // Need installer lock especially for dex file removal.
5087 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005088 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005089 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005090 }
5091
5092 class FileInstallArgs extends InstallArgs {
5093 File installDir;
5094 String codeFileName;
5095 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07005096 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005097 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005098
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005099 FileInstallArgs(InstallParams params) {
5100 super(params.packageURI, params.observer,
5101 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005102 }
5103
Kenny Root85387d72010-08-26 10:13:11 -07005104 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005105 super(null, null, 0, null);
5106 File codeFile = new File(fullCodePath);
5107 installDir = codeFile.getParentFile();
5108 codeFileName = fullCodePath;
5109 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07005110 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005111 }
5112
Kenny Root85387d72010-08-26 10:13:11 -07005113 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005114 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07005115 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005116 String apkName = getNextCodePath(null, pkgName, ".apk");
5117 codeFileName = new File(installDir, apkName + ".apk").getPath();
5118 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07005119 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005120 }
5121
Kenny Root11128572010-10-11 10:51:32 -07005122 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5123 try {
5124 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5125 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5126 return imcs.checkFreeStorage(false, packageURI);
5127 } finally {
5128 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5129 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005130 }
5131
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005132 String getCodePath() {
5133 return codeFileName;
5134 }
5135
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005136 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005137 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005138 codeFileName = createTempPackageFile(installDir).getPath();
5139 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005140 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005141 }
5142
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005143 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005144 if (temp) {
5145 // Generate temp file name
5146 createCopyFile();
5147 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005148 // Get a ParcelFileDescriptor to write to the output file
5149 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005150 if (!created) {
5151 try {
5152 codeFile.createNewFile();
5153 // Set permissions
5154 if (!setPermissions()) {
5155 // Failed setting permissions.
5156 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5157 }
5158 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005159 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005160 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5161 }
5162 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005163 ParcelFileDescriptor out = null;
5164 try {
Kenny Root85387d72010-08-26 10:13:11 -07005165 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005166 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005167 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005168 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5169 }
5170 // Copy the resource now
5171 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5172 try {
Kenny Root11128572010-10-11 10:51:32 -07005173 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5174 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005175 if (imcs.copyResource(packageURI, out)) {
5176 ret = PackageManager.INSTALL_SUCCEEDED;
5177 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005178 } finally {
5179 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005180 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005181 }
Kenny Root85387d72010-08-26 10:13:11 -07005182
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005183 return ret;
5184 }
5185
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005186 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005187 if (status != PackageManager.INSTALL_SUCCEEDED) {
5188 cleanUp();
5189 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005190 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005191 }
5192
5193 boolean doRename(int status, final String pkgName, String oldCodePath) {
5194 if (status != PackageManager.INSTALL_SUCCEEDED) {
5195 cleanUp();
5196 return false;
5197 } else {
5198 // Rename based on packageName
5199 File codeFile = new File(getCodePath());
5200 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5201 File desFile = new File(installDir, apkName + ".apk");
5202 if (!codeFile.renameTo(desFile)) {
5203 return false;
5204 }
5205 // Reset paths since the file has been renamed.
5206 codeFileName = desFile.getPath();
5207 resourceFileName = getResourcePathFromCodePath();
5208 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005209 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005210 // Failed setting permissions.
5211 return false;
5212 }
5213 return true;
5214 }
5215 }
5216
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005217 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005218 if (status != PackageManager.INSTALL_SUCCEEDED) {
5219 cleanUp();
5220 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005221 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005222 }
5223
5224 String getResourcePath() {
5225 return resourceFileName;
5226 }
5227
5228 String getResourcePathFromCodePath() {
5229 String codePath = getCodePath();
5230 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5231 String apkNameOnly = getApkName(codePath);
5232 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5233 } else {
5234 return codePath;
5235 }
5236 }
5237
Kenny Root85387d72010-08-26 10:13:11 -07005238 @Override
5239 String getNativeLibraryPath() {
5240 return libraryPath;
5241 }
5242
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005243 private boolean cleanUp() {
5244 boolean ret = true;
5245 String sourceDir = getCodePath();
5246 String publicSourceDir = getResourcePath();
5247 if (sourceDir != null) {
5248 File sourceFile = new File(sourceDir);
5249 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005250 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005251 ret = false;
5252 }
5253 // Delete application's code and resources
5254 sourceFile.delete();
5255 }
5256 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5257 final File publicSourceFile = new File(publicSourceDir);
5258 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005259 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005260 }
5261 if (publicSourceFile.exists()) {
5262 publicSourceFile.delete();
5263 }
5264 }
5265 return ret;
5266 }
5267
5268 void cleanUpResourcesLI() {
5269 String sourceDir = getCodePath();
5270 if (cleanUp() && mInstaller != null) {
5271 int retCode = mInstaller.rmdex(sourceDir);
5272 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005273 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005274 + " at location "
5275 + sourceDir + ", retcode=" + retCode);
5276 // we don't consider this to be a failure of the core package deletion
5277 }
5278 }
5279 }
5280
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005281 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005282 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005283 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005284 final int filePermissions =
5285 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5286 |FileUtils.S_IROTH;
5287 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5288 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005289 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005290 getCodePath()
5291 + ". The return code was: " + retCode);
5292 // TODO Define new internal error
5293 return false;
5294 }
5295 return true;
5296 }
5297 return true;
5298 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005299
5300 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005301 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005302 cleanUpResourcesLI();
5303 return true;
5304 }
Kenny Root85387d72010-08-26 10:13:11 -07005305
5306 private boolean isFwdLocked() {
5307 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5308 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005309 }
5310
5311 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005312 static final String RES_FILE_NAME = "pkg.apk";
5313
Kenny Root85387d72010-08-26 10:13:11 -07005314 String cid;
5315 String packagePath;
5316 String libraryPath;
5317
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005318 SdInstallArgs(InstallParams params) {
5319 super(params.packageURI, params.observer,
5320 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005321 }
5322
Kenny Root85387d72010-08-26 10:13:11 -07005323 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005324 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005325 // Extract cid from fullCodePath
5326 int eidx = fullCodePath.lastIndexOf("/");
5327 String subStr1 = fullCodePath.substring(0, eidx);
5328 int sidx = subStr1.lastIndexOf("/");
5329 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005330 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005331 }
5332
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005333 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005334 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5335 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005336 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005337 }
5338
5339 SdInstallArgs(Uri packageURI, String cid) {
5340 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005341 this.cid = cid;
5342 }
5343
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005344 void createCopyFile() {
5345 cid = getTempContainerId();
5346 }
5347
Kenny Root11128572010-10-11 10:51:32 -07005348 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5349 try {
5350 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5351 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5352 return imcs.checkFreeStorage(true, packageURI);
5353 } finally {
5354 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5355 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005356 }
5357
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005358 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005359 if (temp) {
5360 createCopyFile();
5361 }
Kenny Root11128572010-10-11 10:51:32 -07005362
5363 final String newCachePath;
5364 try {
5365 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5366 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5367 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5368 getEncryptKey(), RES_FILE_NAME);
5369 } finally {
5370 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5371 }
5372
Kenny Root85387d72010-08-26 10:13:11 -07005373 if (newCachePath != null) {
5374 setCachePath(newCachePath);
5375 return PackageManager.INSTALL_SUCCEEDED;
5376 } else {
5377 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5378 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005379 }
5380
5381 @Override
5382 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005383 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005384 }
5385
5386 @Override
5387 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005388 return packagePath;
5389 }
5390
5391 @Override
5392 String getNativeLibraryPath() {
5393 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005394 }
5395
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005396 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005397 if (status != PackageManager.INSTALL_SUCCEEDED) {
5398 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005399 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005400 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005401 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005402 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005403 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5404 Process.SYSTEM_UID);
5405 if (newCachePath != null) {
5406 setCachePath(newCachePath);
5407 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005408 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5409 }
5410 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005411 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005412 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005413 }
5414
5415 boolean doRename(int status, final String pkgName,
5416 String oldCodePath) {
5417 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005418 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005419 if (PackageHelper.isContainerMounted(cid)) {
5420 // Unmount the container
5421 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005422 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005423 return false;
5424 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005425 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005426 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005427 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5428 " which might be stale. Will try to clean up.");
5429 // Clean up the stale container and proceed to recreate.
5430 if (!PackageHelper.destroySdDir(newCacheId)) {
5431 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5432 return false;
5433 }
5434 // Successfully cleaned up stale container. Try to rename again.
5435 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5436 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5437 + " inspite of cleaning it up.");
5438 return false;
5439 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005440 }
5441 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005442 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005443 newCachePath = PackageHelper.mountSdDir(newCacheId,
5444 getEncryptKey(), Process.SYSTEM_UID);
5445 } else {
5446 newCachePath = PackageHelper.getSdDir(newCacheId);
5447 }
5448 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005449 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005450 return false;
5451 }
5452 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005453 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005454 " at new path: " + newCachePath);
5455 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005456 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005457 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005458 }
5459
Kenny Root85387d72010-08-26 10:13:11 -07005460 private void setCachePath(String newCachePath) {
5461 File cachePath = new File(newCachePath);
5462 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5463 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5464 }
5465
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005466 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005467 if (status != PackageManager.INSTALL_SUCCEEDED) {
5468 cleanUp();
5469 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005470 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005471 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005472 PackageHelper.mountSdDir(cid,
5473 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005474 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005475 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005476 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005477 }
5478
5479 private void cleanUp() {
5480 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005481 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005482 }
5483
5484 void cleanUpResourcesLI() {
5485 String sourceFile = getCodePath();
5486 // Remove dex file
5487 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005488 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005489 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005490 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005491 + " at location "
5492 + sourceFile.toString() + ", retcode=" + retCode);
5493 // we don't consider this to be a failure of the core package deletion
5494 }
5495 }
5496 cleanUp();
5497 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005498
5499 boolean matchContainer(String app) {
5500 if (cid.startsWith(app)) {
5501 return true;
5502 }
5503 return false;
5504 }
5505
5506 String getPackageName() {
5507 int idx = cid.lastIndexOf("-");
5508 if (idx == -1) {
5509 return cid;
5510 }
5511 return cid.substring(0, idx);
5512 }
5513
5514 boolean doPostDeleteLI(boolean delete) {
5515 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005516 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005517 if (mounted) {
5518 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005519 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005520 }
5521 if (ret && delete) {
5522 cleanUpResourcesLI();
5523 }
5524 return ret;
5525 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005526 };
5527
5528 // Utility method used to create code paths based on package name and available index.
5529 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5530 String idxStr = "";
5531 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005532 // Fall back to default value of idx=1 if prefix is not
5533 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005534 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005535 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005536 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005537 if (subStr.endsWith(suffix)) {
5538 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005539 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005540 // If oldCodePath already contains prefix find out the
5541 // ending index to either increment or decrement.
5542 int sidx = subStr.lastIndexOf(prefix);
5543 if (sidx != -1) {
5544 subStr = subStr.substring(sidx + prefix.length());
5545 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005546 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5547 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005548 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005549 try {
5550 idx = Integer.parseInt(subStr);
5551 if (idx <= 1) {
5552 idx++;
5553 } else {
5554 idx--;
5555 }
5556 } catch(NumberFormatException e) {
5557 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005558 }
5559 }
5560 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005561 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005562 return prefix + idxStr;
5563 }
5564
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005565 // Utility method used to ignore ADD/REMOVE events
5566 // by directory observer.
5567 private static boolean ignoreCodePath(String fullPathStr) {
5568 String apkName = getApkName(fullPathStr);
5569 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5570 if (idx != -1 && ((idx+1) < apkName.length())) {
5571 // Make sure the package ends with a numeral
5572 String version = apkName.substring(idx+1);
5573 try {
5574 Integer.parseInt(version);
5575 return true;
5576 } catch (NumberFormatException e) {}
5577 }
5578 return false;
5579 }
5580
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005581 // Utility method that returns the relative package path with respect
5582 // to the installation directory. Like say for /data/data/com.test-1.apk
5583 // string com.test-1 is returned.
5584 static String getApkName(String codePath) {
5585 if (codePath == null) {
5586 return null;
5587 }
5588 int sidx = codePath.lastIndexOf("/");
5589 int eidx = codePath.lastIndexOf(".");
5590 if (eidx == -1) {
5591 eidx = codePath.length();
5592 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005593 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005594 return null;
5595 }
5596 return codePath.substring(sidx+1, eidx);
5597 }
5598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 class PackageInstalledInfo {
5600 String name;
5601 int uid;
5602 PackageParser.Package pkg;
5603 int returnCode;
5604 PackageRemovedInfo removedInfo;
5605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 /*
5608 * Install a non-existing package.
5609 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005610 private void installNewPackageLI(PackageParser.Package pkg,
5611 int parseFlags,
5612 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005613 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005615 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005616
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005617 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 res.name = pkgName;
5619 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005620 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5621 // A package with the same name is already installed, though
5622 // it has been renamed to an older name. The package we
5623 // are trying to install should be installed as an update to
5624 // the existing one, but that has not been requested, so bail.
5625 Slog.w(TAG, "Attempt to re-install " + pkgName
5626 + " without first uninstalling package running as "
5627 + mSettings.mRenamedPackages.get(pkgName));
5628 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5629 return;
5630 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005631 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005633 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 + " without first uninstalling.");
5635 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5636 return;
5637 }
5638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005640 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5641 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005643 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5645 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5646 }
5647 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005648 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005649 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 res);
5651 // delete the partially installed application. the data directory will have to be
5652 // restored if it was already existing
5653 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5654 // remove package from internal structures. Note that we want deletePackageX to
5655 // delete the package data and cache directories that it created in
5656 // scanPackageLocked, unless those directories existed before we even tried to
5657 // install.
5658 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005659 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005661 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 }
5663 }
5664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005665
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005666 private void replacePackageLI(PackageParser.Package pkg,
5667 int parseFlags,
5668 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005669 String installerPackageName, PackageInstalledInfo res) {
5670
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005671 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005672 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 // First find the old package info and check signatures
5674 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005675 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005676 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005677 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5679 return;
5680 }
5681 }
Kenny Root85387d72010-08-26 10:13:11 -07005682 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005683 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005684 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005686 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 }
5688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005690 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005691 PackageParser.Package pkg,
5692 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005693 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 PackageParser.Package newPackage = null;
5695 String pkgName = deletedPackage.packageName;
5696 boolean deletedPkg = true;
5697 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005698
Jacek Surazski65e13172009-04-28 15:26:38 +02005699 String oldInstallerPackageName = null;
5700 synchronized (mPackages) {
5701 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005703
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005704 long origUpdateTime;
5705 if (pkg.mExtras != null) {
5706 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5707 } else {
5708 origUpdateTime = 0;
5709 }
5710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005712 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005713 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005714 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5716 deletedPkg = false;
5717 } else {
5718 // Successfully deleted the old package. Now proceed with re-installation
5719 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005720 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5721 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005723 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5725 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005726 }
5727 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005728 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005729 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 res);
5731 updatedSettings = true;
5732 }
5733 }
5734
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005735 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 // remove package from internal structures. Note that we want deletePackageX to
5737 // delete the package data and cache directories that it created in
5738 // scanPackageLocked, unless those directories existed before we even tried to
5739 // install.
5740 if(updatedSettings) {
5741 deletePackageLI(
5742 pkgName, true,
5743 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005744 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 }
5746 // Since we failed to install the new package we need to restore the old
5747 // package that we deleted.
5748 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005749 File restoreFile = new File(deletedPackage.mPath);
5750 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005751 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005752 return;
5753 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005754 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005755 boolean oldOnSd = isExternal(deletedPackage);
5756 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5757 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5758 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005759 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5760 | SCAN_UPDATE_TIME;
5761 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5762 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005763 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5764 return;
5765 }
5766 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005767 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005768 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005769 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005770 mSettings.writeLP();
5771 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005772 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 }
5774 }
5775 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005778 PackageParser.Package pkg,
5779 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005780 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 PackageParser.Package newPackage = null;
5782 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005783 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 PackageParser.PARSE_IS_SYSTEM;
5785 String packageName = deletedPackage.packageName;
5786 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5787 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005788 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 return;
5790 }
5791 PackageParser.Package oldPkg;
5792 PackageSetting oldPkgSetting;
5793 synchronized (mPackages) {
5794 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005795 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005796 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5797 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005798 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 return;
5800 }
5801 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005802
5803 killApplication(packageName, oldPkg.applicationInfo.uid);
5804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5806 res.removedInfo.removedPackage = packageName;
5807 // Remove existing system package
5808 removePackageLI(oldPkg, true);
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005809 synchronized (mPackages) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005810 if (!mSettings.disableSystemPackageLP(packageName) && deletedPackage != null) {
5811 // We didn't need to disable the .apk as a current system package,
5812 // which means we are replacing another update that is already
5813 // installed. We need to make sure to delete the older one's .apk.
5814 res.removedInfo.args = createInstallArgs(isExternal(pkg)
5815 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL,
5816 deletedPackage.applicationInfo.sourceDir,
5817 deletedPackage.applicationInfo.publicSourceDir,
5818 deletedPackage.applicationInfo.nativeLibraryDir);
5819 } else {
5820 res.removedInfo.args = null;
5821 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005822 }
5823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 // Successfully disabled the old package. Now proceed with re-installation
5825 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5826 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005827 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005829 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005830 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5831 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5832 }
5833 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005834 if (newPackage.mExtras != null) {
5835 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5836 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5837 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5838 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005839 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 updatedSettings = true;
5841 }
5842
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005843 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 // Re installation failed. Restore old information
5845 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005846 if (newPackage != null) {
5847 removePackageLI(newPackage, true);
5848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005850 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 // Restore the old system information in Settings
5852 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005853 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005855 mSettings.setInstallerPackageName(packageName,
5856 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 }
5858 mSettings.writeLP();
5859 }
5860 }
5861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005862
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005863 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005864 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005865 int retCode;
5866 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5867 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5868 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005869 if (mNoDexOpt) {
5870 /*
5871 * If we're in an engineering build, programs are lazily run
5872 * through dexopt. If the .dex file doesn't exist yet, it
5873 * will be created when the program is run next.
5874 */
5875 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5876 } else {
5877 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5878 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5879 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005880 }
5881 }
5882 return PackageManager.INSTALL_SUCCEEDED;
5883 }
5884
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005885 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005886 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005887 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 synchronized (mPackages) {
5889 //write settings. the installStatus will be incomplete at this stage.
5890 //note that the new package setting would have already been
5891 //added to mPackages. It hasn't been persisted yet.
5892 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5893 mSettings.writeLP();
5894 }
5895
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005896 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005897 != PackageManager.INSTALL_SUCCEEDED) {
5898 // Discontinue if moving dex files failed.
5899 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005901 if((res.returnCode = setPermissionsLI(newPackage))
5902 != PackageManager.INSTALL_SUCCEEDED) {
5903 if (mInstaller != null) {
5904 mInstaller.rmdex(newPackage.mScanPath);
5905 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005906 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005908 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005911 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005912 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913 res.name = pkgName;
5914 res.uid = newPackage.applicationInfo.uid;
5915 res.pkg = newPackage;
5916 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005917 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005918 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5919 //to update install status
5920 mSettings.writeLP();
5921 }
5922 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005923
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005924 private void installPackageLI(InstallArgs args,
5925 boolean newInstall, PackageInstalledInfo res) {
5926 int pFlags = args.flags;
5927 String installerPackageName = args.installerPackageName;
5928 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005929 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005930 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005931 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005932 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005933 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005934 // Result object to be returned
5935 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5936
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005937 // Retrieve PackageSettings and parse package
5938 int parseFlags = PackageParser.PARSE_CHATTY |
5939 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5940 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5941 parseFlags |= mDefParseFlags;
5942 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5943 pp.setSeparateProcesses(mSeparateProcesses);
5944 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5945 null, mMetrics, parseFlags);
5946 if (pkg == null) {
5947 res.returnCode = pp.getParseError();
5948 return;
5949 }
5950 String pkgName = res.name = pkg.packageName;
5951 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5952 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5953 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5954 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005956 }
5957 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5958 res.returnCode = pp.getParseError();
5959 return;
5960 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005961 // Get rid of all references to package scan path via parser.
5962 pp = null;
5963 String oldCodePath = null;
5964 boolean systemApp = false;
5965 synchronized (mPackages) {
5966 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005967 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5968 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005969 if (pkg.mOriginalPackages != null
5970 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005971 && mPackages.containsKey(oldName)) {
5972 // This package is derived from an original package,
5973 // and this device has been updating from that original
5974 // name. We must continue using the original name, so
5975 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005976 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005977 pkgName = pkg.packageName;
5978 replace = true;
5979 } else if (mPackages.containsKey(pkgName)) {
5980 // This package, under its official name, already exists
5981 // on the device; we should replace it.
5982 replace = true;
5983 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005984 }
5985 PackageSetting ps = mSettings.mPackages.get(pkgName);
5986 if (ps != null) {
5987 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5988 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5989 systemApp = (ps.pkg.applicationInfo.flags &
5990 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005991 }
5992 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005994
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005995 if (systemApp && onSd) {
5996 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005997 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005998 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5999 return;
6000 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08006001
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006002 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
6003 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6004 return;
6005 }
6006 // Set application objects path explicitly after the rename
6007 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07006008 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006009 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08006010 replacePackageLI(pkg, parseFlags, scanMode,
6011 installerPackageName, res);
6012 } else {
6013 installNewPackageLI(pkg, parseFlags, scanMode,
6014 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 }
6016 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006017
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006018 private int setPermissionsLI(PackageParser.Package newPackage) {
6019 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006020 int retCode = 0;
6021 // TODO Gross hack but fix later. Ideally move this to be a post installation
6022 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07006023 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006024 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 try {
6026 extractPublicFiles(newPackage, destResourceFile);
6027 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006028 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 -08006029 " forward-locked app.");
6030 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6031 } finally {
6032 //TODO clean up the extracted public files
6033 }
6034 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006035 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 newPackage.applicationInfo.uid);
6037 } else {
6038 final int filePermissions =
6039 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006040 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 newPackage.applicationInfo.uid);
6042 }
6043 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006044 // The permissions on the resource file was set when it was copied for
6045 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006049 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006050 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006052 // TODO Define new internal error
6053 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 }
6055 return PackageManager.INSTALL_SUCCEEDED;
6056 }
6057
Kenny Root85387d72010-08-26 10:13:11 -07006058 private static boolean isForwardLocked(PackageParser.Package pkg) {
6059 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 }
6061
Kenny Root85387d72010-08-26 10:13:11 -07006062 private static boolean isExternal(PackageParser.Package pkg) {
6063 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
6064 }
6065
6066 private static boolean isSystemApp(PackageParser.Package pkg) {
6067 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6068 }
6069
Kenny Root502e9a42011-01-10 13:48:15 -08006070 private static boolean isSystemApp(ApplicationInfo info) {
6071 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6072 }
6073
Kenny Root85387d72010-08-26 10:13:11 -07006074 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
6075 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006076 }
6077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 private void extractPublicFiles(PackageParser.Package newPackage,
6079 File publicZipFile) throws IOException {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006080 final FileOutputStream fstr = new FileOutputStream(publicZipFile);
6081 final ZipOutputStream publicZipOutStream = new ZipOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6083
6084 // Copy manifest, resources.arsc and res directory to public zip
6085
6086 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6087 while (privateZipEntries.hasMoreElements()) {
6088 final ZipEntry zipEntry = privateZipEntries.nextElement();
6089 final String zipEntryName = zipEntry.getName();
6090 if ("AndroidManifest.xml".equals(zipEntryName)
6091 || "resources.arsc".equals(zipEntryName)
6092 || zipEntryName.startsWith("res/")) {
6093 try {
6094 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6095 } catch (IOException e) {
6096 try {
6097 publicZipOutStream.close();
6098 throw e;
6099 } finally {
6100 publicZipFile.delete();
6101 }
6102 }
6103 }
6104 }
6105
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006106 publicZipOutStream.finish();
6107 publicZipOutStream.flush();
6108 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 publicZipOutStream.close();
6110 FileUtils.setPermissions(
6111 publicZipFile.getAbsolutePath(),
6112 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6113 -1, -1);
6114 }
6115
6116 private static void copyZipEntry(ZipEntry zipEntry,
6117 ZipFile inZipFile,
6118 ZipOutputStream outZipStream) throws IOException {
6119 byte[] buffer = new byte[4096];
6120 int num;
6121
6122 ZipEntry newEntry;
6123 if (zipEntry.getMethod() == ZipEntry.STORED) {
6124 // Preserve the STORED method of the input entry.
6125 newEntry = new ZipEntry(zipEntry);
6126 } else {
6127 // Create a new entry so that the compressed len is recomputed.
6128 newEntry = new ZipEntry(zipEntry.getName());
6129 }
6130 outZipStream.putNextEntry(newEntry);
6131
6132 InputStream data = inZipFile.getInputStream(zipEntry);
6133 while ((num = data.read(buffer)) > 0) {
6134 outZipStream.write(buffer, 0, num);
6135 }
6136 outZipStream.flush();
6137 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 private void deleteTempPackageFiles() {
6140 FilenameFilter filter = new FilenameFilter() {
6141 public boolean accept(File dir, String name) {
6142 return name.startsWith("vmdl") && name.endsWith(".tmp");
6143 }
6144 };
6145 String tmpFilesList[] = mAppInstallDir.list(filter);
6146 if(tmpFilesList == null) {
6147 return;
6148 }
6149 for(int i = 0; i < tmpFilesList.length; i++) {
6150 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6151 tmpFile.delete();
6152 }
6153 }
6154
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006155 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 File tmpPackageFile;
6157 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006158 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006159 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006160 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 return null;
6162 }
6163 try {
6164 FileUtils.setPermissions(
6165 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6166 -1, -1);
6167 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006168 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 return null;
6170 }
6171 return tmpPackageFile;
6172 }
6173
6174 public void deletePackage(final String packageName,
6175 final IPackageDeleteObserver observer,
6176 final int flags) {
6177 mContext.enforceCallingOrSelfPermission(
6178 android.Manifest.permission.DELETE_PACKAGES, null);
6179 // Queue up an async operation since the package deletion may take a little while.
6180 mHandler.post(new Runnable() {
6181 public void run() {
6182 mHandler.removeCallbacks(this);
6183 final boolean succeded = deletePackageX(packageName, true, true, flags);
6184 if (observer != null) {
6185 try {
6186 observer.packageDeleted(succeded);
6187 } catch (RemoteException e) {
6188 Log.i(TAG, "Observer no longer exists.");
6189 } //end catch
6190 } //end if
6191 } //end run
6192 });
6193 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 /**
6196 * This method is an internal method that could be get invoked either
6197 * to delete an installed package or to clean up a failed installation.
6198 * After deleting an installed package, a broadcast is sent to notify any
6199 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006200 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 * installation wouldn't have sent the initial broadcast either
6202 * The key steps in deleting a package are
6203 * deleting the package information in internal structures like mPackages,
6204 * deleting the packages base directories through installd
6205 * updating mSettings to reflect current status
6206 * persisting settings for later use
6207 * sending a broadcast if necessary
6208 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6210 boolean deleteCodeAndResources, int flags) {
6211 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006212 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006214 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6215 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6216 try {
6217 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006218 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006219 return false;
6220 }
6221 } catch (RemoteException e) {
6222 }
6223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006225 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006226 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006230 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006231 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006232
6233 // If the removed package was a system update, the old system packaged
6234 // was re-enabled; we need to broadcast this information
6235 if (systemUpdate) {
6236 Bundle extras = new Bundle(1);
6237 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6238 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6239
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006240 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6241 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006244 // Force a gc here.
6245 Runtime.getRuntime().gc();
6246 // Delete the resources here after sending the broadcast to let
6247 // other processes clean up before deleting resources.
6248 if (info.args != null) {
6249 synchronized (mInstallLock) {
6250 info.args.doPostDeleteLI(deleteCodeAndResources);
6251 }
6252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 return res;
6254 }
6255
6256 static class PackageRemovedInfo {
6257 String removedPackage;
6258 int uid = -1;
6259 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006260 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006261 // Clean up resources deleted packages.
6262 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006263
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006264 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 Bundle extras = new Bundle(1);
6266 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6267 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6268 if (replacing) {
6269 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6270 }
6271 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006272 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 }
6274 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006275 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 }
6277 }
6278 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 /*
6281 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6282 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006283 * 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 -08006284 * delete a partially installed application.
6285 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006286 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006287 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006289 if (outInfo != null) {
6290 outInfo.removedPackage = packageName;
6291 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006292 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293 // Retrieve object to delete permissions for shared user later on
6294 PackageSetting deletedPs;
6295 synchronized (mPackages) {
6296 deletedPs = mSettings.mPackages.get(packageName);
6297 }
6298 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Jason parksa3cdaa52011-01-13 14:15:43 -06006299 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06006301 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006303 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 + packageName + ", retcode=" + retCode);
6305 // we don't consider this to be a failure of the core package deletion
6306 }
6307 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006308 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 PackageParser.Package pkg = mPackages.get(packageName);
6310 File dataDir = new File(pkg.applicationInfo.dataDir);
6311 dataDir.delete();
6312 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006313 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 }
6315 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006316 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006317 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6318 if (outInfo != null) {
6319 outInfo.removedUid = mSettings.removePackageLP(packageName);
6320 }
6321 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006322 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006323 if (deletedPs.sharedUser != null) {
6324 // remove permissions associated with package
6325 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6326 }
6327 }
6328 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006329 // remove from preferred activities.
6330 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6331 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6332 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6333 removed.add(pa);
6334 }
6335 }
6336 for (PreferredActivity pa : removed) {
6337 mSettings.mPreferredActivities.removeFilter(pa);
6338 }
6339 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006340 if (writeSettings) {
6341 // Save settings now
6342 mSettings.writeLP();
6343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 }
6345 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 /*
6348 * Tries to delete system package.
6349 */
6350 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006351 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 ApplicationInfo applicationInfo = p.applicationInfo;
6353 //applicable for non-partially installed applications only
6354 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006355 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 return false;
6357 }
6358 PackageSetting ps = null;
6359 // Confirm if the system package has been updated
6360 // An updated system app can be deleted. This will also have to restore
6361 // the system pkg from system partition
6362 synchronized (mPackages) {
6363 ps = mSettings.getDisabledSystemPkg(p.packageName);
6364 }
6365 if (ps == null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006366 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 return false;
6368 } else {
6369 Log.i(TAG, "Deleting system pkg from data partition");
6370 }
6371 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006372 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006373 if (ps.versionCode < p.mVersionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006374 // Delete data for downgrades
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006375 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006376 } else {
6377 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006378 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006379 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006380 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006381 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 if (!ret) {
6383 return false;
6384 }
6385 synchronized (mPackages) {
6386 // Reinstate the old system package
6387 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006388 // Remove any native libraries from the upgraded package.
6389 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 }
6391 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006392 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006394 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006397 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 return false;
6399 }
6400 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006401 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006402 if (writeSettings) {
6403 mSettings.writeLP();
6404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 }
6406 return true;
6407 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006410 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6411 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 ApplicationInfo applicationInfo = p.applicationInfo;
6413 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006414 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 return false;
6416 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006417 if (outInfo != null) {
6418 outInfo.uid = applicationInfo.uid;
6419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420
6421 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006422 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423
6424 // Delete application code and resources
6425 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006426 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006427 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6428 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6429 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6430 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 }
6432 return true;
6433 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006435 /*
6436 * This method handles package deletion in general
6437 */
6438 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006439 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6440 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006442 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 return false;
6444 }
6445 PackageParser.Package p;
6446 boolean dataOnly = false;
6447 synchronized (mPackages) {
6448 p = mPackages.get(packageName);
6449 if (p == null) {
6450 //this retrieves partially installed apps
6451 dataOnly = true;
6452 PackageSetting ps = mSettings.mPackages.get(packageName);
6453 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006454 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 return false;
6456 }
6457 p = ps.pkg;
6458 }
6459 }
6460 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006461 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 return false;
6463 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006465 if (dataOnly) {
6466 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006467 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 return true;
6469 }
6470 // At this point the package should have ApplicationInfo associated with it
6471 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006472 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 return false;
6474 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006475 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006476 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 Log.i(TAG, "Removing system package:"+p.packageName);
6478 // When an updated system application is deleted we delete the existing resources as well and
6479 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006480 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006481 } else {
6482 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006483 // Kill application pre-emptively especially for apps on sd.
6484 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006485 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6486 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006488 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 public void clearApplicationUserData(final String packageName,
6492 final IPackageDataObserver observer) {
6493 mContext.enforceCallingOrSelfPermission(
6494 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6495 // Queue up an async operation since the package deletion may take a little while.
6496 mHandler.post(new Runnable() {
6497 public void run() {
6498 mHandler.removeCallbacks(this);
6499 final boolean succeeded;
6500 synchronized (mInstallLock) {
6501 succeeded = clearApplicationUserDataLI(packageName);
6502 }
6503 if (succeeded) {
6504 // invoke DeviceStorageMonitor's update method to clear any notifications
6505 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6506 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6507 if (dsm != null) {
6508 dsm.updateMemory();
6509 }
6510 }
6511 if(observer != null) {
6512 try {
6513 observer.onRemoveCompleted(packageName, succeeded);
6514 } catch (RemoteException e) {
6515 Log.i(TAG, "Observer no longer exists.");
6516 }
6517 } //end if observer
6518 } //end run
6519 });
6520 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 private boolean clearApplicationUserDataLI(String packageName) {
6523 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006524 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 return false;
6526 }
6527 PackageParser.Package p;
6528 boolean dataOnly = false;
6529 synchronized (mPackages) {
6530 p = mPackages.get(packageName);
6531 if(p == null) {
6532 dataOnly = true;
6533 PackageSetting ps = mSettings.mPackages.get(packageName);
6534 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006535 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 return false;
6537 }
6538 p = ps.pkg;
6539 }
6540 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006541 boolean useEncryptedFSDir = false;
6542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 if(!dataOnly) {
6544 //need to check this only for fully installed applications
6545 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006546 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006547 return false;
6548 }
6549 final ApplicationInfo applicationInfo = p.applicationInfo;
6550 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006551 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 return false;
6553 }
Jason parksa3cdaa52011-01-13 14:15:43 -06006554 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006555 }
6556 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06006557 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006558 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006559 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 + packageName);
6561 return false;
6562 }
6563 }
6564 return true;
6565 }
6566
6567 public void deleteApplicationCacheFiles(final String packageName,
6568 final IPackageDataObserver observer) {
6569 mContext.enforceCallingOrSelfPermission(
6570 android.Manifest.permission.DELETE_CACHE_FILES, null);
6571 // Queue up an async operation since the package deletion may take a little while.
6572 mHandler.post(new Runnable() {
6573 public void run() {
6574 mHandler.removeCallbacks(this);
6575 final boolean succeded;
6576 synchronized (mInstallLock) {
6577 succeded = deleteApplicationCacheFilesLI(packageName);
6578 }
6579 if(observer != null) {
6580 try {
6581 observer.onRemoveCompleted(packageName, succeded);
6582 } catch (RemoteException e) {
6583 Log.i(TAG, "Observer no longer exists.");
6584 }
6585 } //end if observer
6586 } //end run
6587 });
6588 }
6589
6590 private boolean deleteApplicationCacheFilesLI(String packageName) {
6591 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006592 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593 return false;
6594 }
6595 PackageParser.Package p;
6596 synchronized (mPackages) {
6597 p = mPackages.get(packageName);
6598 }
6599 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006600 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 return false;
6602 }
6603 final ApplicationInfo applicationInfo = p.applicationInfo;
6604 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006605 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 return false;
6607 }
Jason parksa3cdaa52011-01-13 14:15:43 -06006608 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06006610 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006612 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 + packageName);
6614 return false;
6615 }
6616 }
6617 return true;
6618 }
6619
6620 public void getPackageSizeInfo(final String packageName,
6621 final IPackageStatsObserver observer) {
6622 mContext.enforceCallingOrSelfPermission(
6623 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6624 // Queue up an async operation since the package deletion may take a little while.
6625 mHandler.post(new Runnable() {
6626 public void run() {
6627 mHandler.removeCallbacks(this);
6628 PackageStats lStats = new PackageStats(packageName);
6629 final boolean succeded;
6630 synchronized (mInstallLock) {
6631 succeded = getPackageSizeInfoLI(packageName, lStats);
6632 }
6633 if(observer != null) {
6634 try {
6635 observer.onGetStatsCompleted(lStats, succeded);
6636 } catch (RemoteException e) {
6637 Log.i(TAG, "Observer no longer exists.");
6638 }
6639 } //end if observer
6640 } //end run
6641 });
6642 }
6643
6644 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6645 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006646 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 return false;
6648 }
6649 PackageParser.Package p;
6650 boolean dataOnly = false;
6651 synchronized (mPackages) {
6652 p = mPackages.get(packageName);
6653 if(p == null) {
6654 dataOnly = true;
6655 PackageSetting ps = mSettings.mPackages.get(packageName);
6656 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006657 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 return false;
6659 }
6660 p = ps.pkg;
6661 }
6662 }
6663 String publicSrcDir = null;
6664 if(!dataOnly) {
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 }
6670 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6671 }
Jason parksa3cdaa52011-01-13 14:15:43 -06006672 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 if (mInstaller != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06006674 int res = mInstaller.getSizeInfo(packageName, p.mPath,
6675 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 if (res < 0) {
6677 return false;
6678 } else {
6679 return true;
6680 }
6681 }
6682 return true;
6683 }
6684
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006686 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006687 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 }
6689
6690 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006691 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 }
6693
6694 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006695 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 }
6697
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006698 int getUidTargetSdkVersionLockedLP(int uid) {
6699 Object obj = mSettings.getUserIdLP(uid);
6700 if (obj instanceof SharedUserSetting) {
6701 SharedUserSetting sus = (SharedUserSetting)obj;
6702 final int N = sus.packages.size();
6703 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6704 Iterator<PackageSetting> it = sus.packages.iterator();
6705 int i=0;
6706 while (it.hasNext()) {
6707 PackageSetting ps = it.next();
6708 if (ps.pkg != null) {
6709 int v = ps.pkg.applicationInfo.targetSdkVersion;
6710 if (v < vers) vers = v;
6711 }
6712 }
6713 return vers;
6714 } else if (obj instanceof PackageSetting) {
6715 PackageSetting ps = (PackageSetting)obj;
6716 if (ps.pkg != null) {
6717 return ps.pkg.applicationInfo.targetSdkVersion;
6718 }
6719 }
6720 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6721 }
6722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 public void addPreferredActivity(IntentFilter filter, int match,
6724 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006726 if (mContext.checkCallingOrSelfPermission(
6727 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6728 != PackageManager.PERMISSION_GRANTED) {
6729 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6730 < Build.VERSION_CODES.FROYO) {
6731 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6732 + Binder.getCallingUid());
6733 return;
6734 }
6735 mContext.enforceCallingOrSelfPermission(
6736 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6737 }
6738
6739 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6741 mSettings.mPreferredActivities.addFilter(
6742 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006743 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006744 }
6745 }
6746
Satish Sampath8dbe6122009-06-02 23:35:54 +01006747 public void replacePreferredActivity(IntentFilter filter, int match,
6748 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006749 if (filter.countActions() != 1) {
6750 throw new IllegalArgumentException(
6751 "replacePreferredActivity expects filter to have only 1 action.");
6752 }
6753 if (filter.countCategories() != 1) {
6754 throw new IllegalArgumentException(
6755 "replacePreferredActivity expects filter to have only 1 category.");
6756 }
6757 if (filter.countDataAuthorities() != 0
6758 || filter.countDataPaths() != 0
6759 || filter.countDataSchemes() != 0
6760 || filter.countDataTypes() != 0) {
6761 throw new IllegalArgumentException(
6762 "replacePreferredActivity expects filter to have no data authorities, " +
6763 "paths, schemes or types.");
6764 }
6765 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006766 if (mContext.checkCallingOrSelfPermission(
6767 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6768 != PackageManager.PERMISSION_GRANTED) {
6769 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6770 < Build.VERSION_CODES.FROYO) {
6771 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6772 + Binder.getCallingUid());
6773 return;
6774 }
6775 mContext.enforceCallingOrSelfPermission(
6776 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6777 }
6778
Satish Sampath8dbe6122009-06-02 23:35:54 +01006779 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6780 String action = filter.getAction(0);
6781 String category = filter.getCategory(0);
6782 while (it.hasNext()) {
6783 PreferredActivity pa = it.next();
6784 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6785 it.remove();
6786 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6787 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6788 }
6789 }
6790 addPreferredActivity(filter, match, set, activity);
6791 }
6792 }
6793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006795 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006796 int uid = Binder.getCallingUid();
6797 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006798 if (pkg == null || pkg.applicationInfo.uid != uid) {
6799 if (mContext.checkCallingOrSelfPermission(
6800 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6801 != PackageManager.PERMISSION_GRANTED) {
6802 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6803 < Build.VERSION_CODES.FROYO) {
6804 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6805 + Binder.getCallingUid());
6806 return;
6807 }
6808 mContext.enforceCallingOrSelfPermission(
6809 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6810 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006811 }
6812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006814 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 }
6816 }
6817 }
6818
6819 boolean clearPackagePreferredActivitiesLP(String packageName) {
6820 boolean changed = false;
6821 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6822 while (it.hasNext()) {
6823 PreferredActivity pa = it.next();
6824 if (pa.mActivity.getPackageName().equals(packageName)) {
6825 it.remove();
6826 changed = true;
6827 }
6828 }
6829 return changed;
6830 }
6831
6832 public int getPreferredActivities(List<IntentFilter> outFilters,
6833 List<ComponentName> outActivities, String packageName) {
6834
6835 int num = 0;
6836 synchronized (mPackages) {
6837 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6838 while (it.hasNext()) {
6839 PreferredActivity pa = it.next();
6840 if (packageName == null
6841 || pa.mActivity.getPackageName().equals(packageName)) {
6842 if (outFilters != null) {
6843 outFilters.add(new IntentFilter(pa));
6844 }
6845 if (outActivities != null) {
6846 outActivities.add(pa.mActivity);
6847 }
6848 }
6849 }
6850 }
6851
6852 return num;
6853 }
6854
6855 public void setApplicationEnabledSetting(String appPackageName,
6856 int newState, int flags) {
6857 setEnabledSetting(appPackageName, null, newState, flags);
6858 }
6859
6860 public void setComponentEnabledSetting(ComponentName componentName,
6861 int newState, int flags) {
6862 setEnabledSetting(componentName.getPackageName(),
6863 componentName.getClassName(), newState, flags);
6864 }
6865
6866 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006867 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6869 || newState == COMPONENT_ENABLED_STATE_ENABLED
6870 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6871 throw new IllegalArgumentException("Invalid new component state: "
6872 + newState);
6873 }
6874 PackageSetting pkgSetting;
6875 final int uid = Binder.getCallingUid();
6876 final int permission = mContext.checkCallingPermission(
6877 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6878 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006879 boolean sendNow = false;
6880 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006881 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006883 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006884 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006885 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006887 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006888 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006889 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006890 }
6891 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006892 "Unknown component: " + packageName
6893 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006894 }
6895 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6896 throw new SecurityException(
6897 "Permission Denial: attempt to change component state from pid="
6898 + Binder.getCallingPid()
6899 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6900 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006901 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006902 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006903 if (pkgSetting.enabled == newState) {
6904 // Nothing to do
6905 return;
6906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006907 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006908 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 } else {
6910 // We're dealing with a component level state change
6911 switch (newState) {
6912 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006913 if (!pkgSetting.enableComponentLP(className)) {
6914 return;
6915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006916 break;
6917 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006918 if (!pkgSetting.disableComponentLP(className)) {
6919 return;
6920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006921 break;
6922 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006923 if (!pkgSetting.restoreComponentLP(className)) {
6924 return;
6925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 break;
6927 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006928 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006929 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006930 }
6931 }
6932 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006933 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006934 components = mPendingBroadcasts.get(packageName);
6935 boolean newPackage = components == null;
6936 if (newPackage) {
6937 components = new ArrayList<String>();
6938 }
6939 if (!components.contains(componentName)) {
6940 components.add(componentName);
6941 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006942 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6943 sendNow = true;
6944 // Purge entry from pending broadcast list if another one exists already
6945 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006946 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006947 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006948 if (newPackage) {
6949 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006950 }
6951 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6952 // Schedule a message
6953 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6954 }
6955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 long callingId = Binder.clearCallingIdentity();
6959 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006960 if (sendNow) {
6961 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006962 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006964 } finally {
6965 Binder.restoreCallingIdentity(callingId);
6966 }
6967 }
6968
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006969 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006970 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6971 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6972 + " components=" + componentNames);
6973 Bundle extras = new Bundle(4);
6974 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6975 String nameList[] = new String[componentNames.size()];
6976 componentNames.toArray(nameList);
6977 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006978 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6979 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006980 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006981 }
6982
Jacek Surazski65e13172009-04-28 15:26:38 +02006983 public String getInstallerPackageName(String packageName) {
6984 synchronized (mPackages) {
6985 PackageSetting pkg = mSettings.mPackages.get(packageName);
6986 if (pkg == null) {
6987 throw new IllegalArgumentException("Unknown package: " + packageName);
6988 }
6989 return pkg.installerPackageName;
6990 }
6991 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006993 public int getApplicationEnabledSetting(String appPackageName) {
6994 synchronized (mPackages) {
6995 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6996 if (pkg == null) {
6997 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6998 }
6999 return pkg.enabled;
7000 }
7001 }
7002
7003 public int getComponentEnabledSetting(ComponentName componentName) {
7004 synchronized (mPackages) {
7005 final String packageNameStr = componentName.getPackageName();
7006 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
7007 if (pkg == null) {
7008 throw new IllegalArgumentException("Unknown component: " + componentName);
7009 }
7010 final String classNameStr = componentName.getClassName();
7011 return pkg.currentEnabledStateLP(classNameStr);
7012 }
7013 }
7014
7015 public void enterSafeMode() {
7016 if (!mSystemReady) {
7017 mSafeMode = true;
7018 }
7019 }
7020
7021 public void systemReady() {
7022 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007023
7024 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007025 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007026 mContext.getContentResolver(),
7027 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007028 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007029 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007030 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032 }
7033
7034 public boolean isSafeMode() {
7035 return mSafeMode;
7036 }
7037
7038 public boolean hasSystemUidErrors() {
7039 return mHasSystemUidErrors;
7040 }
7041
7042 static String arrayToString(int[] array) {
7043 StringBuffer buf = new StringBuffer(128);
7044 buf.append('[');
7045 if (array != null) {
7046 for (int i=0; i<array.length; i++) {
7047 if (i > 0) buf.append(", ");
7048 buf.append(array[i]);
7049 }
7050 }
7051 buf.append(']');
7052 return buf.toString();
7053 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 @Override
7056 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7057 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7058 != PackageManager.PERMISSION_GRANTED) {
7059 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7060 + Binder.getCallingPid()
7061 + ", uid=" + Binder.getCallingUid()
7062 + " without permission "
7063 + android.Manifest.permission.DUMP);
7064 return;
7065 }
7066
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007067 boolean dumpStar = true;
7068 boolean dumpLibs = false;
7069 boolean dumpFeatures = false;
7070 boolean dumpResolvers = false;
7071 boolean dumpPermissions = false;
7072 boolean dumpPackages = false;
7073 boolean dumpSharedUsers = false;
7074 boolean dumpMessages = false;
7075 boolean dumpProviders = false;
7076
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007077 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007078 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007079
7080 int opti = 0;
7081 while (opti < args.length) {
7082 String opt = args[opti];
7083 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7084 break;
7085 }
7086 opti++;
7087 if ("-a".equals(opt)) {
7088 // Right now we only know how to print all.
7089 } else if ("-h".equals(opt)) {
7090 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007091 pw.println(" [-h] [-f] [cmd] ...");
7092 pw.println(" -f: print details of intent filters");
7093 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007094 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007095 pw.println(" l[ibraries]: list known shared libraries");
7096 pw.println(" f[ibraries]: list device features");
7097 pw.println(" r[esolvers]: dump intent resolvers");
7098 pw.println(" perm[issions]: dump permissions");
7099 pw.println(" prov[iders]: dump content providers");
7100 pw.println(" p[ackages]: dump installed packages");
7101 pw.println(" s[hared-users]: dump shared user IDs");
7102 pw.println(" m[essages]: print collected runtime messages");
7103 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007104 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007105 } else if ("-f".equals(opt)) {
7106 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007107 } else {
7108 pw.println("Unknown argument: " + opt + "; use -h for help");
7109 }
7110 }
7111
7112 // Is the caller requesting to dump a particular piece of data?
7113 if (opti < args.length) {
7114 String cmd = args[opti];
7115 opti++;
7116 // Is this a package name?
7117 if ("android".equals(cmd) || cmd.contains(".")) {
7118 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007119 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
7120 dumpStar = false;
7121 dumpLibs = true;
7122 } else if ("f".equals(cmd) || "features".equals(cmd)) {
7123 dumpStar = false;
7124 dumpFeatures = true;
7125 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
7126 dumpStar = false;
7127 dumpResolvers = true;
7128 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
7129 dumpStar = false;
7130 dumpPermissions = true;
7131 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
7132 dumpStar = false;
7133 dumpPackages = true;
7134 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
7135 dumpStar = false;
7136 dumpSharedUsers = true;
7137 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
7138 dumpStar = false;
7139 dumpProviders = true;
7140 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
7141 dumpStar = false;
7142 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007143 }
7144 }
7145
7146 boolean printedTitle = false;
7147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007149 if ((dumpStar || dumpLibs) && packageName == null) {
7150 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007151 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007152 pw.println("Libraries:");
7153 Iterator<String> it = mSharedLibraries.keySet().iterator();
7154 while (it.hasNext()) {
7155 String name = it.next();
7156 pw.print(" ");
7157 pw.print(name);
7158 pw.print(" -> ");
7159 pw.println(mSharedLibraries.get(name));
7160 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007161 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007162
7163 if ((dumpStar || dumpFeatures) && packageName == null) {
7164 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007165 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007166 pw.println("Features:");
7167 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7168 while (it.hasNext()) {
7169 String name = it.next();
7170 pw.print(" ");
7171 pw.println(name);
7172 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007173 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007174
7175 if (dumpStar || dumpResolvers) {
7176 if (mActivities.dump(pw, printedTitle
7177 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7178 " ", packageName, showFilters)) {
7179 printedTitle = true;
7180 }
7181 if (mReceivers.dump(pw, printedTitle
7182 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7183 " ", packageName, showFilters)) {
7184 printedTitle = true;
7185 }
7186 if (mServices.dump(pw, printedTitle
7187 ? "\nService Resolver Table:" : "Service Resolver Table:",
7188 " ", packageName, showFilters)) {
7189 printedTitle = true;
7190 }
7191 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7192 ? "\nPreferred Activities:" : "Preferred Activities:",
7193 " ", packageName, showFilters)) {
7194 printedTitle = true;
7195 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007196 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007197
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007198 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007199 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007201 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7202 continue;
7203 }
7204 if (!printedSomething) {
7205 if (printedTitle) pw.println(" ");
7206 pw.println("Permissions:");
7207 printedSomething = true;
7208 printedTitle = true;
7209 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007210 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7211 pw.print(Integer.toHexString(System.identityHashCode(p)));
7212 pw.println("):");
7213 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7214 pw.print(" uid="); pw.print(p.uid);
7215 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007216 pw.print(" type="); pw.print(p.type);
7217 pw.print(" prot="); pw.println(p.protectionLevel);
7218 if (p.packageSetting != null) {
7219 pw.print(" packageSetting="); pw.println(p.packageSetting);
7220 }
7221 if (p.perm != null) {
7222 pw.print(" perm="); pw.println(p.perm);
7223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 }
7225 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007226
7227 if (dumpStar || dumpProviders) {
7228 printedSomething = false;
7229 for (PackageParser.Provider p : mProviders.values()) {
7230 if (packageName != null && !packageName.equals(p.info.packageName)) {
7231 continue;
7232 }
7233 if (!printedSomething) {
7234 if (printedTitle) pw.println(" ");
7235 pw.println("Registered ContentProviders:");
7236 printedSomething = true;
7237 printedTitle = true;
7238 }
7239 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7240 pw.println(p.toString());
7241 }
7242 }
7243
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007244 printedSomething = false;
7245 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007246 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007247 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7248 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007250 if (packageName != null && !packageName.equals(ps.realName)
7251 && !packageName.equals(ps.name)) {
7252 continue;
7253 }
7254 if (!printedSomething) {
7255 if (printedTitle) pw.println(" ");
7256 pw.println("Packages:");
7257 printedSomething = true;
7258 printedTitle = true;
7259 }
7260 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007261 pw.print(" Package [");
7262 pw.print(ps.realName != null ? ps.realName : ps.name);
7263 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007264 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7265 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007266 if (ps.realName != null) {
7267 pw.print(" compat name="); pw.println(ps.name);
7268 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007269 pw.print(" userId="); pw.print(ps.userId);
7270 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7271 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7272 pw.print(" pkg="); pw.println(ps.pkg);
7273 pw.print(" codePath="); pw.println(ps.codePathString);
7274 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007275 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root5d40fe92011-01-14 10:54:46 -08007276 pw.print(" obbPaths="); pw.println(Arrays.toString(ps.obbPathStrings));
Kenny Root1174f712010-10-22 10:07:11 -07007277 pw.print(" versionCode="); pw.println(ps.versionCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007278 if (ps.pkg != null) {
Kenny Root1174f712010-10-22 10:07:11 -07007279 pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007280 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007281 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007282 if (ps.pkg.mOperationPending) {
7283 pw.println(" mOperationPending=true");
7284 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007285 pw.print(" supportsScreens=[");
7286 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007287 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007288 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7289 if (!first) pw.print(", ");
7290 first = false;
7291 pw.print("small");
7292 }
7293 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007294 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007295 if (!first) pw.print(", ");
7296 first = false;
7297 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007298 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007299 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007300 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007301 if (!first) pw.print(", ");
7302 first = false;
7303 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007304 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007305 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007306 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007307 if (!first) pw.print(", ");
7308 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007309 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007310 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007311 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007312 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007313 if (!first) pw.print(", ");
7314 first = false;
7315 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007316 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007317 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007318 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7319 if (!first) pw.print(", ");
7320 first = false;
7321 pw.print("anyDensity");
7322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007323 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007324 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007325 pw.print(" timeStamp=");
7326 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7327 pw.print(" firstInstallTime=");
7328 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7329 pw.print(" lastUpdateTime=");
7330 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007331 pw.print(" signatures="); pw.println(ps.signatures);
7332 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007333 pw.print(" haveGids="); pw.println(ps.haveGids);
7334 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007335 pw.print(" installStatus="); pw.print(ps.installStatus);
7336 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 if (ps.disabledComponents.size() > 0) {
7338 pw.println(" disabledComponents:");
7339 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007340 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007341 }
7342 }
7343 if (ps.enabledComponents.size() > 0) {
7344 pw.println(" enabledComponents:");
7345 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007346 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007347 }
7348 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007349 if (ps.grantedPermissions.size() > 0) {
7350 pw.println(" grantedPermissions:");
7351 for (String s : ps.grantedPermissions) {
7352 pw.print(" "); pw.println(s);
7353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007355 }
7356 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007357 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007358 if (dumpStar || dumpPackages) {
7359 if (mSettings.mRenamedPackages.size() > 0) {
7360 for (HashMap.Entry<String, String> e
7361 : mSettings.mRenamedPackages.entrySet()) {
7362 if (packageName != null && !packageName.equals(e.getKey())
7363 && !packageName.equals(e.getValue())) {
7364 continue;
7365 }
7366 if (!printedSomething) {
7367 if (printedTitle) pw.println(" ");
7368 pw.println("Renamed packages:");
7369 printedSomething = true;
7370 printedTitle = true;
7371 }
7372 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7373 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007374 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007375 }
7376 printedSomething = false;
7377 if (mSettings.mDisabledSysPackages.size() > 0) {
7378 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7379 if (packageName != null && !packageName.equals(ps.realName)
7380 && !packageName.equals(ps.name)) {
7381 continue;
7382 }
7383 if (!printedSomething) {
7384 if (printedTitle) pw.println(" ");
7385 pw.println("Hidden system packages:");
7386 printedSomething = true;
7387 printedTitle = true;
7388 }
7389 pw.print(" Package [");
7390 pw.print(ps.realName != null ? ps.realName : ps.name);
7391 pw.print("] (");
7392 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7393 pw.println("):");
7394 if (ps.realName != null) {
7395 pw.print(" compat name="); pw.println(ps.name);
7396 }
7397 pw.print(" userId="); pw.println(ps.userId);
7398 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7399 pw.print(" codePath="); pw.println(ps.codePathString);
7400 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007401 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007402 }
7403 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007404 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007405 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007407 if (packageName != null && su != packageSharedUser) {
7408 continue;
7409 }
7410 if (!printedSomething) {
7411 if (printedTitle) pw.println(" ");
7412 pw.println("Shared users:");
7413 printedSomething = true;
7414 printedTitle = true;
7415 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007416 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7417 pw.print(Integer.toHexString(System.identityHashCode(su)));
7418 pw.println("):");
7419 pw.print(" userId="); pw.print(su.userId);
7420 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 pw.println(" grantedPermissions:");
7422 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007423 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007425 }
7426 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007427
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007428 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007429 if (printedTitle) pw.println(" ");
7430 printedTitle = true;
7431 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007432 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007433
7434 pw.println(" ");
7435 pw.println("Package warning messages:");
7436 File fname = getSettingsProblemFile();
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08007437 FileInputStream in = null;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007438 try {
7439 in = new FileInputStream(fname);
7440 int avail = in.available();
7441 byte[] data = new byte[avail];
7442 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007443 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007444 } catch (FileNotFoundException e) {
7445 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08007446 } finally {
7447 if (in != null) {
7448 try {
7449 in.close();
7450 } catch (IOException e) {
7451 }
7452 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007453 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007455 }
7456 }
7457
7458 static final class BasePermission {
7459 final static int TYPE_NORMAL = 0;
7460 final static int TYPE_BUILTIN = 1;
7461 final static int TYPE_DYNAMIC = 2;
7462
7463 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007464 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007465 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007466 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007467 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007468 PackageParser.Permission perm;
7469 PermissionInfo pendingInfo;
7470 int uid;
7471 int[] gids;
7472
7473 BasePermission(String _name, String _sourcePackage, int _type) {
7474 name = _name;
7475 sourcePackage = _sourcePackage;
7476 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007477 // Default to most conservative protection level.
7478 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7479 }
7480
7481 public String toString() {
7482 return "BasePermission{"
7483 + Integer.toHexString(System.identityHashCode(this))
7484 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007485 }
7486 }
7487
7488 static class PackageSignatures {
7489 private Signature[] mSignatures;
7490
Kenny Root291e78c2011-01-13 14:53:17 -08007491 PackageSignatures(PackageSignatures orig) {
7492 mSignatures = orig.mSignatures.clone();
7493 }
7494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007495 PackageSignatures(Signature[] sigs) {
7496 assignSignatures(sigs);
7497 }
7498
7499 PackageSignatures() {
7500 }
7501
7502 void writeXml(XmlSerializer serializer, String tagName,
7503 ArrayList<Signature> pastSignatures) throws IOException {
7504 if (mSignatures == null) {
7505 return;
7506 }
7507 serializer.startTag(null, tagName);
7508 serializer.attribute(null, "count",
7509 Integer.toString(mSignatures.length));
7510 for (int i=0; i<mSignatures.length; i++) {
7511 serializer.startTag(null, "cert");
7512 final Signature sig = mSignatures[i];
7513 final int sigHash = sig.hashCode();
7514 final int numPast = pastSignatures.size();
7515 int j;
7516 for (j=0; j<numPast; j++) {
7517 Signature pastSig = pastSignatures.get(j);
7518 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7519 serializer.attribute(null, "index", Integer.toString(j));
7520 break;
7521 }
7522 }
7523 if (j >= numPast) {
7524 pastSignatures.add(sig);
7525 serializer.attribute(null, "index", Integer.toString(numPast));
7526 serializer.attribute(null, "key", sig.toCharsString());
7527 }
7528 serializer.endTag(null, "cert");
7529 }
7530 serializer.endTag(null, tagName);
7531 }
7532
7533 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7534 throws IOException, XmlPullParserException {
7535 String countStr = parser.getAttributeValue(null, "count");
7536 if (countStr == null) {
7537 reportSettingsProblem(Log.WARN,
7538 "Error in package manager settings: <signatures> has"
7539 + " no count at " + parser.getPositionDescription());
7540 XmlUtils.skipCurrentTag(parser);
7541 }
7542 final int count = Integer.parseInt(countStr);
7543 mSignatures = new Signature[count];
7544 int pos = 0;
7545
7546 int outerDepth = parser.getDepth();
7547 int type;
7548 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7549 && (type != XmlPullParser.END_TAG
7550 || parser.getDepth() > outerDepth)) {
7551 if (type == XmlPullParser.END_TAG
7552 || type == XmlPullParser.TEXT) {
7553 continue;
7554 }
7555
7556 String tagName = parser.getName();
7557 if (tagName.equals("cert")) {
7558 if (pos < count) {
7559 String index = parser.getAttributeValue(null, "index");
7560 if (index != null) {
7561 try {
7562 int idx = Integer.parseInt(index);
7563 String key = parser.getAttributeValue(null, "key");
7564 if (key == null) {
7565 if (idx >= 0 && idx < pastSignatures.size()) {
7566 Signature sig = pastSignatures.get(idx);
7567 if (sig != null) {
7568 mSignatures[pos] = pastSignatures.get(idx);
7569 pos++;
7570 } else {
7571 reportSettingsProblem(Log.WARN,
7572 "Error in package manager settings: <cert> "
7573 + "index " + index + " is not defined at "
7574 + parser.getPositionDescription());
7575 }
7576 } else {
7577 reportSettingsProblem(Log.WARN,
7578 "Error in package manager settings: <cert> "
7579 + "index " + index + " is out of bounds at "
7580 + parser.getPositionDescription());
7581 }
7582 } else {
7583 while (pastSignatures.size() <= idx) {
7584 pastSignatures.add(null);
7585 }
7586 Signature sig = new Signature(key);
7587 pastSignatures.set(idx, sig);
7588 mSignatures[pos] = sig;
7589 pos++;
7590 }
7591 } catch (NumberFormatException e) {
7592 reportSettingsProblem(Log.WARN,
7593 "Error in package manager settings: <cert> "
7594 + "index " + index + " is not a number at "
7595 + parser.getPositionDescription());
7596 }
7597 } else {
7598 reportSettingsProblem(Log.WARN,
7599 "Error in package manager settings: <cert> has"
7600 + " no index at " + parser.getPositionDescription());
7601 }
7602 } else {
7603 reportSettingsProblem(Log.WARN,
7604 "Error in package manager settings: too "
7605 + "many <cert> tags, expected " + count
7606 + " at " + parser.getPositionDescription());
7607 }
7608 } else {
7609 reportSettingsProblem(Log.WARN,
7610 "Unknown element under <cert>: "
7611 + parser.getName());
7612 }
7613 XmlUtils.skipCurrentTag(parser);
7614 }
7615
7616 if (pos < count) {
7617 // Should never happen -- there is an error in the written
7618 // settings -- but if it does we don't want to generate
7619 // a bad array.
7620 Signature[] newSigs = new Signature[pos];
7621 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7622 mSignatures = newSigs;
7623 }
7624 }
7625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007626 private void assignSignatures(Signature[] sigs) {
7627 if (sigs == null) {
7628 mSignatures = null;
7629 return;
7630 }
7631 mSignatures = new Signature[sigs.length];
7632 for (int i=0; i<sigs.length; i++) {
7633 mSignatures[i] = sigs[i];
7634 }
7635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 @Override
7638 public String toString() {
7639 StringBuffer buf = new StringBuffer(128);
7640 buf.append("PackageSignatures{");
7641 buf.append(Integer.toHexString(System.identityHashCode(this)));
7642 buf.append(" [");
7643 if (mSignatures != null) {
7644 for (int i=0; i<mSignatures.length; i++) {
7645 if (i > 0) buf.append(", ");
7646 buf.append(Integer.toHexString(
7647 System.identityHashCode(mSignatures[i])));
7648 }
7649 }
7650 buf.append("]}");
7651 return buf.toString();
7652 }
7653 }
7654
7655 static class PreferredActivity extends IntentFilter {
7656 final int mMatch;
7657 final String[] mSetPackages;
7658 final String[] mSetClasses;
7659 final String[] mSetComponents;
7660 final ComponentName mActivity;
7661 final String mShortActivity;
7662 String mParseError;
7663
7664 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7665 ComponentName activity) {
7666 super(filter);
7667 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7668 mActivity = activity;
7669 mShortActivity = activity.flattenToShortString();
7670 mParseError = null;
7671 if (set != null) {
7672 final int N = set.length;
7673 String[] myPackages = new String[N];
7674 String[] myClasses = new String[N];
7675 String[] myComponents = new String[N];
7676 for (int i=0; i<N; i++) {
7677 ComponentName cn = set[i];
7678 if (cn == null) {
7679 mSetPackages = null;
7680 mSetClasses = null;
7681 mSetComponents = null;
7682 return;
7683 }
7684 myPackages[i] = cn.getPackageName().intern();
7685 myClasses[i] = cn.getClassName().intern();
7686 myComponents[i] = cn.flattenToShortString().intern();
7687 }
7688 mSetPackages = myPackages;
7689 mSetClasses = myClasses;
7690 mSetComponents = myComponents;
7691 } else {
7692 mSetPackages = null;
7693 mSetClasses = null;
7694 mSetComponents = null;
7695 }
7696 }
7697
7698 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7699 IOException {
7700 mShortActivity = parser.getAttributeValue(null, "name");
7701 mActivity = ComponentName.unflattenFromString(mShortActivity);
7702 if (mActivity == null) {
7703 mParseError = "Bad activity name " + mShortActivity;
7704 }
7705 String matchStr = parser.getAttributeValue(null, "match");
7706 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7707 String setCountStr = parser.getAttributeValue(null, "set");
7708 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7709
7710 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7711 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7712 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7713
7714 int setPos = 0;
7715
7716 int outerDepth = parser.getDepth();
7717 int type;
7718 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7719 && (type != XmlPullParser.END_TAG
7720 || parser.getDepth() > outerDepth)) {
7721 if (type == XmlPullParser.END_TAG
7722 || type == XmlPullParser.TEXT) {
7723 continue;
7724 }
7725
7726 String tagName = parser.getName();
7727 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7728 // + parser.getDepth() + " tag=" + tagName);
7729 if (tagName.equals("set")) {
7730 String name = parser.getAttributeValue(null, "name");
7731 if (name == null) {
7732 if (mParseError == null) {
7733 mParseError = "No name in set tag in preferred activity "
7734 + mShortActivity;
7735 }
7736 } else if (setPos >= setCount) {
7737 if (mParseError == null) {
7738 mParseError = "Too many set tags in preferred activity "
7739 + mShortActivity;
7740 }
7741 } else {
7742 ComponentName cn = ComponentName.unflattenFromString(name);
7743 if (cn == null) {
7744 if (mParseError == null) {
7745 mParseError = "Bad set name " + name + " in preferred activity "
7746 + mShortActivity;
7747 }
7748 } else {
7749 myPackages[setPos] = cn.getPackageName();
7750 myClasses[setPos] = cn.getClassName();
7751 myComponents[setPos] = name;
7752 setPos++;
7753 }
7754 }
7755 XmlUtils.skipCurrentTag(parser);
7756 } else if (tagName.equals("filter")) {
7757 //Log.i(TAG, "Starting to parse filter...");
7758 readFromXml(parser);
7759 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7760 // + parser.getDepth() + " tag=" + parser.getName());
7761 } else {
7762 reportSettingsProblem(Log.WARN,
7763 "Unknown element under <preferred-activities>: "
7764 + parser.getName());
7765 XmlUtils.skipCurrentTag(parser);
7766 }
7767 }
7768
7769 if (setPos != setCount) {
7770 if (mParseError == null) {
7771 mParseError = "Not enough set tags (expected " + setCount
7772 + " but found " + setPos + ") in " + mShortActivity;
7773 }
7774 }
7775
7776 mSetPackages = myPackages;
7777 mSetClasses = myClasses;
7778 mSetComponents = myComponents;
7779 }
7780
7781 public void writeToXml(XmlSerializer serializer) throws IOException {
7782 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7783 serializer.attribute(null, "name", mShortActivity);
7784 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7785 serializer.attribute(null, "set", Integer.toString(NS));
7786 for (int s=0; s<NS; s++) {
7787 serializer.startTag(null, "set");
7788 serializer.attribute(null, "name", mSetComponents[s]);
7789 serializer.endTag(null, "set");
7790 }
7791 serializer.startTag(null, "filter");
7792 super.writeToXml(serializer);
7793 serializer.endTag(null, "filter");
7794 }
7795
7796 boolean sameSet(List<ResolveInfo> query, int priority) {
7797 if (mSetPackages == null) return false;
7798 final int NQ = query.size();
7799 final int NS = mSetPackages.length;
7800 int numMatch = 0;
7801 for (int i=0; i<NQ; i++) {
7802 ResolveInfo ri = query.get(i);
7803 if (ri.priority != priority) continue;
7804 ActivityInfo ai = ri.activityInfo;
7805 boolean good = false;
7806 for (int j=0; j<NS; j++) {
7807 if (mSetPackages[j].equals(ai.packageName)
7808 && mSetClasses[j].equals(ai.name)) {
7809 numMatch++;
7810 good = true;
7811 break;
7812 }
7813 }
7814 if (!good) return false;
7815 }
7816 return numMatch == NS;
7817 }
7818 }
7819
7820 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007821 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 HashSet<String> grantedPermissions = new HashSet<String>();
7824 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007827 setFlags(pkgFlags);
7828 }
7829
Kenny Root291e78c2011-01-13 14:53:17 -08007830 GrantedPermissions(GrantedPermissions base) {
7831 pkgFlags = base.pkgFlags;
7832 grantedPermissions = (HashSet<String>) base.grantedPermissions.clone();
7833 gids = base.gids.clone();
7834 }
7835
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007836 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007837 this.pkgFlags = pkgFlags & (
7838 ApplicationInfo.FLAG_SYSTEM |
7839 ApplicationInfo.FLAG_FORWARD_LOCK |
Jason parksa3cdaa52011-01-13 14:15:43 -06007840 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
7841 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 }
7843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007845 /**
7846 * Settings base class for pending and resolved classes.
7847 */
7848 static class PackageSettingBase extends GrantedPermissions {
7849 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007850 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007851 File codePath;
7852 String codePathString;
7853 File resourcePath;
7854 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007855 String nativeLibraryPathString;
Kenny Root5d40fe92011-01-14 10:54:46 -08007856 String[] obbPathStrings;
Kenny Root7d794fb2010-09-13 16:29:49 -07007857 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007858 long firstInstallTime;
7859 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007860 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007862 boolean uidError;
Kenny Root291e78c2011-01-13 14:53:17 -08007863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 PackageSignatures signatures = new PackageSignatures();
7865
7866 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007867 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869 /* Explicitly disabled components */
7870 HashSet<String> disabledComponents = new HashSet<String>(0);
7871 /* Explicitly enabled components */
7872 HashSet<String> enabledComponents = new HashSet<String>(0);
7873 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7874 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007875
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007876 PackageSettingBase origPackage;
7877
Jacek Surazski65e13172009-04-28 15:26:38 +02007878 /* package name of the app that installed this package */
7879 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007880
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007881 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007882 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 super(pkgFlags);
7884 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007885 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007886 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007887 }
7888
Kenny Root291e78c2011-01-13 14:53:17 -08007889 /**
7890 * New instance of PackageSetting with one-level-deep cloning.
7891 */
7892 PackageSettingBase(PackageSettingBase base) {
7893 super(base);
7894
7895 name = base.name;
7896 realName = base.realName;
7897 codePath = base.codePath;
7898 codePathString = base.codePathString;
7899 resourcePath = base.resourcePath;
7900 resourcePathString = base.resourcePathString;
7901 nativeLibraryPathString = base.nativeLibraryPathString;
Kenny Root5d40fe92011-01-14 10:54:46 -08007902
7903 if (base.obbPathStrings != null) {
7904 obbPathStrings = base.obbPathStrings.clone();
7905 }
7906
Kenny Root291e78c2011-01-13 14:53:17 -08007907 timeStamp = base.timeStamp;
7908 firstInstallTime = base.firstInstallTime;
7909 lastUpdateTime = base.lastUpdateTime;
7910 versionCode = base.versionCode;
7911
7912 uidError = base.uidError;
7913
7914 signatures = new PackageSignatures(base.signatures);
7915
7916 permissionsFixed = base.permissionsFixed;
7917 haveGids = base.haveGids;
7918
7919 disabledComponents = (HashSet<String>) base.disabledComponents.clone();
7920
7921 enabledComponents = (HashSet<String>) base.enabledComponents.clone();
7922
7923 enabled = base.enabled;
7924 installStatus = base.installStatus;
7925
7926 origPackage = base.origPackage;
7927
7928 installerPackageName = base.installerPackageName;
7929 }
7930
Kenny Root806cc132010-09-12 08:34:19 -07007931 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7932 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 this.codePath = codePath;
7934 this.codePathString = codePath.toString();
7935 this.resourcePath = resourcePath;
7936 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007937 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007938 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007939 }
Kenny Root85387d72010-08-26 10:13:11 -07007940
Jacek Surazski65e13172009-04-28 15:26:38 +02007941 public void setInstallerPackageName(String packageName) {
7942 installerPackageName = packageName;
7943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007944
Jacek Surazski65e13172009-04-28 15:26:38 +02007945 String getInstallerPackageName() {
7946 return installerPackageName;
7947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007949 public void setInstallStatus(int newStatus) {
7950 installStatus = newStatus;
7951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 public int getInstallStatus() {
7954 return installStatus;
7955 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007959 }
7960
Kenny Root291e78c2011-01-13 14:53:17 -08007961 /**
7962 * Make a shallow copy of this package settings.
7963 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007964 public void copyFrom(PackageSettingBase base) {
7965 grantedPermissions = base.grantedPermissions;
7966 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007969 firstInstallTime = base.firstInstallTime;
7970 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 signatures = base.signatures;
7972 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007973 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 disabledComponents = base.disabledComponents;
7975 enabledComponents = base.enabledComponents;
7976 enabled = base.enabled;
7977 installStatus = base.installStatus;
7978 }
7979
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007980 boolean enableComponentLP(String componentClassName) {
7981 boolean changed = disabledComponents.remove(componentClassName);
7982 changed |= enabledComponents.add(componentClassName);
7983 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 }
7985
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007986 boolean disableComponentLP(String componentClassName) {
7987 boolean changed = enabledComponents.remove(componentClassName);
7988 changed |= disabledComponents.add(componentClassName);
7989 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 }
7991
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007992 boolean restoreComponentLP(String componentClassName) {
7993 boolean changed = enabledComponents.remove(componentClassName);
7994 changed |= disabledComponents.remove(componentClassName);
7995 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 }
7997
7998 int currentEnabledStateLP(String componentName) {
7999 if (enabledComponents.contains(componentName)) {
8000 return COMPONENT_ENABLED_STATE_ENABLED;
8001 } else if (disabledComponents.contains(componentName)) {
8002 return COMPONENT_ENABLED_STATE_DISABLED;
8003 } else {
8004 return COMPONENT_ENABLED_STATE_DEFAULT;
8005 }
8006 }
8007 }
8008
8009 /**
8010 * Settings data for a particular package we know about.
8011 */
8012 static final class PackageSetting extends PackageSettingBase {
8013 int userId;
8014 PackageParser.Package pkg;
8015 SharedUserSetting sharedUser;
8016
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008017 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008018 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
8019 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
8020 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008022
Kenny Root291e78c2011-01-13 14:53:17 -08008023 /**
8024 * New instance of PackageSetting replicating the original settings.
8025 * Note that it keeps the same PackageParser.Package instance.
8026 */
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008027 PackageSetting(PackageSetting orig) {
Kenny Root291e78c2011-01-13 14:53:17 -08008028 super(orig);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008029
Kenny Root291e78c2011-01-13 14:53:17 -08008030 userId = orig.userId;
8031 pkg = orig.pkg;
8032 sharedUser = orig.sharedUser;
Kenny Root97ef63b2011-01-11 11:15:35 -08008033 }
8034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 @Override
8036 public String toString() {
8037 return "PackageSetting{"
8038 + Integer.toHexString(System.identityHashCode(this))
8039 + " " + name + "/" + userId + "}";
8040 }
8041 }
8042
8043 /**
8044 * Settings data for a particular shared user ID we know about.
8045 */
8046 static final class SharedUserSetting extends GrantedPermissions {
8047 final String name;
8048 int userId;
8049 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
8050 final PackageSignatures signatures = new PackageSignatures();
8051
8052 SharedUserSetting(String _name, int _pkgFlags) {
8053 super(_pkgFlags);
8054 name = _name;
8055 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 @Override
8058 public String toString() {
8059 return "SharedUserSetting{"
8060 + Integer.toHexString(System.identityHashCode(this))
8061 + " " + name + "/" + userId + "}";
8062 }
8063 }
8064
8065 /**
8066 * Holds information about dynamic settings.
8067 */
8068 private static final class Settings {
8069 private final File mSettingsFilename;
8070 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008071 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008072 private final HashMap<String, PackageSetting> mPackages =
8073 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 // List of replaced system applications
8075 final HashMap<String, PackageSetting> mDisabledSysPackages =
8076 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008077
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008078 // These are the last platform API version we were using for
8079 // the apps installed on internal and external storage. It is
8080 // used to grant newer permissions one time during a system upgrade.
8081 int mInternalSdkPlatform;
8082 int mExternalSdkPlatform;
8083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 // The user's preferred activities associated with particular intent
8085 // filters.
8086 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
8087 new IntentResolver<PreferredActivity, PreferredActivity>() {
8088 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008089 protected String packageForFilter(PreferredActivity filter) {
8090 return filter.mActivity.getPackageName();
8091 }
8092 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008093 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008094 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008095 out.print(prefix); out.print(
8096 Integer.toHexString(System.identityHashCode(filter)));
8097 out.print(' ');
8098 out.print(filter.mActivity.flattenToShortString());
8099 out.print(" match=0x");
8100 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008101 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008102 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008104 out.print(prefix); out.print(" ");
8105 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 }
8107 }
8108 }
8109 };
8110 private final HashMap<String, SharedUserSetting> mSharedUsers =
8111 new HashMap<String, SharedUserSetting>();
8112 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
8113 private final SparseArray<Object> mOtherUserIds =
8114 new SparseArray<Object>();
8115
8116 // For reading/writing settings file.
8117 private final ArrayList<Signature> mPastSignatures =
8118 new ArrayList<Signature>();
8119
8120 // Mapping from permission names to info about them.
8121 final HashMap<String, BasePermission> mPermissions =
8122 new HashMap<String, BasePermission>();
8123
8124 // Mapping from permission tree names to info about them.
8125 final HashMap<String, BasePermission> mPermissionTrees =
8126 new HashMap<String, BasePermission>();
8127
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008128 // Packages that have been uninstalled and still need their external
8129 // storage data deleted.
8130 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
8131
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008132 // Packages that have been renamed since they were first installed.
8133 // Keys are the new names of the packages, values are the original
8134 // names. The packages appear everwhere else under their original
8135 // names.
8136 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
8137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 private final StringBuilder mReadMessages = new StringBuilder();
8139
8140 private static final class PendingPackage extends PackageSettingBase {
8141 final int sharedId;
8142
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008143 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008144 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
8145 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
8146 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008147 this.sharedId = sharedId;
8148 }
8149 }
8150 private final ArrayList<PendingPackage> mPendingPackages
8151 = new ArrayList<PendingPackage>();
8152
8153 Settings() {
8154 File dataDir = Environment.getDataDirectory();
8155 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08008156 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
8157 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008159 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 FileUtils.setPermissions(systemDir.toString(),
8161 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8162 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8163 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08008164 FileUtils.setPermissions(systemSecureDir.toString(),
8165 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8166 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8167 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008168 mSettingsFilename = new File(systemDir, "packages.xml");
8169 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008170 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008171 }
8172
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008173 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008174 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008175 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008176 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008177 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07008178 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008179 return p;
8180 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008181
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008182 PackageSetting peekPackageLP(String name) {
8183 return mPackages.get(name);
8184 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 PackageSetting p = mPackages.get(name);
8186 if (p != null && p.codePath.getPath().equals(codePath)) {
8187 return p;
8188 }
8189 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008190 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 void setInstallStatus(String pkgName, int status) {
8194 PackageSetting p = mPackages.get(pkgName);
8195 if(p != null) {
8196 if(p.getInstallStatus() != status) {
8197 p.setInstallStatus(status);
8198 }
8199 }
8200 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008201
Jacek Surazski65e13172009-04-28 15:26:38 +02008202 void setInstallerPackageName(String pkgName,
8203 String installerPkgName) {
8204 PackageSetting p = mPackages.get(pkgName);
8205 if(p != null) {
8206 p.setInstallerPackageName(installerPkgName);
8207 }
8208 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008209
Jacek Surazski65e13172009-04-28 15:26:38 +02008210 String getInstallerPackageName(String pkgName) {
8211 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008212 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008213 }
8214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008215 int getInstallStatus(String pkgName) {
8216 PackageSetting p = mPackages.get(pkgName);
8217 if(p != null) {
8218 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 return -1;
8221 }
8222
8223 SharedUserSetting getSharedUserLP(String name,
8224 int pkgFlags, boolean create) {
8225 SharedUserSetting s = mSharedUsers.get(name);
8226 if (s == null) {
8227 if (!create) {
8228 return null;
8229 }
8230 s = new SharedUserSetting(name, pkgFlags);
8231 if (MULTIPLE_APPLICATION_UIDS) {
8232 s.userId = newUserIdLP(s);
8233 } else {
8234 s.userId = FIRST_APPLICATION_UID;
8235 }
8236 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8237 // < 0 means we couldn't assign a userid; fall out and return
8238 // s, which is currently null
8239 if (s.userId >= 0) {
8240 mSharedUsers.put(name, s);
8241 }
8242 }
8243
8244 return s;
8245 }
8246
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008247 boolean disableSystemPackageLP(String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008248 PackageSetting p = mPackages.get(name);
8249 if(p == null) {
8250 Log.w(TAG, "Package:"+name+" is not an installed package");
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008251 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008252 }
8253 PackageSetting dp = mDisabledSysPackages.get(name);
8254 // always make sure the system package code and resource paths dont change
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008255 if (dp == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008256 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8257 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8258 }
8259 mDisabledSysPackages.put(name, p);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008260
8261 // a little trick... when we install the new package, we don't
8262 // want to modify the existing PackageSetting for the built-in
8263 // version. so at this point we need a new PackageSetting that
Kenny Root291e78c2011-01-13 14:53:17 -08008264 // is okay to muck with.
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008265 PackageSetting newp = new PackageSetting(p);
8266 replacePackageLP(name, newp);
8267 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008268 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008269 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008270 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 PackageSetting enableSystemPackageLP(String name) {
8273 PackageSetting p = mDisabledSysPackages.get(name);
8274 if(p == null) {
8275 Log.w(TAG, "Package:"+name+" is not disabled");
8276 return null;
8277 }
8278 // Reset flag in ApplicationInfo object
8279 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8280 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8281 }
Kenny Root806cc132010-09-12 08:34:19 -07008282 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8283 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 mDisabledSysPackages.remove(name);
8285 return ret;
8286 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008287
Kenny Root806cc132010-09-12 08:34:19 -07008288 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8289 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 PackageSetting p = mPackages.get(name);
8291 if (p != null) {
8292 if (p.userId == uid) {
8293 return p;
8294 }
8295 reportSettingsProblem(Log.ERROR,
8296 "Adding duplicate package, keeping first: " + name);
8297 return null;
8298 }
Kenny Root806cc132010-09-12 08:34:19 -07008299 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8300 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008301 p.userId = uid;
8302 if (addUserIdLP(uid, p, name)) {
8303 mPackages.put(name, p);
8304 return p;
8305 }
8306 return null;
8307 }
8308
8309 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8310 SharedUserSetting s = mSharedUsers.get(name);
8311 if (s != null) {
8312 if (s.userId == uid) {
8313 return s;
8314 }
8315 reportSettingsProblem(Log.ERROR,
8316 "Adding duplicate shared user, keeping first: " + name);
8317 return null;
8318 }
8319 s = new SharedUserSetting(name, pkgFlags);
8320 s.userId = uid;
8321 if (addUserIdLP(uid, s, name)) {
8322 mSharedUsers.put(name, s);
8323 return s;
8324 }
8325 return null;
8326 }
8327
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008328 // Transfer ownership of permissions from one package to another.
8329 private void transferPermissions(String origPkg, String newPkg) {
8330 // Transfer ownership of permissions to the new package.
8331 for (int i=0; i<2; i++) {
8332 HashMap<String, BasePermission> permissions =
8333 i == 0 ? mPermissionTrees : mPermissions;
8334 for (BasePermission bp : permissions.values()) {
8335 if (origPkg.equals(bp.sourcePackage)) {
8336 if (DEBUG_UPGRADE) Log.v(TAG,
8337 "Moving permission " + bp.name
8338 + " from pkg " + bp.sourcePackage
8339 + " to " + newPkg);
8340 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008341 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008342 bp.perm = null;
8343 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008344 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008345 }
8346 bp.uid = 0;
8347 bp.gids = null;
8348 }
8349 }
8350 }
8351 }
8352
8353 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008354 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008355 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008356 PackageSetting p = mPackages.get(name);
8357 if (p != null) {
8358 if (!p.codePath.equals(codePath)) {
8359 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008360 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008361 // This is an updated system app with versions in both system
8362 // and data partition. Just let the most recent version
8363 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008364 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008365 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008366 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008367 // Just a change in the code path is not an issue, but
8368 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008369 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008370 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008371 /*
8372 * Since we've changed paths, we need to prefer the new
8373 * native library path over the one stored in the
8374 * package settings since we might have moved from
8375 * internal to external storage or vice versa.
8376 */
8377 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008378 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008379 }
8380 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008381 reportSettingsProblem(Log.WARN,
8382 "Package " + name + " shared user changed from "
8383 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8384 + " to "
8385 + (sharedUser != null ? sharedUser.name : "<nothing>")
8386 + "; replacing with new");
8387 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008388 } else {
8389 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8390 // If what we are scanning is a system package, then
8391 // make it so, regardless of whether it was previously
8392 // installed only in the data partition.
8393 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008395 }
8396 }
8397 if (p == null) {
8398 // Create a new PackageSettings entry. this can end up here because
8399 // of code path mismatch or user id mismatch of an updated system partition
8400 if (!create) {
8401 return null;
8402 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008403 if (origPackage != null) {
8404 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008405 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8406 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008407 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8408 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008409 // Note that we will retain the new package's signature so
8410 // that we can keep its data.
8411 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008412 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008413 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008414 p.sharedUser = origPackage.sharedUser;
8415 p.userId = origPackage.userId;
8416 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008417 mRenamedPackages.put(name, origPackage.name);
8418 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008419 // Update new package state.
8420 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008421 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008422 p = new PackageSetting(name, realName, codePath, resourcePath,
8423 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008424 p.setTimeStamp(codePath.lastModified());
8425 p.sharedUser = sharedUser;
8426 if (sharedUser != null) {
8427 p.userId = sharedUser.userId;
8428 } else if (MULTIPLE_APPLICATION_UIDS) {
8429 // Clone the setting here for disabled system packages
8430 PackageSetting dis = mDisabledSysPackages.get(name);
8431 if (dis != null) {
8432 // For disabled packages a new setting is created
8433 // from the existing user id. This still has to be
8434 // added to list of user id's
8435 // Copy signatures from previous setting
8436 if (dis.signatures.mSignatures != null) {
8437 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8438 }
8439 p.userId = dis.userId;
8440 // Clone permissions
8441 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008442 // Clone component info
8443 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8444 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8445 // Add new setting to list of user ids
8446 addUserIdLP(p.userId, p, name);
8447 } else {
8448 // Assign new user id
8449 p.userId = newUserIdLP(p);
8450 }
8451 } else {
8452 p.userId = FIRST_APPLICATION_UID;
8453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008454 }
8455 if (p.userId < 0) {
8456 reportSettingsProblem(Log.WARN,
8457 "Package " + name + " could not be assigned a valid uid");
8458 return null;
8459 }
8460 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008461 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008462 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008463 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 }
8465 }
8466 return p;
8467 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008468
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008469 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008470 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008471 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008472 final String codePath = pkg.applicationInfo.sourceDir;
8473 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008474 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008475 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008476 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008477 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008478 p.codePath = new File(codePath);
8479 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008480 }
8481 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008482 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008483 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008484 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008485 p.resourcePath = new File(resourcePath);
8486 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008487 }
Kenny Root85387d72010-08-26 10:13:11 -07008488 // Update the native library path if needed
8489 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8490 if (nativeLibraryPath != null
8491 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8492 p.nativeLibraryPathString = nativeLibraryPath;
8493 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008494 // Update version code if needed
8495 if (pkg.mVersionCode != p.versionCode) {
8496 p.versionCode = pkg.mVersionCode;
8497 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008498 // Update signatures if needed.
8499 if (p.signatures.mSignatures == null) {
8500 p.signatures.assignSignatures(pkg.mSignatures);
8501 }
8502 // If this app defines a shared user id initialize
8503 // the shared user signatures as well.
8504 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8505 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8506 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008507 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8508 }
8509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008510 // Utility method that adds a PackageSetting to mPackages and
8511 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008512 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008513 SharedUserSetting sharedUser) {
8514 mPackages.put(name, p);
8515 if (sharedUser != null) {
8516 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8517 reportSettingsProblem(Log.ERROR,
8518 "Package " + p.name + " was user "
8519 + p.sharedUser + " but is now " + sharedUser
8520 + "; I am not changing its files so it will probably fail!");
8521 p.sharedUser.packages.remove(p);
8522 } else if (p.userId != sharedUser.userId) {
8523 reportSettingsProblem(Log.ERROR,
8524 "Package " + p.name + " was user id " + p.userId
8525 + " but is now user " + sharedUser
8526 + " with id " + sharedUser.userId
8527 + "; I am not changing its files so it will probably fail!");
8528 }
8529
8530 sharedUser.packages.add(p);
8531 p.sharedUser = sharedUser;
8532 p.userId = sharedUser.userId;
8533 }
8534 }
8535
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008536 /*
8537 * Update the shared user setting when a package using
8538 * specifying the shared user id is removed. The gids
8539 * associated with each permission of the deleted package
8540 * are removed from the shared user's gid list only if its
8541 * not in use by other permissions of packages in the
8542 * shared user setting.
8543 */
8544 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008546 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 return;
8548 }
8549 // No sharedUserId
8550 if (deletedPs.sharedUser == null) {
8551 return;
8552 }
8553 SharedUserSetting sus = deletedPs.sharedUser;
8554 // Update permissions
8555 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8556 boolean used = false;
8557 if (!sus.grantedPermissions.contains (eachPerm)) {
8558 continue;
8559 }
8560 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008561 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008562 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008563 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 used = true;
8565 break;
8566 }
8567 }
8568 if (!used) {
8569 // can safely delete this permission from list
8570 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 }
8572 }
8573 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008574 int newGids[] = globalGids;
8575 for (String eachPerm : sus.grantedPermissions) {
8576 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008577 if (bp != null) {
8578 newGids = appendInts(newGids, bp.gids);
8579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 }
8581 sus.gids = newGids;
8582 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008584 private int removePackageLP(String name) {
8585 PackageSetting p = mPackages.get(name);
8586 if (p != null) {
8587 mPackages.remove(name);
8588 if (p.sharedUser != null) {
8589 p.sharedUser.packages.remove(p);
8590 if (p.sharedUser.packages.size() == 0) {
8591 mSharedUsers.remove(p.sharedUser.name);
8592 removeUserIdLP(p.sharedUser.userId);
8593 return p.sharedUser.userId;
8594 }
8595 } else {
8596 removeUserIdLP(p.userId);
8597 return p.userId;
8598 }
8599 }
8600 return -1;
8601 }
8602
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008603 private void replacePackageLP(String name, PackageSetting newp) {
8604 PackageSetting p = mPackages.get(name);
8605 if (p != null) {
8606 if (p.sharedUser != null) {
8607 p.sharedUser.packages.remove(p);
8608 p.sharedUser.packages.add(newp);
8609 } else {
8610 replaceUserIdLP(p.userId, newp);
8611 }
8612 }
8613 mPackages.put(name, newp);
8614 }
8615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 private boolean addUserIdLP(int uid, Object obj, Object name) {
8617 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8618 return false;
8619 }
8620
8621 if (uid >= FIRST_APPLICATION_UID) {
8622 int N = mUserIds.size();
8623 final int index = uid - FIRST_APPLICATION_UID;
8624 while (index >= N) {
8625 mUserIds.add(null);
8626 N++;
8627 }
8628 if (mUserIds.get(index) != null) {
8629 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008630 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008631 + " name=" + name);
8632 return false;
8633 }
8634 mUserIds.set(index, obj);
8635 } else {
8636 if (mOtherUserIds.get(uid) != null) {
8637 reportSettingsProblem(Log.ERROR,
8638 "Adding duplicate shared id: " + uid
8639 + " name=" + name);
8640 return false;
8641 }
8642 mOtherUserIds.put(uid, obj);
8643 }
8644 return true;
8645 }
8646
8647 public Object getUserIdLP(int uid) {
8648 if (uid >= FIRST_APPLICATION_UID) {
8649 int N = mUserIds.size();
8650 final int index = uid - FIRST_APPLICATION_UID;
8651 return index < N ? mUserIds.get(index) : null;
8652 } else {
8653 return mOtherUserIds.get(uid);
8654 }
8655 }
8656
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008657 private Set<String> findPackagesWithFlag(int flag) {
8658 Set<String> ret = new HashSet<String>();
8659 for (PackageSetting ps : mPackages.values()) {
8660 // Has to match atleast all the flag bits set on flag
8661 if ((ps.pkgFlags & flag) == flag) {
8662 ret.add(ps.name);
8663 }
8664 }
8665 return ret;
8666 }
8667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 private void removeUserIdLP(int uid) {
8669 if (uid >= FIRST_APPLICATION_UID) {
8670 int N = mUserIds.size();
8671 final int index = uid - FIRST_APPLICATION_UID;
8672 if (index < N) mUserIds.set(index, null);
8673 } else {
8674 mOtherUserIds.remove(uid);
8675 }
8676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008677
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008678 private void replaceUserIdLP(int uid, Object obj) {
8679 if (uid >= FIRST_APPLICATION_UID) {
8680 int N = mUserIds.size();
8681 final int index = uid - FIRST_APPLICATION_UID;
8682 if (index < N) mUserIds.set(index, obj);
8683 } else {
8684 mOtherUserIds.put(uid, obj);
8685 }
8686 }
8687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 void writeLP() {
8689 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8690
8691 // Keep the old settings around until we know the new ones have
8692 // been successfully written.
8693 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008694 // Presence of backup settings file indicates that we failed
8695 // to persist settings earlier. So preserve the older
8696 // backup for future reference since the current settings
8697 // might have been corrupted.
8698 if (!mBackupSettingsFilename.exists()) {
8699 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008700 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008701 return;
8702 }
8703 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008704 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008705 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008707 }
8708
8709 mPastSignatures.clear();
8710
8711 try {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008712 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
8713 BufferedOutputStream str = new BufferedOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714
8715 //XmlSerializer serializer = XmlUtils.serializerInstance();
8716 XmlSerializer serializer = new FastXmlSerializer();
8717 serializer.setOutput(str, "utf-8");
8718 serializer.startDocument(null, true);
8719 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8720
8721 serializer.startTag(null, "packages");
8722
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008723 serializer.startTag(null, "last-platform-version");
8724 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8725 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8726 serializer.endTag(null, "last-platform-version");
8727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 serializer.startTag(null, "permission-trees");
8729 for (BasePermission bp : mPermissionTrees.values()) {
8730 writePermission(serializer, bp);
8731 }
8732 serializer.endTag(null, "permission-trees");
8733
8734 serializer.startTag(null, "permissions");
8735 for (BasePermission bp : mPermissions.values()) {
8736 writePermission(serializer, bp);
8737 }
8738 serializer.endTag(null, "permissions");
8739
8740 for (PackageSetting pkg : mPackages.values()) {
8741 writePackage(serializer, pkg);
8742 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008744 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8745 writeDisabledSysPackage(serializer, pkg);
8746 }
8747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008748 serializer.startTag(null, "preferred-activities");
8749 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8750 serializer.startTag(null, "item");
8751 pa.writeToXml(serializer);
8752 serializer.endTag(null, "item");
8753 }
8754 serializer.endTag(null, "preferred-activities");
8755
8756 for (SharedUserSetting usr : mSharedUsers.values()) {
8757 serializer.startTag(null, "shared-user");
8758 serializer.attribute(null, "name", usr.name);
8759 serializer.attribute(null, "userId",
8760 Integer.toString(usr.userId));
8761 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8762 serializer.startTag(null, "perms");
8763 for (String name : usr.grantedPermissions) {
8764 serializer.startTag(null, "item");
8765 serializer.attribute(null, "name", name);
8766 serializer.endTag(null, "item");
8767 }
8768 serializer.endTag(null, "perms");
8769 serializer.endTag(null, "shared-user");
8770 }
8771
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008772 if (mPackagesToBeCleaned.size() > 0) {
8773 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8774 serializer.startTag(null, "cleaning-package");
8775 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8776 serializer.endTag(null, "cleaning-package");
8777 }
8778 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008779
8780 if (mRenamedPackages.size() > 0) {
8781 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8782 serializer.startTag(null, "renamed-package");
8783 serializer.attribute(null, "new", e.getKey());
8784 serializer.attribute(null, "old", e.getValue());
8785 serializer.endTag(null, "renamed-package");
8786 }
8787 }
8788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008789 serializer.endTag(null, "packages");
8790
8791 serializer.endDocument();
8792
8793 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008794 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008795 str.close();
8796
8797 // New settings successfully written, old ones are no longer
8798 // needed.
8799 mBackupSettingsFilename.delete();
8800 FileUtils.setPermissions(mSettingsFilename.toString(),
8801 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8802 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8803 |FileUtils.S_IROTH,
8804 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008805
8806 // Write package list file now, use a JournaledFile.
8807 //
8808 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8809 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8810
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008811 fstr = new FileOutputStream(journal.chooseForWrite());
8812 str = new BufferedOutputStream(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008813 try {
8814 StringBuilder sb = new StringBuilder();
8815 for (PackageSetting pkg : mPackages.values()) {
8816 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008817 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008818 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8819
8820 // Avoid any application that has a space in its path
8821 // or that is handled by the system.
8822 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8823 continue;
8824
8825 // we store on each line the following information for now:
8826 //
8827 // pkgName - package name
8828 // userId - application-specific user id
8829 // debugFlag - 0 or 1 if the package is debuggable.
8830 // dataPath - path to package's data path
8831 //
8832 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8833 //
8834 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8835 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8836 // system/core/run-as/run-as.c
8837 //
8838 sb.setLength(0);
8839 sb.append(ai.packageName);
8840 sb.append(" ");
Jason parksa3cdaa52011-01-13 14:15:43 -06008841 sb.append((int)ai.uid);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008842 sb.append(isDebug ? " 1 " : " 0 ");
8843 sb.append(dataPath);
8844 sb.append("\n");
8845 str.write(sb.toString().getBytes());
8846 }
8847 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008848 FileUtils.sync(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008849 str.close();
8850 journal.commit();
8851 }
8852 catch (Exception e) {
8853 journal.rollback();
8854 }
8855
8856 FileUtils.setPermissions(mPackageListFilename.toString(),
8857 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8858 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8859 |FileUtils.S_IROTH,
8860 -1, -1);
8861
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008862 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863
8864 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008865 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 -08008866 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008867 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 -08008868 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008869 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008870 if (mSettingsFilename.exists()) {
8871 if (!mSettingsFilename.delete()) {
8872 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8873 }
8874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008875 //Debug.stopMethodTracing();
8876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008877
8878 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008879 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 serializer.startTag(null, "updated-package");
8881 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008882 if (pkg.realName != null) {
8883 serializer.attribute(null, "realName", pkg.realName);
8884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008886 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8887 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8888 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008889 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8891 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8892 }
Kenny Root85387d72010-08-26 10:13:11 -07008893 if (pkg.nativeLibraryPathString != null) {
8894 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896 if (pkg.sharedUser == null) {
8897 serializer.attribute(null, "userId",
8898 Integer.toString(pkg.userId));
8899 } else {
8900 serializer.attribute(null, "sharedUserId",
8901 Integer.toString(pkg.userId));
8902 }
8903 serializer.startTag(null, "perms");
8904 if (pkg.sharedUser == null) {
8905 // If this is a shared user, the permissions will
8906 // be written there. We still need to write an
8907 // empty permissions list so permissionsFixed will
8908 // be set.
8909 for (final String name : pkg.grantedPermissions) {
8910 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008911 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008912 // We only need to write signature or system permissions but this wont
8913 // match the semantics of grantedPermissions. So write all permissions.
8914 serializer.startTag(null, "item");
8915 serializer.attribute(null, "name", name);
8916 serializer.endTag(null, "item");
8917 }
8918 }
8919 }
8920 serializer.endTag(null, "perms");
8921 serializer.endTag(null, "updated-package");
8922 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008923
8924 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008925 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926 serializer.startTag(null, "package");
8927 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008928 if (pkg.realName != null) {
8929 serializer.attribute(null, "realName", pkg.realName);
8930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931 serializer.attribute(null, "codePath", pkg.codePathString);
8932 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8933 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8934 }
Kenny Root85387d72010-08-26 10:13:11 -07008935 if (pkg.nativeLibraryPathString != null) {
8936 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8937 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008938 serializer.attribute(null, "flags",
8939 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008940 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8941 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8942 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008943 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 if (pkg.sharedUser == null) {
8945 serializer.attribute(null, "userId",
8946 Integer.toString(pkg.userId));
8947 } else {
8948 serializer.attribute(null, "sharedUserId",
8949 Integer.toString(pkg.userId));
8950 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008951 if (pkg.uidError) {
8952 serializer.attribute(null, "uidError", "true");
8953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008954 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8955 serializer.attribute(null, "enabled",
8956 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8957 ? "true" : "false");
8958 }
8959 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8960 serializer.attribute(null, "installStatus", "false");
8961 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008962 if (pkg.installerPackageName != null) {
8963 serializer.attribute(null, "installer", pkg.installerPackageName);
8964 }
Kenny Root5d40fe92011-01-14 10:54:46 -08008965 if (pkg.obbPathStrings != null && pkg.obbPathStrings.length > 0) {
8966 int N = pkg.obbPathStrings.length;
8967 serializer.startTag(null, "obbs");
8968 for (int i = 0; i < N; i++) {
8969 serializer.startTag(null, "obb");
8970 serializer.attribute(null, "path", pkg.obbPathStrings[i]);
8971 serializer.endTag(null, "obb");
8972 }
8973 serializer.endTag(null, "obbs");
Kenny Root93565c4b2010-06-18 15:46:06 -07008974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8976 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8977 serializer.startTag(null, "perms");
8978 if (pkg.sharedUser == null) {
8979 // If this is a shared user, the permissions will
8980 // be written there. We still need to write an
8981 // empty permissions list so permissionsFixed will
8982 // be set.
8983 for (final String name : pkg.grantedPermissions) {
8984 serializer.startTag(null, "item");
8985 serializer.attribute(null, "name", name);
8986 serializer.endTag(null, "item");
8987 }
8988 }
8989 serializer.endTag(null, "perms");
8990 }
8991 if (pkg.disabledComponents.size() > 0) {
8992 serializer.startTag(null, "disabled-components");
8993 for (final String name : pkg.disabledComponents) {
8994 serializer.startTag(null, "item");
8995 serializer.attribute(null, "name", name);
8996 serializer.endTag(null, "item");
8997 }
8998 serializer.endTag(null, "disabled-components");
8999 }
9000 if (pkg.enabledComponents.size() > 0) {
9001 serializer.startTag(null, "enabled-components");
9002 for (final String name : pkg.enabledComponents) {
9003 serializer.startTag(null, "item");
9004 serializer.attribute(null, "name", name);
9005 serializer.endTag(null, "item");
9006 }
9007 serializer.endTag(null, "enabled-components");
9008 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 serializer.endTag(null, "package");
9011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009013 void writePermission(XmlSerializer serializer, BasePermission bp)
9014 throws XmlPullParserException, java.io.IOException {
9015 if (bp.type != BasePermission.TYPE_BUILTIN
9016 && bp.sourcePackage != null) {
9017 serializer.startTag(null, "item");
9018 serializer.attribute(null, "name", bp.name);
9019 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009020 if (bp.protectionLevel !=
9021 PermissionInfo.PROTECTION_NORMAL) {
9022 serializer.attribute(null, "protection",
9023 Integer.toString(bp.protectionLevel));
9024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 if (DEBUG_SETTINGS) Log.v(TAG,
9026 "Writing perm: name=" + bp.name + " type=" + bp.type);
9027 if (bp.type == BasePermission.TYPE_DYNAMIC) {
9028 PermissionInfo pi = bp.perm != null ? bp.perm.info
9029 : bp.pendingInfo;
9030 if (pi != null) {
9031 serializer.attribute(null, "type", "dynamic");
9032 if (pi.icon != 0) {
9033 serializer.attribute(null, "icon",
9034 Integer.toString(pi.icon));
9035 }
9036 if (pi.nonLocalizedLabel != null) {
9037 serializer.attribute(null, "label",
9038 pi.nonLocalizedLabel.toString());
9039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 }
9041 }
9042 serializer.endTag(null, "item");
9043 }
9044 }
9045
9046 String getReadMessagesLP() {
9047 return mReadMessages.toString();
9048 }
9049
Oscar Montemayora8529f62009-11-18 10:14:20 -08009050 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009051 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
9052 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08009053 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009054 while(its.hasNext()) {
9055 String key = its.next();
9056 PackageSetting ps = mPackages.get(key);
9057 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08009058 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 }
9060 }
9061 return ret;
9062 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009064 boolean readLP() {
9065 FileInputStream str = null;
9066 if (mBackupSettingsFilename.exists()) {
9067 try {
9068 str = new FileInputStream(mBackupSettingsFilename);
9069 mReadMessages.append("Reading from backup settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009070 reportSettingsProblem(Log.INFO, "Need to read from backup settings file");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07009071 if (mSettingsFilename.exists()) {
9072 // If both the backup and settings file exist, we
9073 // ignore the settings since it might have been
9074 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009075 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07009076 mSettingsFilename.delete();
9077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 } catch (java.io.IOException e) {
9079 // We'll try for the normal settings file.
9080 }
9081 }
9082
9083 mPastSignatures.clear();
9084
9085 try {
9086 if (str == null) {
9087 if (!mSettingsFilename.exists()) {
9088 mReadMessages.append("No settings file found\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009089 reportSettingsProblem(Log.INFO, "No settings file; creating initial state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009090 return false;
9091 }
9092 str = new FileInputStream(mSettingsFilename);
9093 }
9094 XmlPullParser parser = Xml.newPullParser();
9095 parser.setInput(str, null);
9096
9097 int type;
9098 while ((type=parser.next()) != XmlPullParser.START_TAG
9099 && type != XmlPullParser.END_DOCUMENT) {
9100 ;
9101 }
9102
9103 if (type != XmlPullParser.START_TAG) {
9104 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009105 reportSettingsProblem(Log.WARN, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009106 return false;
9107 }
9108
9109 int outerDepth = parser.getDepth();
9110 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9111 && (type != XmlPullParser.END_TAG
9112 || parser.getDepth() > outerDepth)) {
9113 if (type == XmlPullParser.END_TAG
9114 || type == XmlPullParser.TEXT) {
9115 continue;
9116 }
9117
9118 String tagName = parser.getName();
9119 if (tagName.equals("package")) {
9120 readPackageLP(parser);
9121 } else if (tagName.equals("permissions")) {
9122 readPermissionsLP(mPermissions, parser);
9123 } else if (tagName.equals("permission-trees")) {
9124 readPermissionsLP(mPermissionTrees, parser);
9125 } else if (tagName.equals("shared-user")) {
9126 readSharedUserLP(parser);
9127 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08009128 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 } else if (tagName.equals("preferred-activities")) {
9130 readPreferredActivitiesLP(parser);
9131 } else if(tagName.equals("updated-package")) {
9132 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009133 } else if (tagName.equals("cleaning-package")) {
9134 String name = parser.getAttributeValue(null, "name");
9135 if (name != null) {
9136 mPackagesToBeCleaned.add(name);
9137 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009138 } else if (tagName.equals("renamed-package")) {
9139 String nname = parser.getAttributeValue(null, "new");
9140 String oname = parser.getAttributeValue(null, "old");
9141 if (nname != null && oname != null) {
9142 mRenamedPackages.put(nname, oname);
9143 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009144 } else if (tagName.equals("last-platform-version")) {
9145 mInternalSdkPlatform = mExternalSdkPlatform = 0;
9146 try {
9147 String internal = parser.getAttributeValue(null, "internal");
9148 if (internal != null) {
9149 mInternalSdkPlatform = Integer.parseInt(internal);
9150 }
9151 String external = parser.getAttributeValue(null, "external");
9152 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01009153 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009154 }
9155 } catch (NumberFormatException e) {
9156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009157 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009158 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009159 + parser.getName());
9160 XmlUtils.skipCurrentTag(parser);
9161 }
9162 }
9163
9164 str.close();
9165
9166 } catch(XmlPullParserException e) {
9167 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07009168 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009169 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009170
9171 } catch(java.io.IOException e) {
9172 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07009173 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009174 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175
9176 }
9177
9178 int N = mPendingPackages.size();
9179 for (int i=0; i<N; i++) {
9180 final PendingPackage pp = mPendingPackages.get(i);
9181 Object idObj = getUserIdLP(pp.sharedId);
9182 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009183 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07009184 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
9185 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 if (p == null) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07009187 reportSettingsProblem(Log.WARN, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009188 + pp.name);
9189 continue;
9190 }
9191 p.copyFrom(pp);
9192 } else if (idObj != null) {
9193 String msg = "Bad package setting: package " + pp.name
9194 + " has shared uid " + pp.sharedId
9195 + " that is not a shared uid\n";
9196 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009197 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198 } else {
9199 String msg = "Bad package setting: package " + pp.name
9200 + " has shared uid " + pp.sharedId
9201 + " that is not defined\n";
9202 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009203 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009204 }
9205 }
9206 mPendingPackages.clear();
9207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009208 mReadMessages.append("Read completed successfully: "
9209 + mPackages.size() + " packages, "
9210 + mSharedUsers.size() + " shared uids\n");
9211
9212 return true;
9213 }
9214
9215 private int readInt(XmlPullParser parser, String ns, String name,
9216 int defValue) {
9217 String v = parser.getAttributeValue(ns, name);
9218 try {
9219 if (v == null) {
9220 return defValue;
9221 }
9222 return Integer.parseInt(v);
9223 } catch (NumberFormatException e) {
9224 reportSettingsProblem(Log.WARN,
9225 "Error in package manager settings: attribute " +
9226 name + " has bad integer value " + v + " at "
9227 + parser.getPositionDescription());
9228 }
9229 return defValue;
9230 }
9231
9232 private void readPermissionsLP(HashMap<String, BasePermission> out,
9233 XmlPullParser parser)
9234 throws IOException, XmlPullParserException {
9235 int outerDepth = parser.getDepth();
9236 int type;
9237 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9238 && (type != XmlPullParser.END_TAG
9239 || parser.getDepth() > outerDepth)) {
9240 if (type == XmlPullParser.END_TAG
9241 || type == XmlPullParser.TEXT) {
9242 continue;
9243 }
9244
9245 String tagName = parser.getName();
9246 if (tagName.equals("item")) {
9247 String name = parser.getAttributeValue(null, "name");
9248 String sourcePackage = parser.getAttributeValue(null, "package");
9249 String ptype = parser.getAttributeValue(null, "type");
9250 if (name != null && sourcePackage != null) {
9251 boolean dynamic = "dynamic".equals(ptype);
9252 BasePermission bp = new BasePermission(name, sourcePackage,
9253 dynamic
9254 ? BasePermission.TYPE_DYNAMIC
9255 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009256 bp.protectionLevel = readInt(parser, null, "protection",
9257 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009258 if (dynamic) {
9259 PermissionInfo pi = new PermissionInfo();
9260 pi.packageName = sourcePackage.intern();
9261 pi.name = name.intern();
9262 pi.icon = readInt(parser, null, "icon", 0);
9263 pi.nonLocalizedLabel = parser.getAttributeValue(
9264 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009265 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 bp.pendingInfo = pi;
9267 }
9268 out.put(bp.name, bp);
9269 } else {
9270 reportSettingsProblem(Log.WARN,
9271 "Error in package manager settings: permissions has"
9272 + " no name at " + parser.getPositionDescription());
9273 }
9274 } else {
9275 reportSettingsProblem(Log.WARN,
9276 "Unknown element reading permissions: "
9277 + parser.getName() + " at "
9278 + parser.getPositionDescription());
9279 }
9280 XmlUtils.skipCurrentTag(parser);
9281 }
9282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009284 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009285 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009287 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009288 String codePathStr = parser.getAttributeValue(null, "codePath");
9289 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009290 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009291 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009292 resourcePathStr = codePathStr;
9293 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009294 String version = parser.getAttributeValue(null, "version");
9295 int versionCode = 0;
9296 if (version != null) {
9297 try {
9298 versionCode = Integer.parseInt(version);
9299 } catch (NumberFormatException e) {
9300 }
9301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 int pkgFlags = 0;
9304 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009305 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9306 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009307 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009308 if (timeStampStr != null) {
9309 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009310 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009311 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009312 } catch (NumberFormatException e) {
9313 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009314 } else {
9315 timeStampStr = parser.getAttributeValue(null, "ts");
9316 if (timeStampStr != null) {
9317 try {
9318 long timeStamp = Long.parseLong(timeStampStr);
9319 ps.setTimeStamp(timeStamp);
9320 } catch (NumberFormatException e) {
9321 }
9322 }
9323 }
9324 timeStampStr = parser.getAttributeValue(null, "it");
9325 if (timeStampStr != null) {
9326 try {
9327 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9328 } catch (NumberFormatException e) {
9329 }
9330 }
9331 timeStampStr = parser.getAttributeValue(null, "ut");
9332 if (timeStampStr != null) {
9333 try {
9334 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9335 } catch (NumberFormatException e) {
9336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 }
9338 String idStr = parser.getAttributeValue(null, "userId");
9339 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9340 if(ps.userId <= 0) {
9341 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9342 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9343 }
9344 int outerDepth = parser.getDepth();
9345 int type;
9346 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9347 && (type != XmlPullParser.END_TAG
9348 || parser.getDepth() > outerDepth)) {
9349 if (type == XmlPullParser.END_TAG
9350 || type == XmlPullParser.TEXT) {
9351 continue;
9352 }
9353
9354 String tagName = parser.getName();
9355 if (tagName.equals("perms")) {
9356 readGrantedPermissionsLP(parser,
9357 ps.grantedPermissions);
9358 } else {
9359 reportSettingsProblem(Log.WARN,
9360 "Unknown element under <updated-package>: "
9361 + parser.getName());
9362 XmlUtils.skipCurrentTag(parser);
9363 }
9364 }
9365 mDisabledSysPackages.put(name, ps);
9366 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009368 private void readPackageLP(XmlPullParser parser)
9369 throws XmlPullParserException, IOException {
9370 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009371 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009372 String idStr = null;
9373 String sharedIdStr = null;
9374 String codePathStr = null;
9375 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009376 String nativeLibraryPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009377 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009378 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009379 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009380 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009382 long firstInstallTime = 0;
9383 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009384 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009385 String version = null;
9386 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009387 try {
9388 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009389 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009390 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009391 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009392 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9393 codePathStr = parser.getAttributeValue(null, "codePath");
9394 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009395 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009396 version = parser.getAttributeValue(null, "version");
9397 if (version != null) {
9398 try {
9399 versionCode = Integer.parseInt(version);
9400 } catch (NumberFormatException e) {
9401 }
9402 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009403 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009404
9405 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009406 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009407 try {
9408 pkgFlags = Integer.parseInt(systemStr);
9409 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009410 }
9411 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009412 // For backward compatibility
9413 systemStr = parser.getAttributeValue(null, "system");
9414 if (systemStr != null) {
9415 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9416 } else {
9417 // Old settings that don't specify system... just treat
9418 // them as system, good enough.
9419 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009421 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009422 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423 if (timeStampStr != null) {
9424 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009425 timeStamp = Long.parseLong(timeStampStr, 16);
9426 } catch (NumberFormatException e) {
9427 }
9428 } else {
9429 timeStampStr = parser.getAttributeValue(null, "ts");
9430 if (timeStampStr != null) {
9431 try {
9432 timeStamp = Long.parseLong(timeStampStr);
9433 } catch (NumberFormatException e) {
9434 }
9435 }
9436 }
9437 timeStampStr = parser.getAttributeValue(null, "it");
9438 if (timeStampStr != null) {
9439 try {
9440 firstInstallTime = Long.parseLong(timeStampStr, 16);
9441 } catch (NumberFormatException e) {
9442 }
9443 }
9444 timeStampStr = parser.getAttributeValue(null, "ut");
9445 if (timeStampStr != null) {
9446 try {
9447 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 } catch (NumberFormatException e) {
9449 }
9450 }
9451 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9452 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9453 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9454 if (resourcePathStr == null) {
9455 resourcePathStr = codePathStr;
9456 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009457 if (realName != null) {
9458 realName = realName.intern();
9459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009460 if (name == null) {
9461 reportSettingsProblem(Log.WARN,
9462 "Error in package manager settings: <package> has no name at "
9463 + parser.getPositionDescription());
9464 } else if (codePathStr == null) {
9465 reportSettingsProblem(Log.WARN,
9466 "Error in package manager settings: <package> has no codePath at "
9467 + parser.getPositionDescription());
9468 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009469 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9470 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9471 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009472 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9473 + ": userId=" + userId + " pkg=" + packageSetting);
9474 if (packageSetting == null) {
9475 reportSettingsProblem(Log.ERROR,
9476 "Failure adding uid " + userId
9477 + " while parsing settings at "
9478 + parser.getPositionDescription());
9479 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009480 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009481 packageSetting.firstInstallTime = firstInstallTime;
9482 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009483 }
9484 } else if (sharedIdStr != null) {
9485 userId = sharedIdStr != null
9486 ? Integer.parseInt(sharedIdStr) : 0;
9487 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009488 packageSetting = new PendingPackage(name.intern(), realName,
9489 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009490 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009491 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009492 packageSetting.firstInstallTime = firstInstallTime;
9493 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009494 mPendingPackages.add((PendingPackage) packageSetting);
9495 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9496 + ": sharedUserId=" + userId + " pkg="
9497 + packageSetting);
9498 } else {
9499 reportSettingsProblem(Log.WARN,
9500 "Error in package manager settings: package "
9501 + name + " has bad sharedId " + sharedIdStr
9502 + " at " + parser.getPositionDescription());
9503 }
9504 } else {
9505 reportSettingsProblem(Log.WARN,
9506 "Error in package manager settings: package "
9507 + name + " has bad userId " + idStr + " at "
9508 + parser.getPositionDescription());
9509 }
9510 } catch (NumberFormatException e) {
9511 reportSettingsProblem(Log.WARN,
9512 "Error in package manager settings: package "
9513 + name + " has bad userId " + idStr + " at "
9514 + parser.getPositionDescription());
9515 }
9516 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009517 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009518 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009519 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009520 final String enabledStr = parser.getAttributeValue(null, "enabled");
9521 if (enabledStr != null) {
9522 if (enabledStr.equalsIgnoreCase("true")) {
9523 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9524 } else if (enabledStr.equalsIgnoreCase("false")) {
9525 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9526 } else if (enabledStr.equalsIgnoreCase("default")) {
9527 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9528 } else {
9529 reportSettingsProblem(Log.WARN,
9530 "Error in package manager settings: package "
9531 + name + " has bad enabled value: " + idStr
9532 + " at " + parser.getPositionDescription());
9533 }
9534 } else {
9535 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9536 }
9537 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9538 if (installStatusStr != null) {
9539 if (installStatusStr.equalsIgnoreCase("false")) {
9540 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9541 } else {
9542 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9543 }
9544 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009546 int outerDepth = parser.getDepth();
9547 int type;
9548 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9549 && (type != XmlPullParser.END_TAG
9550 || parser.getDepth() > outerDepth)) {
9551 if (type == XmlPullParser.END_TAG
9552 || type == XmlPullParser.TEXT) {
9553 continue;
9554 }
9555
9556 String tagName = parser.getName();
9557 if (tagName.equals("disabled-components")) {
9558 readDisabledComponentsLP(packageSetting, parser);
9559 } else if (tagName.equals("enabled-components")) {
9560 readEnabledComponentsLP(packageSetting, parser);
9561 } else if (tagName.equals("sigs")) {
9562 packageSetting.signatures.readXml(parser, mPastSignatures);
9563 } else if (tagName.equals("perms")) {
9564 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009565 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009566 packageSetting.permissionsFixed = true;
Kenny Root5d40fe92011-01-14 10:54:46 -08009567 } else if (tagName.equals("obbs")) {
9568 readObbPathsLP(packageSetting, parser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569 } else {
9570 reportSettingsProblem(Log.WARN,
9571 "Unknown element under <package>: "
9572 + parser.getName());
9573 XmlUtils.skipCurrentTag(parser);
9574 }
9575 }
9576 } else {
9577 XmlUtils.skipCurrentTag(parser);
9578 }
9579 }
9580
9581 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9582 XmlPullParser parser)
9583 throws IOException, XmlPullParserException {
9584 int outerDepth = parser.getDepth();
9585 int type;
9586 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9587 && (type != XmlPullParser.END_TAG
9588 || parser.getDepth() > outerDepth)) {
9589 if (type == XmlPullParser.END_TAG
9590 || type == XmlPullParser.TEXT) {
9591 continue;
9592 }
9593
9594 String tagName = parser.getName();
9595 if (tagName.equals("item")) {
9596 String name = parser.getAttributeValue(null, "name");
9597 if (name != null) {
9598 packageSetting.disabledComponents.add(name.intern());
9599 } else {
9600 reportSettingsProblem(Log.WARN,
9601 "Error in package manager settings: <disabled-components> has"
9602 + " no name at " + parser.getPositionDescription());
9603 }
9604 } else {
9605 reportSettingsProblem(Log.WARN,
9606 "Unknown element under <disabled-components>: "
9607 + parser.getName());
9608 }
9609 XmlUtils.skipCurrentTag(parser);
9610 }
9611 }
9612
9613 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9614 XmlPullParser parser)
9615 throws IOException, XmlPullParserException {
9616 int outerDepth = parser.getDepth();
9617 int type;
9618 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9619 && (type != XmlPullParser.END_TAG
9620 || parser.getDepth() > outerDepth)) {
9621 if (type == XmlPullParser.END_TAG
9622 || type == XmlPullParser.TEXT) {
9623 continue;
9624 }
9625
9626 String tagName = parser.getName();
9627 if (tagName.equals("item")) {
9628 String name = parser.getAttributeValue(null, "name");
9629 if (name != null) {
9630 packageSetting.enabledComponents.add(name.intern());
9631 } else {
9632 reportSettingsProblem(Log.WARN,
9633 "Error in package manager settings: <enabled-components> has"
9634 + " no name at " + parser.getPositionDescription());
9635 }
9636 } else {
9637 reportSettingsProblem(Log.WARN,
9638 "Unknown element under <enabled-components>: "
9639 + parser.getName());
9640 }
9641 XmlUtils.skipCurrentTag(parser);
9642 }
9643 }
9644
9645 private void readSharedUserLP(XmlPullParser parser)
9646 throws XmlPullParserException, IOException {
9647 String name = null;
9648 String idStr = null;
9649 int pkgFlags = 0;
9650 SharedUserSetting su = null;
9651 try {
9652 name = parser.getAttributeValue(null, "name");
9653 idStr = parser.getAttributeValue(null, "userId");
9654 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9655 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9656 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9657 }
9658 if (name == null) {
9659 reportSettingsProblem(Log.WARN,
9660 "Error in package manager settings: <shared-user> has no name at "
9661 + parser.getPositionDescription());
9662 } else if (userId == 0) {
9663 reportSettingsProblem(Log.WARN,
9664 "Error in package manager settings: shared-user "
9665 + name + " has bad userId " + idStr + " at "
9666 + parser.getPositionDescription());
9667 } else {
9668 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9669 reportSettingsProblem(Log.ERROR,
9670 "Occurred while parsing settings at "
9671 + parser.getPositionDescription());
9672 }
9673 }
9674 } catch (NumberFormatException e) {
9675 reportSettingsProblem(Log.WARN,
9676 "Error in package manager settings: package "
9677 + name + " has bad userId " + idStr + " at "
9678 + parser.getPositionDescription());
9679 };
9680
9681 if (su != null) {
9682 int outerDepth = parser.getDepth();
9683 int type;
9684 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9685 && (type != XmlPullParser.END_TAG
9686 || parser.getDepth() > outerDepth)) {
9687 if (type == XmlPullParser.END_TAG
9688 || type == XmlPullParser.TEXT) {
9689 continue;
9690 }
9691
9692 String tagName = parser.getName();
9693 if (tagName.equals("sigs")) {
9694 su.signatures.readXml(parser, mPastSignatures);
9695 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009696 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697 } else {
9698 reportSettingsProblem(Log.WARN,
9699 "Unknown element under <shared-user>: "
9700 + parser.getName());
9701 XmlUtils.skipCurrentTag(parser);
9702 }
9703 }
9704
9705 } else {
9706 XmlUtils.skipCurrentTag(parser);
9707 }
9708 }
9709
9710 private void readGrantedPermissionsLP(XmlPullParser parser,
9711 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9712 int outerDepth = parser.getDepth();
9713 int type;
9714 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9715 && (type != XmlPullParser.END_TAG
9716 || parser.getDepth() > outerDepth)) {
9717 if (type == XmlPullParser.END_TAG
9718 || type == XmlPullParser.TEXT) {
9719 continue;
9720 }
9721
9722 String tagName = parser.getName();
9723 if (tagName.equals("item")) {
9724 String name = parser.getAttributeValue(null, "name");
9725 if (name != null) {
9726 outPerms.add(name.intern());
9727 } else {
9728 reportSettingsProblem(Log.WARN,
9729 "Error in package manager settings: <perms> has"
9730 + " no name at " + parser.getPositionDescription());
9731 }
9732 } else {
9733 reportSettingsProblem(Log.WARN,
9734 "Unknown element under <perms>: "
9735 + parser.getName());
9736 }
9737 XmlUtils.skipCurrentTag(parser);
9738 }
9739 }
9740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009741 private void readPreferredActivitiesLP(XmlPullParser parser)
9742 throws XmlPullParserException, IOException {
9743 int outerDepth = parser.getDepth();
9744 int type;
9745 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9746 && (type != XmlPullParser.END_TAG
9747 || parser.getDepth() > outerDepth)) {
9748 if (type == XmlPullParser.END_TAG
9749 || type == XmlPullParser.TEXT) {
9750 continue;
9751 }
9752
9753 String tagName = parser.getName();
9754 if (tagName.equals("item")) {
9755 PreferredActivity pa = new PreferredActivity(parser);
9756 if (pa.mParseError == null) {
9757 mPreferredActivities.addFilter(pa);
9758 } else {
9759 reportSettingsProblem(Log.WARN,
9760 "Error in package manager settings: <preferred-activity> "
9761 + pa.mParseError + " at "
9762 + parser.getPositionDescription());
9763 }
9764 } else {
9765 reportSettingsProblem(Log.WARN,
9766 "Unknown element under <preferred-activities>: "
9767 + parser.getName());
9768 XmlUtils.skipCurrentTag(parser);
9769 }
9770 }
9771 }
9772
Kenny Root5d40fe92011-01-14 10:54:46 -08009773 private void readObbPathsLP(PackageSettingBase packageSetting, XmlPullParser parser)
9774 throws XmlPullParserException, IOException {
9775 final List<String> obbPaths = new ArrayList<String>();
9776 final int outerDepth = parser.getDepth();
9777 int type;
9778 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9779 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9780 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9781 continue;
9782 }
9783
9784 final String tagName = parser.getName();
9785 if (tagName.equals("obb")) {
9786 final String path = parser.getAttributeValue(null, "path");
9787 obbPaths.add(path);
9788 } else {
9789 reportSettingsProblem(Log.WARN, "Unknown element under <obbs>: "
9790 + parser.getName());
9791 }
9792 XmlUtils.skipCurrentTag(parser);
9793 }
9794 if (obbPaths.size() == 0) {
9795 return;
9796 } else {
9797 packageSetting.obbPathStrings = obbPaths.toArray(new String[obbPaths.size()]);
9798 }
9799 }
9800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009801 // Returns -1 if we could not find an available UserId to assign
9802 private int newUserIdLP(Object obj) {
9803 // Let's be stupidly inefficient for now...
9804 final int N = mUserIds.size();
9805 for (int i=0; i<N; i++) {
9806 if (mUserIds.get(i) == null) {
9807 mUserIds.set(i, obj);
9808 return FIRST_APPLICATION_UID + i;
9809 }
9810 }
9811
9812 // None left?
9813 if (N >= MAX_APPLICATION_UIDS) {
9814 return -1;
9815 }
9816
9817 mUserIds.add(obj);
9818 return FIRST_APPLICATION_UID + N;
9819 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009821 public PackageSetting getDisabledSystemPkg(String name) {
9822 synchronized(mPackages) {
9823 PackageSetting ps = mDisabledSysPackages.get(name);
9824 return ps;
9825 }
9826 }
9827
9828 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009829 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9830 return true;
9831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9833 if (Config.LOGV) {
9834 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9835 + " componentName = " + componentInfo.name);
9836 Log.v(TAG, "enabledComponents: "
9837 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9838 Log.v(TAG, "disabledComponents: "
9839 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9840 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009841 if (packageSettings == null) {
9842 if (false) {
9843 Log.w(TAG, "WAITING FOR DEBUGGER");
9844 Debug.waitForDebugger();
9845 Log.i(TAG, "We will crash!");
9846 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009847 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009848 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009849 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9850 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9851 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9852 return false;
9853 }
9854 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9855 return true;
9856 }
9857 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9858 return false;
9859 }
9860 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009861 }
9862 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009863
9864 // ------- apps on sdcard specific code -------
9865 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009866 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9867 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9868 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009869 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009870
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009871 private String getEncryptKey() {
9872 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009873 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9874 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009875 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009876 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9877 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009878 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009879 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009880 return null;
9881 }
9882 }
9883 return sdEncKey;
9884 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009885 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009886 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009887 } catch (IOException ioe) {
9888 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9889 + ioe);
9890 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009891 }
Rich Cannings8d578832010-09-09 15:12:40 -07009892
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009893 }
9894
Kenny Rootc78a8072010-07-27 15:18:38 -07009895 /* package */ static String getTempContainerId() {
9896 int tmpIdx = 1;
9897 String list[] = PackageHelper.getSecureContainerList();
9898 if (list != null) {
9899 for (final String name : list) {
9900 // Ignore null and non-temporary container entries
9901 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9902 continue;
9903 }
9904
9905 String subStr = name.substring(mTempContainerPrefix.length());
9906 try {
9907 int cid = Integer.parseInt(subStr);
9908 if (cid >= tmpIdx) {
9909 tmpIdx = cid + 1;
9910 }
9911 } catch (NumberFormatException e) {
9912 }
9913 }
9914 }
9915 return mTempContainerPrefix + tmpIdx;
9916 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009917
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009918 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009919 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009920 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009921 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
Marco Nelissen584f1372010-05-24 16:34:30 -07009922 int callingUid = Binder.getCallingUid();
9923 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009924 throw new SecurityException("Media status can only be updated by the system");
9925 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009926 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009927 Log.i(TAG, "Updating external media status from " +
9928 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9929 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009930 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9931 mediaStatus+", mMediaMounted=" + mMediaMounted);
9932 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009933 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9934 reportStatus ? 1 : 0, -1);
9935 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009936 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009937 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009938 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009939 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009940 // Queue up an async operation since the package installation may take a little while.
9941 mHandler.post(new Runnable() {
9942 public void run() {
9943 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009944 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009945 }
9946 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009947 }
9948
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009949 /*
9950 * Collect information of applications on external media, map them
9951 * against existing containers and update information based on current
9952 * mount status. Please note that we always have to report status
9953 * if reportStatus has been set to true especially when unloading packages.
9954 */
9955 private void updateExternalMediaStatusInner(boolean mediaStatus,
9956 boolean reportStatus) {
9957 // Collection of uids
9958 int uidArr[] = null;
9959 // Collection of stale containers
9960 HashSet<String> removeCids = new HashSet<String>();
9961 // Collection of packages on external media with valid containers.
9962 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9963 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009964 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009965 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009966 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009967 } else {
9968 // Process list of secure containers and categorize them
9969 // as active or stale based on their package internal state.
9970 int uidList[] = new int[list.length];
9971 int num = 0;
9972 synchronized (mPackages) {
9973 for (String cid : list) {
9974 SdInstallArgs args = new SdInstallArgs(cid);
9975 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009976 String pkgName = args.getPackageName();
9977 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009978 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9979 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009980 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009981 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009982 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9983 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009984 // The package status is changed only if the code path
9985 // matches between settings and the container id.
9986 if (ps != null && ps.codePathString != null &&
9987 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009988 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9989 " corresponds to pkg : " + pkgName +
9990 " at code path: " + ps.codePathString);
9991 // We do have a valid package installed on sdcard
9992 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009993 int uid = ps.userId;
9994 if (uid != -1) {
9995 uidList[num++] = uid;
9996 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009997 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009998 // Stale container on sdcard. Just delete
9999 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
10000 removeCids.add(cid);
10001 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080010002 }
10003 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010004
10005 if (num > 0) {
10006 // Sort uid list
10007 Arrays.sort(uidList, 0, num);
10008 // Throw away duplicates
10009 uidArr = new int[num];
10010 uidArr[0] = uidList[0];
10011 int di = 0;
10012 for (int i = 1; i < num; i++) {
10013 if (uidList[i-1] != uidList[i]) {
10014 uidArr[di++] = uidList[i];
10015 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010016 }
10017 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010018 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010019 // Process packages with valid entries.
10020 if (mediaStatus) {
10021 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010022 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010023 startCleaningPackages();
10024 } else {
10025 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010026 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010027 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010028 }
10029
10030 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010031 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010032 int size = pkgList.size();
10033 if (size > 0) {
10034 // Send broadcasts here
10035 Bundle extras = new Bundle();
10036 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
10037 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010038 if (uidArr != null) {
10039 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
10040 }
10041 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
10042 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010043 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010044 }
10045 }
10046
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010047 /*
10048 * Look at potentially valid container ids from processCids
10049 * If package information doesn't match the one on record
10050 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010051 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010052 */
10053 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010054 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010055 ArrayList<String> pkgList = new ArrayList<String>();
10056 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010057 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010058 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010059 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010060 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
10061 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010062 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010063 try {
10064 // Make sure there are no container errors first.
10065 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
10066 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -080010067 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010068 " when installing from sdcard");
10069 continue;
10070 }
10071 // Check code path here.
10072 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -080010073 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010074 " does not match one in settings " + codePath);
10075 continue;
10076 }
10077 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -070010078 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010079 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010080 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010081 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -070010082 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010083 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010084 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010085 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010086 retCode = PackageManager.INSTALL_SUCCEEDED;
10087 pkgList.add(pkg.packageName);
10088 // Post process args
10089 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
10090 }
10091 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010092 Slog.i(TAG, "Failed to install pkg from " +
10093 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010094 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010095 }
10096
10097 } finally {
10098 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
10099 // Don't destroy container here. Wait till gc clears things up.
10100 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010101 }
10102 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010103 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010104 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -070010105 // If the platform SDK has changed since the last time we booted,
10106 // we need to re-grant app permission to catch any new ones that
10107 // appear. This is really a hack, and means that apps can in some
10108 // cases get permissions that the user didn't initially explicitly
10109 // allow... it would be nice to have some better way to handle
10110 // this situation.
10111 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
10112 != mSdkVersion;
10113 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
10114 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
10115 + "; regranting permissions for external storage");
10116 mSettings.mExternalSdkPlatform = mSdkVersion;
10117
Dianne Hackbornaf7cea32010-03-24 12:59:52 -070010118 // Make sure group IDs have been assigned, and any permission
10119 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -070010120 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010121 // Persist settings
10122 mSettings.writeLP();
10123 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080010124 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010125 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010126 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010127 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010128 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010129 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010130 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010131 }
Kenny Rootf369a9b2010-07-28 14:47:01 -070010132 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010133 if (removeCids != null) {
10134 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -070010135 if (cid.startsWith(mTempContainerPrefix)) {
10136 Log.i(TAG, "Destroying stale temporary container " + cid);
10137 PackageHelper.destroySdDir(cid);
10138 } else {
10139 Log.w(TAG, "Container " + cid + " is stale");
10140 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010141 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010142 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010143 }
10144
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010145 /*
10146 * Utility method to unload a list of specified containers
10147 */
10148 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
10149 // Just unmount all valid containers.
10150 for (SdInstallArgs arg : cidArgs) {
10151 synchronized (mInstallLock) {
10152 arg.doPostDeleteLI(false);
10153 }
10154 }
10155 }
10156
10157 /*
10158 * Unload packages mounted on external media. This involves deleting
10159 * package data from internal structures, sending broadcasts about
10160 * diabled packages, gc'ing to free up references, unmounting all
10161 * secure containers corresponding to packages on external media, and
10162 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
10163 * Please note that we always have to post this message if status has
10164 * been requested no matter what.
10165 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010166 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010167 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010168 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010169 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010170 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010171 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010172 for (SdInstallArgs args : keys) {
10173 String cid = args.cid;
10174 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010175 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010176 // Delete package internally
10177 PackageRemovedInfo outInfo = new PackageRemovedInfo();
10178 synchronized (mInstallLock) {
10179 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010180 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010181 if (res) {
10182 pkgList.add(pkgName);
10183 } else {
Jeff Brown07330792010-03-30 19:57:08 -070010184 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010185 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010186 }
10187 }
10188 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010189
10190 synchronized (mPackages) {
10191 // We didn't update the settings after removing each package;
10192 // write them now for all packages.
10193 mSettings.writeLP();
10194 }
10195
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010196 // We have to absolutely send UPDATED_MEDIA_STATUS only
10197 // after confirming that all the receivers processed the ordered
10198 // broadcast when packages get disabled, force a gc to clean things up.
10199 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010200 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010201 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
10202 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
10203 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010204 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10205 reportStatus ? 1 : 0, 1, keys);
10206 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010207 }
10208 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010209 } else {
10210 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10211 reportStatus ? 1 : 0, -1, keys);
10212 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010213 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -080010214 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010215
10216 public void movePackage(final String packageName,
10217 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010218 mContext.enforceCallingOrSelfPermission(
10219 android.Manifest.permission.MOVE_PACKAGE, null);
10220 int returnCode = PackageManager.MOVE_SUCCEEDED;
10221 int currFlags = 0;
10222 int newFlags = 0;
10223 synchronized (mPackages) {
10224 PackageParser.Package pkg = mPackages.get(packageName);
10225 if (pkg == null) {
10226 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010227 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010228 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -070010229 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010230 Slog.w(TAG, "Cannot move system application");
10231 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -070010232 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010233 Slog.w(TAG, "Cannot move forward locked app.");
10234 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -070010235 } else if (pkg.mOperationPending) {
10236 Slog.w(TAG, "Attempt to move package which has pending operations");
10237 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010238 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010239 // Find install location first
10240 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
10241 (flags & PackageManager.MOVE_INTERNAL) != 0) {
10242 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010243 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010244 } else {
10245 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
10246 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -070010247 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
10248 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010249 if (newFlags == currFlags) {
10250 Slog.w(TAG, "No move required. Trying to move to same location");
10251 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
10252 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010253 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010254 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10255 pkg.mOperationPending = true;
10256 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010257 }
10258 }
10259 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -070010260 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010261 } else {
10262 Message msg = mHandler.obtainMessage(INIT_COPY);
10263 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -070010264 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
10265 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
10266 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010267 msg.obj = mp;
10268 mHandler.sendMessage(msg);
10269 }
10270 }
10271 }
10272
10273 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10274 // Queue up an async operation since the package deletion may take a little while.
10275 mHandler.post(new Runnable() {
10276 public void run() {
10277 mHandler.removeCallbacks(this);
10278 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010279 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10280 int uidArr[] = null;
10281 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010282 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010283 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010284 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010285 Slog.w(TAG, " Package " + mp.packageName +
10286 " doesn't exist. Aborting move");
10287 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10288 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10289 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10290 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10291 " Aborting move and returning error");
10292 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10293 } else {
10294 uidArr = new int[] { pkg.applicationInfo.uid };
10295 pkgList = new ArrayList<String>();
10296 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010297 }
10298 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010299 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10300 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010301 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010302 // Update package code and resource paths
10303 synchronized (mInstallLock) {
10304 synchronized (mPackages) {
10305 PackageParser.Package pkg = mPackages.get(mp.packageName);
10306 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010307 if (pkg == null) {
10308 Slog.w(TAG, " Package " + mp.packageName
10309 + " doesn't exist. Aborting move");
10310 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010311 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10312 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10313 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10314 " Aborting move and returning error");
10315 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10316 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010317 final String oldCodePath = pkg.mPath;
10318 final String newCodePath = mp.targetArgs.getCodePath();
10319 final String newResPath = mp.targetArgs.getResourcePath();
10320 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010321
10322 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10323 if (mInstaller
10324 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10325 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10326 } else {
10327 NativeLibraryHelper.copyNativeBinariesLI(
10328 new File(newCodePath), new File(newNativePath));
10329 }
10330 } else {
10331 if (mInstaller.linkNativeLibraryDirectory(
10332 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10333 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10334 }
10335 }
10336
10337 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10338 pkg.mPath = newCodePath;
10339 // Move dex files around
10340 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10341 // Moving of dex files failed. Set
10342 // error code and abort move.
10343 pkg.mPath = pkg.mScanPath;
10344 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10345 }
10346 }
10347
10348 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010349 pkg.mScanPath = newCodePath;
10350 pkg.applicationInfo.sourceDir = newCodePath;
10351 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010352 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010353 PackageSetting ps = (PackageSetting) pkg.mExtras;
10354 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10355 ps.codePathString = ps.codePath.getPath();
10356 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10357 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010358 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010359 // Set the application info flag correctly.
10360 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10361 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10362 } else {
10363 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10364 }
10365 ps.setFlags(pkg.applicationInfo.flags);
10366 mAppDirs.remove(oldCodePath);
10367 mAppDirs.put(newCodePath, pkg);
10368 // Persist settings
10369 mSettings.writeLP();
10370 }
10371 }
10372 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010373 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010374 // Send resources available broadcast
10375 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010376 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010377 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010378 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010379 // Clean up failed installation
10380 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010381 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010382 }
10383 } else {
10384 // Force a gc to clear things up.
10385 Runtime.getRuntime().gc();
10386 // Delete older code
10387 synchronized (mInstallLock) {
10388 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010389 }
10390 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010391
10392 // Allow more operations on this file if we didn't fail because
10393 // an operation was already pending for this package.
10394 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10395 synchronized (mPackages) {
10396 PackageParser.Package pkg = mPackages.get(mp.packageName);
10397 if (pkg != null) {
10398 pkg.mOperationPending = false;
10399 }
10400 }
10401 }
10402
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010403 IPackageMoveObserver observer = mp.observer;
10404 if (observer != null) {
10405 try {
10406 observer.packageMoved(mp.packageName, returnCode);
10407 } catch (RemoteException e) {
10408 Log.i(TAG, "Observer no longer exists.");
10409 }
10410 }
10411 }
10412 });
10413 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010414
10415 public boolean setInstallLocation(int loc) {
10416 mContext.enforceCallingOrSelfPermission(
10417 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10418 if (getInstallLocation() == loc) {
10419 return true;
10420 }
10421 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10422 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10423 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10424 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10425 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10426 return true;
10427 }
10428 return false;
10429 }
10430
10431 public int getInstallLocation() {
10432 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10433 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010435}