blob: cc7a027feee330f03fb30dab2f432a22086e6c27 [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
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import 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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import 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;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import 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;
57import android.content.pm.PackageStats;
58import 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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import 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;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import 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;
Kenny Root85387d72010-08-26 10:13:11 -0700117import 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;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800122import 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 Pellybc21fde2010-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,
574 (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 Pellybc21fde2010-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) {
967 // XXX how to set useEncryptedFSDir for packages that
968 // are not encrypted?
969 mInstaller.remove(ps.name, true);
970 }
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) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001053 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 }
1228 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001229 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001231 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
1234
1235 void readPermission(XmlPullParser parser, String name)
1236 throws IOException, XmlPullParserException {
1237
1238 name = name.intern();
1239
1240 BasePermission bp = mSettings.mPermissions.get(name);
1241 if (bp == null) {
1242 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1243 mSettings.mPermissions.put(name, bp);
1244 }
1245 int outerDepth = parser.getDepth();
1246 int type;
1247 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1248 && (type != XmlPullParser.END_TAG
1249 || parser.getDepth() > outerDepth)) {
1250 if (type == XmlPullParser.END_TAG
1251 || type == XmlPullParser.TEXT) {
1252 continue;
1253 }
1254
1255 String tagName = parser.getName();
1256 if ("group".equals(tagName)) {
1257 String gidStr = parser.getAttributeValue(null, "gid");
1258 if (gidStr != null) {
1259 int gid = Process.getGidForName(gidStr);
1260 bp.gids = appendInt(bp.gids, gid);
1261 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001262 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 + parser.getPositionDescription());
1264 }
1265 }
1266 XmlUtils.skipCurrentTag(parser);
1267 }
1268 }
1269
1270 static int[] appendInt(int[] cur, int val) {
1271 if (cur == null) {
1272 return new int[] { val };
1273 }
1274 final int N = cur.length;
1275 for (int i=0; i<N; i++) {
1276 if (cur[i] == val) {
1277 return cur;
1278 }
1279 }
1280 int[] ret = new int[N+1];
1281 System.arraycopy(cur, 0, ret, 0, N);
1282 ret[N] = val;
1283 return ret;
1284 }
1285
1286 static int[] appendInts(int[] cur, int[] add) {
1287 if (add == null) return cur;
1288 if (cur == null) return add;
1289 final int N = add.length;
1290 for (int i=0; i<N; i++) {
1291 cur = appendInt(cur, add[i]);
1292 }
1293 return cur;
1294 }
1295
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001296 static int[] removeInt(int[] cur, int val) {
1297 if (cur == null) {
1298 return null;
1299 }
1300 final int N = cur.length;
1301 for (int i=0; i<N; i++) {
1302 if (cur[i] == val) {
1303 int[] ret = new int[N-1];
1304 if (i > 0) {
1305 System.arraycopy(cur, 0, ret, 0, i);
1306 }
1307 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001308 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001309 }
1310 return ret;
1311 }
1312 }
1313 return cur;
1314 }
1315
1316 static int[] removeInts(int[] cur, int[] rem) {
1317 if (rem == null) return cur;
1318 if (cur == null) return cur;
1319 final int N = rem.length;
1320 for (int i=0; i<N; i++) {
1321 cur = removeInt(cur, rem[i]);
1322 }
1323 return cur;
1324 }
1325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001327 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1328 // The package has been uninstalled but has retained data and resources.
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001329 return PackageParser.generatePackageInfo(p, null, flags, 0, 0);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 final PackageSetting ps = (PackageSetting)p.mExtras;
1332 if (ps == null) {
1333 return null;
1334 }
1335 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001336 return PackageParser.generatePackageInfo(p, gp.gids, flags,
1337 ps.firstInstallTime, ps.lastUpdateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 }
1339
1340 public PackageInfo getPackageInfo(String packageName, int flags) {
1341 synchronized (mPackages) {
1342 PackageParser.Package p = mPackages.get(packageName);
1343 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001344 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 + ": " + p);
1346 if (p != null) {
1347 return generatePackageInfo(p, flags);
1348 }
1349 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1350 return generatePackageInfoFromSettingsLP(packageName, flags);
1351 }
1352 }
1353 return null;
1354 }
1355
Dianne Hackborn47096932010-02-11 15:57:09 -08001356 public String[] currentToCanonicalPackageNames(String[] names) {
1357 String[] out = new String[names.length];
1358 synchronized (mPackages) {
1359 for (int i=names.length-1; i>=0; i--) {
1360 PackageSetting ps = mSettings.mPackages.get(names[i]);
1361 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1362 }
1363 }
1364 return out;
1365 }
1366
1367 public String[] canonicalToCurrentPackageNames(String[] names) {
1368 String[] out = new String[names.length];
1369 synchronized (mPackages) {
1370 for (int i=names.length-1; i>=0; i--) {
1371 String cur = mSettings.mRenamedPackages.get(names[i]);
1372 out[i] = cur != null ? cur : names[i];
1373 }
1374 }
1375 return out;
1376 }
1377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 public int getPackageUid(String packageName) {
1379 synchronized (mPackages) {
1380 PackageParser.Package p = mPackages.get(packageName);
1381 if(p != null) {
1382 return p.applicationInfo.uid;
1383 }
1384 PackageSetting ps = mSettings.mPackages.get(packageName);
1385 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1386 return -1;
1387 }
1388 p = ps.pkg;
1389 return p != null ? p.applicationInfo.uid : -1;
1390 }
1391 }
1392
1393 public int[] getPackageGids(String packageName) {
1394 synchronized (mPackages) {
1395 PackageParser.Package p = mPackages.get(packageName);
1396 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001397 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 + ": " + p);
1399 if (p != null) {
1400 final PackageSetting ps = (PackageSetting)p.mExtras;
1401 final SharedUserSetting suid = ps.sharedUser;
1402 return suid != null ? suid.gids : ps.gids;
1403 }
1404 }
1405 // stupid thing to indicate an error.
1406 return new int[0];
1407 }
1408
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001409 static final PermissionInfo generatePermissionInfo(
1410 BasePermission bp, int flags) {
1411 if (bp.perm != null) {
1412 return PackageParser.generatePermissionInfo(bp.perm, flags);
1413 }
1414 PermissionInfo pi = new PermissionInfo();
1415 pi.name = bp.name;
1416 pi.packageName = bp.sourcePackage;
1417 pi.nonLocalizedLabel = bp.name;
1418 pi.protectionLevel = bp.protectionLevel;
1419 return pi;
1420 }
1421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 public PermissionInfo getPermissionInfo(String name, int flags) {
1423 synchronized (mPackages) {
1424 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001425 if (p != null) {
1426 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428 return null;
1429 }
1430 }
1431
1432 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1433 synchronized (mPackages) {
1434 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1435 for (BasePermission p : mSettings.mPermissions.values()) {
1436 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001437 if (p.perm == null || p.perm.info.group == null) {
1438 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001441 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1443 }
1444 }
1445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 if (out.size() > 0) {
1448 return out;
1449 }
1450 return mPermissionGroups.containsKey(group) ? out : null;
1451 }
1452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1455 synchronized (mPackages) {
1456 return PackageParser.generatePermissionGroupInfo(
1457 mPermissionGroups.get(name), flags);
1458 }
1459 }
1460
1461 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1462 synchronized (mPackages) {
1463 final int N = mPermissionGroups.size();
1464 ArrayList<PermissionGroupInfo> out
1465 = new ArrayList<PermissionGroupInfo>(N);
1466 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1467 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1468 }
1469 return out;
1470 }
1471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1474 PackageSetting ps = mSettings.mPackages.get(packageName);
1475 if(ps != null) {
1476 if(ps.pkg == null) {
1477 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1478 if(pInfo != null) {
1479 return pInfo.applicationInfo;
1480 }
1481 return null;
1482 }
1483 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1484 }
1485 return null;
1486 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1489 PackageSetting ps = mSettings.mPackages.get(packageName);
1490 if(ps != null) {
1491 if(ps.pkg == null) {
1492 ps.pkg = new PackageParser.Package(packageName);
1493 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001494 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1495 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1496 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1497 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001498 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001499 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 }
1501 return generatePackageInfo(ps.pkg, flags);
1502 }
1503 return null;
1504 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1507 synchronized (mPackages) {
1508 PackageParser.Package p = mPackages.get(packageName);
1509 if (Config.LOGV) Log.v(
1510 TAG, "getApplicationInfo " + packageName
1511 + ": " + p);
1512 if (p != null) {
1513 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001514 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516 if ("android".equals(packageName)||"system".equals(packageName)) {
1517 return mAndroidApplication;
1518 }
1519 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1520 return generateApplicationInfoFromSettingsLP(packageName, flags);
1521 }
1522 }
1523 return null;
1524 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001525
1526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1528 mContext.enforceCallingOrSelfPermission(
1529 android.Manifest.permission.CLEAR_APP_CACHE, null);
1530 // Queue up an async operation since clearing cache may take a little while.
1531 mHandler.post(new Runnable() {
1532 public void run() {
1533 mHandler.removeCallbacks(this);
1534 int retCode = -1;
1535 if (mInstaller != null) {
1536 retCode = mInstaller.freeCache(freeStorageSize);
1537 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001538 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 } //end if mInstaller
1541 if (observer != null) {
1542 try {
1543 observer.onRemoveCompleted(null, (retCode >= 0));
1544 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001545 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547 }
1548 }
1549 });
1550 }
1551
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001552 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001553 mContext.enforceCallingOrSelfPermission(
1554 android.Manifest.permission.CLEAR_APP_CACHE, null);
1555 // Queue up an async operation since clearing cache may take a little while.
1556 mHandler.post(new Runnable() {
1557 public void run() {
1558 mHandler.removeCallbacks(this);
1559 int retCode = -1;
1560 if (mInstaller != null) {
1561 retCode = mInstaller.freeCache(freeStorageSize);
1562 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001563 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001564 }
1565 }
1566 if(pi != null) {
1567 try {
1568 // Callback via pending intent
1569 int code = (retCode >= 0) ? 1 : 0;
1570 pi.sendIntent(null, code, null,
1571 null, null);
1572 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001573 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001574 }
1575 }
1576 }
1577 });
1578 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1581 synchronized (mPackages) {
1582 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001583
1584 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001586 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
1588 if (mResolveComponentName.equals(component)) {
1589 return mResolveActivity;
1590 }
1591 }
1592 return null;
1593 }
1594
1595 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1596 synchronized (mPackages) {
1597 PackageParser.Activity a = mReceivers.mActivities.get(component);
1598 if (Config.LOGV) Log.v(
1599 TAG, "getReceiverInfo " + component + ": " + a);
1600 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1601 return PackageParser.generateActivityInfo(a, flags);
1602 }
1603 }
1604 return null;
1605 }
1606
1607 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1608 synchronized (mPackages) {
1609 PackageParser.Service s = mServices.mServices.get(component);
1610 if (Config.LOGV) Log.v(
1611 TAG, "getServiceInfo " + component + ": " + s);
1612 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1613 return PackageParser.generateServiceInfo(s, flags);
1614 }
1615 }
1616 return null;
1617 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001618
Dianne Hackborn361199b2010-08-30 17:42:07 -07001619 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1620 synchronized (mPackages) {
1621 PackageParser.Provider p = mProvidersByComponent.get(component);
1622 if (Config.LOGV) Log.v(
1623 TAG, "getProviderInfo " + component + ": " + p);
1624 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1625 return PackageParser.generateProviderInfo(p, flags);
1626 }
1627 }
1628 return null;
1629 }
1630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 public String[] getSystemSharedLibraryNames() {
1632 Set<String> libSet;
1633 synchronized (mPackages) {
1634 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001635 int size = libSet.size();
1636 if (size > 0) {
1637 String[] libs = new String[size];
1638 libSet.toArray(libs);
1639 return libs;
1640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001642 return null;
1643 }
1644
1645 public FeatureInfo[] getSystemAvailableFeatures() {
1646 Collection<FeatureInfo> featSet;
1647 synchronized (mPackages) {
1648 featSet = mAvailableFeatures.values();
1649 int size = featSet.size();
1650 if (size > 0) {
1651 FeatureInfo[] features = new FeatureInfo[size+1];
1652 featSet.toArray(features);
1653 FeatureInfo fi = new FeatureInfo();
1654 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1655 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1656 features[size] = fi;
1657 return features;
1658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 }
1660 return null;
1661 }
1662
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001663 public boolean hasSystemFeature(String name) {
1664 synchronized (mPackages) {
1665 return mAvailableFeatures.containsKey(name);
1666 }
1667 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 public int checkPermission(String permName, String pkgName) {
1670 synchronized (mPackages) {
1671 PackageParser.Package p = mPackages.get(pkgName);
1672 if (p != null && p.mExtras != null) {
1673 PackageSetting ps = (PackageSetting)p.mExtras;
1674 if (ps.sharedUser != null) {
1675 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1676 return PackageManager.PERMISSION_GRANTED;
1677 }
1678 } else if (ps.grantedPermissions.contains(permName)) {
1679 return PackageManager.PERMISSION_GRANTED;
1680 }
1681 }
1682 }
1683 return PackageManager.PERMISSION_DENIED;
1684 }
1685
1686 public int checkUidPermission(String permName, int uid) {
1687 synchronized (mPackages) {
1688 Object obj = mSettings.getUserIdLP(uid);
1689 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001690 GrantedPermissions gp = (GrantedPermissions)obj;
1691 if (gp.grantedPermissions.contains(permName)) {
1692 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694 } else {
1695 HashSet<String> perms = mSystemPermissions.get(uid);
1696 if (perms != null && perms.contains(permName)) {
1697 return PackageManager.PERMISSION_GRANTED;
1698 }
1699 }
1700 }
1701 return PackageManager.PERMISSION_DENIED;
1702 }
1703
1704 private BasePermission findPermissionTreeLP(String permName) {
1705 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1706 if (permName.startsWith(bp.name) &&
1707 permName.length() > bp.name.length() &&
1708 permName.charAt(bp.name.length()) == '.') {
1709 return bp;
1710 }
1711 }
1712 return null;
1713 }
1714
1715 private BasePermission checkPermissionTreeLP(String permName) {
1716 if (permName != null) {
1717 BasePermission bp = findPermissionTreeLP(permName);
1718 if (bp != null) {
1719 if (bp.uid == Binder.getCallingUid()) {
1720 return bp;
1721 }
1722 throw new SecurityException("Calling uid "
1723 + Binder.getCallingUid()
1724 + " is not allowed to add to permission tree "
1725 + bp.name + " owned by uid " + bp.uid);
1726 }
1727 }
1728 throw new SecurityException("No permission tree found for " + permName);
1729 }
1730
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001731 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1732 if (s1 == null) {
1733 return s2 == null;
1734 }
1735 if (s2 == null) {
1736 return false;
1737 }
1738 if (s1.getClass() != s2.getClass()) {
1739 return false;
1740 }
1741 return s1.equals(s2);
1742 }
1743
1744 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1745 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001746 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001747 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1748 if (!compareStrings(pi1.name, pi2.name)) return false;
1749 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1750 // We'll take care of setting this one.
1751 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1752 // These are not currently stored in settings.
1753 //if (!compareStrings(pi1.group, pi2.group)) return false;
1754 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1755 //if (pi1.labelRes != pi2.labelRes) return false;
1756 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1757 return true;
1758 }
1759
1760 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1761 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1762 throw new SecurityException("Label must be specified in permission");
1763 }
1764 BasePermission tree = checkPermissionTreeLP(info.name);
1765 BasePermission bp = mSettings.mPermissions.get(info.name);
1766 boolean added = bp == null;
1767 boolean changed = true;
1768 if (added) {
1769 bp = new BasePermission(info.name, tree.sourcePackage,
1770 BasePermission.TYPE_DYNAMIC);
1771 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1772 throw new SecurityException(
1773 "Not allowed to modify non-dynamic permission "
1774 + info.name);
1775 } else {
1776 if (bp.protectionLevel == info.protectionLevel
1777 && bp.perm.owner.equals(tree.perm.owner)
1778 && bp.uid == tree.uid
1779 && comparePermissionInfos(bp.perm.info, info)) {
1780 changed = false;
1781 }
1782 }
1783 bp.protectionLevel = info.protectionLevel;
1784 bp.perm = new PackageParser.Permission(tree.perm.owner,
1785 new PermissionInfo(info));
1786 bp.perm.info.packageName = tree.perm.info.packageName;
1787 bp.uid = tree.uid;
1788 if (added) {
1789 mSettings.mPermissions.put(info.name, bp);
1790 }
1791 if (changed) {
1792 if (!async) {
1793 mSettings.writeLP();
1794 } else {
1795 scheduleWriteSettingsLocked();
1796 }
1797 }
1798 return added;
1799 }
1800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 public boolean addPermission(PermissionInfo info) {
1802 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001803 return addPermissionLocked(info, false);
1804 }
1805 }
1806
1807 public boolean addPermissionAsync(PermissionInfo info) {
1808 synchronized (mPackages) {
1809 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 }
1811 }
1812
1813 public void removePermission(String name) {
1814 synchronized (mPackages) {
1815 checkPermissionTreeLP(name);
1816 BasePermission bp = mSettings.mPermissions.get(name);
1817 if (bp != null) {
1818 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1819 throw new SecurityException(
1820 "Not allowed to modify non-dynamic permission "
1821 + name);
1822 }
1823 mSettings.mPermissions.remove(name);
1824 mSettings.writeLP();
1825 }
1826 }
1827 }
1828
Dianne Hackborn854060af2009-07-09 18:14:31 -07001829 public boolean isProtectedBroadcast(String actionName) {
1830 synchronized (mPackages) {
1831 return mProtectedBroadcasts.contains(actionName);
1832 }
1833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 public int checkSignatures(String pkg1, String pkg2) {
1836 synchronized (mPackages) {
1837 PackageParser.Package p1 = mPackages.get(pkg1);
1838 PackageParser.Package p2 = mPackages.get(pkg2);
1839 if (p1 == null || p1.mExtras == null
1840 || p2 == null || p2.mExtras == null) {
1841 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1842 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001843 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
1845 }
1846
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001847 public int checkUidSignatures(int uid1, int uid2) {
1848 synchronized (mPackages) {
1849 Signature[] s1;
1850 Signature[] s2;
1851 Object obj = mSettings.getUserIdLP(uid1);
1852 if (obj != null) {
1853 if (obj instanceof SharedUserSetting) {
1854 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1855 } else if (obj instanceof PackageSetting) {
1856 s1 = ((PackageSetting)obj).signatures.mSignatures;
1857 } else {
1858 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1859 }
1860 } else {
1861 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1862 }
1863 obj = mSettings.getUserIdLP(uid2);
1864 if (obj != null) {
1865 if (obj instanceof SharedUserSetting) {
1866 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1867 } else if (obj instanceof PackageSetting) {
1868 s2 = ((PackageSetting)obj).signatures.mSignatures;
1869 } else {
1870 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1871 }
1872 } else {
1873 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1874 }
1875 return checkSignaturesLP(s1, s2);
1876 }
1877 }
1878
1879 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1880 if (s1 == null) {
1881 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1883 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1884 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001885 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1887 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001888 HashSet<Signature> set1 = new HashSet<Signature>();
1889 for (Signature sig : s1) {
1890 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001892 HashSet<Signature> set2 = new HashSet<Signature>();
1893 for (Signature sig : s2) {
1894 set2.add(sig);
1895 }
1896 // Make sure s2 contains all signatures in s1.
1897 if (set1.equals(set2)) {
1898 return PackageManager.SIGNATURE_MATCH;
1899 }
1900 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
1902
1903 public String[] getPackagesForUid(int uid) {
1904 synchronized (mPackages) {
1905 Object obj = mSettings.getUserIdLP(uid);
1906 if (obj instanceof SharedUserSetting) {
1907 SharedUserSetting sus = (SharedUserSetting)obj;
1908 final int N = sus.packages.size();
1909 String[] res = new String[N];
1910 Iterator<PackageSetting> it = sus.packages.iterator();
1911 int i=0;
1912 while (it.hasNext()) {
1913 res[i++] = it.next().name;
1914 }
1915 return res;
1916 } else if (obj instanceof PackageSetting) {
1917 PackageSetting ps = (PackageSetting)obj;
1918 return new String[] { ps.name };
1919 }
1920 }
1921 return null;
1922 }
1923
1924 public String getNameForUid(int uid) {
1925 synchronized (mPackages) {
1926 Object obj = mSettings.getUserIdLP(uid);
1927 if (obj instanceof SharedUserSetting) {
1928 SharedUserSetting sus = (SharedUserSetting)obj;
1929 return sus.name + ":" + sus.userId;
1930 } else if (obj instanceof PackageSetting) {
1931 PackageSetting ps = (PackageSetting)obj;
1932 return ps.name;
1933 }
1934 }
1935 return null;
1936 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 public int getUidForSharedUser(String sharedUserName) {
1939 if(sharedUserName == null) {
1940 return -1;
1941 }
1942 synchronized (mPackages) {
1943 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1944 if(suid == null) {
1945 return -1;
1946 }
1947 return suid.userId;
1948 }
1949 }
1950
1951 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1952 int flags) {
1953 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001954 return chooseBestActivity(intent, resolvedType, flags, query);
1955 }
1956
Mihai Predaeae850c2009-05-13 10:13:48 +02001957 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1958 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 if (query != null) {
1960 final int N = query.size();
1961 if (N == 1) {
1962 return query.get(0);
1963 } else if (N > 1) {
1964 // If there is more than one activity with the same priority,
1965 // then let the user decide between them.
1966 ResolveInfo r0 = query.get(0);
1967 ResolveInfo r1 = query.get(1);
1968 if (false) {
1969 System.out.println(r0.activityInfo.name +
1970 "=" + r0.priority + " vs " +
1971 r1.activityInfo.name +
1972 "=" + r1.priority);
1973 }
1974 // If the first activity has a higher priority, or a different
1975 // default, then it is always desireable to pick it.
1976 if (r0.priority != r1.priority
1977 || r0.preferredOrder != r1.preferredOrder
1978 || r0.isDefault != r1.isDefault) {
1979 return query.get(0);
1980 }
1981 // If we have saved a preference for a preferred activity for
1982 // this Intent, use that.
1983 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1984 flags, query, r0.priority);
1985 if (ri != null) {
1986 return ri;
1987 }
1988 return mResolveInfo;
1989 }
1990 }
1991 return null;
1992 }
1993
1994 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1995 int flags, List<ResolveInfo> query, int priority) {
1996 synchronized (mPackages) {
1997 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1998 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001999 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2001 if (prefs != null && prefs.size() > 0) {
2002 // First figure out how good the original match set is.
2003 // We will only allow preferred activities that came
2004 // from the same match quality.
2005 int match = 0;
2006 final int N = query.size();
2007 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2008 for (int j=0; j<N; j++) {
2009 ResolveInfo ri = query.get(j);
2010 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2011 + ": 0x" + Integer.toHexString(match));
2012 if (ri.match > match) match = ri.match;
2013 }
2014 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2015 + Integer.toHexString(match));
2016 match &= IntentFilter.MATCH_CATEGORY_MASK;
2017 final int M = prefs.size();
2018 for (int i=0; i<M; i++) {
2019 PreferredActivity pa = prefs.get(i);
2020 if (pa.mMatch != match) {
2021 continue;
2022 }
2023 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2024 if (DEBUG_PREFERRED) {
2025 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002026 if (ai != null) {
2027 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2028 } else {
2029 Log.v(TAG, " null");
2030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
2032 if (ai != null) {
2033 for (int j=0; j<N; j++) {
2034 ResolveInfo ri = query.get(j);
2035 if (!ri.activityInfo.applicationInfo.packageName
2036 .equals(ai.applicationInfo.packageName)) {
2037 continue;
2038 }
2039 if (!ri.activityInfo.name.equals(ai.name)) {
2040 continue;
2041 }
2042
2043 // Okay we found a previously set preferred app.
2044 // If the result set is different from when this
2045 // was created, we need to clear it and re-ask the
2046 // user their preference.
2047 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002048 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 + intent + " type " + resolvedType);
2050 mSettings.mPreferredActivities.removeFilter(pa);
2051 return null;
2052 }
2053
2054 // Yay!
2055 return ri;
2056 }
2057 }
2058 }
2059 }
2060 }
2061 return null;
2062 }
2063
2064 public List<ResolveInfo> queryIntentActivities(Intent intent,
2065 String resolvedType, int flags) {
2066 ComponentName comp = intent.getComponent();
2067 if (comp != null) {
2068 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2069 ActivityInfo ai = getActivityInfo(comp, flags);
2070 if (ai != null) {
2071 ResolveInfo ri = new ResolveInfo();
2072 ri.activityInfo = ai;
2073 list.add(ri);
2074 }
2075 return list;
2076 }
2077
2078 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002079 String pkgName = intent.getPackage();
2080 if (pkgName == null) {
2081 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2082 resolvedType, flags);
2083 }
2084 PackageParser.Package pkg = mPackages.get(pkgName);
2085 if (pkg != null) {
2086 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2087 resolvedType, flags, pkg.activities);
2088 }
2089 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
2091 }
2092
2093 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2094 Intent[] specifics, String[] specificTypes, Intent intent,
2095 String resolvedType, int flags) {
2096 final String resultsAction = intent.getAction();
2097
2098 List<ResolveInfo> results = queryIntentActivities(
2099 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2100 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2101
2102 int specificsPos = 0;
2103 int N;
2104
2105 // todo: note that the algorithm used here is O(N^2). This
2106 // isn't a problem in our current environment, but if we start running
2107 // into situations where we have more than 5 or 10 matches then this
2108 // should probably be changed to something smarter...
2109
2110 // First we go through and resolve each of the specific items
2111 // that were supplied, taking care of removing any corresponding
2112 // duplicate items in the generic resolve list.
2113 if (specifics != null) {
2114 for (int i=0; i<specifics.length; i++) {
2115 final Intent sintent = specifics[i];
2116 if (sintent == null) {
2117 continue;
2118 }
2119
2120 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2121 String action = sintent.getAction();
2122 if (resultsAction != null && resultsAction.equals(action)) {
2123 // If this action was explicitly requested, then don't
2124 // remove things that have it.
2125 action = null;
2126 }
2127 ComponentName comp = sintent.getComponent();
2128 ResolveInfo ri = null;
2129 ActivityInfo ai = null;
2130 if (comp == null) {
2131 ri = resolveIntent(
2132 sintent,
2133 specificTypes != null ? specificTypes[i] : null,
2134 flags);
2135 if (ri == null) {
2136 continue;
2137 }
2138 if (ri == mResolveInfo) {
2139 // ACK! Must do something better with this.
2140 }
2141 ai = ri.activityInfo;
2142 comp = new ComponentName(ai.applicationInfo.packageName,
2143 ai.name);
2144 } else {
2145 ai = getActivityInfo(comp, flags);
2146 if (ai == null) {
2147 continue;
2148 }
2149 }
2150
2151 // Look for any generic query activities that are duplicates
2152 // of this specific one, and remove them from the results.
2153 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2154 N = results.size();
2155 int j;
2156 for (j=specificsPos; j<N; j++) {
2157 ResolveInfo sri = results.get(j);
2158 if ((sri.activityInfo.name.equals(comp.getClassName())
2159 && sri.activityInfo.applicationInfo.packageName.equals(
2160 comp.getPackageName()))
2161 || (action != null && sri.filter.matchAction(action))) {
2162 results.remove(j);
2163 if (Config.LOGV) Log.v(
2164 TAG, "Removing duplicate item from " + j
2165 + " due to specific " + specificsPos);
2166 if (ri == null) {
2167 ri = sri;
2168 }
2169 j--;
2170 N--;
2171 }
2172 }
2173
2174 // Add this specific item to its proper place.
2175 if (ri == null) {
2176 ri = new ResolveInfo();
2177 ri.activityInfo = ai;
2178 }
2179 results.add(specificsPos, ri);
2180 ri.specificIndex = i;
2181 specificsPos++;
2182 }
2183 }
2184
2185 // Now we go through the remaining generic results and remove any
2186 // duplicate actions that are found here.
2187 N = results.size();
2188 for (int i=specificsPos; i<N-1; i++) {
2189 final ResolveInfo rii = results.get(i);
2190 if (rii.filter == null) {
2191 continue;
2192 }
2193
2194 // Iterate over all of the actions of this result's intent
2195 // filter... typically this should be just one.
2196 final Iterator<String> it = rii.filter.actionsIterator();
2197 if (it == null) {
2198 continue;
2199 }
2200 while (it.hasNext()) {
2201 final String action = it.next();
2202 if (resultsAction != null && resultsAction.equals(action)) {
2203 // If this action was explicitly requested, then don't
2204 // remove things that have it.
2205 continue;
2206 }
2207 for (int j=i+1; j<N; j++) {
2208 final ResolveInfo rij = results.get(j);
2209 if (rij.filter != null && rij.filter.hasAction(action)) {
2210 results.remove(j);
2211 if (Config.LOGV) Log.v(
2212 TAG, "Removing duplicate item from " + j
2213 + " due to action " + action + " at " + i);
2214 j--;
2215 N--;
2216 }
2217 }
2218 }
2219
2220 // If the caller didn't request filter information, drop it now
2221 // so we don't have to marshall/unmarshall it.
2222 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2223 rii.filter = null;
2224 }
2225 }
2226
2227 // Filter out the caller activity if so requested.
2228 if (caller != null) {
2229 N = results.size();
2230 for (int i=0; i<N; i++) {
2231 ActivityInfo ainfo = results.get(i).activityInfo;
2232 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2233 && caller.getClassName().equals(ainfo.name)) {
2234 results.remove(i);
2235 break;
2236 }
2237 }
2238 }
2239
2240 // If the caller didn't request filter information,
2241 // drop them now so we don't have to
2242 // marshall/unmarshall it.
2243 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2244 N = results.size();
2245 for (int i=0; i<N; i++) {
2246 results.get(i).filter = null;
2247 }
2248 }
2249
2250 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2251 return results;
2252 }
2253
2254 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2255 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002256 ComponentName comp = intent.getComponent();
2257 if (comp != null) {
2258 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2259 ActivityInfo ai = getReceiverInfo(comp, flags);
2260 if (ai != null) {
2261 ResolveInfo ri = new ResolveInfo();
2262 ri.activityInfo = ai;
2263 list.add(ri);
2264 }
2265 return list;
2266 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002269 String pkgName = intent.getPackage();
2270 if (pkgName == null) {
2271 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2272 resolvedType, flags);
2273 }
2274 PackageParser.Package pkg = mPackages.get(pkgName);
2275 if (pkg != null) {
2276 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2277 resolvedType, flags, pkg.receivers);
2278 }
2279 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 }
2281 }
2282
2283 public ResolveInfo resolveService(Intent intent, String resolvedType,
2284 int flags) {
2285 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2286 flags);
2287 if (query != null) {
2288 if (query.size() >= 1) {
2289 // If there is more than one service with the same priority,
2290 // just arbitrarily pick the first one.
2291 return query.get(0);
2292 }
2293 }
2294 return null;
2295 }
2296
2297 public List<ResolveInfo> queryIntentServices(Intent intent,
2298 String resolvedType, int flags) {
2299 ComponentName comp = intent.getComponent();
2300 if (comp != null) {
2301 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2302 ServiceInfo si = getServiceInfo(comp, flags);
2303 if (si != null) {
2304 ResolveInfo ri = new ResolveInfo();
2305 ri.serviceInfo = si;
2306 list.add(ri);
2307 }
2308 return list;
2309 }
2310
2311 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002312 String pkgName = intent.getPackage();
2313 if (pkgName == null) {
2314 return (List<ResolveInfo>)mServices.queryIntent(intent,
2315 resolvedType, flags);
2316 }
2317 PackageParser.Package pkg = mPackages.get(pkgName);
2318 if (pkg != null) {
2319 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2320 resolvedType, flags, pkg.services);
2321 }
2322 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
2324 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 public List<PackageInfo> getInstalledPackages(int flags) {
2327 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2328
2329 synchronized (mPackages) {
2330 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2331 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2332 while (i.hasNext()) {
2333 final PackageSetting ps = i.next();
2334 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2335 if(psPkg != null) {
2336 finalList.add(psPkg);
2337 }
2338 }
2339 }
2340 else {
2341 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2342 while (i.hasNext()) {
2343 final PackageParser.Package p = i.next();
2344 if (p.applicationInfo != null) {
2345 PackageInfo pi = generatePackageInfo(p, flags);
2346 if(pi != null) {
2347 finalList.add(pi);
2348 }
2349 }
2350 }
2351 }
2352 }
2353 return finalList;
2354 }
2355
2356 public List<ApplicationInfo> getInstalledApplications(int flags) {
2357 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2358 synchronized(mPackages) {
2359 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2360 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2361 while (i.hasNext()) {
2362 final PackageSetting ps = i.next();
2363 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2364 if(ai != null) {
2365 finalList.add(ai);
2366 }
2367 }
2368 }
2369 else {
2370 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2371 while (i.hasNext()) {
2372 final PackageParser.Package p = i.next();
2373 if (p.applicationInfo != null) {
2374 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2375 if(ai != null) {
2376 finalList.add(ai);
2377 }
2378 }
2379 }
2380 }
2381 }
2382 return finalList;
2383 }
2384
2385 public List<ApplicationInfo> getPersistentApplications(int flags) {
2386 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2387
2388 synchronized (mPackages) {
2389 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2390 while (i.hasNext()) {
2391 PackageParser.Package p = i.next();
2392 if (p.applicationInfo != null
2393 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002394 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002395 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 }
2397 }
2398 }
2399
2400 return finalList;
2401 }
2402
2403 public ProviderInfo resolveContentProvider(String name, int flags) {
2404 synchronized (mPackages) {
2405 final PackageParser.Provider provider = mProviders.get(name);
2406 return provider != null
2407 && mSettings.isEnabledLP(provider.info, flags)
2408 && (!mSafeMode || (provider.info.applicationInfo.flags
2409 &ApplicationInfo.FLAG_SYSTEM) != 0)
2410 ? PackageParser.generateProviderInfo(provider, flags)
2411 : null;
2412 }
2413 }
2414
Fred Quintana718d8a22009-04-29 17:53:20 -07002415 /**
2416 * @deprecated
2417 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 public void querySyncProviders(List outNames, List outInfo) {
2419 synchronized (mPackages) {
2420 Iterator<Map.Entry<String, PackageParser.Provider>> i
2421 = mProviders.entrySet().iterator();
2422
2423 while (i.hasNext()) {
2424 Map.Entry<String, PackageParser.Provider> entry = i.next();
2425 PackageParser.Provider p = entry.getValue();
2426
2427 if (p.syncable
2428 && (!mSafeMode || (p.info.applicationInfo.flags
2429 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2430 outNames.add(entry.getKey());
2431 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2432 }
2433 }
2434 }
2435 }
2436
2437 public List<ProviderInfo> queryContentProviders(String processName,
2438 int uid, int flags) {
2439 ArrayList<ProviderInfo> finalList = null;
2440
2441 synchronized (mPackages) {
2442 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2443 while (i.hasNext()) {
2444 PackageParser.Provider p = i.next();
2445 if (p.info.authority != null
2446 && (processName == null ||
2447 (p.info.processName.equals(processName)
2448 && p.info.applicationInfo.uid == uid))
2449 && mSettings.isEnabledLP(p.info, flags)
2450 && (!mSafeMode || (p.info.applicationInfo.flags
2451 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2452 if (finalList == null) {
2453 finalList = new ArrayList<ProviderInfo>(3);
2454 }
2455 finalList.add(PackageParser.generateProviderInfo(p,
2456 flags));
2457 }
2458 }
2459 }
2460
2461 if (finalList != null) {
2462 Collections.sort(finalList, mProviderInitOrderSorter);
2463 }
2464
2465 return finalList;
2466 }
2467
2468 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2469 int flags) {
2470 synchronized (mPackages) {
2471 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2472 return PackageParser.generateInstrumentationInfo(i, flags);
2473 }
2474 }
2475
2476 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2477 int flags) {
2478 ArrayList<InstrumentationInfo> finalList =
2479 new ArrayList<InstrumentationInfo>();
2480
2481 synchronized (mPackages) {
2482 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2483 while (i.hasNext()) {
2484 PackageParser.Instrumentation p = i.next();
2485 if (targetPackage == null
2486 || targetPackage.equals(p.info.targetPackage)) {
2487 finalList.add(PackageParser.generateInstrumentationInfo(p,
2488 flags));
2489 }
2490 }
2491 }
2492
2493 return finalList;
2494 }
2495
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002496 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002498 if (files == null) {
2499 Log.d(TAG, "No files in app dir " + dir);
2500 return;
2501 }
2502
2503 Log.d(TAG, "Scanning app dir " + dir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504
2505 int i;
2506 for (i=0; i<files.length; i++) {
2507 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002508 if (!isPackageFilename(files[i])) {
2509 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002510 continue;
2511 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002512 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002513 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002514 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002515 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2516 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002517 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002518 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002519 file.delete();
2520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 }
2522 }
2523
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002524 private static File getSettingsProblemFile() {
2525 File dataDir = Environment.getDataDirectory();
2526 File systemDir = new File(dataDir, "system");
2527 File fname = new File(systemDir, "uiderrors.txt");
2528 return fname;
2529 }
2530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 private static void reportSettingsProblem(int priority, String msg) {
2532 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002533 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 FileOutputStream out = new FileOutputStream(fname, true);
2535 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002536 SimpleDateFormat formatter = new SimpleDateFormat();
2537 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2538 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 pw.close();
2540 FileUtils.setPermissions(
2541 fname.toString(),
2542 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2543 -1, -1);
2544 } catch (java.io.IOException e) {
2545 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002546 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 }
2548
2549 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2550 PackageParser.Package pkg, File srcFile, int parseFlags) {
2551 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002552 if (ps != null
2553 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002554 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002555 if (ps.signatures.mSignatures != null
2556 && ps.signatures.mSignatures.length != 0) {
2557 // Optimization: reuse the existing cached certificates
2558 // if the package appears to be unchanged.
2559 pkg.mSignatures = ps.signatures.mSignatures;
2560 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
Jeff Browne7600722010-04-07 18:28:23 -07002562
2563 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002564 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002565 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2566 }
2567
2568 if (!pp.collectCertificates(pkg, parseFlags)) {
2569 mLastScanError = pp.getParseError();
2570 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 }
2572 }
2573 return true;
2574 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 /*
2577 * Scan a package and return the newly parsed package.
2578 * Returns null in case of errors and the error code is stored in mLastScanError
2579 */
2580 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002581 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002583 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002585 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002588 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 if (pkg == null) {
2590 mLastScanError = pp.getParseError();
2591 return null;
2592 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002593 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 PackageSetting updatedPkg;
2595 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002596 // Look to see if we already know about this package.
2597 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002598 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002599 // This package has been renamed to its original name. Let's
2600 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002601 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002602 }
2603 // If there was no original package, see one for the real package name.
2604 if (ps == null) {
2605 ps = mSettings.peekPackageLP(pkg.packageName);
2606 }
2607 // Check to see if this package could be hiding/updating a system
2608 // package. Must look for it either under the original or real
2609 // package name depending on our state.
2610 updatedPkg = mSettings.mDisabledSysPackages.get(
2611 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002613 // First check if this is a system package that may involve an update
2614 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002615 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 // The path has changed from what was last scanned... check the
2617 // version of the new path against what we have stored to determine
2618 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002619 if (pkg.mVersionCode < ps.versionCode) {
2620 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002621 // Ignore entry. Skip it.
2622 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002623 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002624 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002625 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2626 return null;
2627 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002628 // The current app on the system partion is better than
2629 // what we have updated to on the data partition; switch
2630 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002631 // At this point, its safely assumed that package installation for
2632 // apps in system partition will go through. If not there won't be a working
2633 // version of the app
2634 synchronized (mPackages) {
2635 // Just remove the loaded entries from package lists.
2636 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002637 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002638 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002639 + "reverting from " + ps.codePathString
2640 + ": new version " + pkg.mVersionCode
2641 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002642 InstallArgs args = new FileInstallArgs(ps.codePathString,
2643 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002644 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002645 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 }
2648 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002649 if (updatedPkg != null) {
2650 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2651 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2652 }
2653 // Verify certificates against what was last scanned
2654 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002655 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002656 return null;
2657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 // The apk is forward locked (not public) if its code and resources
2659 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002660 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002662 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002663 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002664
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002665 String codePath = null;
2666 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002667 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2668 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002669 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002670 } else {
2671 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002672 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002673 }
2674 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002675 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002676 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002677 codePath = pkg.mScanPath;
2678 // Set application objects path explicitly.
2679 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002681 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 }
2683
Kenny Root85387d72010-08-26 10:13:11 -07002684 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2685 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002686 pkg.mPath = pkg.mScanPath = destCodePath;
2687 pkg.applicationInfo.sourceDir = destCodePath;
2688 pkg.applicationInfo.publicSourceDir = destResPath;
2689 }
2690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 private static String fixProcessName(String defProcessName,
2692 String processName, int uid) {
2693 if (processName == null) {
2694 return defProcessName;
2695 }
2696 return processName;
2697 }
2698
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002699 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002700 PackageParser.Package pkg) {
2701 if (pkgSetting.signatures.mSignatures != null) {
2702 // Already existing package. Make sure signatures match
2703 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2704 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002705 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002706 + " signatures do not match the previously installed version; ignoring!");
2707 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 return false;
2709 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002710 }
2711 // Check for shared user signatures
2712 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2713 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2714 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2715 Slog.e(TAG, "Package " + pkg.packageName
2716 + " has no signatures that match those in shared user "
2717 + pkgSetting.sharedUser.name + "; ignoring!");
2718 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2719 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 }
2722 return true;
2723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002724
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002725 public boolean performDexOpt(String packageName) {
2726 if (!mNoDexOpt) {
2727 return false;
2728 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002729
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002730 PackageParser.Package p;
2731 synchronized (mPackages) {
2732 p = mPackages.get(packageName);
2733 if (p == null || p.mDidDexOpt) {
2734 return false;
2735 }
2736 }
2737 synchronized (mInstallLock) {
2738 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2739 }
2740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002741
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002742 static final int DEX_OPT_SKIPPED = 0;
2743 static final int DEX_OPT_PERFORMED = 1;
2744 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002745
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002746 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2747 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002748 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002749 String path = pkg.mScanPath;
2750 int ret = 0;
2751 try {
2752 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002753 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002754 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002755 pkg.mDidDexOpt = true;
2756 performed = true;
2757 }
2758 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002759 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002760 ret = -1;
2761 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002762 Slog.w(TAG, "IOException reading apk: " + path, e);
2763 ret = -1;
2764 } catch (dalvik.system.StaleDexCacheError e) {
2765 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2766 ret = -1;
2767 } catch (Exception e) {
2768 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002769 ret = -1;
2770 }
2771 if (ret < 0) {
2772 //error from installer
2773 return DEX_OPT_FAILED;
2774 }
2775 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002776
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002777 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2778 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002779
2780 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2781 return Environment.isEncryptedFilesystemEnabled() &&
2782 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2783 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002784
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002785 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2786 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002787 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002788 + " to " + newPkg.packageName
2789 + ": old package not in system partition");
2790 return false;
2791 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002792 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002793 + " to " + newPkg.packageName
2794 + ": old package still exists");
2795 return false;
2796 }
2797 return true;
2798 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002799
2800 private File getDataPathForPackage(PackageParser.Package pkg) {
2801 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2802 File dataPath;
2803 if (useEncryptedFSDir) {
2804 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2805 } else {
2806 dataPath = new File(mAppDataDir, pkg.packageName);
2807 }
2808 return dataPath;
2809 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002810
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002811 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002812 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002813 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002814 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2815 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002816 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002817 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002818 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2819 return null;
2820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 mScanningPath = scanFile;
2822 if (pkg == null) {
2823 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2824 return null;
2825 }
2826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2828 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2829 }
2830
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002831 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 synchronized (mPackages) {
2833 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002834 Slog.w(TAG, "*************************************************");
2835 Slog.w(TAG, "Core android package being redefined. Skipping.");
2836 Slog.w(TAG, " file=" + mScanningPath);
2837 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2839 return null;
2840 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 // Set up information for our fall-back user intent resolution
2843 // activity.
2844 mPlatformPackage = pkg;
2845 pkg.mVersionCode = mSdkVersion;
2846 mAndroidApplication = pkg.applicationInfo;
2847 mResolveActivity.applicationInfo = mAndroidApplication;
2848 mResolveActivity.name = ResolverActivity.class.getName();
2849 mResolveActivity.packageName = mAndroidApplication.packageName;
2850 mResolveActivity.processName = mAndroidApplication.processName;
2851 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2852 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2853 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2854 mResolveActivity.exported = true;
2855 mResolveActivity.enabled = true;
2856 mResolveInfo.activityInfo = mResolveActivity;
2857 mResolveInfo.priority = 0;
2858 mResolveInfo.preferredOrder = 0;
2859 mResolveInfo.match = 0;
2860 mResolveComponentName = new ComponentName(
2861 mAndroidApplication.packageName, mResolveActivity.name);
2862 }
2863 }
2864
2865 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002866 TAG, "Scanning package " + pkg.packageName);
2867 if (mPackages.containsKey(pkg.packageName)
2868 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002869 Slog.w(TAG, "*************************************************");
2870 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002872 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2874 return null;
2875 }
2876
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002877 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002878 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2879 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 SharedUserSetting suid = null;
2882 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002883
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002884 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2885 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002886 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002887 pkg.mRealPackage = null;
2888 pkg.mAdoptPermissions = null;
2889 }
2890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 synchronized (mPackages) {
2892 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002893 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2894 if (mTmpSharedLibraries == null ||
2895 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2896 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2897 }
2898 int num = 0;
2899 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2900 for (int i=0; i<N; i++) {
2901 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002903 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002905 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2907 return null;
2908 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002909 mTmpSharedLibraries[num] = file;
2910 num++;
2911 }
2912 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2913 for (int i=0; i<N; i++) {
2914 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2915 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002916 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002917 + " desires unavailable shared library "
2918 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2919 } else {
2920 mTmpSharedLibraries[num] = file;
2921 num++;
2922 }
2923 }
2924 if (num > 0) {
2925 pkg.usesLibraryFiles = new String[num];
2926 System.arraycopy(mTmpSharedLibraries, 0,
2927 pkg.usesLibraryFiles, 0, num);
2928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002929
Dianne Hackborn49237342009-08-27 20:08:01 -07002930 if (pkg.reqFeatures != null) {
2931 N = pkg.reqFeatures.size();
2932 for (int i=0; i<N; i++) {
2933 FeatureInfo fi = pkg.reqFeatures.get(i);
2934 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2935 // Don't care.
2936 continue;
2937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002938
Dianne Hackborn49237342009-08-27 20:08:01 -07002939 if (fi.name != null) {
2940 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002941 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002942 + " requires unavailable feature "
2943 + fi.name + "; failing!");
2944 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2945 return null;
2946 }
2947 }
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.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003160 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) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003177 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.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003188 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) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003229 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) {
3289 final File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3290 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3291 /*
3292 * Upgrading from a previous version of the OS sometimes
3293 * leaves native libraries in the /data/data/<app>/lib
3294 * directory for system apps even when they shouldn't be.
3295 * Recent changes in the JNI library search path
3296 * necessitates we remove those to match previous behavior.
3297 */
3298 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(sharedLibraryDir)) {
3299 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3300 }
3301 } else if (!isExternal(pkg)) {
3302 Log.i(TAG, path + " changed; unpacking");
Kenny Root6a6b0072010-10-07 16:46:10 -07003303 mInstaller.unlinkNativeLibraryDirectory(dataPath.getPath());
Kenny Root831baa22010-10-05 12:29:25 -07003304 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003305 } else {
3306 mInstaller.linkNativeLibraryDirectory(dataPath.getPath(),
3307 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003310 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003311
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003312 if ((scanMode&SCAN_NO_DEX) == 0) {
3313 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3315 return null;
3316 }
3317 }
3318 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 if (mFactoryTest && pkg.requestedPermissions.contains(
3321 android.Manifest.permission.FACTORY_TEST)) {
3322 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3323 }
3324
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003325 // Request the ActivityManager to kill the process(only for existing packages)
3326 // so that we do not end up in a confused state while the user is still using the older
3327 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003328 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003329 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003330 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003331 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003334 // We don't expect installation to fail beyond this point,
3335 if ((scanMode&SCAN_MONITOR) != 0) {
3336 mAppDirs.put(pkg.mPath, pkg);
3337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003339 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003341 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003342 // Make sure we don't accidentally delete its data.
3343 mSettings.mPackagesToBeCleaned.remove(pkgName);
3344
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003345 // Take care of first install / last update times.
3346 if (currentTime != 0) {
3347 if (pkgSetting.firstInstallTime == 0) {
3348 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3349 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3350 pkgSetting.lastUpdateTime = currentTime;
3351 }
3352 } else if (pkgSetting.firstInstallTime == 0) {
3353 // We need *something*. Take time time stamp of the file.
3354 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3355 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3356 if (scanFileTime != pkgSetting.timeStamp) {
3357 // A package on the system image has changed; consider this
3358 // to be an update.
3359 pkgSetting.lastUpdateTime = scanFileTime;
3360 }
3361 }
3362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 int N = pkg.providers.size();
3364 StringBuilder r = null;
3365 int i;
3366 for (i=0; i<N; i++) {
3367 PackageParser.Provider p = pkg.providers.get(i);
3368 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3369 p.info.processName, pkg.applicationInfo.uid);
3370 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3371 p.info.name), p);
3372 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003373 if (p.info.authority != null) {
3374 String names[] = p.info.authority.split(";");
3375 p.info.authority = null;
3376 for (int j = 0; j < names.length; j++) {
3377 if (j == 1 && p.syncable) {
3378 // We only want the first authority for a provider to possibly be
3379 // syncable, so if we already added this provider using a different
3380 // authority clear the syncable flag. We copy the provider before
3381 // changing it because the mProviders object contains a reference
3382 // to a provider that we don't want to change.
3383 // Only do this for the second authority since the resulting provider
3384 // object can be the same for all future authorities for this provider.
3385 p = new PackageParser.Provider(p);
3386 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003388 if (!mProviders.containsKey(names[j])) {
3389 mProviders.put(names[j], p);
3390 if (p.info.authority == null) {
3391 p.info.authority = names[j];
3392 } else {
3393 p.info.authority = p.info.authority + ";" + names[j];
3394 }
3395 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3396 Log.d(TAG, "Registered content provider: " + names[j] +
3397 ", className = " + p.info.name +
3398 ", isSyncable = " + p.info.isSyncable);
3399 } else {
3400 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003401 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003402 " (in package " + pkg.applicationInfo.packageName +
3403 "): name already used by "
3404 + ((other != null && other.getComponentName() != null)
3405 ? other.getComponentName().getPackageName() : "?"));
3406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 }
3408 }
3409 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3410 if (r == null) {
3411 r = new StringBuilder(256);
3412 } else {
3413 r.append(' ');
3414 }
3415 r.append(p.info.name);
3416 }
3417 }
3418 if (r != null) {
3419 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3420 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 N = pkg.services.size();
3423 r = null;
3424 for (i=0; i<N; i++) {
3425 PackageParser.Service s = pkg.services.get(i);
3426 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3427 s.info.processName, pkg.applicationInfo.uid);
3428 mServices.addService(s);
3429 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3430 if (r == null) {
3431 r = new StringBuilder(256);
3432 } else {
3433 r.append(' ');
3434 }
3435 r.append(s.info.name);
3436 }
3437 }
3438 if (r != null) {
3439 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 N = pkg.receivers.size();
3443 r = null;
3444 for (i=0; i<N; i++) {
3445 PackageParser.Activity a = pkg.receivers.get(i);
3446 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3447 a.info.processName, pkg.applicationInfo.uid);
3448 mReceivers.addActivity(a, "receiver");
3449 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3450 if (r == null) {
3451 r = new StringBuilder(256);
3452 } else {
3453 r.append(' ');
3454 }
3455 r.append(a.info.name);
3456 }
3457 }
3458 if (r != null) {
3459 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3460 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 N = pkg.activities.size();
3463 r = null;
3464 for (i=0; i<N; i++) {
3465 PackageParser.Activity a = pkg.activities.get(i);
3466 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3467 a.info.processName, pkg.applicationInfo.uid);
3468 mActivities.addActivity(a, "activity");
3469 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3470 if (r == null) {
3471 r = new StringBuilder(256);
3472 } else {
3473 r.append(' ');
3474 }
3475 r.append(a.info.name);
3476 }
3477 }
3478 if (r != null) {
3479 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3480 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 N = pkg.permissionGroups.size();
3483 r = null;
3484 for (i=0; i<N; i++) {
3485 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3486 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3487 if (cur == null) {
3488 mPermissionGroups.put(pg.info.name, pg);
3489 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3490 if (r == null) {
3491 r = new StringBuilder(256);
3492 } else {
3493 r.append(' ');
3494 }
3495 r.append(pg.info.name);
3496 }
3497 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003498 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 + pg.info.packageName + " ignored: original from "
3500 + cur.info.packageName);
3501 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3502 if (r == null) {
3503 r = new StringBuilder(256);
3504 } else {
3505 r.append(' ');
3506 }
3507 r.append("DUP:");
3508 r.append(pg.info.name);
3509 }
3510 }
3511 }
3512 if (r != null) {
3513 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3514 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 N = pkg.permissions.size();
3517 r = null;
3518 for (i=0; i<N; i++) {
3519 PackageParser.Permission p = pkg.permissions.get(i);
3520 HashMap<String, BasePermission> permissionMap =
3521 p.tree ? mSettings.mPermissionTrees
3522 : mSettings.mPermissions;
3523 p.group = mPermissionGroups.get(p.info.group);
3524 if (p.info.group == null || p.group != null) {
3525 BasePermission bp = permissionMap.get(p.info.name);
3526 if (bp == null) {
3527 bp = new BasePermission(p.info.name, p.info.packageName,
3528 BasePermission.TYPE_NORMAL);
3529 permissionMap.put(p.info.name, bp);
3530 }
3531 if (bp.perm == null) {
3532 if (bp.sourcePackage == null
3533 || bp.sourcePackage.equals(p.info.packageName)) {
3534 BasePermission tree = findPermissionTreeLP(p.info.name);
3535 if (tree == null
3536 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003537 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 bp.perm = p;
3539 bp.uid = pkg.applicationInfo.uid;
3540 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3541 if (r == null) {
3542 r = new StringBuilder(256);
3543 } else {
3544 r.append(' ');
3545 }
3546 r.append(p.info.name);
3547 }
3548 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003549 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 + p.info.packageName + " ignored: base tree "
3551 + tree.name + " is from package "
3552 + tree.sourcePackage);
3553 }
3554 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003555 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 + p.info.packageName + " ignored: original from "
3557 + bp.sourcePackage);
3558 }
3559 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3560 if (r == null) {
3561 r = new StringBuilder(256);
3562 } else {
3563 r.append(' ');
3564 }
3565 r.append("DUP:");
3566 r.append(p.info.name);
3567 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003568 if (bp.perm == p) {
3569 bp.protectionLevel = p.info.protectionLevel;
3570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003572 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 + p.info.packageName + " ignored: no group "
3574 + p.group);
3575 }
3576 }
3577 if (r != null) {
3578 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 N = pkg.instrumentation.size();
3582 r = null;
3583 for (i=0; i<N; i++) {
3584 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3585 a.info.packageName = pkg.applicationInfo.packageName;
3586 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3587 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3588 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003589 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003590 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3592 if (r == null) {
3593 r = new StringBuilder(256);
3594 } else {
3595 r.append(' ');
3596 }
3597 r.append(a.info.name);
3598 }
3599 }
3600 if (r != null) {
3601 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003603
Dianne Hackborn854060af2009-07-09 18:14:31 -07003604 if (pkg.protectedBroadcasts != null) {
3605 N = pkg.protectedBroadcasts.size();
3606 for (i=0; i<N; i++) {
3607 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3608 }
3609 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 pkgSetting.setTimeStamp(scanFileTime);
3612 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 return pkg;
3615 }
3616
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003617 private void killApplication(String pkgName, int uid) {
3618 // Request the ActivityManager to kill the process(only for existing packages)
3619 // so that we do not end up in a confused state while the user is still using the older
3620 // version of the application while the new one gets installed.
3621 IActivityManager am = ActivityManagerNative.getDefault();
3622 if (am != null) {
3623 try {
3624 am.killApplicationWithUid(pkgName, uid);
3625 } catch (RemoteException e) {
3626 }
3627 }
3628 }
3629
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003630 // Return the path of the directory that will contain the native binaries
3631 // of a given installed package. This is relative to the data path.
3632 //
Kenny Root85387d72010-08-26 10:13:11 -07003633 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3634 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3635 if (nativeLibraryDir != null) {
3636 return new File(nativeLibraryDir);
3637 } else {
3638 // Fall back for old packages
3639 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3640 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003641 }
3642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3644 if (chatty && Config.LOGD) Log.d(
3645 TAG, "Removing package " + pkg.applicationInfo.packageName );
3646
3647 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 mPackages.remove(pkg.applicationInfo.packageName);
3651 if (pkg.mPath != null) {
3652 mAppDirs.remove(pkg.mPath);
3653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 PackageSetting ps = (PackageSetting)pkg.mExtras;
3656 if (ps != null && ps.sharedUser != null) {
3657 // XXX don't do this until the data is removed.
3658 if (false) {
3659 ps.sharedUser.packages.remove(ps);
3660 if (ps.sharedUser.packages.size() == 0) {
3661 // Remove.
3662 }
3663 }
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) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004083 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 if (SHOW_INFO || Config.LOGV) Log.v(
4085 TAG, " " + type + " " +
4086 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4087 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4088 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004089 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4091 if (SHOW_INFO || Config.LOGV) {
4092 Log.v(TAG, " IntentFilter:");
4093 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4094 }
4095 if (!intent.debugCheck()) {
4096 Log.w(TAG, "==> For Activity " + a.info.name);
4097 }
4098 addFilter(intent);
4099 }
4100 }
4101
4102 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004103 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 if (SHOW_INFO || Config.LOGV) Log.v(
4105 TAG, " " + type + " " +
4106 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4107 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4108 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004109 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4111 if (SHOW_INFO || Config.LOGV) {
4112 Log.v(TAG, " IntentFilter:");
4113 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4114 }
4115 removeFilter(intent);
4116 }
4117 }
4118
4119 @Override
4120 protected boolean allowFilterResult(
4121 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4122 ActivityInfo filterAi = filter.activity.info;
4123 for (int i=dest.size()-1; i>=0; i--) {
4124 ActivityInfo destAi = dest.get(i).activityInfo;
4125 if (destAi.name == filterAi.name
4126 && destAi.packageName == filterAi.packageName) {
4127 return false;
4128 }
4129 }
4130 return true;
4131 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004134 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4135 return info.activity.owner.packageName;
4136 }
4137
4138 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4140 int match) {
4141 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4142 return null;
4143 }
4144 final PackageParser.Activity activity = info.activity;
4145 if (mSafeMode && (activity.info.applicationInfo.flags
4146 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4147 return null;
4148 }
4149 final ResolveInfo res = new ResolveInfo();
4150 res.activityInfo = PackageParser.generateActivityInfo(activity,
4151 mFlags);
4152 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4153 res.filter = info;
4154 }
4155 res.priority = info.getPriority();
4156 res.preferredOrder = activity.owner.mPreferredOrder;
4157 //System.out.println("Result: " + res.activityInfo.className +
4158 // " = " + res.priority);
4159 res.match = match;
4160 res.isDefault = info.hasDefault;
4161 res.labelRes = info.labelRes;
4162 res.nonLocalizedLabel = info.nonLocalizedLabel;
4163 res.icon = info.icon;
4164 return res;
4165 }
4166
4167 @Override
4168 protected void sortResults(List<ResolveInfo> results) {
4169 Collections.sort(results, mResolvePrioritySorter);
4170 }
4171
4172 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004173 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004175 out.print(prefix); out.print(
4176 Integer.toHexString(System.identityHashCode(filter.activity)));
4177 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004178 out.print(filter.activity.getComponentShortName());
4179 out.print(" filter ");
4180 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 }
4182
4183// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4184// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4185// final List<ResolveInfo> retList = Lists.newArrayList();
4186// while (i.hasNext()) {
4187// final ResolveInfo resolveInfo = i.next();
4188// if (isEnabledLP(resolveInfo.activityInfo)) {
4189// retList.add(resolveInfo);
4190// }
4191// }
4192// return retList;
4193// }
4194
4195 // Keys are String (activity class name), values are Activity.
4196 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4197 = new HashMap<ComponentName, PackageParser.Activity>();
4198 private int mFlags;
4199 }
4200
4201 private final class ServiceIntentResolver
4202 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004203 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004205 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 }
4207
Mihai Preda074edef2009-05-18 17:13:31 +02004208 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004210 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4212 }
4213
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004214 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4215 ArrayList<PackageParser.Service> packageServices) {
4216 if (packageServices == null) {
4217 return null;
4218 }
4219 mFlags = flags;
4220 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4221 int N = packageServices.size();
4222 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4223 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4224
4225 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4226 for (int i = 0; i < N; ++i) {
4227 intentFilters = packageServices.get(i).intents;
4228 if (intentFilters != null && intentFilters.size() > 0) {
4229 listCut.add(intentFilters);
4230 }
4231 }
4232 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4233 }
4234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004236 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 if (SHOW_INFO || Config.LOGV) Log.v(
4238 TAG, " " + (s.info.nonLocalizedLabel != null
4239 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4240 if (SHOW_INFO || Config.LOGV) Log.v(
4241 TAG, " Class=" + s.info.name);
4242 int NI = s.intents.size();
4243 int j;
4244 for (j=0; j<NI; j++) {
4245 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4246 if (SHOW_INFO || Config.LOGV) {
4247 Log.v(TAG, " IntentFilter:");
4248 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4249 }
4250 if (!intent.debugCheck()) {
4251 Log.w(TAG, "==> For Service " + s.info.name);
4252 }
4253 addFilter(intent);
4254 }
4255 }
4256
4257 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004258 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 if (SHOW_INFO || Config.LOGV) Log.v(
4260 TAG, " " + (s.info.nonLocalizedLabel != null
4261 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4262 if (SHOW_INFO || Config.LOGV) Log.v(
4263 TAG, " Class=" + s.info.name);
4264 int NI = s.intents.size();
4265 int j;
4266 for (j=0; j<NI; j++) {
4267 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4268 if (SHOW_INFO || Config.LOGV) {
4269 Log.v(TAG, " IntentFilter:");
4270 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4271 }
4272 removeFilter(intent);
4273 }
4274 }
4275
4276 @Override
4277 protected boolean allowFilterResult(
4278 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4279 ServiceInfo filterSi = filter.service.info;
4280 for (int i=dest.size()-1; i>=0; i--) {
4281 ServiceInfo destAi = dest.get(i).serviceInfo;
4282 if (destAi.name == filterSi.name
4283 && destAi.packageName == filterSi.packageName) {
4284 return false;
4285 }
4286 }
4287 return true;
4288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004291 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4292 return info.service.owner.packageName;
4293 }
4294
4295 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4297 int match) {
4298 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4299 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4300 return null;
4301 }
4302 final PackageParser.Service service = info.service;
4303 if (mSafeMode && (service.info.applicationInfo.flags
4304 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4305 return null;
4306 }
4307 final ResolveInfo res = new ResolveInfo();
4308 res.serviceInfo = PackageParser.generateServiceInfo(service,
4309 mFlags);
4310 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4311 res.filter = filter;
4312 }
4313 res.priority = info.getPriority();
4314 res.preferredOrder = service.owner.mPreferredOrder;
4315 //System.out.println("Result: " + res.activityInfo.className +
4316 // " = " + res.priority);
4317 res.match = match;
4318 res.isDefault = info.hasDefault;
4319 res.labelRes = info.labelRes;
4320 res.nonLocalizedLabel = info.nonLocalizedLabel;
4321 res.icon = info.icon;
4322 return res;
4323 }
4324
4325 @Override
4326 protected void sortResults(List<ResolveInfo> results) {
4327 Collections.sort(results, mResolvePrioritySorter);
4328 }
4329
4330 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004331 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004333 out.print(prefix); out.print(
4334 Integer.toHexString(System.identityHashCode(filter.service)));
4335 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004336 out.print(filter.service.getComponentShortName());
4337 out.print(" filter ");
4338 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 }
4340
4341// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4342// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4343// final List<ResolveInfo> retList = Lists.newArrayList();
4344// while (i.hasNext()) {
4345// final ResolveInfo resolveInfo = (ResolveInfo) i;
4346// if (isEnabledLP(resolveInfo.serviceInfo)) {
4347// retList.add(resolveInfo);
4348// }
4349// }
4350// return retList;
4351// }
4352
4353 // Keys are String (activity class name), values are Activity.
4354 private final HashMap<ComponentName, PackageParser.Service> mServices
4355 = new HashMap<ComponentName, PackageParser.Service>();
4356 private int mFlags;
4357 };
4358
4359 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4360 new Comparator<ResolveInfo>() {
4361 public int compare(ResolveInfo r1, ResolveInfo r2) {
4362 int v1 = r1.priority;
4363 int v2 = r2.priority;
4364 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4365 if (v1 != v2) {
4366 return (v1 > v2) ? -1 : 1;
4367 }
4368 v1 = r1.preferredOrder;
4369 v2 = r2.preferredOrder;
4370 if (v1 != v2) {
4371 return (v1 > v2) ? -1 : 1;
4372 }
4373 if (r1.isDefault != r2.isDefault) {
4374 return r1.isDefault ? -1 : 1;
4375 }
4376 v1 = r1.match;
4377 v2 = r2.match;
4378 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4379 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4380 }
4381 };
4382
4383 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4384 new Comparator<ProviderInfo>() {
4385 public int compare(ProviderInfo p1, ProviderInfo p2) {
4386 final int v1 = p1.initOrder;
4387 final int v2 = p2.initOrder;
4388 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4389 }
4390 };
4391
Kenny Root93565c4b2010-06-18 15:46:06 -07004392 private static final boolean DEBUG_OBB = false;
4393
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004394 private static final void sendPackageBroadcast(String action, String pkg,
4395 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 IActivityManager am = ActivityManagerNative.getDefault();
4397 if (am != null) {
4398 try {
4399 final Intent intent = new Intent(action,
4400 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4401 if (extras != null) {
4402 intent.putExtras(extras);
4403 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004404 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004405 am.broadcastIntent(null, intent, null, finishedReceiver,
4406 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004407 } catch (RemoteException ex) {
4408 }
4409 }
4410 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004411
4412 public String nextPackageToClean(String lastPackage) {
4413 synchronized (mPackages) {
4414 if (!mMediaMounted) {
4415 // If the external storage is no longer mounted at this point,
4416 // the caller may not have been able to delete all of this
4417 // packages files and can not delete any more. Bail.
4418 return null;
4419 }
4420 if (lastPackage != null) {
4421 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4422 }
4423 return mSettings.mPackagesToBeCleaned.size() > 0
4424 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4425 }
4426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004428 void schedulePackageCleaning(String packageName) {
4429 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4430 }
4431
4432 void startCleaningPackages() {
4433 synchronized (mPackages) {
4434 if (!mMediaMounted) {
4435 return;
4436 }
4437 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4438 return;
4439 }
4440 }
4441 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4442 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4443 IActivityManager am = ActivityManagerNative.getDefault();
4444 if (am != null) {
4445 try {
4446 am.startService(null, intent, null);
4447 } catch (RemoteException e) {
4448 }
4449 }
4450 }
4451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 private final class AppDirObserver extends FileObserver {
4453 public AppDirObserver(String path, int mask, boolean isrom) {
4454 super(path, mask);
4455 mRootDir = path;
4456 mIsRom = isrom;
4457 }
4458
4459 public void onEvent(int event, String path) {
4460 String removedPackage = null;
4461 int removedUid = -1;
4462 String addedPackage = null;
4463 int addedUid = -1;
4464
4465 synchronized (mInstallLock) {
4466 String fullPathStr = null;
4467 File fullPath = null;
4468 if (path != null) {
4469 fullPath = new File(mRootDir, path);
4470 fullPathStr = fullPath.getPath();
4471 }
4472
4473 if (Config.LOGV) Log.v(
4474 TAG, "File " + fullPathStr + " changed: "
4475 + Integer.toHexString(event));
4476
4477 if (!isPackageFilename(path)) {
4478 if (Config.LOGV) Log.v(
4479 TAG, "Ignoring change of non-package file: " + fullPathStr);
4480 return;
4481 }
4482
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004483 // Ignore packages that are being installed or
4484 // have just been installed.
4485 if (ignoreCodePath(fullPathStr)) {
4486 return;
4487 }
4488 PackageParser.Package p = null;
4489 synchronized (mPackages) {
4490 p = mAppDirs.get(fullPathStr);
4491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004493 if (p != null) {
4494 removePackageLI(p, true);
4495 removedPackage = p.applicationInfo.packageName;
4496 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 }
4498 }
4499
4500 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004502 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004503 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4504 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 PackageParser.PARSE_CHATTY |
4506 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004507 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4508 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 if (p != null) {
4510 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004511 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004512 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 }
4514 addedPackage = p.applicationInfo.packageName;
4515 addedUid = p.applicationInfo.uid;
4516 }
4517 }
4518 }
4519
4520 synchronized (mPackages) {
4521 mSettings.writeLP();
4522 }
4523 }
4524
4525 if (removedPackage != null) {
4526 Bundle extras = new Bundle(1);
4527 extras.putInt(Intent.EXTRA_UID, removedUid);
4528 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004529 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4530 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004531 }
4532 if (addedPackage != null) {
4533 Bundle extras = new Bundle(1);
4534 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004535 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4536 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 }
4538 }
4539
4540 private final String mRootDir;
4541 private final boolean mIsRom;
4542 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 /* Called when a downloaded package installation has been confirmed by the user */
4545 public void installPackage(
4546 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004547 installPackage(packageURI, observer, flags, null);
4548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004549
Jacek Surazski65e13172009-04-28 15:26:38 +02004550 /* 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,
4553 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004554 mContext.enforceCallingOrSelfPermission(
4555 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004556
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004557 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004558 msg.obj = new InstallParams(packageURI, observer, flags,
4559 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004560 mHandler.sendMessage(msg);
4561 }
4562
Christopher Tate1bb69062010-02-19 17:02:12 -08004563 public void finishPackageInstall(int token) {
4564 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4565 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4566 mHandler.sendMessage(msg);
4567 }
4568
Kenny Root93565c4b2010-06-18 15:46:06 -07004569 public void setPackageObbPath(String packageName, String path) {
4570 if (DEBUG_OBB)
4571 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4572 PackageSetting pkgSetting;
4573 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004574 final int permission = mContext.checkCallingPermission(
4575 android.Manifest.permission.INSTALL_PACKAGES);
4576 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004577 synchronized (mPackages) {
4578 pkgSetting = mSettings.mPackages.get(packageName);
4579 if (pkgSetting == null) {
4580 throw new IllegalArgumentException("Unknown package: " + packageName);
4581 }
4582 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4583 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4584 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4585 + pkgSetting.userId);
4586 }
4587 pkgSetting.obbPathString = path;
4588 mSettings.writeLP();
4589 }
4590 }
4591
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004592 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 // Queue up an async operation since the package installation may take a little while.
4594 mHandler.post(new Runnable() {
4595 public void run() {
4596 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004597 // Result object to be returned
4598 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004599 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004600 res.uid = -1;
4601 res.pkg = null;
4602 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004603 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004604 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004605 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004606 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004607 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004608 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004610
4611 // A restore should be performed at this point if (a) the install
4612 // succeeded, (b) the operation is not an update, and (c) the new
4613 // package has a backupAgent defined.
4614 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004615 boolean doRestore = (!update
4616 && res.pkg != null
4617 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004618
4619 // Set up the post-install work request bookkeeping. This will be used
4620 // and cleaned up by the post-install event handling regardless of whether
4621 // there's a restore pass performed. Token values are >= 1.
4622 int token;
4623 if (mNextInstallToken < 0) mNextInstallToken = 1;
4624 token = mNextInstallToken++;
4625
4626 PostInstallData data = new PostInstallData(args, res);
4627 mRunningInstalls.put(token, data);
4628 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4629
4630 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4631 // Pass responsibility to the Backup Manager. It will perform a
4632 // restore if appropriate, then pass responsibility back to the
4633 // Package Manager to run the post-install observer callbacks
4634 // and broadcasts.
4635 IBackupManager bm = IBackupManager.Stub.asInterface(
4636 ServiceManager.getService(Context.BACKUP_SERVICE));
4637 if (bm != null) {
4638 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4639 + " to BM for possible restore");
4640 try {
4641 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4642 } catch (RemoteException e) {
4643 // can't happen; the backup manager is local
4644 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004645 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004646 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004647 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004648 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004649 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004650 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004653
4654 if (!doRestore) {
4655 // No restore possible, or the Backup Manager was mysteriously not
4656 // available -- just fire the post-install work request directly.
4657 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4658 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4659 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 }
4662 });
4663 }
4664
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004665 abstract class HandlerParams {
4666 final static int MAX_RETRIES = 4;
4667 int retry = 0;
4668 final void startCopy() {
4669 try {
4670 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4671 retry++;
4672 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004673 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004674 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4675 handleServiceError();
4676 return;
4677 } else {
4678 handleStartCopy();
4679 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4680 mHandler.sendEmptyMessage(MCS_UNBIND);
4681 }
4682 } catch (RemoteException e) {
4683 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4684 mHandler.sendEmptyMessage(MCS_RECONNECT);
4685 }
4686 handleReturnCode();
4687 }
4688
4689 final void serviceError() {
4690 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4691 handleServiceError();
4692 handleReturnCode();
4693 }
4694 abstract void handleStartCopy() throws RemoteException;
4695 abstract void handleServiceError();
4696 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004697 }
4698
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004699 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004700 final IPackageInstallObserver observer;
4701 int flags;
4702 final Uri packageURI;
4703 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004704 private InstallArgs mArgs;
4705 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004706 InstallParams(Uri packageURI,
4707 IPackageInstallObserver observer, int flags,
4708 String installerPackageName) {
4709 this.packageURI = packageURI;
4710 this.flags = flags;
4711 this.observer = observer;
4712 this.installerPackageName = installerPackageName;
4713 }
4714
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004715 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4716 String packageName = pkgLite.packageName;
4717 int installLocation = pkgLite.installLocation;
4718 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4719 synchronized (mPackages) {
4720 PackageParser.Package pkg = mPackages.get(packageName);
4721 if (pkg != null) {
4722 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4723 // Check for updated system application.
4724 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4725 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004726 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004727 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4728 }
4729 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4730 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004731 if (onSd) {
4732 // Install flag overrides everything.
4733 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4734 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004735 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004736 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4737 // Application explicitly specified internal.
4738 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4739 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4740 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004741 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004742 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004743 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004744 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4745 }
4746 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004747 }
4748 }
4749 } else {
4750 // Invalid install. Return error code
4751 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4752 }
4753 }
4754 }
4755 // All the special cases have been taken care of.
4756 // Return result based on recommended install location.
4757 if (onSd) {
4758 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4759 }
4760 return pkgLite.recommendedInstallLocation;
4761 }
4762
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004763 /*
4764 * Invoke remote method to get package information and install
4765 * location values. Override install location based on default
4766 * policy if needed and then create install arguments based
4767 * on the install location.
4768 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004769 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004770 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004771 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4772 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004773 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4774 if (onInt && onSd) {
4775 // Check if both bits are set.
4776 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4777 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4778 } else if (fwdLocked && onSd) {
4779 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004780 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004781 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004782 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004783 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07004784 final PackageInfoLite pkgLite;
4785 try {
4786 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4787 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4788 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
4789 } finally {
4790 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4791 }
4792
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004793 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004794 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4795 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4796 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4797 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4798 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004799 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4800 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4801 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004802 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4803 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004804 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004805 // Override with defaults if needed.
4806 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004807 if (!onSd && !onInt) {
4808 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004809 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4810 // Set the flag to install on external media.
4811 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004812 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004813 } else {
4814 // Make sure the flag for installing on external
4815 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004816 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004817 flags &= ~PackageManager.INSTALL_EXTERNAL;
4818 }
4819 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004820 }
4821 }
4822 // Create the file args now.
4823 mArgs = createInstallArgs(this);
4824 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4825 // Create copy only if we are not in an erroneous state.
4826 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004827 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004828 }
4829 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004830 }
4831
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004832 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004833 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004834 // If mArgs is null, then MCS couldn't be reached. When it
4835 // reconnects, it will try again to install. At that point, this
4836 // will succeed.
4837 if (mArgs != null) {
4838 processPendingInstall(mArgs, mRet);
4839 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004840 }
4841
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004842 @Override
4843 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004844 mArgs = createInstallArgs(this);
4845 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004846 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004847 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004848
4849 /*
4850 * Utility class used in movePackage api.
4851 * srcArgs and targetArgs are not set for invalid flags and make
4852 * sure to do null checks when invoking methods on them.
4853 * We probably want to return ErrorPrams for both failed installs
4854 * and moves.
4855 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004856 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004857 final IPackageMoveObserver observer;
4858 final int flags;
4859 final String packageName;
4860 final InstallArgs srcArgs;
4861 final InstallArgs targetArgs;
4862 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004863
4864 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4865 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004866 this.srcArgs = srcArgs;
4867 this.observer = observer;
4868 this.flags = flags;
4869 this.packageName = packageName;
4870 if (srcArgs != null) {
4871 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004872 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004873 } else {
4874 targetArgs = null;
4875 }
4876 }
4877
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004878 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004879 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4880 // Check for storage space on target medium
4881 if (!targetArgs.checkFreeStorage(mContainerService)) {
4882 Log.w(TAG, "Insufficient storage to install");
4883 return;
4884 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004885 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004886 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004887 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004888 if (DEBUG_SD_INSTALL) {
4889 StringBuilder builder = new StringBuilder();
4890 if (srcArgs != null) {
4891 builder.append("src: ");
4892 builder.append(srcArgs.getCodePath());
4893 }
4894 if (targetArgs != null) {
4895 builder.append(" target : ");
4896 builder.append(targetArgs.getCodePath());
4897 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004898 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004899 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004900 }
4901
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004902 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004903 void handleReturnCode() {
4904 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004905 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4906 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4907 currentStatus = PackageManager.MOVE_SUCCEEDED;
4908 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4909 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4910 }
4911 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004912 }
4913
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004914 @Override
4915 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004916 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004917 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004918 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004919
4920 private InstallArgs createInstallArgs(InstallParams params) {
4921 if (installOnSd(params.flags)) {
4922 return new SdInstallArgs(params);
4923 } else {
4924 return new FileInstallArgs(params);
4925 }
4926 }
4927
Kenny Root85387d72010-08-26 10:13:11 -07004928 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4929 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004930 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004931 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004932 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004933 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004934 }
4935 }
4936
Kenny Root85387d72010-08-26 10:13:11 -07004937 // Used by package mover
4938 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004939 if (installOnSd(flags)) {
4940 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4941 return new SdInstallArgs(packageURI, cid);
4942 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004943 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004944 }
4945 }
4946
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004947 static abstract class InstallArgs {
4948 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004949 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004950 final int flags;
4951 final Uri packageURI;
4952 final String installerPackageName;
4953
4954 InstallArgs(Uri packageURI,
4955 IPackageInstallObserver observer, int flags,
4956 String installerPackageName) {
4957 this.packageURI = packageURI;
4958 this.flags = flags;
4959 this.observer = observer;
4960 this.installerPackageName = installerPackageName;
4961 }
4962
4963 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004964 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004965 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004966 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004967 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004968 abstract String getCodePath();
4969 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004970 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004971 // Need installer lock especially for dex file removal.
4972 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004973 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004974 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004975 }
4976
4977 class FileInstallArgs extends InstallArgs {
4978 File installDir;
4979 String codeFileName;
4980 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004981 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004982 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004983
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004984 FileInstallArgs(InstallParams params) {
4985 super(params.packageURI, params.observer,
4986 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004987 }
4988
Kenny Root85387d72010-08-26 10:13:11 -07004989 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004990 super(null, null, 0, null);
4991 File codeFile = new File(fullCodePath);
4992 installDir = codeFile.getParentFile();
4993 codeFileName = fullCodePath;
4994 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004995 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004996 }
4997
Kenny Root85387d72010-08-26 10:13:11 -07004998 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004999 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07005000 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005001 String apkName = getNextCodePath(null, pkgName, ".apk");
5002 codeFileName = new File(installDir, apkName + ".apk").getPath();
5003 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07005004 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005005 }
5006
Kenny Root11128572010-10-11 10:51:32 -07005007 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5008 try {
5009 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5010 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5011 return imcs.checkFreeStorage(false, packageURI);
5012 } finally {
5013 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5014 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005015 }
5016
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005017 String getCodePath() {
5018 return codeFileName;
5019 }
5020
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005021 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005022 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005023 codeFileName = createTempPackageFile(installDir).getPath();
5024 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005025 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005026 }
5027
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005028 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005029 if (temp) {
5030 // Generate temp file name
5031 createCopyFile();
5032 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005033 // Get a ParcelFileDescriptor to write to the output file
5034 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005035 if (!created) {
5036 try {
5037 codeFile.createNewFile();
5038 // Set permissions
5039 if (!setPermissions()) {
5040 // Failed setting permissions.
5041 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5042 }
5043 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005044 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005045 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5046 }
5047 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005048 ParcelFileDescriptor out = null;
5049 try {
Kenny Root85387d72010-08-26 10:13:11 -07005050 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005051 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005052 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005053 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5054 }
5055 // Copy the resource now
5056 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5057 try {
Kenny Root11128572010-10-11 10:51:32 -07005058 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5059 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005060 if (imcs.copyResource(packageURI, out)) {
5061 ret = PackageManager.INSTALL_SUCCEEDED;
5062 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 } finally {
5064 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005065 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005066 }
Kenny Root85387d72010-08-26 10:13:11 -07005067
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005068 return ret;
5069 }
5070
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005071 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005072 if (status != PackageManager.INSTALL_SUCCEEDED) {
5073 cleanUp();
5074 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005075 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005076 }
5077
5078 boolean doRename(int status, final String pkgName, String oldCodePath) {
5079 if (status != PackageManager.INSTALL_SUCCEEDED) {
5080 cleanUp();
5081 return false;
5082 } else {
5083 // Rename based on packageName
5084 File codeFile = new File(getCodePath());
5085 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5086 File desFile = new File(installDir, apkName + ".apk");
5087 if (!codeFile.renameTo(desFile)) {
5088 return false;
5089 }
5090 // Reset paths since the file has been renamed.
5091 codeFileName = desFile.getPath();
5092 resourceFileName = getResourcePathFromCodePath();
5093 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005094 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005095 // Failed setting permissions.
5096 return false;
5097 }
5098 return true;
5099 }
5100 }
5101
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005102 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005103 if (status != PackageManager.INSTALL_SUCCEEDED) {
5104 cleanUp();
5105 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005106 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 }
5108
5109 String getResourcePath() {
5110 return resourceFileName;
5111 }
5112
5113 String getResourcePathFromCodePath() {
5114 String codePath = getCodePath();
5115 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5116 String apkNameOnly = getApkName(codePath);
5117 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5118 } else {
5119 return codePath;
5120 }
5121 }
5122
Kenny Root85387d72010-08-26 10:13:11 -07005123 @Override
5124 String getNativeLibraryPath() {
5125 return libraryPath;
5126 }
5127
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005128 private boolean cleanUp() {
5129 boolean ret = true;
5130 String sourceDir = getCodePath();
5131 String publicSourceDir = getResourcePath();
5132 if (sourceDir != null) {
5133 File sourceFile = new File(sourceDir);
5134 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005135 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005136 ret = false;
5137 }
5138 // Delete application's code and resources
5139 sourceFile.delete();
5140 }
5141 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5142 final File publicSourceFile = new File(publicSourceDir);
5143 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005144 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005145 }
5146 if (publicSourceFile.exists()) {
5147 publicSourceFile.delete();
5148 }
5149 }
5150 return ret;
5151 }
5152
5153 void cleanUpResourcesLI() {
5154 String sourceDir = getCodePath();
5155 if (cleanUp() && mInstaller != null) {
5156 int retCode = mInstaller.rmdex(sourceDir);
5157 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005158 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005159 + " at location "
5160 + sourceDir + ", retcode=" + retCode);
5161 // we don't consider this to be a failure of the core package deletion
5162 }
5163 }
5164 }
5165
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005166 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005167 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005168 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005169 final int filePermissions =
5170 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5171 |FileUtils.S_IROTH;
5172 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5173 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005174 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005175 getCodePath()
5176 + ". The return code was: " + retCode);
5177 // TODO Define new internal error
5178 return false;
5179 }
5180 return true;
5181 }
5182 return true;
5183 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005184
5185 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005186 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005187 cleanUpResourcesLI();
5188 return true;
5189 }
Kenny Root85387d72010-08-26 10:13:11 -07005190
5191 private boolean isFwdLocked() {
5192 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5193 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005194 }
5195
5196 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005197 static final String RES_FILE_NAME = "pkg.apk";
5198
Kenny Root85387d72010-08-26 10:13:11 -07005199 String cid;
5200 String packagePath;
5201 String libraryPath;
5202
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005203 SdInstallArgs(InstallParams params) {
5204 super(params.packageURI, params.observer,
5205 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005206 }
5207
Kenny Root85387d72010-08-26 10:13:11 -07005208 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005209 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005210 // Extract cid from fullCodePath
5211 int eidx = fullCodePath.lastIndexOf("/");
5212 String subStr1 = fullCodePath.substring(0, eidx);
5213 int sidx = subStr1.lastIndexOf("/");
5214 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005215 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005216 }
5217
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005218 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005219 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5220 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005221 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005222 }
5223
5224 SdInstallArgs(Uri packageURI, String cid) {
5225 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005226 this.cid = cid;
5227 }
5228
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005229 void createCopyFile() {
5230 cid = getTempContainerId();
5231 }
5232
Kenny Root11128572010-10-11 10:51:32 -07005233 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5234 try {
5235 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5236 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5237 return imcs.checkFreeStorage(true, packageURI);
5238 } finally {
5239 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5240 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005241 }
5242
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005243 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005244 if (temp) {
5245 createCopyFile();
5246 }
Kenny Root11128572010-10-11 10:51:32 -07005247
5248 final String newCachePath;
5249 try {
5250 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5251 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5252 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5253 getEncryptKey(), RES_FILE_NAME);
5254 } finally {
5255 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5256 }
5257
Kenny Root85387d72010-08-26 10:13:11 -07005258 if (newCachePath != null) {
5259 setCachePath(newCachePath);
5260 return PackageManager.INSTALL_SUCCEEDED;
5261 } else {
5262 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5263 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005264 }
5265
5266 @Override
5267 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005268 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005269 }
5270
5271 @Override
5272 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005273 return packagePath;
5274 }
5275
5276 @Override
5277 String getNativeLibraryPath() {
5278 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005279 }
5280
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005281 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005282 if (status != PackageManager.INSTALL_SUCCEEDED) {
5283 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005284 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005285 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005286 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005287 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005288 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5289 Process.SYSTEM_UID);
5290 if (newCachePath != null) {
5291 setCachePath(newCachePath);
5292 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005293 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5294 }
5295 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005296 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005297 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005298 }
5299
5300 boolean doRename(int status, final String pkgName,
5301 String oldCodePath) {
5302 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005303 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005304 if (PackageHelper.isContainerMounted(cid)) {
5305 // Unmount the container
5306 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005307 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005308 return false;
5309 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005310 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005311 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005312 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5313 " which might be stale. Will try to clean up.");
5314 // Clean up the stale container and proceed to recreate.
5315 if (!PackageHelper.destroySdDir(newCacheId)) {
5316 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5317 return false;
5318 }
5319 // Successfully cleaned up stale container. Try to rename again.
5320 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5321 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5322 + " inspite of cleaning it up.");
5323 return false;
5324 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005325 }
5326 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005327 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005328 newCachePath = PackageHelper.mountSdDir(newCacheId,
5329 getEncryptKey(), Process.SYSTEM_UID);
5330 } else {
5331 newCachePath = PackageHelper.getSdDir(newCacheId);
5332 }
5333 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005334 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005335 return false;
5336 }
5337 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005338 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005339 " at new path: " + newCachePath);
5340 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005341 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005342 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005343 }
5344
Kenny Root85387d72010-08-26 10:13:11 -07005345 private void setCachePath(String newCachePath) {
5346 File cachePath = new File(newCachePath);
5347 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5348 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5349 }
5350
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005351 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005352 if (status != PackageManager.INSTALL_SUCCEEDED) {
5353 cleanUp();
5354 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005355 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005356 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005357 PackageHelper.mountSdDir(cid,
5358 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005359 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005360 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005361 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005362 }
5363
5364 private void cleanUp() {
5365 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005366 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005367 }
5368
5369 void cleanUpResourcesLI() {
5370 String sourceFile = getCodePath();
5371 // Remove dex file
5372 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005373 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005374 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005375 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005376 + " at location "
5377 + sourceFile.toString() + ", retcode=" + retCode);
5378 // we don't consider this to be a failure of the core package deletion
5379 }
5380 }
5381 cleanUp();
5382 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005383
5384 boolean matchContainer(String app) {
5385 if (cid.startsWith(app)) {
5386 return true;
5387 }
5388 return false;
5389 }
5390
5391 String getPackageName() {
5392 int idx = cid.lastIndexOf("-");
5393 if (idx == -1) {
5394 return cid;
5395 }
5396 return cid.substring(0, idx);
5397 }
5398
5399 boolean doPostDeleteLI(boolean delete) {
5400 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005401 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005402 if (mounted) {
5403 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005404 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005405 }
5406 if (ret && delete) {
5407 cleanUpResourcesLI();
5408 }
5409 return ret;
5410 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005411 };
5412
5413 // Utility method used to create code paths based on package name and available index.
5414 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5415 String idxStr = "";
5416 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005417 // Fall back to default value of idx=1 if prefix is not
5418 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005419 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005420 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005421 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005422 if (subStr.endsWith(suffix)) {
5423 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005424 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005425 // If oldCodePath already contains prefix find out the
5426 // ending index to either increment or decrement.
5427 int sidx = subStr.lastIndexOf(prefix);
5428 if (sidx != -1) {
5429 subStr = subStr.substring(sidx + prefix.length());
5430 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005431 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5432 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005433 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005434 try {
5435 idx = Integer.parseInt(subStr);
5436 if (idx <= 1) {
5437 idx++;
5438 } else {
5439 idx--;
5440 }
5441 } catch(NumberFormatException e) {
5442 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005443 }
5444 }
5445 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005446 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005447 return prefix + idxStr;
5448 }
5449
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005450 // Utility method used to ignore ADD/REMOVE events
5451 // by directory observer.
5452 private static boolean ignoreCodePath(String fullPathStr) {
5453 String apkName = getApkName(fullPathStr);
5454 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5455 if (idx != -1 && ((idx+1) < apkName.length())) {
5456 // Make sure the package ends with a numeral
5457 String version = apkName.substring(idx+1);
5458 try {
5459 Integer.parseInt(version);
5460 return true;
5461 } catch (NumberFormatException e) {}
5462 }
5463 return false;
5464 }
5465
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005466 // Utility method that returns the relative package path with respect
5467 // to the installation directory. Like say for /data/data/com.test-1.apk
5468 // string com.test-1 is returned.
5469 static String getApkName(String codePath) {
5470 if (codePath == null) {
5471 return null;
5472 }
5473 int sidx = codePath.lastIndexOf("/");
5474 int eidx = codePath.lastIndexOf(".");
5475 if (eidx == -1) {
5476 eidx = codePath.length();
5477 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005478 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005479 return null;
5480 }
5481 return codePath.substring(sidx+1, eidx);
5482 }
5483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 class PackageInstalledInfo {
5485 String name;
5486 int uid;
5487 PackageParser.Package pkg;
5488 int returnCode;
5489 PackageRemovedInfo removedInfo;
5490 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492 /*
5493 * Install a non-existing package.
5494 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005495 private void installNewPackageLI(PackageParser.Package pkg,
5496 int parseFlags,
5497 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005498 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005500 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005501
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005502 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005503 res.name = pkgName;
5504 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005505 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5506 // A package with the same name is already installed, though
5507 // it has been renamed to an older name. The package we
5508 // are trying to install should be installed as an update to
5509 // the existing one, but that has not been requested, so bail.
5510 Slog.w(TAG, "Attempt to re-install " + pkgName
5511 + " without first uninstalling package running as "
5512 + mSettings.mRenamedPackages.get(pkgName));
5513 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5514 return;
5515 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005516 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005518 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 + " without first uninstalling.");
5520 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5521 return;
5522 }
5523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005525 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5526 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005528 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5530 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5531 }
5532 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005533 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005534 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 res);
5536 // delete the partially installed application. the data directory will have to be
5537 // restored if it was already existing
5538 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5539 // remove package from internal structures. Note that we want deletePackageX to
5540 // delete the package data and cache directories that it created in
5541 // scanPackageLocked, unless those directories existed before we even tried to
5542 // install.
5543 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005544 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005546 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 }
5548 }
5549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005550
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005551 private void replacePackageLI(PackageParser.Package pkg,
5552 int parseFlags,
5553 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005554 String installerPackageName, PackageInstalledInfo res) {
5555
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005556 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005557 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 // First find the old package info and check signatures
5559 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005560 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005561 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005562 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5564 return;
5565 }
5566 }
Kenny Root85387d72010-08-26 10:13:11 -07005567 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005568 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005569 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005571 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 }
5573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005576 PackageParser.Package pkg,
5577 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005578 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 PackageParser.Package newPackage = null;
5580 String pkgName = deletedPackage.packageName;
5581 boolean deletedPkg = true;
5582 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005583
Jacek Surazski65e13172009-04-28 15:26:38 +02005584 String oldInstallerPackageName = null;
5585 synchronized (mPackages) {
5586 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5587 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005588
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005589 long origUpdateTime;
5590 if (pkg.mExtras != null) {
5591 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5592 } else {
5593 origUpdateTime = 0;
5594 }
5595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005597 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005598 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005599 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005600 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5601 deletedPkg = false;
5602 } else {
5603 // Successfully deleted the old package. Now proceed with re-installation
5604 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005605 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5606 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005608 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5610 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005611 }
5612 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005613 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005614 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 res);
5616 updatedSettings = true;
5617 }
5618 }
5619
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005620 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 // remove package from internal structures. Note that we want deletePackageX to
5622 // delete the package data and cache directories that it created in
5623 // scanPackageLocked, unless those directories existed before we even tried to
5624 // install.
5625 if(updatedSettings) {
5626 deletePackageLI(
5627 pkgName, true,
5628 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005629 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 }
5631 // Since we failed to install the new package we need to restore the old
5632 // package that we deleted.
5633 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005634 File restoreFile = new File(deletedPackage.mPath);
5635 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005636 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005637 return;
5638 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005639 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005640 boolean oldOnSd = isExternal(deletedPackage);
5641 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5642 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5643 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005644 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5645 | SCAN_UPDATE_TIME;
5646 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5647 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005648 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5649 return;
5650 }
5651 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005652 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005653 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005654 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005655 mSettings.writeLP();
5656 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005657 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 }
5659 }
5660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005663 PackageParser.Package pkg,
5664 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005665 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 PackageParser.Package newPackage = null;
5667 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005668 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 PackageParser.PARSE_IS_SYSTEM;
5670 String packageName = deletedPackage.packageName;
5671 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5672 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005673 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 return;
5675 }
5676 PackageParser.Package oldPkg;
5677 PackageSetting oldPkgSetting;
5678 synchronized (mPackages) {
5679 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005680 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5682 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005683 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 return;
5685 }
5686 }
5687 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5688 res.removedInfo.removedPackage = packageName;
5689 // Remove existing system package
5690 removePackageLI(oldPkg, true);
5691 synchronized (mPackages) {
5692 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5693 }
5694
5695 // Successfully disabled the old package. Now proceed with re-installation
5696 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5697 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005698 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005700 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5702 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5703 }
5704 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005705 if (newPackage.mExtras != null) {
5706 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5707 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5708 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5709 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005710 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 updatedSettings = true;
5712 }
5713
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005714 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 // Re installation failed. Restore old information
5716 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005717 if (newPackage != null) {
5718 removePackageLI(newPackage, true);
5719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005721 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 // Restore the old system information in Settings
5723 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005724 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005726 mSettings.setInstallerPackageName(packageName,
5727 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 }
5729 mSettings.writeLP();
5730 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005731 } else {
5732 // If this is an update to an existing update, setup
5733 // to remove the existing update.
5734 synchronized (mPackages) {
5735 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5736 if (ps != null && ps.codePathString != null &&
5737 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005738 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005739 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005740 }
5741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005742 }
5743 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005744
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005745 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005746 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005747 int retCode;
5748 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5749 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5750 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005751 if (mNoDexOpt) {
5752 /*
5753 * If we're in an engineering build, programs are lazily run
5754 * through dexopt. If the .dex file doesn't exist yet, it
5755 * will be created when the program is run next.
5756 */
5757 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5758 } else {
5759 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5760 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5761 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005762 }
5763 }
5764 return PackageManager.INSTALL_SUCCEEDED;
5765 }
5766
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005767 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005768 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005769 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 synchronized (mPackages) {
5771 //write settings. the installStatus will be incomplete at this stage.
5772 //note that the new package setting would have already been
5773 //added to mPackages. It hasn't been persisted yet.
5774 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5775 mSettings.writeLP();
5776 }
5777
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005778 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005779 != PackageManager.INSTALL_SUCCEEDED) {
5780 // Discontinue if moving dex files failed.
5781 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005783 if((res.returnCode = setPermissionsLI(newPackage))
5784 != PackageManager.INSTALL_SUCCEEDED) {
5785 if (mInstaller != null) {
5786 mInstaller.rmdex(newPackage.mScanPath);
5787 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005788 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005790 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005793 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005794 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 res.name = pkgName;
5796 res.uid = newPackage.applicationInfo.uid;
5797 res.pkg = newPackage;
5798 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005799 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5801 //to update install status
5802 mSettings.writeLP();
5803 }
5804 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005805
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005806 private void installPackageLI(InstallArgs args,
5807 boolean newInstall, PackageInstalledInfo res) {
5808 int pFlags = args.flags;
5809 String installerPackageName = args.installerPackageName;
5810 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005811 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005812 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005813 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005814 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005815 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005816 // Result object to be returned
5817 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5818
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005819 // Retrieve PackageSettings and parse package
5820 int parseFlags = PackageParser.PARSE_CHATTY |
5821 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5822 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5823 parseFlags |= mDefParseFlags;
5824 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5825 pp.setSeparateProcesses(mSeparateProcesses);
5826 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5827 null, mMetrics, parseFlags);
5828 if (pkg == null) {
5829 res.returnCode = pp.getParseError();
5830 return;
5831 }
5832 String pkgName = res.name = pkg.packageName;
5833 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5834 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5835 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5836 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005838 }
5839 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5840 res.returnCode = pp.getParseError();
5841 return;
5842 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005843 // Get rid of all references to package scan path via parser.
5844 pp = null;
5845 String oldCodePath = null;
5846 boolean systemApp = false;
5847 synchronized (mPackages) {
5848 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005849 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5850 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005851 if (pkg.mOriginalPackages != null
5852 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005853 && mPackages.containsKey(oldName)) {
5854 // This package is derived from an original package,
5855 // and this device has been updating from that original
5856 // name. We must continue using the original name, so
5857 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005858 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005859 pkgName = pkg.packageName;
5860 replace = true;
5861 } else if (mPackages.containsKey(pkgName)) {
5862 // This package, under its official name, already exists
5863 // on the device; we should replace it.
5864 replace = true;
5865 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005866 }
5867 PackageSetting ps = mSettings.mPackages.get(pkgName);
5868 if (ps != null) {
5869 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5870 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5871 systemApp = (ps.pkg.applicationInfo.flags &
5872 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005873 }
5874 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005876
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005877 if (systemApp && onSd) {
5878 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005879 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005880 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5881 return;
5882 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005883
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005884 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5885 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5886 return;
5887 }
5888 // Set application objects path explicitly after the rename
5889 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005890 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005891 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005892 replacePackageLI(pkg, parseFlags, scanMode,
5893 installerPackageName, res);
5894 } else {
5895 installNewPackageLI(pkg, parseFlags, scanMode,
5896 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 }
5898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005899
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005900 private int setPermissionsLI(PackageParser.Package newPackage) {
5901 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005902 int retCode = 0;
5903 // TODO Gross hack but fix later. Ideally move this to be a post installation
5904 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005905 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005906 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 try {
5908 extractPublicFiles(newPackage, destResourceFile);
5909 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005910 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 -08005911 " forward-locked app.");
5912 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5913 } finally {
5914 //TODO clean up the extracted public files
5915 }
5916 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005917 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005918 newPackage.applicationInfo.uid);
5919 } else {
5920 final int filePermissions =
5921 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005922 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 newPackage.applicationInfo.uid);
5924 }
5925 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005926 // The permissions on the resource file was set when it was copied for
5927 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005931 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005932 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005934 // TODO Define new internal error
5935 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005936 }
5937 return PackageManager.INSTALL_SUCCEEDED;
5938 }
5939
Kenny Root85387d72010-08-26 10:13:11 -07005940 private static boolean isForwardLocked(PackageParser.Package pkg) {
5941 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 }
5943
Kenny Root85387d72010-08-26 10:13:11 -07005944 private static boolean isExternal(PackageParser.Package pkg) {
5945 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5946 }
5947
5948 private static boolean isSystemApp(PackageParser.Package pkg) {
5949 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5950 }
5951
5952 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5953 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005954 }
5955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 private void extractPublicFiles(PackageParser.Package newPackage,
5957 File publicZipFile) throws IOException {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07005958 final FileOutputStream fstr = new FileOutputStream(publicZipFile);
5959 final ZipOutputStream publicZipOutStream = new ZipOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5961
5962 // Copy manifest, resources.arsc and res directory to public zip
5963
5964 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5965 while (privateZipEntries.hasMoreElements()) {
5966 final ZipEntry zipEntry = privateZipEntries.nextElement();
5967 final String zipEntryName = zipEntry.getName();
5968 if ("AndroidManifest.xml".equals(zipEntryName)
5969 || "resources.arsc".equals(zipEntryName)
5970 || zipEntryName.startsWith("res/")) {
5971 try {
5972 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5973 } catch (IOException e) {
5974 try {
5975 publicZipOutStream.close();
5976 throw e;
5977 } finally {
5978 publicZipFile.delete();
5979 }
5980 }
5981 }
5982 }
5983
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07005984 publicZipOutStream.finish();
5985 publicZipOutStream.flush();
5986 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 publicZipOutStream.close();
5988 FileUtils.setPermissions(
5989 publicZipFile.getAbsolutePath(),
5990 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5991 -1, -1);
5992 }
5993
5994 private static void copyZipEntry(ZipEntry zipEntry,
5995 ZipFile inZipFile,
5996 ZipOutputStream outZipStream) throws IOException {
5997 byte[] buffer = new byte[4096];
5998 int num;
5999
6000 ZipEntry newEntry;
6001 if (zipEntry.getMethod() == ZipEntry.STORED) {
6002 // Preserve the STORED method of the input entry.
6003 newEntry = new ZipEntry(zipEntry);
6004 } else {
6005 // Create a new entry so that the compressed len is recomputed.
6006 newEntry = new ZipEntry(zipEntry.getName());
6007 }
6008 outZipStream.putNextEntry(newEntry);
6009
6010 InputStream data = inZipFile.getInputStream(zipEntry);
6011 while ((num = data.read(buffer)) > 0) {
6012 outZipStream.write(buffer, 0, num);
6013 }
6014 outZipStream.flush();
6015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 private void deleteTempPackageFiles() {
6018 FilenameFilter filter = new FilenameFilter() {
6019 public boolean accept(File dir, String name) {
6020 return name.startsWith("vmdl") && name.endsWith(".tmp");
6021 }
6022 };
6023 String tmpFilesList[] = mAppInstallDir.list(filter);
6024 if(tmpFilesList == null) {
6025 return;
6026 }
6027 for(int i = 0; i < tmpFilesList.length; i++) {
6028 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6029 tmpFile.delete();
6030 }
6031 }
6032
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006033 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006034 File tmpPackageFile;
6035 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006036 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006038 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 return null;
6040 }
6041 try {
6042 FileUtils.setPermissions(
6043 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6044 -1, -1);
6045 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006046 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 return null;
6048 }
6049 return tmpPackageFile;
6050 }
6051
6052 public void deletePackage(final String packageName,
6053 final IPackageDeleteObserver observer,
6054 final int flags) {
6055 mContext.enforceCallingOrSelfPermission(
6056 android.Manifest.permission.DELETE_PACKAGES, null);
6057 // Queue up an async operation since the package deletion may take a little while.
6058 mHandler.post(new Runnable() {
6059 public void run() {
6060 mHandler.removeCallbacks(this);
6061 final boolean succeded = deletePackageX(packageName, true, true, flags);
6062 if (observer != null) {
6063 try {
6064 observer.packageDeleted(succeded);
6065 } catch (RemoteException e) {
6066 Log.i(TAG, "Observer no longer exists.");
6067 } //end catch
6068 } //end if
6069 } //end run
6070 });
6071 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 /**
6074 * This method is an internal method that could be get invoked either
6075 * to delete an installed package or to clean up a failed installation.
6076 * After deleting an installed package, a broadcast is sent to notify any
6077 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006078 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 * installation wouldn't have sent the initial broadcast either
6080 * The key steps in deleting a package are
6081 * deleting the package information in internal structures like mPackages,
6082 * deleting the packages base directories through installd
6083 * updating mSettings to reflect current status
6084 * persisting settings for later use
6085 * sending a broadcast if necessary
6086 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6088 boolean deleteCodeAndResources, int flags) {
6089 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006090 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006092 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6093 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6094 try {
6095 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006096 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006097 return false;
6098 }
6099 } catch (RemoteException e) {
6100 }
6101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006103 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006104 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006108 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006109 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006110
6111 // If the removed package was a system update, the old system packaged
6112 // was re-enabled; we need to broadcast this information
6113 if (systemUpdate) {
6114 Bundle extras = new Bundle(1);
6115 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6116 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6117
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006118 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6119 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006122 // Force a gc here.
6123 Runtime.getRuntime().gc();
6124 // Delete the resources here after sending the broadcast to let
6125 // other processes clean up before deleting resources.
6126 if (info.args != null) {
6127 synchronized (mInstallLock) {
6128 info.args.doPostDeleteLI(deleteCodeAndResources);
6129 }
6130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 return res;
6132 }
6133
6134 static class PackageRemovedInfo {
6135 String removedPackage;
6136 int uid = -1;
6137 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006138 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006139 // Clean up resources deleted packages.
6140 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006141
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006142 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 Bundle extras = new Bundle(1);
6144 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6145 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6146 if (replacing) {
6147 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6148 }
6149 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006150 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 }
6152 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006153 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 }
6155 }
6156 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 /*
6159 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6160 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006161 * 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 -08006162 * delete a partially installed application.
6163 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006164 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006165 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006167 if (outInfo != null) {
6168 outInfo.removedPackage = packageName;
6169 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006170 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 // Retrieve object to delete permissions for shared user later on
6172 PackageSetting deletedPs;
6173 synchronized (mPackages) {
6174 deletedPs = mSettings.mPackages.get(packageName);
6175 }
6176 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006177 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006179 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006180 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006181 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 + packageName + ", retcode=" + retCode);
6183 // we don't consider this to be a failure of the core package deletion
6184 }
6185 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006186 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 PackageParser.Package pkg = mPackages.get(packageName);
6188 File dataDir = new File(pkg.applicationInfo.dataDir);
6189 dataDir.delete();
6190 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006191 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 }
6193 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006194 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006195 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6196 if (outInfo != null) {
6197 outInfo.removedUid = mSettings.removePackageLP(packageName);
6198 }
6199 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006200 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006201 if (deletedPs.sharedUser != null) {
6202 // remove permissions associated with package
6203 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6204 }
6205 }
6206 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006207 // remove from preferred activities.
6208 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6209 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6210 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6211 removed.add(pa);
6212 }
6213 }
6214 for (PreferredActivity pa : removed) {
6215 mSettings.mPreferredActivities.removeFilter(pa);
6216 }
6217 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006218 if (writeSettings) {
6219 // Save settings now
6220 mSettings.writeLP();
6221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 }
6223 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 /*
6226 * Tries to delete system package.
6227 */
6228 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006229 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 ApplicationInfo applicationInfo = p.applicationInfo;
6231 //applicable for non-partially installed applications only
6232 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006233 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 return false;
6235 }
6236 PackageSetting ps = null;
6237 // Confirm if the system package has been updated
6238 // An updated system app can be deleted. This will also have to restore
6239 // the system pkg from system partition
6240 synchronized (mPackages) {
6241 ps = mSettings.getDisabledSystemPkg(p.packageName);
6242 }
6243 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006244 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 return false;
6246 } else {
6247 Log.i(TAG, "Deleting system pkg from data partition");
6248 }
6249 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006250 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006251 final boolean deleteCodeAndResources;
6252 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006253 // Delete code and resources for downgrades
6254 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006255 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006256 } else {
6257 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006258 deleteCodeAndResources = false;
6259 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006260 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006261 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6262 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 if (!ret) {
6264 return false;
6265 }
6266 synchronized (mPackages) {
6267 // Reinstate the old system package
6268 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006269 // Remove any native libraries from the upgraded package.
6270 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 }
6272 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006273 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006275 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006278 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 return false;
6280 }
6281 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006282 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006283 if (writeSettings) {
6284 mSettings.writeLP();
6285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 }
6287 return true;
6288 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006291 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6292 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293 ApplicationInfo applicationInfo = p.applicationInfo;
6294 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006295 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006296 return false;
6297 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006298 if (outInfo != null) {
6299 outInfo.uid = applicationInfo.uid;
6300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301
6302 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006303 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304
6305 // Delete application code and resources
6306 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006307 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006308 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6309 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6310 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6311 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 }
6313 return true;
6314 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 /*
6317 * This method handles package deletion in general
6318 */
6319 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006320 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6321 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006323 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 return false;
6325 }
6326 PackageParser.Package p;
6327 boolean dataOnly = false;
6328 synchronized (mPackages) {
6329 p = mPackages.get(packageName);
6330 if (p == null) {
6331 //this retrieves partially installed apps
6332 dataOnly = true;
6333 PackageSetting ps = mSettings.mPackages.get(packageName);
6334 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006335 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 return false;
6337 }
6338 p = ps.pkg;
6339 }
6340 }
6341 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006342 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 return false;
6344 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 if (dataOnly) {
6347 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006348 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 return true;
6350 }
6351 // At this point the package should have ApplicationInfo associated with it
6352 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006353 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 return false;
6355 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006356 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006357 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 Log.i(TAG, "Removing system package:"+p.packageName);
6359 // When an updated system application is deleted we delete the existing resources as well and
6360 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006361 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006362 } else {
6363 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006364 // Kill application pre-emptively especially for apps on sd.
6365 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006366 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6367 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006369 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 public void clearApplicationUserData(final String packageName,
6373 final IPackageDataObserver observer) {
6374 mContext.enforceCallingOrSelfPermission(
6375 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6376 // Queue up an async operation since the package deletion may take a little while.
6377 mHandler.post(new Runnable() {
6378 public void run() {
6379 mHandler.removeCallbacks(this);
6380 final boolean succeeded;
6381 synchronized (mInstallLock) {
6382 succeeded = clearApplicationUserDataLI(packageName);
6383 }
6384 if (succeeded) {
6385 // invoke DeviceStorageMonitor's update method to clear any notifications
6386 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6387 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6388 if (dsm != null) {
6389 dsm.updateMemory();
6390 }
6391 }
6392 if(observer != null) {
6393 try {
6394 observer.onRemoveCompleted(packageName, succeeded);
6395 } catch (RemoteException e) {
6396 Log.i(TAG, "Observer no longer exists.");
6397 }
6398 } //end if observer
6399 } //end run
6400 });
6401 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 private boolean clearApplicationUserDataLI(String packageName) {
6404 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006405 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 return false;
6407 }
6408 PackageParser.Package p;
6409 boolean dataOnly = false;
6410 synchronized (mPackages) {
6411 p = mPackages.get(packageName);
6412 if(p == null) {
6413 dataOnly = true;
6414 PackageSetting ps = mSettings.mPackages.get(packageName);
6415 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006416 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 return false;
6418 }
6419 p = ps.pkg;
6420 }
6421 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006422 boolean useEncryptedFSDir = false;
6423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 if(!dataOnly) {
6425 //need to check this only for fully installed applications
6426 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006427 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 return false;
6429 }
6430 final ApplicationInfo applicationInfo = p.applicationInfo;
6431 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006432 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 return false;
6434 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006435 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 }
6437 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006438 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006440 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 + packageName);
6442 return false;
6443 }
6444 }
6445 return true;
6446 }
6447
6448 public void deleteApplicationCacheFiles(final String packageName,
6449 final IPackageDataObserver observer) {
6450 mContext.enforceCallingOrSelfPermission(
6451 android.Manifest.permission.DELETE_CACHE_FILES, null);
6452 // Queue up an async operation since the package deletion may take a little while.
6453 mHandler.post(new Runnable() {
6454 public void run() {
6455 mHandler.removeCallbacks(this);
6456 final boolean succeded;
6457 synchronized (mInstallLock) {
6458 succeded = deleteApplicationCacheFilesLI(packageName);
6459 }
6460 if(observer != null) {
6461 try {
6462 observer.onRemoveCompleted(packageName, succeded);
6463 } catch (RemoteException e) {
6464 Log.i(TAG, "Observer no longer exists.");
6465 }
6466 } //end if observer
6467 } //end run
6468 });
6469 }
6470
6471 private boolean deleteApplicationCacheFilesLI(String packageName) {
6472 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006473 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 return false;
6475 }
6476 PackageParser.Package p;
6477 synchronized (mPackages) {
6478 p = mPackages.get(packageName);
6479 }
6480 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006481 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 return false;
6483 }
6484 final ApplicationInfo applicationInfo = p.applicationInfo;
6485 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006486 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 return false;
6488 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006489 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006491 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006493 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 + packageName);
6495 return false;
6496 }
6497 }
6498 return true;
6499 }
6500
6501 public void getPackageSizeInfo(final String packageName,
6502 final IPackageStatsObserver observer) {
6503 mContext.enforceCallingOrSelfPermission(
6504 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6505 // Queue up an async operation since the package deletion may take a little while.
6506 mHandler.post(new Runnable() {
6507 public void run() {
6508 mHandler.removeCallbacks(this);
6509 PackageStats lStats = new PackageStats(packageName);
6510 final boolean succeded;
6511 synchronized (mInstallLock) {
6512 succeded = getPackageSizeInfoLI(packageName, lStats);
6513 }
6514 if(observer != null) {
6515 try {
6516 observer.onGetStatsCompleted(lStats, succeded);
6517 } catch (RemoteException e) {
6518 Log.i(TAG, "Observer no longer exists.");
6519 }
6520 } //end if observer
6521 } //end run
6522 });
6523 }
6524
6525 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6526 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006527 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 return false;
6529 }
6530 PackageParser.Package p;
6531 boolean dataOnly = false;
6532 synchronized (mPackages) {
6533 p = mPackages.get(packageName);
6534 if(p == null) {
6535 dataOnly = true;
6536 PackageSetting ps = mSettings.mPackages.get(packageName);
6537 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006538 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 return false;
6540 }
6541 p = ps.pkg;
6542 }
6543 }
6544 String publicSrcDir = null;
6545 if(!dataOnly) {
6546 final ApplicationInfo applicationInfo = p.applicationInfo;
6547 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006548 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 return false;
6550 }
6551 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6552 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006553 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006554 if (mInstaller != null) {
6555 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006556 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 if (res < 0) {
6558 return false;
6559 } else {
6560 return true;
6561 }
6562 }
6563 return true;
6564 }
6565
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006567 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006568 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006569 }
6570
6571 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006572 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 }
6574
6575 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006576 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 }
6578
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006579 int getUidTargetSdkVersionLockedLP(int uid) {
6580 Object obj = mSettings.getUserIdLP(uid);
6581 if (obj instanceof SharedUserSetting) {
6582 SharedUserSetting sus = (SharedUserSetting)obj;
6583 final int N = sus.packages.size();
6584 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6585 Iterator<PackageSetting> it = sus.packages.iterator();
6586 int i=0;
6587 while (it.hasNext()) {
6588 PackageSetting ps = it.next();
6589 if (ps.pkg != null) {
6590 int v = ps.pkg.applicationInfo.targetSdkVersion;
6591 if (v < vers) vers = v;
6592 }
6593 }
6594 return vers;
6595 } else if (obj instanceof PackageSetting) {
6596 PackageSetting ps = (PackageSetting)obj;
6597 if (ps.pkg != null) {
6598 return ps.pkg.applicationInfo.targetSdkVersion;
6599 }
6600 }
6601 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6602 }
6603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 public void addPreferredActivity(IntentFilter filter, int match,
6605 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006607 if (mContext.checkCallingOrSelfPermission(
6608 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6609 != PackageManager.PERMISSION_GRANTED) {
6610 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6611 < Build.VERSION_CODES.FROYO) {
6612 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6613 + Binder.getCallingUid());
6614 return;
6615 }
6616 mContext.enforceCallingOrSelfPermission(
6617 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6618 }
6619
6620 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6622 mSettings.mPreferredActivities.addFilter(
6623 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006624 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 }
6626 }
6627
Satish Sampath8dbe6122009-06-02 23:35:54 +01006628 public void replacePreferredActivity(IntentFilter filter, int match,
6629 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006630 if (filter.countActions() != 1) {
6631 throw new IllegalArgumentException(
6632 "replacePreferredActivity expects filter to have only 1 action.");
6633 }
6634 if (filter.countCategories() != 1) {
6635 throw new IllegalArgumentException(
6636 "replacePreferredActivity expects filter to have only 1 category.");
6637 }
6638 if (filter.countDataAuthorities() != 0
6639 || filter.countDataPaths() != 0
6640 || filter.countDataSchemes() != 0
6641 || filter.countDataTypes() != 0) {
6642 throw new IllegalArgumentException(
6643 "replacePreferredActivity expects filter to have no data authorities, " +
6644 "paths, schemes or types.");
6645 }
6646 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006647 if (mContext.checkCallingOrSelfPermission(
6648 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6649 != PackageManager.PERMISSION_GRANTED) {
6650 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6651 < Build.VERSION_CODES.FROYO) {
6652 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6653 + Binder.getCallingUid());
6654 return;
6655 }
6656 mContext.enforceCallingOrSelfPermission(
6657 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6658 }
6659
Satish Sampath8dbe6122009-06-02 23:35:54 +01006660 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6661 String action = filter.getAction(0);
6662 String category = filter.getCategory(0);
6663 while (it.hasNext()) {
6664 PreferredActivity pa = it.next();
6665 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6666 it.remove();
6667 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6668 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6669 }
6670 }
6671 addPreferredActivity(filter, match, set, activity);
6672 }
6673 }
6674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006677 int uid = Binder.getCallingUid();
6678 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006679 if (pkg == null || pkg.applicationInfo.uid != uid) {
6680 if (mContext.checkCallingOrSelfPermission(
6681 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6682 != PackageManager.PERMISSION_GRANTED) {
6683 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6684 < Build.VERSION_CODES.FROYO) {
6685 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6686 + Binder.getCallingUid());
6687 return;
6688 }
6689 mContext.enforceCallingOrSelfPermission(
6690 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6691 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006692 }
6693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006695 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 }
6697 }
6698 }
6699
6700 boolean clearPackagePreferredActivitiesLP(String packageName) {
6701 boolean changed = false;
6702 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6703 while (it.hasNext()) {
6704 PreferredActivity pa = it.next();
6705 if (pa.mActivity.getPackageName().equals(packageName)) {
6706 it.remove();
6707 changed = true;
6708 }
6709 }
6710 return changed;
6711 }
6712
6713 public int getPreferredActivities(List<IntentFilter> outFilters,
6714 List<ComponentName> outActivities, String packageName) {
6715
6716 int num = 0;
6717 synchronized (mPackages) {
6718 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6719 while (it.hasNext()) {
6720 PreferredActivity pa = it.next();
6721 if (packageName == null
6722 || pa.mActivity.getPackageName().equals(packageName)) {
6723 if (outFilters != null) {
6724 outFilters.add(new IntentFilter(pa));
6725 }
6726 if (outActivities != null) {
6727 outActivities.add(pa.mActivity);
6728 }
6729 }
6730 }
6731 }
6732
6733 return num;
6734 }
6735
6736 public void setApplicationEnabledSetting(String appPackageName,
6737 int newState, int flags) {
6738 setEnabledSetting(appPackageName, null, newState, flags);
6739 }
6740
6741 public void setComponentEnabledSetting(ComponentName componentName,
6742 int newState, int flags) {
6743 setEnabledSetting(componentName.getPackageName(),
6744 componentName.getClassName(), newState, flags);
6745 }
6746
6747 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006748 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6750 || newState == COMPONENT_ENABLED_STATE_ENABLED
6751 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6752 throw new IllegalArgumentException("Invalid new component state: "
6753 + newState);
6754 }
6755 PackageSetting pkgSetting;
6756 final int uid = Binder.getCallingUid();
6757 final int permission = mContext.checkCallingPermission(
6758 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6759 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006760 boolean sendNow = false;
6761 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006762 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006764 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006765 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006766 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006768 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006770 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 }
6772 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006773 "Unknown component: " + packageName
6774 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 }
6776 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6777 throw new SecurityException(
6778 "Permission Denial: attempt to change component state from pid="
6779 + Binder.getCallingPid()
6780 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6781 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006782 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006784 if (pkgSetting.enabled == newState) {
6785 // Nothing to do
6786 return;
6787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006789 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006790 } else {
6791 // We're dealing with a component level state change
6792 switch (newState) {
6793 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006794 if (!pkgSetting.enableComponentLP(className)) {
6795 return;
6796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 break;
6798 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006799 if (!pkgSetting.disableComponentLP(className)) {
6800 return;
6801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 break;
6803 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006804 if (!pkgSetting.restoreComponentLP(className)) {
6805 return;
6806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 break;
6808 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006809 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006810 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 }
6812 }
6813 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006814 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006815 components = mPendingBroadcasts.get(packageName);
6816 boolean newPackage = components == null;
6817 if (newPackage) {
6818 components = new ArrayList<String>();
6819 }
6820 if (!components.contains(componentName)) {
6821 components.add(componentName);
6822 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006823 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6824 sendNow = true;
6825 // Purge entry from pending broadcast list if another one exists already
6826 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006827 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006828 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006829 if (newPackage) {
6830 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006831 }
6832 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6833 // Schedule a message
6834 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6835 }
6836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 long callingId = Binder.clearCallingIdentity();
6840 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006841 if (sendNow) {
6842 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006843 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 } finally {
6846 Binder.restoreCallingIdentity(callingId);
6847 }
6848 }
6849
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006850 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006851 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6852 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6853 + " components=" + componentNames);
6854 Bundle extras = new Bundle(4);
6855 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6856 String nameList[] = new String[componentNames.size()];
6857 componentNames.toArray(nameList);
6858 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006859 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6860 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006861 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006862 }
6863
Jacek Surazski65e13172009-04-28 15:26:38 +02006864 public String getInstallerPackageName(String packageName) {
6865 synchronized (mPackages) {
6866 PackageSetting pkg = mSettings.mPackages.get(packageName);
6867 if (pkg == null) {
6868 throw new IllegalArgumentException("Unknown package: " + packageName);
6869 }
6870 return pkg.installerPackageName;
6871 }
6872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 public int getApplicationEnabledSetting(String appPackageName) {
6875 synchronized (mPackages) {
6876 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6877 if (pkg == null) {
6878 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6879 }
6880 return pkg.enabled;
6881 }
6882 }
6883
6884 public int getComponentEnabledSetting(ComponentName componentName) {
6885 synchronized (mPackages) {
6886 final String packageNameStr = componentName.getPackageName();
6887 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6888 if (pkg == null) {
6889 throw new IllegalArgumentException("Unknown component: " + componentName);
6890 }
6891 final String classNameStr = componentName.getClassName();
6892 return pkg.currentEnabledStateLP(classNameStr);
6893 }
6894 }
6895
6896 public void enterSafeMode() {
6897 if (!mSystemReady) {
6898 mSafeMode = true;
6899 }
6900 }
6901
6902 public void systemReady() {
6903 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006904
6905 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006906 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006907 mContext.getContentResolver(),
6908 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006909 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006910 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006911 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006913 }
6914
6915 public boolean isSafeMode() {
6916 return mSafeMode;
6917 }
6918
6919 public boolean hasSystemUidErrors() {
6920 return mHasSystemUidErrors;
6921 }
6922
6923 static String arrayToString(int[] array) {
6924 StringBuffer buf = new StringBuffer(128);
6925 buf.append('[');
6926 if (array != null) {
6927 for (int i=0; i<array.length; i++) {
6928 if (i > 0) buf.append(", ");
6929 buf.append(array[i]);
6930 }
6931 }
6932 buf.append(']');
6933 return buf.toString();
6934 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006936 @Override
6937 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6938 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6939 != PackageManager.PERMISSION_GRANTED) {
6940 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6941 + Binder.getCallingPid()
6942 + ", uid=" + Binder.getCallingUid()
6943 + " without permission "
6944 + android.Manifest.permission.DUMP);
6945 return;
6946 }
6947
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006948 boolean dumpStar = true;
6949 boolean dumpLibs = false;
6950 boolean dumpFeatures = false;
6951 boolean dumpResolvers = false;
6952 boolean dumpPermissions = false;
6953 boolean dumpPackages = false;
6954 boolean dumpSharedUsers = false;
6955 boolean dumpMessages = false;
6956 boolean dumpProviders = false;
6957
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006958 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006959 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006960
6961 int opti = 0;
6962 while (opti < args.length) {
6963 String opt = args[opti];
6964 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6965 break;
6966 }
6967 opti++;
6968 if ("-a".equals(opt)) {
6969 // Right now we only know how to print all.
6970 } else if ("-h".equals(opt)) {
6971 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006972 pw.println(" [-h] [-f] [cmd] ...");
6973 pw.println(" -f: print details of intent filters");
6974 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006975 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006976 pw.println(" l[ibraries]: list known shared libraries");
6977 pw.println(" f[ibraries]: list device features");
6978 pw.println(" r[esolvers]: dump intent resolvers");
6979 pw.println(" perm[issions]: dump permissions");
6980 pw.println(" prov[iders]: dump content providers");
6981 pw.println(" p[ackages]: dump installed packages");
6982 pw.println(" s[hared-users]: dump shared user IDs");
6983 pw.println(" m[essages]: print collected runtime messages");
6984 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006985 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006986 } else if ("-f".equals(opt)) {
6987 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006988 } else {
6989 pw.println("Unknown argument: " + opt + "; use -h for help");
6990 }
6991 }
6992
6993 // Is the caller requesting to dump a particular piece of data?
6994 if (opti < args.length) {
6995 String cmd = args[opti];
6996 opti++;
6997 // Is this a package name?
6998 if ("android".equals(cmd) || cmd.contains(".")) {
6999 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007000 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
7001 dumpStar = false;
7002 dumpLibs = true;
7003 } else if ("f".equals(cmd) || "features".equals(cmd)) {
7004 dumpStar = false;
7005 dumpFeatures = true;
7006 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
7007 dumpStar = false;
7008 dumpResolvers = true;
7009 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
7010 dumpStar = false;
7011 dumpPermissions = true;
7012 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
7013 dumpStar = false;
7014 dumpPackages = true;
7015 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
7016 dumpStar = false;
7017 dumpSharedUsers = true;
7018 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
7019 dumpStar = false;
7020 dumpProviders = true;
7021 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
7022 dumpStar = false;
7023 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007024 }
7025 }
7026
7027 boolean printedTitle = false;
7028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007029 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007030 if ((dumpStar || dumpLibs) && packageName == null) {
7031 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007032 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007033 pw.println("Libraries:");
7034 Iterator<String> it = mSharedLibraries.keySet().iterator();
7035 while (it.hasNext()) {
7036 String name = it.next();
7037 pw.print(" ");
7038 pw.print(name);
7039 pw.print(" -> ");
7040 pw.println(mSharedLibraries.get(name));
7041 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007042 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007043
7044 if ((dumpStar || dumpFeatures) && packageName == null) {
7045 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007046 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007047 pw.println("Features:");
7048 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7049 while (it.hasNext()) {
7050 String name = it.next();
7051 pw.print(" ");
7052 pw.println(name);
7053 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007054 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007055
7056 if (dumpStar || dumpResolvers) {
7057 if (mActivities.dump(pw, printedTitle
7058 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7059 " ", packageName, showFilters)) {
7060 printedTitle = true;
7061 }
7062 if (mReceivers.dump(pw, printedTitle
7063 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7064 " ", packageName, showFilters)) {
7065 printedTitle = true;
7066 }
7067 if (mServices.dump(pw, printedTitle
7068 ? "\nService Resolver Table:" : "Service Resolver Table:",
7069 " ", packageName, showFilters)) {
7070 printedTitle = true;
7071 }
7072 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7073 ? "\nPreferred Activities:" : "Preferred Activities:",
7074 " ", packageName, showFilters)) {
7075 printedTitle = true;
7076 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007077 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007078
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007079 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007080 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007082 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7083 continue;
7084 }
7085 if (!printedSomething) {
7086 if (printedTitle) pw.println(" ");
7087 pw.println("Permissions:");
7088 printedSomething = true;
7089 printedTitle = true;
7090 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007091 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7092 pw.print(Integer.toHexString(System.identityHashCode(p)));
7093 pw.println("):");
7094 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7095 pw.print(" uid="); pw.print(p.uid);
7096 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007097 pw.print(" type="); pw.print(p.type);
7098 pw.print(" prot="); pw.println(p.protectionLevel);
7099 if (p.packageSetting != null) {
7100 pw.print(" packageSetting="); pw.println(p.packageSetting);
7101 }
7102 if (p.perm != null) {
7103 pw.print(" perm="); pw.println(p.perm);
7104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 }
7106 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007107
7108 if (dumpStar || dumpProviders) {
7109 printedSomething = false;
7110 for (PackageParser.Provider p : mProviders.values()) {
7111 if (packageName != null && !packageName.equals(p.info.packageName)) {
7112 continue;
7113 }
7114 if (!printedSomething) {
7115 if (printedTitle) pw.println(" ");
7116 pw.println("Registered ContentProviders:");
7117 printedSomething = true;
7118 printedTitle = true;
7119 }
7120 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7121 pw.println(p.toString());
7122 }
7123 }
7124
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007125 printedSomething = false;
7126 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007127 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007128 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7129 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007130 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007131 if (packageName != null && !packageName.equals(ps.realName)
7132 && !packageName.equals(ps.name)) {
7133 continue;
7134 }
7135 if (!printedSomething) {
7136 if (printedTitle) pw.println(" ");
7137 pw.println("Packages:");
7138 printedSomething = true;
7139 printedTitle = true;
7140 }
7141 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007142 pw.print(" Package [");
7143 pw.print(ps.realName != null ? ps.realName : ps.name);
7144 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007145 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7146 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007147 if (ps.realName != null) {
7148 pw.print(" compat name="); pw.println(ps.name);
7149 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007150 pw.print(" userId="); pw.print(ps.userId);
7151 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7152 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7153 pw.print(" pkg="); pw.println(ps.pkg);
7154 pw.print(" codePath="); pw.println(ps.codePathString);
7155 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007156 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007157 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007158 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007159 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007160 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007161 if (ps.pkg.mOperationPending) {
7162 pw.println(" mOperationPending=true");
7163 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007164 pw.print(" supportsScreens=[");
7165 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007166 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007167 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7168 if (!first) pw.print(", ");
7169 first = false;
7170 pw.print("small");
7171 }
7172 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007173 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007174 if (!first) pw.print(", ");
7175 first = false;
7176 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007178 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007179 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007180 if (!first) pw.print(", ");
7181 first = false;
7182 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007183 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007184 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007185 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007186 if (!first) pw.print(", ");
7187 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007188 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007189 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007190 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007191 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007192 if (!first) pw.print(", ");
7193 first = false;
7194 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007195 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007196 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007197 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7198 if (!first) pw.print(", ");
7199 first = false;
7200 pw.print("anyDensity");
7201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007203 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007204 pw.print(" timeStamp=");
7205 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7206 pw.print(" firstInstallTime=");
7207 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7208 pw.print(" lastUpdateTime=");
7209 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007210 pw.print(" signatures="); pw.println(ps.signatures);
7211 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007212 pw.print(" haveGids="); pw.println(ps.haveGids);
7213 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007214 pw.print(" installStatus="); pw.print(ps.installStatus);
7215 pw.print(" enabled="); pw.println(ps.enabled);
Andy Stadler8e2be262010-10-12 15:00:43 -07007216 pw.print(" versionCode="); pw.print(ps.versionCode);
7217 pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007218 if (ps.disabledComponents.size() > 0) {
7219 pw.println(" disabledComponents:");
7220 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007221 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007222 }
7223 }
7224 if (ps.enabledComponents.size() > 0) {
7225 pw.println(" enabledComponents:");
7226 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007227 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 }
7229 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007230 if (ps.grantedPermissions.size() > 0) {
7231 pw.println(" grantedPermissions:");
7232 for (String s : ps.grantedPermissions) {
7233 pw.print(" "); pw.println(s);
7234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007236 }
7237 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007238 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007239 if (dumpStar || dumpPackages) {
7240 if (mSettings.mRenamedPackages.size() > 0) {
7241 for (HashMap.Entry<String, String> e
7242 : mSettings.mRenamedPackages.entrySet()) {
7243 if (packageName != null && !packageName.equals(e.getKey())
7244 && !packageName.equals(e.getValue())) {
7245 continue;
7246 }
7247 if (!printedSomething) {
7248 if (printedTitle) pw.println(" ");
7249 pw.println("Renamed packages:");
7250 printedSomething = true;
7251 printedTitle = true;
7252 }
7253 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7254 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007255 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007256 }
7257 printedSomething = false;
7258 if (mSettings.mDisabledSysPackages.size() > 0) {
7259 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7260 if (packageName != null && !packageName.equals(ps.realName)
7261 && !packageName.equals(ps.name)) {
7262 continue;
7263 }
7264 if (!printedSomething) {
7265 if (printedTitle) pw.println(" ");
7266 pw.println("Hidden system packages:");
7267 printedSomething = true;
7268 printedTitle = true;
7269 }
7270 pw.print(" Package [");
7271 pw.print(ps.realName != null ? ps.realName : ps.name);
7272 pw.print("] (");
7273 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7274 pw.println("):");
7275 if (ps.realName != null) {
7276 pw.print(" compat name="); pw.println(ps.name);
7277 }
7278 pw.print(" userId="); pw.println(ps.userId);
7279 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7280 pw.print(" codePath="); pw.println(ps.codePathString);
7281 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007282 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007283 }
7284 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007285 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007286 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007288 if (packageName != null && su != packageSharedUser) {
7289 continue;
7290 }
7291 if (!printedSomething) {
7292 if (printedTitle) pw.println(" ");
7293 pw.println("Shared users:");
7294 printedSomething = true;
7295 printedTitle = true;
7296 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007297 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7298 pw.print(Integer.toHexString(System.identityHashCode(su)));
7299 pw.println("):");
7300 pw.print(" userId="); pw.print(su.userId);
7301 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 pw.println(" grantedPermissions:");
7303 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007304 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 }
7307 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007308
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007309 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007310 if (printedTitle) pw.println(" ");
7311 printedTitle = true;
7312 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007313 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007314
7315 pw.println(" ");
7316 pw.println("Package warning messages:");
7317 File fname = getSettingsProblemFile();
7318 FileInputStream in;
7319 try {
7320 in = new FileInputStream(fname);
7321 int avail = in.available();
7322 byte[] data = new byte[avail];
7323 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007324 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007325 } catch (FileNotFoundException e) {
7326 } catch (IOException e) {
7327 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 }
7330 }
7331
7332 static final class BasePermission {
7333 final static int TYPE_NORMAL = 0;
7334 final static int TYPE_BUILTIN = 1;
7335 final static int TYPE_DYNAMIC = 2;
7336
7337 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007338 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007339 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007340 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007341 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 PackageParser.Permission perm;
7343 PermissionInfo pendingInfo;
7344 int uid;
7345 int[] gids;
7346
7347 BasePermission(String _name, String _sourcePackage, int _type) {
7348 name = _name;
7349 sourcePackage = _sourcePackage;
7350 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007351 // Default to most conservative protection level.
7352 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7353 }
7354
7355 public String toString() {
7356 return "BasePermission{"
7357 + Integer.toHexString(System.identityHashCode(this))
7358 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007359 }
7360 }
7361
7362 static class PackageSignatures {
7363 private Signature[] mSignatures;
7364
7365 PackageSignatures(Signature[] sigs) {
7366 assignSignatures(sigs);
7367 }
7368
7369 PackageSignatures() {
7370 }
7371
7372 void writeXml(XmlSerializer serializer, String tagName,
7373 ArrayList<Signature> pastSignatures) throws IOException {
7374 if (mSignatures == null) {
7375 return;
7376 }
7377 serializer.startTag(null, tagName);
7378 serializer.attribute(null, "count",
7379 Integer.toString(mSignatures.length));
7380 for (int i=0; i<mSignatures.length; i++) {
7381 serializer.startTag(null, "cert");
7382 final Signature sig = mSignatures[i];
7383 final int sigHash = sig.hashCode();
7384 final int numPast = pastSignatures.size();
7385 int j;
7386 for (j=0; j<numPast; j++) {
7387 Signature pastSig = pastSignatures.get(j);
7388 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7389 serializer.attribute(null, "index", Integer.toString(j));
7390 break;
7391 }
7392 }
7393 if (j >= numPast) {
7394 pastSignatures.add(sig);
7395 serializer.attribute(null, "index", Integer.toString(numPast));
7396 serializer.attribute(null, "key", sig.toCharsString());
7397 }
7398 serializer.endTag(null, "cert");
7399 }
7400 serializer.endTag(null, tagName);
7401 }
7402
7403 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7404 throws IOException, XmlPullParserException {
7405 String countStr = parser.getAttributeValue(null, "count");
7406 if (countStr == null) {
7407 reportSettingsProblem(Log.WARN,
7408 "Error in package manager settings: <signatures> has"
7409 + " no count at " + parser.getPositionDescription());
7410 XmlUtils.skipCurrentTag(parser);
7411 }
7412 final int count = Integer.parseInt(countStr);
7413 mSignatures = new Signature[count];
7414 int pos = 0;
7415
7416 int outerDepth = parser.getDepth();
7417 int type;
7418 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7419 && (type != XmlPullParser.END_TAG
7420 || parser.getDepth() > outerDepth)) {
7421 if (type == XmlPullParser.END_TAG
7422 || type == XmlPullParser.TEXT) {
7423 continue;
7424 }
7425
7426 String tagName = parser.getName();
7427 if (tagName.equals("cert")) {
7428 if (pos < count) {
7429 String index = parser.getAttributeValue(null, "index");
7430 if (index != null) {
7431 try {
7432 int idx = Integer.parseInt(index);
7433 String key = parser.getAttributeValue(null, "key");
7434 if (key == null) {
7435 if (idx >= 0 && idx < pastSignatures.size()) {
7436 Signature sig = pastSignatures.get(idx);
7437 if (sig != null) {
7438 mSignatures[pos] = pastSignatures.get(idx);
7439 pos++;
7440 } else {
7441 reportSettingsProblem(Log.WARN,
7442 "Error in package manager settings: <cert> "
7443 + "index " + index + " is not defined at "
7444 + parser.getPositionDescription());
7445 }
7446 } else {
7447 reportSettingsProblem(Log.WARN,
7448 "Error in package manager settings: <cert> "
7449 + "index " + index + " is out of bounds at "
7450 + parser.getPositionDescription());
7451 }
7452 } else {
7453 while (pastSignatures.size() <= idx) {
7454 pastSignatures.add(null);
7455 }
7456 Signature sig = new Signature(key);
7457 pastSignatures.set(idx, sig);
7458 mSignatures[pos] = sig;
7459 pos++;
7460 }
7461 } catch (NumberFormatException e) {
7462 reportSettingsProblem(Log.WARN,
7463 "Error in package manager settings: <cert> "
7464 + "index " + index + " is not a number at "
7465 + parser.getPositionDescription());
7466 }
7467 } else {
7468 reportSettingsProblem(Log.WARN,
7469 "Error in package manager settings: <cert> has"
7470 + " no index at " + parser.getPositionDescription());
7471 }
7472 } else {
7473 reportSettingsProblem(Log.WARN,
7474 "Error in package manager settings: too "
7475 + "many <cert> tags, expected " + count
7476 + " at " + parser.getPositionDescription());
7477 }
7478 } else {
7479 reportSettingsProblem(Log.WARN,
7480 "Unknown element under <cert>: "
7481 + parser.getName());
7482 }
7483 XmlUtils.skipCurrentTag(parser);
7484 }
7485
7486 if (pos < count) {
7487 // Should never happen -- there is an error in the written
7488 // settings -- but if it does we don't want to generate
7489 // a bad array.
7490 Signature[] newSigs = new Signature[pos];
7491 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7492 mSignatures = newSigs;
7493 }
7494 }
7495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007496 private void assignSignatures(Signature[] sigs) {
7497 if (sigs == null) {
7498 mSignatures = null;
7499 return;
7500 }
7501 mSignatures = new Signature[sigs.length];
7502 for (int i=0; i<sigs.length; i++) {
7503 mSignatures[i] = sigs[i];
7504 }
7505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 @Override
7508 public String toString() {
7509 StringBuffer buf = new StringBuffer(128);
7510 buf.append("PackageSignatures{");
7511 buf.append(Integer.toHexString(System.identityHashCode(this)));
7512 buf.append(" [");
7513 if (mSignatures != null) {
7514 for (int i=0; i<mSignatures.length; i++) {
7515 if (i > 0) buf.append(", ");
7516 buf.append(Integer.toHexString(
7517 System.identityHashCode(mSignatures[i])));
7518 }
7519 }
7520 buf.append("]}");
7521 return buf.toString();
7522 }
7523 }
7524
7525 static class PreferredActivity extends IntentFilter {
7526 final int mMatch;
7527 final String[] mSetPackages;
7528 final String[] mSetClasses;
7529 final String[] mSetComponents;
7530 final ComponentName mActivity;
7531 final String mShortActivity;
7532 String mParseError;
7533
7534 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7535 ComponentName activity) {
7536 super(filter);
7537 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7538 mActivity = activity;
7539 mShortActivity = activity.flattenToShortString();
7540 mParseError = null;
7541 if (set != null) {
7542 final int N = set.length;
7543 String[] myPackages = new String[N];
7544 String[] myClasses = new String[N];
7545 String[] myComponents = new String[N];
7546 for (int i=0; i<N; i++) {
7547 ComponentName cn = set[i];
7548 if (cn == null) {
7549 mSetPackages = null;
7550 mSetClasses = null;
7551 mSetComponents = null;
7552 return;
7553 }
7554 myPackages[i] = cn.getPackageName().intern();
7555 myClasses[i] = cn.getClassName().intern();
7556 myComponents[i] = cn.flattenToShortString().intern();
7557 }
7558 mSetPackages = myPackages;
7559 mSetClasses = myClasses;
7560 mSetComponents = myComponents;
7561 } else {
7562 mSetPackages = null;
7563 mSetClasses = null;
7564 mSetComponents = null;
7565 }
7566 }
7567
7568 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7569 IOException {
7570 mShortActivity = parser.getAttributeValue(null, "name");
7571 mActivity = ComponentName.unflattenFromString(mShortActivity);
7572 if (mActivity == null) {
7573 mParseError = "Bad activity name " + mShortActivity;
7574 }
7575 String matchStr = parser.getAttributeValue(null, "match");
7576 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7577 String setCountStr = parser.getAttributeValue(null, "set");
7578 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7579
7580 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7581 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7582 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7583
7584 int setPos = 0;
7585
7586 int outerDepth = parser.getDepth();
7587 int type;
7588 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7589 && (type != XmlPullParser.END_TAG
7590 || parser.getDepth() > outerDepth)) {
7591 if (type == XmlPullParser.END_TAG
7592 || type == XmlPullParser.TEXT) {
7593 continue;
7594 }
7595
7596 String tagName = parser.getName();
7597 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7598 // + parser.getDepth() + " tag=" + tagName);
7599 if (tagName.equals("set")) {
7600 String name = parser.getAttributeValue(null, "name");
7601 if (name == null) {
7602 if (mParseError == null) {
7603 mParseError = "No name in set tag in preferred activity "
7604 + mShortActivity;
7605 }
7606 } else if (setPos >= setCount) {
7607 if (mParseError == null) {
7608 mParseError = "Too many set tags in preferred activity "
7609 + mShortActivity;
7610 }
7611 } else {
7612 ComponentName cn = ComponentName.unflattenFromString(name);
7613 if (cn == null) {
7614 if (mParseError == null) {
7615 mParseError = "Bad set name " + name + " in preferred activity "
7616 + mShortActivity;
7617 }
7618 } else {
7619 myPackages[setPos] = cn.getPackageName();
7620 myClasses[setPos] = cn.getClassName();
7621 myComponents[setPos] = name;
7622 setPos++;
7623 }
7624 }
7625 XmlUtils.skipCurrentTag(parser);
7626 } else if (tagName.equals("filter")) {
7627 //Log.i(TAG, "Starting to parse filter...");
7628 readFromXml(parser);
7629 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7630 // + parser.getDepth() + " tag=" + parser.getName());
7631 } else {
7632 reportSettingsProblem(Log.WARN,
7633 "Unknown element under <preferred-activities>: "
7634 + parser.getName());
7635 XmlUtils.skipCurrentTag(parser);
7636 }
7637 }
7638
7639 if (setPos != setCount) {
7640 if (mParseError == null) {
7641 mParseError = "Not enough set tags (expected " + setCount
7642 + " but found " + setPos + ") in " + mShortActivity;
7643 }
7644 }
7645
7646 mSetPackages = myPackages;
7647 mSetClasses = myClasses;
7648 mSetComponents = myComponents;
7649 }
7650
7651 public void writeToXml(XmlSerializer serializer) throws IOException {
7652 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7653 serializer.attribute(null, "name", mShortActivity);
7654 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7655 serializer.attribute(null, "set", Integer.toString(NS));
7656 for (int s=0; s<NS; s++) {
7657 serializer.startTag(null, "set");
7658 serializer.attribute(null, "name", mSetComponents[s]);
7659 serializer.endTag(null, "set");
7660 }
7661 serializer.startTag(null, "filter");
7662 super.writeToXml(serializer);
7663 serializer.endTag(null, "filter");
7664 }
7665
7666 boolean sameSet(List<ResolveInfo> query, int priority) {
7667 if (mSetPackages == null) return false;
7668 final int NQ = query.size();
7669 final int NS = mSetPackages.length;
7670 int numMatch = 0;
7671 for (int i=0; i<NQ; i++) {
7672 ResolveInfo ri = query.get(i);
7673 if (ri.priority != priority) continue;
7674 ActivityInfo ai = ri.activityInfo;
7675 boolean good = false;
7676 for (int j=0; j<NS; j++) {
7677 if (mSetPackages[j].equals(ai.packageName)
7678 && mSetClasses[j].equals(ai.name)) {
7679 numMatch++;
7680 good = true;
7681 break;
7682 }
7683 }
7684 if (!good) return false;
7685 }
7686 return numMatch == NS;
7687 }
7688 }
7689
7690 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007691 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 HashSet<String> grantedPermissions = new HashSet<String>();
7694 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007696 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007697 setFlags(pkgFlags);
7698 }
7699
7700 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007701 this.pkgFlags = pkgFlags & (
7702 ApplicationInfo.FLAG_SYSTEM |
7703 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007704 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007705 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007706 }
7707 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007709 /**
7710 * Settings base class for pending and resolved classes.
7711 */
7712 static class PackageSettingBase extends GrantedPermissions {
7713 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007714 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007715 File codePath;
7716 String codePathString;
7717 File resourcePath;
7718 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007719 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007720 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007721 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007722 long firstInstallTime;
7723 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007724 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007725
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007726 boolean uidError;
7727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007728 PackageSignatures signatures = new PackageSignatures();
7729
7730 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007731 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007733 /* Explicitly disabled components */
7734 HashSet<String> disabledComponents = new HashSet<String>(0);
7735 /* Explicitly enabled components */
7736 HashSet<String> enabledComponents = new HashSet<String>(0);
7737 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7738 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007739
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007740 PackageSettingBase origPackage;
7741
Jacek Surazski65e13172009-04-28 15:26:38 +02007742 /* package name of the app that installed this package */
7743 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007744
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007745 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007746 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 super(pkgFlags);
7748 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007749 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007750 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007751 }
7752
Kenny Root806cc132010-09-12 08:34:19 -07007753 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7754 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 this.codePath = codePath;
7756 this.codePathString = codePath.toString();
7757 this.resourcePath = resourcePath;
7758 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007759 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007760 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 }
Kenny Root85387d72010-08-26 10:13:11 -07007762
Jacek Surazski65e13172009-04-28 15:26:38 +02007763 public void setInstallerPackageName(String packageName) {
7764 installerPackageName = packageName;
7765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007766
Jacek Surazski65e13172009-04-28 15:26:38 +02007767 String getInstallerPackageName() {
7768 return installerPackageName;
7769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 public void setInstallStatus(int newStatus) {
7772 installStatus = newStatus;
7773 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007775 public int getInstallStatus() {
7776 return installStatus;
7777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 }
7782
7783 public void copyFrom(PackageSettingBase base) {
7784 grantedPermissions = base.grantedPermissions;
7785 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007788 firstInstallTime = base.firstInstallTime;
7789 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007790 signatures = base.signatures;
7791 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007792 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 disabledComponents = base.disabledComponents;
7794 enabledComponents = base.enabledComponents;
7795 enabled = base.enabled;
7796 installStatus = base.installStatus;
7797 }
7798
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007799 boolean enableComponentLP(String componentClassName) {
7800 boolean changed = disabledComponents.remove(componentClassName);
7801 changed |= enabledComponents.add(componentClassName);
7802 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 }
7804
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007805 boolean disableComponentLP(String componentClassName) {
7806 boolean changed = enabledComponents.remove(componentClassName);
7807 changed |= disabledComponents.add(componentClassName);
7808 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 }
7810
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007811 boolean restoreComponentLP(String componentClassName) {
7812 boolean changed = enabledComponents.remove(componentClassName);
7813 changed |= disabledComponents.remove(componentClassName);
7814 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 }
7816
7817 int currentEnabledStateLP(String componentName) {
7818 if (enabledComponents.contains(componentName)) {
7819 return COMPONENT_ENABLED_STATE_ENABLED;
7820 } else if (disabledComponents.contains(componentName)) {
7821 return COMPONENT_ENABLED_STATE_DISABLED;
7822 } else {
7823 return COMPONENT_ENABLED_STATE_DEFAULT;
7824 }
7825 }
7826 }
7827
7828 /**
7829 * Settings data for a particular package we know about.
7830 */
7831 static final class PackageSetting extends PackageSettingBase {
7832 int userId;
7833 PackageParser.Package pkg;
7834 SharedUserSetting sharedUser;
7835
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007836 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007837 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7838 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7839 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 @Override
7843 public String toString() {
7844 return "PackageSetting{"
7845 + Integer.toHexString(System.identityHashCode(this))
7846 + " " + name + "/" + userId + "}";
7847 }
7848 }
7849
7850 /**
7851 * Settings data for a particular shared user ID we know about.
7852 */
7853 static final class SharedUserSetting extends GrantedPermissions {
7854 final String name;
7855 int userId;
7856 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7857 final PackageSignatures signatures = new PackageSignatures();
7858
7859 SharedUserSetting(String _name, int _pkgFlags) {
7860 super(_pkgFlags);
7861 name = _name;
7862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 @Override
7865 public String toString() {
7866 return "SharedUserSetting{"
7867 + Integer.toHexString(System.identityHashCode(this))
7868 + " " + name + "/" + userId + "}";
7869 }
7870 }
7871
7872 /**
7873 * Holds information about dynamic settings.
7874 */
7875 private static final class Settings {
7876 private final File mSettingsFilename;
7877 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007878 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 private final HashMap<String, PackageSetting> mPackages =
7880 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007881 // List of replaced system applications
7882 final HashMap<String, PackageSetting> mDisabledSysPackages =
7883 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007884
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007885 // These are the last platform API version we were using for
7886 // the apps installed on internal and external storage. It is
7887 // used to grant newer permissions one time during a system upgrade.
7888 int mInternalSdkPlatform;
7889 int mExternalSdkPlatform;
7890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 // The user's preferred activities associated with particular intent
7892 // filters.
7893 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7894 new IntentResolver<PreferredActivity, PreferredActivity>() {
7895 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007896 protected String packageForFilter(PreferredActivity filter) {
7897 return filter.mActivity.getPackageName();
7898 }
7899 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007900 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007902 out.print(prefix); out.print(
7903 Integer.toHexString(System.identityHashCode(filter)));
7904 out.print(' ');
7905 out.print(filter.mActivity.flattenToShortString());
7906 out.print(" match=0x");
7907 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007909 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007910 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007911 out.print(prefix); out.print(" ");
7912 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007913 }
7914 }
7915 }
7916 };
7917 private final HashMap<String, SharedUserSetting> mSharedUsers =
7918 new HashMap<String, SharedUserSetting>();
7919 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7920 private final SparseArray<Object> mOtherUserIds =
7921 new SparseArray<Object>();
7922
7923 // For reading/writing settings file.
7924 private final ArrayList<Signature> mPastSignatures =
7925 new ArrayList<Signature>();
7926
7927 // Mapping from permission names to info about them.
7928 final HashMap<String, BasePermission> mPermissions =
7929 new HashMap<String, BasePermission>();
7930
7931 // Mapping from permission tree names to info about them.
7932 final HashMap<String, BasePermission> mPermissionTrees =
7933 new HashMap<String, BasePermission>();
7934
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007935 // Packages that have been uninstalled and still need their external
7936 // storage data deleted.
7937 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7938
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007939 // Packages that have been renamed since they were first installed.
7940 // Keys are the new names of the packages, values are the original
7941 // names. The packages appear everwhere else under their original
7942 // names.
7943 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007945 private final StringBuilder mReadMessages = new StringBuilder();
7946
7947 private static final class PendingPackage extends PackageSettingBase {
7948 final int sharedId;
7949
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007950 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007951 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7952 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7953 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007954 this.sharedId = sharedId;
7955 }
7956 }
7957 private final ArrayList<PendingPackage> mPendingPackages
7958 = new ArrayList<PendingPackage>();
7959
7960 Settings() {
7961 File dataDir = Environment.getDataDirectory();
7962 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007963 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7964 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007965 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007966 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967 FileUtils.setPermissions(systemDir.toString(),
7968 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7969 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7970 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007971 FileUtils.setPermissions(systemSecureDir.toString(),
7972 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7973 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7974 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 mSettingsFilename = new File(systemDir, "packages.xml");
7976 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007977 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007978 }
7979
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007980 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007981 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007982 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007984 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007985 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 return p;
7987 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007988
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007989 PackageSetting peekPackageLP(String name) {
7990 return mPackages.get(name);
7991 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 PackageSetting p = mPackages.get(name);
7993 if (p != null && p.codePath.getPath().equals(codePath)) {
7994 return p;
7995 }
7996 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007997 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 void setInstallStatus(String pkgName, int status) {
8001 PackageSetting p = mPackages.get(pkgName);
8002 if(p != null) {
8003 if(p.getInstallStatus() != status) {
8004 p.setInstallStatus(status);
8005 }
8006 }
8007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008008
Jacek Surazski65e13172009-04-28 15:26:38 +02008009 void setInstallerPackageName(String pkgName,
8010 String installerPkgName) {
8011 PackageSetting p = mPackages.get(pkgName);
8012 if(p != null) {
8013 p.setInstallerPackageName(installerPkgName);
8014 }
8015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008016
Jacek Surazski65e13172009-04-28 15:26:38 +02008017 String getInstallerPackageName(String pkgName) {
8018 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008019 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008020 }
8021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008022 int getInstallStatus(String pkgName) {
8023 PackageSetting p = mPackages.get(pkgName);
8024 if(p != null) {
8025 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 return -1;
8028 }
8029
8030 SharedUserSetting getSharedUserLP(String name,
8031 int pkgFlags, boolean create) {
8032 SharedUserSetting s = mSharedUsers.get(name);
8033 if (s == null) {
8034 if (!create) {
8035 return null;
8036 }
8037 s = new SharedUserSetting(name, pkgFlags);
8038 if (MULTIPLE_APPLICATION_UIDS) {
8039 s.userId = newUserIdLP(s);
8040 } else {
8041 s.userId = FIRST_APPLICATION_UID;
8042 }
8043 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8044 // < 0 means we couldn't assign a userid; fall out and return
8045 // s, which is currently null
8046 if (s.userId >= 0) {
8047 mSharedUsers.put(name, s);
8048 }
8049 }
8050
8051 return s;
8052 }
8053
8054 int disableSystemPackageLP(String name) {
8055 PackageSetting p = mPackages.get(name);
8056 if(p == null) {
8057 Log.w(TAG, "Package:"+name+" is not an installed package");
8058 return -1;
8059 }
8060 PackageSetting dp = mDisabledSysPackages.get(name);
8061 // always make sure the system package code and resource paths dont change
8062 if(dp == null) {
8063 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8064 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8065 }
8066 mDisabledSysPackages.put(name, p);
8067 }
8068 return removePackageLP(name);
8069 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008071 PackageSetting enableSystemPackageLP(String name) {
8072 PackageSetting p = mDisabledSysPackages.get(name);
8073 if(p == null) {
8074 Log.w(TAG, "Package:"+name+" is not disabled");
8075 return null;
8076 }
8077 // Reset flag in ApplicationInfo object
8078 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8079 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8080 }
Kenny Root806cc132010-09-12 08:34:19 -07008081 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8082 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 mDisabledSysPackages.remove(name);
8084 return ret;
8085 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008086
Kenny Root806cc132010-09-12 08:34:19 -07008087 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8088 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 PackageSetting p = mPackages.get(name);
8090 if (p != null) {
8091 if (p.userId == uid) {
8092 return p;
8093 }
8094 reportSettingsProblem(Log.ERROR,
8095 "Adding duplicate package, keeping first: " + name);
8096 return null;
8097 }
Kenny Root806cc132010-09-12 08:34:19 -07008098 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8099 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008100 p.userId = uid;
8101 if (addUserIdLP(uid, p, name)) {
8102 mPackages.put(name, p);
8103 return p;
8104 }
8105 return null;
8106 }
8107
8108 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8109 SharedUserSetting s = mSharedUsers.get(name);
8110 if (s != null) {
8111 if (s.userId == uid) {
8112 return s;
8113 }
8114 reportSettingsProblem(Log.ERROR,
8115 "Adding duplicate shared user, keeping first: " + name);
8116 return null;
8117 }
8118 s = new SharedUserSetting(name, pkgFlags);
8119 s.userId = uid;
8120 if (addUserIdLP(uid, s, name)) {
8121 mSharedUsers.put(name, s);
8122 return s;
8123 }
8124 return null;
8125 }
8126
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008127 // Transfer ownership of permissions from one package to another.
8128 private void transferPermissions(String origPkg, String newPkg) {
8129 // Transfer ownership of permissions to the new package.
8130 for (int i=0; i<2; i++) {
8131 HashMap<String, BasePermission> permissions =
8132 i == 0 ? mPermissionTrees : mPermissions;
8133 for (BasePermission bp : permissions.values()) {
8134 if (origPkg.equals(bp.sourcePackage)) {
8135 if (DEBUG_UPGRADE) Log.v(TAG,
8136 "Moving permission " + bp.name
8137 + " from pkg " + bp.sourcePackage
8138 + " to " + newPkg);
8139 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008140 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008141 bp.perm = null;
8142 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008143 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008144 }
8145 bp.uid = 0;
8146 bp.gids = null;
8147 }
8148 }
8149 }
8150 }
8151
8152 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008153 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008154 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 PackageSetting p = mPackages.get(name);
8156 if (p != null) {
8157 if (!p.codePath.equals(codePath)) {
8158 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008159 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008160 // This is an updated system app with versions in both system
8161 // and data partition. Just let the most recent version
8162 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008163 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008164 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008165 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008166 // Just a change in the code path is not an issue, but
8167 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008168 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008169 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008170 /*
8171 * Since we've changed paths, we need to prefer the new
8172 * native library path over the one stored in the
8173 * package settings since we might have moved from
8174 * internal to external storage or vice versa.
8175 */
8176 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008178 }
8179 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008180 reportSettingsProblem(Log.WARN,
8181 "Package " + name + " shared user changed from "
8182 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8183 + " to "
8184 + (sharedUser != null ? sharedUser.name : "<nothing>")
8185 + "; replacing with new");
8186 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008187 } else {
8188 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8189 // If what we are scanning is a system package, then
8190 // make it so, regardless of whether it was previously
8191 // installed only in the data partition.
8192 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008194 }
8195 }
8196 if (p == null) {
8197 // Create a new PackageSettings entry. this can end up here because
8198 // of code path mismatch or user id mismatch of an updated system partition
8199 if (!create) {
8200 return null;
8201 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008202 if (origPackage != null) {
8203 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008204 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8205 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008206 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8207 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008208 // Note that we will retain the new package's signature so
8209 // that we can keep its data.
8210 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008211 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008212 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008213 p.sharedUser = origPackage.sharedUser;
8214 p.userId = origPackage.userId;
8215 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008216 mRenamedPackages.put(name, origPackage.name);
8217 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008218 // Update new package state.
8219 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008221 p = new PackageSetting(name, realName, codePath, resourcePath,
8222 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008223 p.setTimeStamp(codePath.lastModified());
8224 p.sharedUser = sharedUser;
8225 if (sharedUser != null) {
8226 p.userId = sharedUser.userId;
8227 } else if (MULTIPLE_APPLICATION_UIDS) {
8228 // Clone the setting here for disabled system packages
8229 PackageSetting dis = mDisabledSysPackages.get(name);
8230 if (dis != null) {
8231 // For disabled packages a new setting is created
8232 // from the existing user id. This still has to be
8233 // added to list of user id's
8234 // Copy signatures from previous setting
8235 if (dis.signatures.mSignatures != null) {
8236 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8237 }
8238 p.userId = dis.userId;
8239 // Clone permissions
8240 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008241 // Clone component info
8242 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8243 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8244 // Add new setting to list of user ids
8245 addUserIdLP(p.userId, p, name);
8246 } else {
8247 // Assign new user id
8248 p.userId = newUserIdLP(p);
8249 }
8250 } else {
8251 p.userId = FIRST_APPLICATION_UID;
8252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008253 }
8254 if (p.userId < 0) {
8255 reportSettingsProblem(Log.WARN,
8256 "Package " + name + " could not be assigned a valid uid");
8257 return null;
8258 }
8259 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008260 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008261 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008262 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008263 }
8264 }
8265 return p;
8266 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008267
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008268 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008269 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008270 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008271 final String codePath = pkg.applicationInfo.sourceDir;
8272 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008273 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008274 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008275 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008276 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008277 p.codePath = new File(codePath);
8278 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008279 }
8280 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008281 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008282 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008283 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008284 p.resourcePath = new File(resourcePath);
8285 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008286 }
Kenny Root85387d72010-08-26 10:13:11 -07008287 // Update the native library path if needed
8288 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8289 if (nativeLibraryPath != null
8290 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8291 p.nativeLibraryPathString = nativeLibraryPath;
8292 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008293 // Update version code if needed
8294 if (pkg.mVersionCode != p.versionCode) {
8295 p.versionCode = pkg.mVersionCode;
8296 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008297 // Update signatures if needed.
8298 if (p.signatures.mSignatures == null) {
8299 p.signatures.assignSignatures(pkg.mSignatures);
8300 }
8301 // If this app defines a shared user id initialize
8302 // the shared user signatures as well.
8303 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8304 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8305 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008306 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8307 }
8308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008309 // Utility method that adds a PackageSetting to mPackages and
8310 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008311 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 SharedUserSetting sharedUser) {
8313 mPackages.put(name, p);
8314 if (sharedUser != null) {
8315 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8316 reportSettingsProblem(Log.ERROR,
8317 "Package " + p.name + " was user "
8318 + p.sharedUser + " but is now " + sharedUser
8319 + "; I am not changing its files so it will probably fail!");
8320 p.sharedUser.packages.remove(p);
8321 } else if (p.userId != sharedUser.userId) {
8322 reportSettingsProblem(Log.ERROR,
8323 "Package " + p.name + " was user id " + p.userId
8324 + " but is now user " + sharedUser
8325 + " with id " + sharedUser.userId
8326 + "; I am not changing its files so it will probably fail!");
8327 }
8328
8329 sharedUser.packages.add(p);
8330 p.sharedUser = sharedUser;
8331 p.userId = sharedUser.userId;
8332 }
8333 }
8334
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008335 /*
8336 * Update the shared user setting when a package using
8337 * specifying the shared user id is removed. The gids
8338 * associated with each permission of the deleted package
8339 * are removed from the shared user's gid list only if its
8340 * not in use by other permissions of packages in the
8341 * shared user setting.
8342 */
8343 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008345 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 return;
8347 }
8348 // No sharedUserId
8349 if (deletedPs.sharedUser == null) {
8350 return;
8351 }
8352 SharedUserSetting sus = deletedPs.sharedUser;
8353 // Update permissions
8354 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8355 boolean used = false;
8356 if (!sus.grantedPermissions.contains (eachPerm)) {
8357 continue;
8358 }
8359 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008360 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008361 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008362 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008363 used = true;
8364 break;
8365 }
8366 }
8367 if (!used) {
8368 // can safely delete this permission from list
8369 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370 }
8371 }
8372 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008373 int newGids[] = globalGids;
8374 for (String eachPerm : sus.grantedPermissions) {
8375 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008376 if (bp != null) {
8377 newGids = appendInts(newGids, bp.gids);
8378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008379 }
8380 sus.gids = newGids;
8381 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 private int removePackageLP(String name) {
8384 PackageSetting p = mPackages.get(name);
8385 if (p != null) {
8386 mPackages.remove(name);
8387 if (p.sharedUser != null) {
8388 p.sharedUser.packages.remove(p);
8389 if (p.sharedUser.packages.size() == 0) {
8390 mSharedUsers.remove(p.sharedUser.name);
8391 removeUserIdLP(p.sharedUser.userId);
8392 return p.sharedUser.userId;
8393 }
8394 } else {
8395 removeUserIdLP(p.userId);
8396 return p.userId;
8397 }
8398 }
8399 return -1;
8400 }
8401
8402 private boolean addUserIdLP(int uid, Object obj, Object name) {
8403 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8404 return false;
8405 }
8406
8407 if (uid >= FIRST_APPLICATION_UID) {
8408 int N = mUserIds.size();
8409 final int index = uid - FIRST_APPLICATION_UID;
8410 while (index >= N) {
8411 mUserIds.add(null);
8412 N++;
8413 }
8414 if (mUserIds.get(index) != null) {
8415 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008416 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008417 + " name=" + name);
8418 return false;
8419 }
8420 mUserIds.set(index, obj);
8421 } else {
8422 if (mOtherUserIds.get(uid) != null) {
8423 reportSettingsProblem(Log.ERROR,
8424 "Adding duplicate shared id: " + uid
8425 + " name=" + name);
8426 return false;
8427 }
8428 mOtherUserIds.put(uid, obj);
8429 }
8430 return true;
8431 }
8432
8433 public Object getUserIdLP(int uid) {
8434 if (uid >= FIRST_APPLICATION_UID) {
8435 int N = mUserIds.size();
8436 final int index = uid - FIRST_APPLICATION_UID;
8437 return index < N ? mUserIds.get(index) : null;
8438 } else {
8439 return mOtherUserIds.get(uid);
8440 }
8441 }
8442
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008443 private Set<String> findPackagesWithFlag(int flag) {
8444 Set<String> ret = new HashSet<String>();
8445 for (PackageSetting ps : mPackages.values()) {
8446 // Has to match atleast all the flag bits set on flag
8447 if ((ps.pkgFlags & flag) == flag) {
8448 ret.add(ps.name);
8449 }
8450 }
8451 return ret;
8452 }
8453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008454 private void removeUserIdLP(int uid) {
8455 if (uid >= FIRST_APPLICATION_UID) {
8456 int N = mUserIds.size();
8457 final int index = uid - FIRST_APPLICATION_UID;
8458 if (index < N) mUserIds.set(index, null);
8459 } else {
8460 mOtherUserIds.remove(uid);
8461 }
8462 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 void writeLP() {
8465 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8466
8467 // Keep the old settings around until we know the new ones have
8468 // been successfully written.
8469 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008470 // Presence of backup settings file indicates that we failed
8471 // to persist settings earlier. So preserve the older
8472 // backup for future reference since the current settings
8473 // might have been corrupted.
8474 if (!mBackupSettingsFilename.exists()) {
8475 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008476 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008477 return;
8478 }
8479 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008480 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008481 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483 }
8484
8485 mPastSignatures.clear();
8486
8487 try {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008488 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
8489 BufferedOutputStream str = new BufferedOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008490
8491 //XmlSerializer serializer = XmlUtils.serializerInstance();
8492 XmlSerializer serializer = new FastXmlSerializer();
8493 serializer.setOutput(str, "utf-8");
8494 serializer.startDocument(null, true);
8495 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8496
8497 serializer.startTag(null, "packages");
8498
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008499 serializer.startTag(null, "last-platform-version");
8500 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8501 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8502 serializer.endTag(null, "last-platform-version");
8503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 serializer.startTag(null, "permission-trees");
8505 for (BasePermission bp : mPermissionTrees.values()) {
8506 writePermission(serializer, bp);
8507 }
8508 serializer.endTag(null, "permission-trees");
8509
8510 serializer.startTag(null, "permissions");
8511 for (BasePermission bp : mPermissions.values()) {
8512 writePermission(serializer, bp);
8513 }
8514 serializer.endTag(null, "permissions");
8515
8516 for (PackageSetting pkg : mPackages.values()) {
8517 writePackage(serializer, pkg);
8518 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008520 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8521 writeDisabledSysPackage(serializer, pkg);
8522 }
8523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 serializer.startTag(null, "preferred-activities");
8525 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8526 serializer.startTag(null, "item");
8527 pa.writeToXml(serializer);
8528 serializer.endTag(null, "item");
8529 }
8530 serializer.endTag(null, "preferred-activities");
8531
8532 for (SharedUserSetting usr : mSharedUsers.values()) {
8533 serializer.startTag(null, "shared-user");
8534 serializer.attribute(null, "name", usr.name);
8535 serializer.attribute(null, "userId",
8536 Integer.toString(usr.userId));
8537 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8538 serializer.startTag(null, "perms");
8539 for (String name : usr.grantedPermissions) {
8540 serializer.startTag(null, "item");
8541 serializer.attribute(null, "name", name);
8542 serializer.endTag(null, "item");
8543 }
8544 serializer.endTag(null, "perms");
8545 serializer.endTag(null, "shared-user");
8546 }
8547
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008548 if (mPackagesToBeCleaned.size() > 0) {
8549 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8550 serializer.startTag(null, "cleaning-package");
8551 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8552 serializer.endTag(null, "cleaning-package");
8553 }
8554 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008555
8556 if (mRenamedPackages.size() > 0) {
8557 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8558 serializer.startTag(null, "renamed-package");
8559 serializer.attribute(null, "new", e.getKey());
8560 serializer.attribute(null, "old", e.getValue());
8561 serializer.endTag(null, "renamed-package");
8562 }
8563 }
8564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 serializer.endTag(null, "packages");
8566
8567 serializer.endDocument();
8568
8569 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008570 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 str.close();
8572
8573 // New settings successfully written, old ones are no longer
8574 // needed.
8575 mBackupSettingsFilename.delete();
8576 FileUtils.setPermissions(mSettingsFilename.toString(),
8577 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8578 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8579 |FileUtils.S_IROTH,
8580 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008581
8582 // Write package list file now, use a JournaledFile.
8583 //
8584 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8585 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8586
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008587 fstr = new FileOutputStream(journal.chooseForWrite());
8588 str = new BufferedOutputStream(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008589 try {
8590 StringBuilder sb = new StringBuilder();
8591 for (PackageSetting pkg : mPackages.values()) {
8592 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008593 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008594 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8595
8596 // Avoid any application that has a space in its path
8597 // or that is handled by the system.
8598 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8599 continue;
8600
8601 // we store on each line the following information for now:
8602 //
8603 // pkgName - package name
8604 // userId - application-specific user id
8605 // debugFlag - 0 or 1 if the package is debuggable.
8606 // dataPath - path to package's data path
8607 //
8608 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8609 //
8610 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8611 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8612 // system/core/run-as/run-as.c
8613 //
8614 sb.setLength(0);
8615 sb.append(ai.packageName);
8616 sb.append(" ");
8617 sb.append((int)ai.uid);
8618 sb.append(isDebug ? " 1 " : " 0 ");
8619 sb.append(dataPath);
8620 sb.append("\n");
8621 str.write(sb.toString().getBytes());
8622 }
8623 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008624 FileUtils.sync(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008625 str.close();
8626 journal.commit();
8627 }
8628 catch (Exception e) {
8629 journal.rollback();
8630 }
8631
8632 FileUtils.setPermissions(mPackageListFilename.toString(),
8633 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8634 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8635 |FileUtils.S_IROTH,
8636 -1, -1);
8637
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008638 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639
8640 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008641 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 -08008642 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008643 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 -08008644 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008645 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008646 if (mSettingsFilename.exists()) {
8647 if (!mSettingsFilename.delete()) {
8648 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8649 }
8650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 //Debug.stopMethodTracing();
8652 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008653
8654 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008655 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 serializer.startTag(null, "updated-package");
8657 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008658 if (pkg.realName != null) {
8659 serializer.attribute(null, "realName", pkg.realName);
8660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008662 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8663 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8664 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008665 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008666 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8667 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8668 }
Kenny Root85387d72010-08-26 10:13:11 -07008669 if (pkg.nativeLibraryPathString != null) {
8670 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008672 if (pkg.sharedUser == null) {
8673 serializer.attribute(null, "userId",
8674 Integer.toString(pkg.userId));
8675 } else {
8676 serializer.attribute(null, "sharedUserId",
8677 Integer.toString(pkg.userId));
8678 }
8679 serializer.startTag(null, "perms");
8680 if (pkg.sharedUser == null) {
8681 // If this is a shared user, the permissions will
8682 // be written there. We still need to write an
8683 // empty permissions list so permissionsFixed will
8684 // be set.
8685 for (final String name : pkg.grantedPermissions) {
8686 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008687 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 // We only need to write signature or system permissions but this wont
8689 // match the semantics of grantedPermissions. So write all permissions.
8690 serializer.startTag(null, "item");
8691 serializer.attribute(null, "name", name);
8692 serializer.endTag(null, "item");
8693 }
8694 }
8695 }
8696 serializer.endTag(null, "perms");
8697 serializer.endTag(null, "updated-package");
8698 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008699
8700 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008701 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008702 serializer.startTag(null, "package");
8703 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008704 if (pkg.realName != null) {
8705 serializer.attribute(null, "realName", pkg.realName);
8706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008707 serializer.attribute(null, "codePath", pkg.codePathString);
8708 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8709 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8710 }
Kenny Root85387d72010-08-26 10:13:11 -07008711 if (pkg.nativeLibraryPathString != null) {
8712 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8713 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008714 serializer.attribute(null, "flags",
8715 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008716 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8717 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8718 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008719 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 if (pkg.sharedUser == null) {
8721 serializer.attribute(null, "userId",
8722 Integer.toString(pkg.userId));
8723 } else {
8724 serializer.attribute(null, "sharedUserId",
8725 Integer.toString(pkg.userId));
8726 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008727 if (pkg.uidError) {
8728 serializer.attribute(null, "uidError", "true");
8729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008730 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8731 serializer.attribute(null, "enabled",
8732 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8733 ? "true" : "false");
8734 }
8735 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8736 serializer.attribute(null, "installStatus", "false");
8737 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008738 if (pkg.installerPackageName != null) {
8739 serializer.attribute(null, "installer", pkg.installerPackageName);
8740 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008741 if (pkg.obbPathString != null) {
8742 serializer.attribute(null, "obbPath", pkg.obbPathString);
8743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008744 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8745 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8746 serializer.startTag(null, "perms");
8747 if (pkg.sharedUser == null) {
8748 // If this is a shared user, the permissions will
8749 // be written there. We still need to write an
8750 // empty permissions list so permissionsFixed will
8751 // be set.
8752 for (final String name : pkg.grantedPermissions) {
8753 serializer.startTag(null, "item");
8754 serializer.attribute(null, "name", name);
8755 serializer.endTag(null, "item");
8756 }
8757 }
8758 serializer.endTag(null, "perms");
8759 }
8760 if (pkg.disabledComponents.size() > 0) {
8761 serializer.startTag(null, "disabled-components");
8762 for (final String name : pkg.disabledComponents) {
8763 serializer.startTag(null, "item");
8764 serializer.attribute(null, "name", name);
8765 serializer.endTag(null, "item");
8766 }
8767 serializer.endTag(null, "disabled-components");
8768 }
8769 if (pkg.enabledComponents.size() > 0) {
8770 serializer.startTag(null, "enabled-components");
8771 for (final String name : pkg.enabledComponents) {
8772 serializer.startTag(null, "item");
8773 serializer.attribute(null, "name", name);
8774 serializer.endTag(null, "item");
8775 }
8776 serializer.endTag(null, "enabled-components");
8777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779 serializer.endTag(null, "package");
8780 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 void writePermission(XmlSerializer serializer, BasePermission bp)
8783 throws XmlPullParserException, java.io.IOException {
8784 if (bp.type != BasePermission.TYPE_BUILTIN
8785 && bp.sourcePackage != null) {
8786 serializer.startTag(null, "item");
8787 serializer.attribute(null, "name", bp.name);
8788 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008789 if (bp.protectionLevel !=
8790 PermissionInfo.PROTECTION_NORMAL) {
8791 serializer.attribute(null, "protection",
8792 Integer.toString(bp.protectionLevel));
8793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 if (DEBUG_SETTINGS) Log.v(TAG,
8795 "Writing perm: name=" + bp.name + " type=" + bp.type);
8796 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8797 PermissionInfo pi = bp.perm != null ? bp.perm.info
8798 : bp.pendingInfo;
8799 if (pi != null) {
8800 serializer.attribute(null, "type", "dynamic");
8801 if (pi.icon != 0) {
8802 serializer.attribute(null, "icon",
8803 Integer.toString(pi.icon));
8804 }
8805 if (pi.nonLocalizedLabel != null) {
8806 serializer.attribute(null, "label",
8807 pi.nonLocalizedLabel.toString());
8808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809 }
8810 }
8811 serializer.endTag(null, "item");
8812 }
8813 }
8814
8815 String getReadMessagesLP() {
8816 return mReadMessages.toString();
8817 }
8818
Oscar Montemayora8529f62009-11-18 10:14:20 -08008819 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008820 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8821 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008822 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008823 while(its.hasNext()) {
8824 String key = its.next();
8825 PackageSetting ps = mPackages.get(key);
8826 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008827 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008828 }
8829 }
8830 return ret;
8831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833 boolean readLP() {
8834 FileInputStream str = null;
8835 if (mBackupSettingsFilename.exists()) {
8836 try {
8837 str = new FileInputStream(mBackupSettingsFilename);
8838 mReadMessages.append("Reading from backup settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008839 reportSettingsProblem(Log.INFO, "Need to read from backup settings file");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008840 if (mSettingsFilename.exists()) {
8841 // If both the backup and settings file exist, we
8842 // ignore the settings since it might have been
8843 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008844 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008845 mSettingsFilename.delete();
8846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008847 } catch (java.io.IOException e) {
8848 // We'll try for the normal settings file.
8849 }
8850 }
8851
8852 mPastSignatures.clear();
8853
8854 try {
8855 if (str == null) {
8856 if (!mSettingsFilename.exists()) {
8857 mReadMessages.append("No settings file found\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008858 reportSettingsProblem(Log.INFO, "No settings file; creating initial state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008859 return false;
8860 }
8861 str = new FileInputStream(mSettingsFilename);
8862 }
8863 XmlPullParser parser = Xml.newPullParser();
8864 parser.setInput(str, null);
8865
8866 int type;
8867 while ((type=parser.next()) != XmlPullParser.START_TAG
8868 && type != XmlPullParser.END_DOCUMENT) {
8869 ;
8870 }
8871
8872 if (type != XmlPullParser.START_TAG) {
8873 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008874 reportSettingsProblem(Log.WARN, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008875 return false;
8876 }
8877
8878 int outerDepth = parser.getDepth();
8879 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8880 && (type != XmlPullParser.END_TAG
8881 || parser.getDepth() > outerDepth)) {
8882 if (type == XmlPullParser.END_TAG
8883 || type == XmlPullParser.TEXT) {
8884 continue;
8885 }
8886
8887 String tagName = parser.getName();
8888 if (tagName.equals("package")) {
8889 readPackageLP(parser);
8890 } else if (tagName.equals("permissions")) {
8891 readPermissionsLP(mPermissions, parser);
8892 } else if (tagName.equals("permission-trees")) {
8893 readPermissionsLP(mPermissionTrees, parser);
8894 } else if (tagName.equals("shared-user")) {
8895 readSharedUserLP(parser);
8896 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008897 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 } else if (tagName.equals("preferred-activities")) {
8899 readPreferredActivitiesLP(parser);
8900 } else if(tagName.equals("updated-package")) {
8901 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008902 } else if (tagName.equals("cleaning-package")) {
8903 String name = parser.getAttributeValue(null, "name");
8904 if (name != null) {
8905 mPackagesToBeCleaned.add(name);
8906 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008907 } else if (tagName.equals("renamed-package")) {
8908 String nname = parser.getAttributeValue(null, "new");
8909 String oname = parser.getAttributeValue(null, "old");
8910 if (nname != null && oname != null) {
8911 mRenamedPackages.put(nname, oname);
8912 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008913 } else if (tagName.equals("last-platform-version")) {
8914 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8915 try {
8916 String internal = parser.getAttributeValue(null, "internal");
8917 if (internal != null) {
8918 mInternalSdkPlatform = Integer.parseInt(internal);
8919 }
8920 String external = parser.getAttributeValue(null, "external");
8921 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008922 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008923 }
8924 } catch (NumberFormatException e) {
8925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008927 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 + parser.getName());
8929 XmlUtils.skipCurrentTag(parser);
8930 }
8931 }
8932
8933 str.close();
8934
8935 } catch(XmlPullParserException e) {
8936 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07008937 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008938 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939
8940 } catch(java.io.IOException e) {
8941 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07008942 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008943 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944
8945 }
8946
8947 int N = mPendingPackages.size();
8948 for (int i=0; i<N; i++) {
8949 final PendingPackage pp = mPendingPackages.get(i);
8950 Object idObj = getUserIdLP(pp.sharedId);
8951 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008952 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008953 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8954 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 if (p == null) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07008956 reportSettingsProblem(Log.WARN, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 + pp.name);
8958 continue;
8959 }
8960 p.copyFrom(pp);
8961 } else if (idObj != null) {
8962 String msg = "Bad package setting: package " + pp.name
8963 + " has shared uid " + pp.sharedId
8964 + " that is not a shared uid\n";
8965 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07008966 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008967 } else {
8968 String msg = "Bad package setting: package " + pp.name
8969 + " has shared uid " + pp.sharedId
8970 + " that is not defined\n";
8971 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07008972 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008973 }
8974 }
8975 mPendingPackages.clear();
8976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008977 mReadMessages.append("Read completed successfully: "
8978 + mPackages.size() + " packages, "
8979 + mSharedUsers.size() + " shared uids\n");
8980
8981 return true;
8982 }
8983
8984 private int readInt(XmlPullParser parser, String ns, String name,
8985 int defValue) {
8986 String v = parser.getAttributeValue(ns, name);
8987 try {
8988 if (v == null) {
8989 return defValue;
8990 }
8991 return Integer.parseInt(v);
8992 } catch (NumberFormatException e) {
8993 reportSettingsProblem(Log.WARN,
8994 "Error in package manager settings: attribute " +
8995 name + " has bad integer value " + v + " at "
8996 + parser.getPositionDescription());
8997 }
8998 return defValue;
8999 }
9000
9001 private void readPermissionsLP(HashMap<String, BasePermission> out,
9002 XmlPullParser parser)
9003 throws IOException, XmlPullParserException {
9004 int outerDepth = parser.getDepth();
9005 int type;
9006 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9007 && (type != XmlPullParser.END_TAG
9008 || parser.getDepth() > outerDepth)) {
9009 if (type == XmlPullParser.END_TAG
9010 || type == XmlPullParser.TEXT) {
9011 continue;
9012 }
9013
9014 String tagName = parser.getName();
9015 if (tagName.equals("item")) {
9016 String name = parser.getAttributeValue(null, "name");
9017 String sourcePackage = parser.getAttributeValue(null, "package");
9018 String ptype = parser.getAttributeValue(null, "type");
9019 if (name != null && sourcePackage != null) {
9020 boolean dynamic = "dynamic".equals(ptype);
9021 BasePermission bp = new BasePermission(name, sourcePackage,
9022 dynamic
9023 ? BasePermission.TYPE_DYNAMIC
9024 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009025 bp.protectionLevel = readInt(parser, null, "protection",
9026 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 if (dynamic) {
9028 PermissionInfo pi = new PermissionInfo();
9029 pi.packageName = sourcePackage.intern();
9030 pi.name = name.intern();
9031 pi.icon = readInt(parser, null, "icon", 0);
9032 pi.nonLocalizedLabel = parser.getAttributeValue(
9033 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009034 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 bp.pendingInfo = pi;
9036 }
9037 out.put(bp.name, bp);
9038 } else {
9039 reportSettingsProblem(Log.WARN,
9040 "Error in package manager settings: permissions has"
9041 + " no name at " + parser.getPositionDescription());
9042 }
9043 } else {
9044 reportSettingsProblem(Log.WARN,
9045 "Unknown element reading permissions: "
9046 + parser.getName() + " at "
9047 + parser.getPositionDescription());
9048 }
9049 XmlUtils.skipCurrentTag(parser);
9050 }
9051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009054 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009055 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009056 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009057 String codePathStr = parser.getAttributeValue(null, "codePath");
9058 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009059 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009060 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 resourcePathStr = codePathStr;
9062 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009063 String version = parser.getAttributeValue(null, "version");
9064 int versionCode = 0;
9065 if (version != null) {
9066 try {
9067 versionCode = Integer.parseInt(version);
9068 } catch (NumberFormatException e) {
9069 }
9070 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009072 int pkgFlags = 0;
9073 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009074 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9075 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009076 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009077 if (timeStampStr != null) {
9078 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009079 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009080 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081 } catch (NumberFormatException e) {
9082 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009083 } else {
9084 timeStampStr = parser.getAttributeValue(null, "ts");
9085 if (timeStampStr != null) {
9086 try {
9087 long timeStamp = Long.parseLong(timeStampStr);
9088 ps.setTimeStamp(timeStamp);
9089 } catch (NumberFormatException e) {
9090 }
9091 }
9092 }
9093 timeStampStr = parser.getAttributeValue(null, "it");
9094 if (timeStampStr != null) {
9095 try {
9096 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9097 } catch (NumberFormatException e) {
9098 }
9099 }
9100 timeStampStr = parser.getAttributeValue(null, "ut");
9101 if (timeStampStr != null) {
9102 try {
9103 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9104 } catch (NumberFormatException e) {
9105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009106 }
9107 String idStr = parser.getAttributeValue(null, "userId");
9108 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9109 if(ps.userId <= 0) {
9110 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9111 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9112 }
9113 int outerDepth = parser.getDepth();
9114 int type;
9115 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9116 && (type != XmlPullParser.END_TAG
9117 || parser.getDepth() > outerDepth)) {
9118 if (type == XmlPullParser.END_TAG
9119 || type == XmlPullParser.TEXT) {
9120 continue;
9121 }
9122
9123 String tagName = parser.getName();
9124 if (tagName.equals("perms")) {
9125 readGrantedPermissionsLP(parser,
9126 ps.grantedPermissions);
9127 } else {
9128 reportSettingsProblem(Log.WARN,
9129 "Unknown element under <updated-package>: "
9130 + parser.getName());
9131 XmlUtils.skipCurrentTag(parser);
9132 }
9133 }
9134 mDisabledSysPackages.put(name, ps);
9135 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009137 private void readPackageLP(XmlPullParser parser)
9138 throws XmlPullParserException, IOException {
9139 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009140 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009141 String idStr = null;
9142 String sharedIdStr = null;
9143 String codePathStr = null;
9144 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009145 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009146 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009148 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009149 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009150 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009151 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009152 long firstInstallTime = 0;
9153 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009154 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009155 String version = null;
9156 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009157 try {
9158 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009159 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009160 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009161 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009162 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9163 codePathStr = parser.getAttributeValue(null, "codePath");
9164 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009165 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009166 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009167 version = parser.getAttributeValue(null, "version");
9168 if (version != null) {
9169 try {
9170 versionCode = Integer.parseInt(version);
9171 } catch (NumberFormatException e) {
9172 }
9173 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009174 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009175
9176 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009177 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009178 try {
9179 pkgFlags = Integer.parseInt(systemStr);
9180 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 }
9182 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009183 // For backward compatibility
9184 systemStr = parser.getAttributeValue(null, "system");
9185 if (systemStr != null) {
9186 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9187 } else {
9188 // Old settings that don't specify system... just treat
9189 // them as system, good enough.
9190 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009192 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009193 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194 if (timeStampStr != null) {
9195 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009196 timeStamp = Long.parseLong(timeStampStr, 16);
9197 } catch (NumberFormatException e) {
9198 }
9199 } else {
9200 timeStampStr = parser.getAttributeValue(null, "ts");
9201 if (timeStampStr != null) {
9202 try {
9203 timeStamp = Long.parseLong(timeStampStr);
9204 } catch (NumberFormatException e) {
9205 }
9206 }
9207 }
9208 timeStampStr = parser.getAttributeValue(null, "it");
9209 if (timeStampStr != null) {
9210 try {
9211 firstInstallTime = Long.parseLong(timeStampStr, 16);
9212 } catch (NumberFormatException e) {
9213 }
9214 }
9215 timeStampStr = parser.getAttributeValue(null, "ut");
9216 if (timeStampStr != null) {
9217 try {
9218 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219 } catch (NumberFormatException e) {
9220 }
9221 }
9222 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9223 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9224 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9225 if (resourcePathStr == null) {
9226 resourcePathStr = codePathStr;
9227 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009228 if (realName != null) {
9229 realName = realName.intern();
9230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009231 if (name == null) {
9232 reportSettingsProblem(Log.WARN,
9233 "Error in package manager settings: <package> has no name at "
9234 + parser.getPositionDescription());
9235 } else if (codePathStr == null) {
9236 reportSettingsProblem(Log.WARN,
9237 "Error in package manager settings: <package> has no codePath at "
9238 + parser.getPositionDescription());
9239 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009240 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9241 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9242 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009243 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9244 + ": userId=" + userId + " pkg=" + packageSetting);
9245 if (packageSetting == null) {
9246 reportSettingsProblem(Log.ERROR,
9247 "Failure adding uid " + userId
9248 + " while parsing settings at "
9249 + parser.getPositionDescription());
9250 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009251 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009252 packageSetting.firstInstallTime = firstInstallTime;
9253 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009254 }
9255 } else if (sharedIdStr != null) {
9256 userId = sharedIdStr != null
9257 ? Integer.parseInt(sharedIdStr) : 0;
9258 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009259 packageSetting = new PendingPackage(name.intern(), realName,
9260 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009261 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009262 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009263 packageSetting.firstInstallTime = firstInstallTime;
9264 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009265 mPendingPackages.add((PendingPackage) packageSetting);
9266 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9267 + ": sharedUserId=" + userId + " pkg="
9268 + packageSetting);
9269 } else {
9270 reportSettingsProblem(Log.WARN,
9271 "Error in package manager settings: package "
9272 + name + " has bad sharedId " + sharedIdStr
9273 + " at " + parser.getPositionDescription());
9274 }
9275 } else {
9276 reportSettingsProblem(Log.WARN,
9277 "Error in package manager settings: package "
9278 + name + " has bad userId " + idStr + " at "
9279 + parser.getPositionDescription());
9280 }
9281 } catch (NumberFormatException e) {
9282 reportSettingsProblem(Log.WARN,
9283 "Error in package manager settings: package "
9284 + name + " has bad userId " + idStr + " at "
9285 + parser.getPositionDescription());
9286 }
9287 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009288 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009289 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009290 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009291 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009292 final String enabledStr = parser.getAttributeValue(null, "enabled");
9293 if (enabledStr != null) {
9294 if (enabledStr.equalsIgnoreCase("true")) {
9295 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9296 } else if (enabledStr.equalsIgnoreCase("false")) {
9297 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9298 } else if (enabledStr.equalsIgnoreCase("default")) {
9299 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9300 } else {
9301 reportSettingsProblem(Log.WARN,
9302 "Error in package manager settings: package "
9303 + name + " has bad enabled value: " + idStr
9304 + " at " + parser.getPositionDescription());
9305 }
9306 } else {
9307 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9308 }
9309 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9310 if (installStatusStr != null) {
9311 if (installStatusStr.equalsIgnoreCase("false")) {
9312 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9313 } else {
9314 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9315 }
9316 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009318 int outerDepth = parser.getDepth();
9319 int type;
9320 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9321 && (type != XmlPullParser.END_TAG
9322 || parser.getDepth() > outerDepth)) {
9323 if (type == XmlPullParser.END_TAG
9324 || type == XmlPullParser.TEXT) {
9325 continue;
9326 }
9327
9328 String tagName = parser.getName();
9329 if (tagName.equals("disabled-components")) {
9330 readDisabledComponentsLP(packageSetting, parser);
9331 } else if (tagName.equals("enabled-components")) {
9332 readEnabledComponentsLP(packageSetting, parser);
9333 } else if (tagName.equals("sigs")) {
9334 packageSetting.signatures.readXml(parser, mPastSignatures);
9335 } else if (tagName.equals("perms")) {
9336 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009337 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009338 packageSetting.permissionsFixed = true;
9339 } else {
9340 reportSettingsProblem(Log.WARN,
9341 "Unknown element under <package>: "
9342 + parser.getName());
9343 XmlUtils.skipCurrentTag(parser);
9344 }
9345 }
9346 } else {
9347 XmlUtils.skipCurrentTag(parser);
9348 }
9349 }
9350
9351 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9352 XmlPullParser parser)
9353 throws IOException, XmlPullParserException {
9354 int outerDepth = parser.getDepth();
9355 int type;
9356 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9357 && (type != XmlPullParser.END_TAG
9358 || parser.getDepth() > outerDepth)) {
9359 if (type == XmlPullParser.END_TAG
9360 || type == XmlPullParser.TEXT) {
9361 continue;
9362 }
9363
9364 String tagName = parser.getName();
9365 if (tagName.equals("item")) {
9366 String name = parser.getAttributeValue(null, "name");
9367 if (name != null) {
9368 packageSetting.disabledComponents.add(name.intern());
9369 } else {
9370 reportSettingsProblem(Log.WARN,
9371 "Error in package manager settings: <disabled-components> has"
9372 + " no name at " + parser.getPositionDescription());
9373 }
9374 } else {
9375 reportSettingsProblem(Log.WARN,
9376 "Unknown element under <disabled-components>: "
9377 + parser.getName());
9378 }
9379 XmlUtils.skipCurrentTag(parser);
9380 }
9381 }
9382
9383 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9384 XmlPullParser parser)
9385 throws IOException, XmlPullParserException {
9386 int outerDepth = parser.getDepth();
9387 int type;
9388 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9389 && (type != XmlPullParser.END_TAG
9390 || parser.getDepth() > outerDepth)) {
9391 if (type == XmlPullParser.END_TAG
9392 || type == XmlPullParser.TEXT) {
9393 continue;
9394 }
9395
9396 String tagName = parser.getName();
9397 if (tagName.equals("item")) {
9398 String name = parser.getAttributeValue(null, "name");
9399 if (name != null) {
9400 packageSetting.enabledComponents.add(name.intern());
9401 } else {
9402 reportSettingsProblem(Log.WARN,
9403 "Error in package manager settings: <enabled-components> has"
9404 + " no name at " + parser.getPositionDescription());
9405 }
9406 } else {
9407 reportSettingsProblem(Log.WARN,
9408 "Unknown element under <enabled-components>: "
9409 + parser.getName());
9410 }
9411 XmlUtils.skipCurrentTag(parser);
9412 }
9413 }
9414
9415 private void readSharedUserLP(XmlPullParser parser)
9416 throws XmlPullParserException, IOException {
9417 String name = null;
9418 String idStr = null;
9419 int pkgFlags = 0;
9420 SharedUserSetting su = null;
9421 try {
9422 name = parser.getAttributeValue(null, "name");
9423 idStr = parser.getAttributeValue(null, "userId");
9424 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9425 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9426 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9427 }
9428 if (name == null) {
9429 reportSettingsProblem(Log.WARN,
9430 "Error in package manager settings: <shared-user> has no name at "
9431 + parser.getPositionDescription());
9432 } else if (userId == 0) {
9433 reportSettingsProblem(Log.WARN,
9434 "Error in package manager settings: shared-user "
9435 + name + " has bad userId " + idStr + " at "
9436 + parser.getPositionDescription());
9437 } else {
9438 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9439 reportSettingsProblem(Log.ERROR,
9440 "Occurred while parsing settings at "
9441 + parser.getPositionDescription());
9442 }
9443 }
9444 } catch (NumberFormatException e) {
9445 reportSettingsProblem(Log.WARN,
9446 "Error in package manager settings: package "
9447 + name + " has bad userId " + idStr + " at "
9448 + parser.getPositionDescription());
9449 };
9450
9451 if (su != null) {
9452 int outerDepth = parser.getDepth();
9453 int type;
9454 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9455 && (type != XmlPullParser.END_TAG
9456 || parser.getDepth() > outerDepth)) {
9457 if (type == XmlPullParser.END_TAG
9458 || type == XmlPullParser.TEXT) {
9459 continue;
9460 }
9461
9462 String tagName = parser.getName();
9463 if (tagName.equals("sigs")) {
9464 su.signatures.readXml(parser, mPastSignatures);
9465 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009466 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009467 } else {
9468 reportSettingsProblem(Log.WARN,
9469 "Unknown element under <shared-user>: "
9470 + parser.getName());
9471 XmlUtils.skipCurrentTag(parser);
9472 }
9473 }
9474
9475 } else {
9476 XmlUtils.skipCurrentTag(parser);
9477 }
9478 }
9479
9480 private void readGrantedPermissionsLP(XmlPullParser parser,
9481 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9482 int outerDepth = parser.getDepth();
9483 int type;
9484 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9485 && (type != XmlPullParser.END_TAG
9486 || parser.getDepth() > outerDepth)) {
9487 if (type == XmlPullParser.END_TAG
9488 || type == XmlPullParser.TEXT) {
9489 continue;
9490 }
9491
9492 String tagName = parser.getName();
9493 if (tagName.equals("item")) {
9494 String name = parser.getAttributeValue(null, "name");
9495 if (name != null) {
9496 outPerms.add(name.intern());
9497 } else {
9498 reportSettingsProblem(Log.WARN,
9499 "Error in package manager settings: <perms> has"
9500 + " no name at " + parser.getPositionDescription());
9501 }
9502 } else {
9503 reportSettingsProblem(Log.WARN,
9504 "Unknown element under <perms>: "
9505 + parser.getName());
9506 }
9507 XmlUtils.skipCurrentTag(parser);
9508 }
9509 }
9510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009511 private void readPreferredActivitiesLP(XmlPullParser parser)
9512 throws XmlPullParserException, IOException {
9513 int outerDepth = parser.getDepth();
9514 int type;
9515 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9516 && (type != XmlPullParser.END_TAG
9517 || parser.getDepth() > outerDepth)) {
9518 if (type == XmlPullParser.END_TAG
9519 || type == XmlPullParser.TEXT) {
9520 continue;
9521 }
9522
9523 String tagName = parser.getName();
9524 if (tagName.equals("item")) {
9525 PreferredActivity pa = new PreferredActivity(parser);
9526 if (pa.mParseError == null) {
9527 mPreferredActivities.addFilter(pa);
9528 } else {
9529 reportSettingsProblem(Log.WARN,
9530 "Error in package manager settings: <preferred-activity> "
9531 + pa.mParseError + " at "
9532 + parser.getPositionDescription());
9533 }
9534 } else {
9535 reportSettingsProblem(Log.WARN,
9536 "Unknown element under <preferred-activities>: "
9537 + parser.getName());
9538 XmlUtils.skipCurrentTag(parser);
9539 }
9540 }
9541 }
9542
9543 // Returns -1 if we could not find an available UserId to assign
9544 private int newUserIdLP(Object obj) {
9545 // Let's be stupidly inefficient for now...
9546 final int N = mUserIds.size();
9547 for (int i=0; i<N; i++) {
9548 if (mUserIds.get(i) == null) {
9549 mUserIds.set(i, obj);
9550 return FIRST_APPLICATION_UID + i;
9551 }
9552 }
9553
9554 // None left?
9555 if (N >= MAX_APPLICATION_UIDS) {
9556 return -1;
9557 }
9558
9559 mUserIds.add(obj);
9560 return FIRST_APPLICATION_UID + N;
9561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009563 public PackageSetting getDisabledSystemPkg(String name) {
9564 synchronized(mPackages) {
9565 PackageSetting ps = mDisabledSysPackages.get(name);
9566 return ps;
9567 }
9568 }
9569
9570 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009571 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9572 return true;
9573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9575 if (Config.LOGV) {
9576 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9577 + " componentName = " + componentInfo.name);
9578 Log.v(TAG, "enabledComponents: "
9579 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9580 Log.v(TAG, "disabledComponents: "
9581 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9582 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009583 if (packageSettings == null) {
9584 if (false) {
9585 Log.w(TAG, "WAITING FOR DEBUGGER");
9586 Debug.waitForDebugger();
9587 Log.i(TAG, "We will crash!");
9588 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009589 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009590 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009591 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9592 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9593 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9594 return false;
9595 }
9596 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9597 return true;
9598 }
9599 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9600 return false;
9601 }
9602 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009603 }
9604 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009605
9606 // ------- apps on sdcard specific code -------
9607 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009608 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9609 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9610 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009611 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009612
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009613 private String getEncryptKey() {
9614 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009615 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9616 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009617 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009618 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9619 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009620 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009621 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009622 return null;
9623 }
9624 }
9625 return sdEncKey;
9626 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009627 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009628 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009629 } catch (IOException ioe) {
9630 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9631 + ioe);
9632 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009633 }
Rich Cannings8d578832010-09-09 15:12:40 -07009634
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009635 }
9636
Kenny Rootc78a8072010-07-27 15:18:38 -07009637 /* package */ static String getTempContainerId() {
9638 int tmpIdx = 1;
9639 String list[] = PackageHelper.getSecureContainerList();
9640 if (list != null) {
9641 for (final String name : list) {
9642 // Ignore null and non-temporary container entries
9643 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9644 continue;
9645 }
9646
9647 String subStr = name.substring(mTempContainerPrefix.length());
9648 try {
9649 int cid = Integer.parseInt(subStr);
9650 if (cid >= tmpIdx) {
9651 tmpIdx = cid + 1;
9652 }
9653 } catch (NumberFormatException e) {
9654 }
9655 }
9656 }
9657 return mTempContainerPrefix + tmpIdx;
9658 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009659
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009660 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009661 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009662 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009663 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9664 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9665 throw new SecurityException("Media status can only be updated by the system");
9666 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009667 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009668 Log.i(TAG, "Updating external media status from " +
9669 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9670 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009671 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9672 mediaStatus+", mMediaMounted=" + mMediaMounted);
9673 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009674 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9675 reportStatus ? 1 : 0, -1);
9676 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009677 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009678 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009679 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009680 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009681 // Queue up an async operation since the package installation may take a little while.
9682 mHandler.post(new Runnable() {
9683 public void run() {
9684 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009685 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009686 }
9687 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009688 }
9689
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009690 /*
9691 * Collect information of applications on external media, map them
9692 * against existing containers and update information based on current
9693 * mount status. Please note that we always have to report status
9694 * if reportStatus has been set to true especially when unloading packages.
9695 */
9696 private void updateExternalMediaStatusInner(boolean mediaStatus,
9697 boolean reportStatus) {
9698 // Collection of uids
9699 int uidArr[] = null;
9700 // Collection of stale containers
9701 HashSet<String> removeCids = new HashSet<String>();
9702 // Collection of packages on external media with valid containers.
9703 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9704 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009705 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009706 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009707 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009708 } else {
9709 // Process list of secure containers and categorize them
9710 // as active or stale based on their package internal state.
9711 int uidList[] = new int[list.length];
9712 int num = 0;
9713 synchronized (mPackages) {
9714 for (String cid : list) {
9715 SdInstallArgs args = new SdInstallArgs(cid);
9716 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009717 String pkgName = args.getPackageName();
9718 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009719 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9720 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009721 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009722 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009723 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9724 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009725 // The package status is changed only if the code path
9726 // matches between settings and the container id.
9727 if (ps != null && ps.codePathString != null &&
9728 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009729 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9730 " corresponds to pkg : " + pkgName +
9731 " at code path: " + ps.codePathString);
9732 // We do have a valid package installed on sdcard
9733 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009734 int uid = ps.userId;
9735 if (uid != -1) {
9736 uidList[num++] = uid;
9737 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009738 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009739 // Stale container on sdcard. Just delete
9740 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9741 removeCids.add(cid);
9742 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009743 }
9744 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009745
9746 if (num > 0) {
9747 // Sort uid list
9748 Arrays.sort(uidList, 0, num);
9749 // Throw away duplicates
9750 uidArr = new int[num];
9751 uidArr[0] = uidList[0];
9752 int di = 0;
9753 for (int i = 1; i < num; i++) {
9754 if (uidList[i-1] != uidList[i]) {
9755 uidArr[di++] = uidList[i];
9756 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009757 }
9758 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009759 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009760 // Process packages with valid entries.
9761 if (mediaStatus) {
9762 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009763 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009764 startCleaningPackages();
9765 } else {
9766 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009767 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009768 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009769 }
9770
9771 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009772 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009773 int size = pkgList.size();
9774 if (size > 0) {
9775 // Send broadcasts here
9776 Bundle extras = new Bundle();
9777 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9778 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009779 if (uidArr != null) {
9780 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9781 }
9782 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9783 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009784 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009785 }
9786 }
9787
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009788 /*
9789 * Look at potentially valid container ids from processCids
9790 * If package information doesn't match the one on record
9791 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009792 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009793 */
9794 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009795 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009796 ArrayList<String> pkgList = new ArrayList<String>();
9797 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009798 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009799 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009800 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009801 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9802 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009803 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009804 try {
9805 // Make sure there are no container errors first.
9806 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9807 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009808 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009809 " when installing from sdcard");
9810 continue;
9811 }
9812 // Check code path here.
9813 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009814 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009815 " does not match one in settings " + codePath);
9816 continue;
9817 }
9818 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009819 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009820 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009821 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009822 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009823 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009824 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009825 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009826 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009827 retCode = PackageManager.INSTALL_SUCCEEDED;
9828 pkgList.add(pkg.packageName);
9829 // Post process args
9830 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9831 }
9832 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009833 Slog.i(TAG, "Failed to install pkg from " +
9834 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009835 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009836 }
9837
9838 } finally {
9839 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9840 // Don't destroy container here. Wait till gc clears things up.
9841 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009842 }
9843 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009844 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009845 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009846 // If the platform SDK has changed since the last time we booted,
9847 // we need to re-grant app permission to catch any new ones that
9848 // appear. This is really a hack, and means that apps can in some
9849 // cases get permissions that the user didn't initially explicitly
9850 // allow... it would be nice to have some better way to handle
9851 // this situation.
9852 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9853 != mSdkVersion;
9854 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9855 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9856 + "; regranting permissions for external storage");
9857 mSettings.mExternalSdkPlatform = mSdkVersion;
9858
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009859 // Make sure group IDs have been assigned, and any permission
9860 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009861 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009862 // Persist settings
9863 mSettings.writeLP();
9864 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009865 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009866 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009867 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009868 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009869 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009870 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009871 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009872 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009873 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009874 if (removeCids != null) {
9875 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009876 if (cid.startsWith(mTempContainerPrefix)) {
9877 Log.i(TAG, "Destroying stale temporary container " + cid);
9878 PackageHelper.destroySdDir(cid);
9879 } else {
9880 Log.w(TAG, "Container " + cid + " is stale");
9881 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009882 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009883 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009884 }
9885
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009886 /*
9887 * Utility method to unload a list of specified containers
9888 */
9889 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9890 // Just unmount all valid containers.
9891 for (SdInstallArgs arg : cidArgs) {
9892 synchronized (mInstallLock) {
9893 arg.doPostDeleteLI(false);
9894 }
9895 }
9896 }
9897
9898 /*
9899 * Unload packages mounted on external media. This involves deleting
9900 * package data from internal structures, sending broadcasts about
9901 * diabled packages, gc'ing to free up references, unmounting all
9902 * secure containers corresponding to packages on external media, and
9903 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9904 * Please note that we always have to post this message if status has
9905 * been requested no matter what.
9906 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009907 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009908 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009909 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009910 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009911 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009912 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009913 for (SdInstallArgs args : keys) {
9914 String cid = args.cid;
9915 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009916 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009917 // Delete package internally
9918 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9919 synchronized (mInstallLock) {
9920 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009921 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009922 if (res) {
9923 pkgList.add(pkgName);
9924 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009925 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009926 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009927 }
9928 }
9929 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009930
9931 synchronized (mPackages) {
9932 // We didn't update the settings after removing each package;
9933 // write them now for all packages.
9934 mSettings.writeLP();
9935 }
9936
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009937 // We have to absolutely send UPDATED_MEDIA_STATUS only
9938 // after confirming that all the receivers processed the ordered
9939 // broadcast when packages get disabled, force a gc to clean things up.
9940 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009941 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009942 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9943 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9944 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009945 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9946 reportStatus ? 1 : 0, 1, keys);
9947 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009948 }
9949 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009950 } else {
9951 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9952 reportStatus ? 1 : 0, -1, keys);
9953 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009954 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009955 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009956
9957 public void movePackage(final String packageName,
9958 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009959 mContext.enforceCallingOrSelfPermission(
9960 android.Manifest.permission.MOVE_PACKAGE, null);
9961 int returnCode = PackageManager.MOVE_SUCCEEDED;
9962 int currFlags = 0;
9963 int newFlags = 0;
9964 synchronized (mPackages) {
9965 PackageParser.Package pkg = mPackages.get(packageName);
9966 if (pkg == null) {
9967 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009968 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009969 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009970 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009971 Slog.w(TAG, "Cannot move system application");
9972 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009973 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009974 Slog.w(TAG, "Cannot move forward locked app.");
9975 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009976 } else if (pkg.mOperationPending) {
9977 Slog.w(TAG, "Attempt to move package which has pending operations");
9978 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009979 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009980 // Find install location first
9981 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9982 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9983 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009984 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009985 } else {
9986 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9987 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009988 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9989 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009990 if (newFlags == currFlags) {
9991 Slog.w(TAG, "No move required. Trying to move to same location");
9992 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9993 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009994 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009995 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9996 pkg.mOperationPending = true;
9997 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009998 }
9999 }
10000 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -070010001 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010002 } else {
10003 Message msg = mHandler.obtainMessage(INIT_COPY);
10004 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -070010005 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
10006 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
10007 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010008 msg.obj = mp;
10009 mHandler.sendMessage(msg);
10010 }
10011 }
10012 }
10013
10014 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10015 // Queue up an async operation since the package deletion may take a little while.
10016 mHandler.post(new Runnable() {
10017 public void run() {
10018 mHandler.removeCallbacks(this);
10019 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010020 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10021 int uidArr[] = null;
10022 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010023 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010024 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010025 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010026 Slog.w(TAG, " Package " + mp.packageName +
10027 " doesn't exist. Aborting move");
10028 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10029 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10030 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10031 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10032 " Aborting move and returning error");
10033 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10034 } else {
10035 uidArr = new int[] { pkg.applicationInfo.uid };
10036 pkgList = new ArrayList<String>();
10037 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010038 }
10039 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010040 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10041 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010042 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010043 // Update package code and resource paths
10044 synchronized (mInstallLock) {
10045 synchronized (mPackages) {
10046 PackageParser.Package pkg = mPackages.get(mp.packageName);
10047 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010048 if (pkg == null) {
10049 Slog.w(TAG, " Package " + mp.packageName
10050 + " doesn't exist. Aborting move");
10051 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010052 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10053 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10054 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10055 " Aborting move and returning error");
10056 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10057 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010058 final String oldCodePath = pkg.mPath;
10059 final String newCodePath = mp.targetArgs.getCodePath();
10060 final String newResPath = mp.targetArgs.getResourcePath();
10061 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010062
10063 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10064 if (mInstaller
10065 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10066 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10067 } else {
10068 NativeLibraryHelper.copyNativeBinariesLI(
10069 new File(newCodePath), new File(newNativePath));
10070 }
10071 } else {
10072 if (mInstaller.linkNativeLibraryDirectory(
10073 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10074 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10075 }
10076 }
10077
10078 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10079 pkg.mPath = newCodePath;
10080 // Move dex files around
10081 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10082 // Moving of dex files failed. Set
10083 // error code and abort move.
10084 pkg.mPath = pkg.mScanPath;
10085 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10086 }
10087 }
10088
10089 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010090 pkg.mScanPath = newCodePath;
10091 pkg.applicationInfo.sourceDir = newCodePath;
10092 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010093 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010094 PackageSetting ps = (PackageSetting) pkg.mExtras;
10095 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10096 ps.codePathString = ps.codePath.getPath();
10097 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10098 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010099 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010100 // Set the application info flag correctly.
10101 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10102 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10103 } else {
10104 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10105 }
10106 ps.setFlags(pkg.applicationInfo.flags);
10107 mAppDirs.remove(oldCodePath);
10108 mAppDirs.put(newCodePath, pkg);
10109 // Persist settings
10110 mSettings.writeLP();
10111 }
10112 }
10113 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010114 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010115 // Send resources available broadcast
10116 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010117 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010118 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010119 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010120 // Clean up failed installation
10121 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010122 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010123 }
10124 } else {
10125 // Force a gc to clear things up.
10126 Runtime.getRuntime().gc();
10127 // Delete older code
10128 synchronized (mInstallLock) {
10129 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010130 }
10131 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010132
10133 // Allow more operations on this file if we didn't fail because
10134 // an operation was already pending for this package.
10135 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10136 synchronized (mPackages) {
10137 PackageParser.Package pkg = mPackages.get(mp.packageName);
10138 if (pkg != null) {
10139 pkg.mOperationPending = false;
10140 }
10141 }
10142 }
10143
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010144 IPackageMoveObserver observer = mp.observer;
10145 if (observer != null) {
10146 try {
10147 observer.packageMoved(mp.packageName, returnCode);
10148 } catch (RemoteException e) {
10149 Log.i(TAG, "Observer no longer exists.");
10150 }
10151 }
10152 }
10153 });
10154 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010155
10156 public boolean setInstallLocation(int loc) {
10157 mContext.enforceCallingOrSelfPermission(
10158 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10159 if (getInstallLocation() == loc) {
10160 return true;
10161 }
10162 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10163 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10164 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10165 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10166 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10167 return true;
10168 }
10169 return false;
10170 }
10171
10172 public int getInstallLocation() {
10173 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10174 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010176}