blob: be3cd754e068bde10829ff67572a7b7f6d0b5494 [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
Joe Onorato431bb222010-10-18 19:13:23 -04002503 if (false) {
2504 Log.d(TAG, "Scanning app dir " + dir);
2505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506
2507 int i;
2508 for (i=0; i<files.length; i++) {
2509 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002510 if (!isPackageFilename(files[i])) {
2511 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002512 continue;
2513 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002514 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002515 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002516 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002517 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2518 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002519 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002520 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002521 file.delete();
2522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
2524 }
2525
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002526 private static File getSettingsProblemFile() {
2527 File dataDir = Environment.getDataDirectory();
2528 File systemDir = new File(dataDir, "system");
2529 File fname = new File(systemDir, "uiderrors.txt");
2530 return fname;
2531 }
2532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 private static void reportSettingsProblem(int priority, String msg) {
2534 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002535 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 FileOutputStream out = new FileOutputStream(fname, true);
2537 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002538 SimpleDateFormat formatter = new SimpleDateFormat();
2539 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2540 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 pw.close();
2542 FileUtils.setPermissions(
2543 fname.toString(),
2544 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2545 -1, -1);
2546 } catch (java.io.IOException e) {
2547 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002548 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 }
2550
2551 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2552 PackageParser.Package pkg, File srcFile, int parseFlags) {
2553 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002554 if (ps != null
2555 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002556 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002557 if (ps.signatures.mSignatures != null
2558 && ps.signatures.mSignatures.length != 0) {
2559 // Optimization: reuse the existing cached certificates
2560 // if the package appears to be unchanged.
2561 pkg.mSignatures = ps.signatures.mSignatures;
2562 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 }
Jeff Browne7600722010-04-07 18:28:23 -07002564
2565 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002566 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002567 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2568 }
2569
2570 if (!pp.collectCertificates(pkg, parseFlags)) {
2571 mLastScanError = pp.getParseError();
2572 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
2574 }
2575 return true;
2576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 /*
2579 * Scan a package and return the newly parsed package.
2580 * Returns null in case of errors and the error code is stored in mLastScanError
2581 */
2582 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002583 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002585 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002587 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002590 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 if (pkg == null) {
2592 mLastScanError = pp.getParseError();
2593 return null;
2594 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002595 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 PackageSetting updatedPkg;
2597 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002598 // Look to see if we already know about this package.
2599 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002600 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002601 // This package has been renamed to its original name. Let's
2602 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002603 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002604 }
2605 // If there was no original package, see one for the real package name.
2606 if (ps == null) {
2607 ps = mSettings.peekPackageLP(pkg.packageName);
2608 }
2609 // Check to see if this package could be hiding/updating a system
2610 // package. Must look for it either under the original or real
2611 // package name depending on our state.
2612 updatedPkg = mSettings.mDisabledSysPackages.get(
2613 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002615 // First check if this is a system package that may involve an update
2616 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002617 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002618 // The path has changed from what was last scanned... check the
2619 // version of the new path against what we have stored to determine
2620 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002621 if (pkg.mVersionCode < ps.versionCode) {
2622 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002623 // Ignore entry. Skip it.
2624 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002625 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002626 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002627 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2628 return null;
2629 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002630 // The current app on the system partion is better than
2631 // what we have updated to on the data partition; switch
2632 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002633 // At this point, its safely assumed that package installation for
2634 // apps in system partition will go through. If not there won't be a working
2635 // version of the app
2636 synchronized (mPackages) {
2637 // Just remove the loaded entries from package lists.
2638 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002639 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002640 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002641 + "reverting from " + ps.codePathString
2642 + ": new version " + pkg.mVersionCode
2643 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002644 InstallArgs args = new FileInstallArgs(ps.codePathString,
2645 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002646 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002647 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 }
2650 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002651 if (updatedPkg != null) {
2652 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2653 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2654 }
2655 // Verify certificates against what was last scanned
2656 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002657 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002658 return null;
2659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 // The apk is forward locked (not public) if its code and resources
2661 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002662 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002664 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002665 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002666
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002667 String codePath = null;
2668 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002669 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2670 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002671 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002672 } else {
2673 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002674 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002675 }
2676 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002677 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002678 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002679 codePath = pkg.mScanPath;
2680 // Set application objects path explicitly.
2681 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002683 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 }
2685
Kenny Root85387d72010-08-26 10:13:11 -07002686 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2687 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002688 pkg.mPath = pkg.mScanPath = destCodePath;
2689 pkg.applicationInfo.sourceDir = destCodePath;
2690 pkg.applicationInfo.publicSourceDir = destResPath;
2691 }
2692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 private static String fixProcessName(String defProcessName,
2694 String processName, int uid) {
2695 if (processName == null) {
2696 return defProcessName;
2697 }
2698 return processName;
2699 }
2700
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002701 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002702 PackageParser.Package pkg) {
2703 if (pkgSetting.signatures.mSignatures != null) {
2704 // Already existing package. Make sure signatures match
2705 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2706 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002707 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002708 + " signatures do not match the previously installed version; ignoring!");
2709 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 return false;
2711 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002712 }
2713 // Check for shared user signatures
2714 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2715 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2716 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2717 Slog.e(TAG, "Package " + pkg.packageName
2718 + " has no signatures that match those in shared user "
2719 + pkgSetting.sharedUser.name + "; ignoring!");
2720 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2721 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
2724 return true;
2725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002726
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002727 public boolean performDexOpt(String packageName) {
2728 if (!mNoDexOpt) {
2729 return false;
2730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002731
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002732 PackageParser.Package p;
2733 synchronized (mPackages) {
2734 p = mPackages.get(packageName);
2735 if (p == null || p.mDidDexOpt) {
2736 return false;
2737 }
2738 }
2739 synchronized (mInstallLock) {
2740 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2741 }
2742 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002743
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002744 static final int DEX_OPT_SKIPPED = 0;
2745 static final int DEX_OPT_PERFORMED = 1;
2746 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002747
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002748 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2749 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002750 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002751 String path = pkg.mScanPath;
2752 int ret = 0;
2753 try {
2754 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002755 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002756 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002757 pkg.mDidDexOpt = true;
2758 performed = true;
2759 }
2760 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002761 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002762 ret = -1;
2763 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002764 Slog.w(TAG, "IOException reading apk: " + path, e);
2765 ret = -1;
2766 } catch (dalvik.system.StaleDexCacheError e) {
2767 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2768 ret = -1;
2769 } catch (Exception e) {
2770 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002771 ret = -1;
2772 }
2773 if (ret < 0) {
2774 //error from installer
2775 return DEX_OPT_FAILED;
2776 }
2777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002778
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002779 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2780 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002781
2782 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2783 return Environment.isEncryptedFilesystemEnabled() &&
2784 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2785 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002786
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002787 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2788 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002789 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002790 + " to " + newPkg.packageName
2791 + ": old package not in system partition");
2792 return false;
2793 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002794 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002795 + " to " + newPkg.packageName
2796 + ": old package still exists");
2797 return false;
2798 }
2799 return true;
2800 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002801
2802 private File getDataPathForPackage(PackageParser.Package pkg) {
2803 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2804 File dataPath;
2805 if (useEncryptedFSDir) {
2806 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2807 } else {
2808 dataPath = new File(mAppDataDir, pkg.packageName);
2809 }
2810 return dataPath;
2811 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002812
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002813 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002814 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002815 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002816 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2817 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002818 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002819 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002820 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2821 return null;
2822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 mScanningPath = scanFile;
2824 if (pkg == null) {
2825 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2826 return null;
2827 }
2828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2830 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2831 }
2832
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002833 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 synchronized (mPackages) {
2835 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002836 Slog.w(TAG, "*************************************************");
2837 Slog.w(TAG, "Core android package being redefined. Skipping.");
2838 Slog.w(TAG, " file=" + mScanningPath);
2839 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2841 return null;
2842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 // Set up information for our fall-back user intent resolution
2845 // activity.
2846 mPlatformPackage = pkg;
2847 pkg.mVersionCode = mSdkVersion;
2848 mAndroidApplication = pkg.applicationInfo;
2849 mResolveActivity.applicationInfo = mAndroidApplication;
2850 mResolveActivity.name = ResolverActivity.class.getName();
2851 mResolveActivity.packageName = mAndroidApplication.packageName;
2852 mResolveActivity.processName = mAndroidApplication.processName;
2853 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2854 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2855 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2856 mResolveActivity.exported = true;
2857 mResolveActivity.enabled = true;
2858 mResolveInfo.activityInfo = mResolveActivity;
2859 mResolveInfo.priority = 0;
2860 mResolveInfo.preferredOrder = 0;
2861 mResolveInfo.match = 0;
2862 mResolveComponentName = new ComponentName(
2863 mAndroidApplication.packageName, mResolveActivity.name);
2864 }
2865 }
2866
2867 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002868 TAG, "Scanning package " + pkg.packageName);
2869 if (mPackages.containsKey(pkg.packageName)
2870 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002871 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 + " already installed. Skipping duplicate.");
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) {
Kenny Roote68d58a2010-10-18 16:08:54 -07003289 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3290 final String dataPathString = dataPath.getPath();
3291
Kenny Root831baa22010-10-05 12:29:25 -07003292 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3293 /*
3294 * Upgrading from a previous version of the OS sometimes
3295 * leaves native libraries in the /data/data/<app>/lib
3296 * directory for system apps even when they shouldn't be.
3297 * Recent changes in the JNI library search path
3298 * necessitates we remove those to match previous behavior.
3299 */
Kenny Roote68d58a2010-10-18 16:08:54 -07003300 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Kenny Root831baa22010-10-05 12:29:25 -07003301 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3302 }
Kenny Roote68d58a2010-10-18 16:08:54 -07003303 } else if (nativeLibraryDir.getParent().equals(dataPathString)) {
3304 /*
3305 * If this is an internal application or our
3306 * nativeLibraryPath points to our data directory, unpack
3307 * the libraries. The native library path pointing to the
3308 * data directory for an application in an ASEC container
3309 * can happen for older apps that existed before an OTA to
3310 * Gingerbread.
3311 */
3312 Slog.i(TAG, "Unpacking native libraries for " + path);
3313 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
3314 NativeLibraryHelper.copyNativeBinariesLI(scanFile, nativeLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003315 } else {
Kenny Roote68d58a2010-10-18 16:08:54 -07003316 Slog.i(TAG, "Linking native library dir for " + path);
3317 mInstaller.linkNativeLibraryDirectory(dataPathString,
Kenny Root6a6b0072010-10-07 16:46:10 -07003318 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003321 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003322
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003323 if ((scanMode&SCAN_NO_DEX) == 0) {
3324 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3326 return null;
3327 }
3328 }
3329 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 if (mFactoryTest && pkg.requestedPermissions.contains(
3332 android.Manifest.permission.FACTORY_TEST)) {
3333 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3334 }
3335
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003336 // Request the ActivityManager to kill the process(only for existing packages)
3337 // so that we do not end up in a confused state while the user is still using the older
3338 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003339 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003340 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003341 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003342 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003345 // We don't expect installation to fail beyond this point,
3346 if ((scanMode&SCAN_MONITOR) != 0) {
3347 mAppDirs.put(pkg.mPath, pkg);
3348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003350 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003352 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003353 // Make sure we don't accidentally delete its data.
3354 mSettings.mPackagesToBeCleaned.remove(pkgName);
3355
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003356 // Take care of first install / last update times.
3357 if (currentTime != 0) {
3358 if (pkgSetting.firstInstallTime == 0) {
3359 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3360 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3361 pkgSetting.lastUpdateTime = currentTime;
3362 }
3363 } else if (pkgSetting.firstInstallTime == 0) {
3364 // We need *something*. Take time time stamp of the file.
3365 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3366 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3367 if (scanFileTime != pkgSetting.timeStamp) {
3368 // A package on the system image has changed; consider this
3369 // to be an update.
3370 pkgSetting.lastUpdateTime = scanFileTime;
3371 }
3372 }
3373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 int N = pkg.providers.size();
3375 StringBuilder r = null;
3376 int i;
3377 for (i=0; i<N; i++) {
3378 PackageParser.Provider p = pkg.providers.get(i);
3379 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3380 p.info.processName, pkg.applicationInfo.uid);
3381 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3382 p.info.name), p);
3383 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003384 if (p.info.authority != null) {
3385 String names[] = p.info.authority.split(";");
3386 p.info.authority = null;
3387 for (int j = 0; j < names.length; j++) {
3388 if (j == 1 && p.syncable) {
3389 // We only want the first authority for a provider to possibly be
3390 // syncable, so if we already added this provider using a different
3391 // authority clear the syncable flag. We copy the provider before
3392 // changing it because the mProviders object contains a reference
3393 // to a provider that we don't want to change.
3394 // Only do this for the second authority since the resulting provider
3395 // object can be the same for all future authorities for this provider.
3396 p = new PackageParser.Provider(p);
3397 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003399 if (!mProviders.containsKey(names[j])) {
3400 mProviders.put(names[j], p);
3401 if (p.info.authority == null) {
3402 p.info.authority = names[j];
3403 } else {
3404 p.info.authority = p.info.authority + ";" + names[j];
3405 }
3406 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3407 Log.d(TAG, "Registered content provider: " + names[j] +
3408 ", className = " + p.info.name +
3409 ", isSyncable = " + p.info.isSyncable);
3410 } else {
3411 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003412 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003413 " (in package " + pkg.applicationInfo.packageName +
3414 "): name already used by "
3415 + ((other != null && other.getComponentName() != null)
3416 ? other.getComponentName().getPackageName() : "?"));
3417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 }
3419 }
3420 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3421 if (r == null) {
3422 r = new StringBuilder(256);
3423 } else {
3424 r.append(' ');
3425 }
3426 r.append(p.info.name);
3427 }
3428 }
3429 if (r != null) {
3430 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 N = pkg.services.size();
3434 r = null;
3435 for (i=0; i<N; i++) {
3436 PackageParser.Service s = pkg.services.get(i);
3437 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3438 s.info.processName, pkg.applicationInfo.uid);
3439 mServices.addService(s);
3440 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3441 if (r == null) {
3442 r = new StringBuilder(256);
3443 } else {
3444 r.append(' ');
3445 }
3446 r.append(s.info.name);
3447 }
3448 }
3449 if (r != null) {
3450 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 N = pkg.receivers.size();
3454 r = null;
3455 for (i=0; i<N; i++) {
3456 PackageParser.Activity a = pkg.receivers.get(i);
3457 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3458 a.info.processName, pkg.applicationInfo.uid);
3459 mReceivers.addActivity(a, "receiver");
3460 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3461 if (r == null) {
3462 r = new StringBuilder(256);
3463 } else {
3464 r.append(' ');
3465 }
3466 r.append(a.info.name);
3467 }
3468 }
3469 if (r != null) {
3470 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 N = pkg.activities.size();
3474 r = null;
3475 for (i=0; i<N; i++) {
3476 PackageParser.Activity a = pkg.activities.get(i);
3477 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3478 a.info.processName, pkg.applicationInfo.uid);
3479 mActivities.addActivity(a, "activity");
3480 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3481 if (r == null) {
3482 r = new StringBuilder(256);
3483 } else {
3484 r.append(' ');
3485 }
3486 r.append(a.info.name);
3487 }
3488 }
3489 if (r != null) {
3490 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3491 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 N = pkg.permissionGroups.size();
3494 r = null;
3495 for (i=0; i<N; i++) {
3496 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3497 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3498 if (cur == null) {
3499 mPermissionGroups.put(pg.info.name, pg);
3500 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3501 if (r == null) {
3502 r = new StringBuilder(256);
3503 } else {
3504 r.append(' ');
3505 }
3506 r.append(pg.info.name);
3507 }
3508 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003509 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 + pg.info.packageName + " ignored: original from "
3511 + cur.info.packageName);
3512 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3513 if (r == null) {
3514 r = new StringBuilder(256);
3515 } else {
3516 r.append(' ');
3517 }
3518 r.append("DUP:");
3519 r.append(pg.info.name);
3520 }
3521 }
3522 }
3523 if (r != null) {
3524 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 N = pkg.permissions.size();
3528 r = null;
3529 for (i=0; i<N; i++) {
3530 PackageParser.Permission p = pkg.permissions.get(i);
3531 HashMap<String, BasePermission> permissionMap =
3532 p.tree ? mSettings.mPermissionTrees
3533 : mSettings.mPermissions;
3534 p.group = mPermissionGroups.get(p.info.group);
3535 if (p.info.group == null || p.group != null) {
3536 BasePermission bp = permissionMap.get(p.info.name);
3537 if (bp == null) {
3538 bp = new BasePermission(p.info.name, p.info.packageName,
3539 BasePermission.TYPE_NORMAL);
3540 permissionMap.put(p.info.name, bp);
3541 }
3542 if (bp.perm == null) {
3543 if (bp.sourcePackage == null
3544 || bp.sourcePackage.equals(p.info.packageName)) {
3545 BasePermission tree = findPermissionTreeLP(p.info.name);
3546 if (tree == null
3547 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003548 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 bp.perm = p;
3550 bp.uid = pkg.applicationInfo.uid;
3551 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3552 if (r == null) {
3553 r = new StringBuilder(256);
3554 } else {
3555 r.append(' ');
3556 }
3557 r.append(p.info.name);
3558 }
3559 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003560 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 + p.info.packageName + " ignored: base tree "
3562 + tree.name + " is from package "
3563 + tree.sourcePackage);
3564 }
3565 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003566 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 + p.info.packageName + " ignored: original from "
3568 + bp.sourcePackage);
3569 }
3570 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3571 if (r == null) {
3572 r = new StringBuilder(256);
3573 } else {
3574 r.append(' ');
3575 }
3576 r.append("DUP:");
3577 r.append(p.info.name);
3578 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003579 if (bp.perm == p) {
3580 bp.protectionLevel = p.info.protectionLevel;
3581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003583 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 + p.info.packageName + " ignored: no group "
3585 + p.group);
3586 }
3587 }
3588 if (r != null) {
3589 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 N = pkg.instrumentation.size();
3593 r = null;
3594 for (i=0; i<N; i++) {
3595 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3596 a.info.packageName = pkg.applicationInfo.packageName;
3597 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3598 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3599 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003600 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003601 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3603 if (r == null) {
3604 r = new StringBuilder(256);
3605 } else {
3606 r.append(' ');
3607 }
3608 r.append(a.info.name);
3609 }
3610 }
3611 if (r != null) {
3612 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003614
Dianne Hackborn854060af2009-07-09 18:14:31 -07003615 if (pkg.protectedBroadcasts != null) {
3616 N = pkg.protectedBroadcasts.size();
3617 for (i=0; i<N; i++) {
3618 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3619 }
3620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 pkgSetting.setTimeStamp(scanFileTime);
3623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 return pkg;
3626 }
3627
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003628 private void killApplication(String pkgName, int uid) {
3629 // Request the ActivityManager to kill the process(only for existing packages)
3630 // so that we do not end up in a confused state while the user is still using the older
3631 // version of the application while the new one gets installed.
3632 IActivityManager am = ActivityManagerNative.getDefault();
3633 if (am != null) {
3634 try {
3635 am.killApplicationWithUid(pkgName, uid);
3636 } catch (RemoteException e) {
3637 }
3638 }
3639 }
3640
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003641 // Return the path of the directory that will contain the native binaries
3642 // of a given installed package. This is relative to the data path.
3643 //
Kenny Root85387d72010-08-26 10:13:11 -07003644 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3645 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3646 if (nativeLibraryDir != null) {
3647 return new File(nativeLibraryDir);
3648 } else {
3649 // Fall back for old packages
3650 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3651 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003652 }
3653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3655 if (chatty && Config.LOGD) Log.d(
3656 TAG, "Removing package " + pkg.applicationInfo.packageName );
3657
3658 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 mPackages.remove(pkg.applicationInfo.packageName);
3662 if (pkg.mPath != null) {
3663 mAppDirs.remove(pkg.mPath);
3664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 PackageSetting ps = (PackageSetting)pkg.mExtras;
3667 if (ps != null && ps.sharedUser != null) {
3668 // XXX don't do this until the data is removed.
3669 if (false) {
3670 ps.sharedUser.packages.remove(ps);
3671 if (ps.sharedUser.packages.size() == 0) {
3672 // Remove.
3673 }
3674 }
3675 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 int N = pkg.providers.size();
3678 StringBuilder r = null;
3679 int i;
3680 for (i=0; i<N; i++) {
3681 PackageParser.Provider p = pkg.providers.get(i);
3682 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3683 p.info.name));
3684 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 /* The is another ContentProvider with this authority when
3687 * this app was installed so this authority is null,
3688 * Ignore it as we don't have to unregister the provider.
3689 */
3690 continue;
3691 }
3692 String names[] = p.info.authority.split(";");
3693 for (int j = 0; j < names.length; j++) {
3694 if (mProviders.get(names[j]) == p) {
3695 mProviders.remove(names[j]);
3696 if (chatty && Config.LOGD) Log.d(
3697 TAG, "Unregistered content provider: " + names[j] +
3698 ", className = " + p.info.name +
3699 ", isSyncable = " + p.info.isSyncable);
3700 }
3701 }
3702 if (chatty) {
3703 if (r == null) {
3704 r = new StringBuilder(256);
3705 } else {
3706 r.append(' ');
3707 }
3708 r.append(p.info.name);
3709 }
3710 }
3711 if (r != null) {
3712 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 N = pkg.services.size();
3716 r = null;
3717 for (i=0; i<N; i++) {
3718 PackageParser.Service s = pkg.services.get(i);
3719 mServices.removeService(s);
3720 if (chatty) {
3721 if (r == null) {
3722 r = new StringBuilder(256);
3723 } else {
3724 r.append(' ');
3725 }
3726 r.append(s.info.name);
3727 }
3728 }
3729 if (r != null) {
3730 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 N = pkg.receivers.size();
3734 r = null;
3735 for (i=0; i<N; i++) {
3736 PackageParser.Activity a = pkg.receivers.get(i);
3737 mReceivers.removeActivity(a, "receiver");
3738 if (chatty) {
3739 if (r == null) {
3740 r = new StringBuilder(256);
3741 } else {
3742 r.append(' ');
3743 }
3744 r.append(a.info.name);
3745 }
3746 }
3747 if (r != null) {
3748 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3749 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 N = pkg.activities.size();
3752 r = null;
3753 for (i=0; i<N; i++) {
3754 PackageParser.Activity a = pkg.activities.get(i);
3755 mActivities.removeActivity(a, "activity");
3756 if (chatty) {
3757 if (r == null) {
3758 r = new StringBuilder(256);
3759 } else {
3760 r.append(' ');
3761 }
3762 r.append(a.info.name);
3763 }
3764 }
3765 if (r != null) {
3766 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3767 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 N = pkg.permissions.size();
3770 r = null;
3771 for (i=0; i<N; i++) {
3772 PackageParser.Permission p = pkg.permissions.get(i);
3773 boolean tree = false;
3774 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3775 if (bp == null) {
3776 tree = true;
3777 bp = mSettings.mPermissionTrees.get(p.info.name);
3778 }
3779 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003780 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 if (chatty) {
3782 if (r == null) {
3783 r = new StringBuilder(256);
3784 } else {
3785 r.append(' ');
3786 }
3787 r.append(p.info.name);
3788 }
3789 }
3790 }
3791 if (r != null) {
3792 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 N = pkg.instrumentation.size();
3796 r = null;
3797 for (i=0; i<N; i++) {
3798 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003799 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 if (chatty) {
3801 if (r == null) {
3802 r = new StringBuilder(256);
3803 } else {
3804 r.append(' ');
3805 }
3806 r.append(a.info.name);
3807 }
3808 }
3809 if (r != null) {
3810 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3811 }
3812 }
3813 }
3814
3815 private static final boolean isPackageFilename(String name) {
3816 return name != null && name.endsWith(".apk");
3817 }
3818
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003819 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3820 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3821 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3822 return true;
3823 }
3824 }
3825 return false;
3826 }
3827
3828 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003829 PackageParser.Package pkgInfo, boolean grantPermissions,
3830 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 // Make sure there are no dangling permission trees.
3832 Iterator<BasePermission> it = mSettings.mPermissionTrees
3833 .values().iterator();
3834 while (it.hasNext()) {
3835 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003836 if (bp.packageSetting == null) {
3837 // We may not yet have parsed the package, so just see if
3838 // we still know about its settings.
3839 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3840 }
3841 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003842 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 + " from package " + bp.sourcePackage);
3844 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003845 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3846 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3847 Slog.i(TAG, "Removing old permission tree: " + bp.name
3848 + " from package " + bp.sourcePackage);
3849 grantPermissions = true;
3850 it.remove();
3851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 }
3853 }
3854
3855 // Make sure all dynamic permissions have been assigned to a package,
3856 // and make sure there are no dangling permissions.
3857 it = mSettings.mPermissions.values().iterator();
3858 while (it.hasNext()) {
3859 BasePermission bp = it.next();
3860 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3861 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3862 + bp.name + " pkg=" + bp.sourcePackage
3863 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003864 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 BasePermission tree = findPermissionTreeLP(bp.name);
3866 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003867 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 bp.perm = new PackageParser.Permission(tree.perm.owner,
3869 new PermissionInfo(bp.pendingInfo));
3870 bp.perm.info.packageName = tree.perm.info.packageName;
3871 bp.perm.info.name = bp.name;
3872 bp.uid = tree.uid;
3873 }
3874 }
3875 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003876 if (bp.packageSetting == null) {
3877 // We may not yet have parsed the package, so just see if
3878 // we still know about its settings.
3879 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3880 }
3881 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003882 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 + " from package " + bp.sourcePackage);
3884 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003885 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3886 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3887 Slog.i(TAG, "Removing old permission: " + bp.name
3888 + " from package " + bp.sourcePackage);
3889 grantPermissions = true;
3890 it.remove();
3891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 }
3893 }
3894
3895 // Now update the permissions for all packages, in particular
3896 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003897 if (grantPermissions) {
3898 for (PackageParser.Package pkg : mPackages.values()) {
3899 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003900 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003901 }
3902 }
3903 }
3904
3905 if (pkgInfo != null) {
3906 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 }
3908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3911 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3912 if (ps == null) {
3913 return;
3914 }
3915 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003916 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 if (replace) {
3919 ps.permissionsFixed = false;
3920 if (gp == ps) {
3921 gp.grantedPermissions.clear();
3922 gp.gids = mGlobalGids;
3923 }
3924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 if (gp.gids == null) {
3927 gp.gids = mGlobalGids;
3928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 final int N = pkg.requestedPermissions.size();
3931 for (int i=0; i<N; i++) {
3932 String name = pkg.requestedPermissions.get(i);
3933 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 if (false) {
3935 if (gp != ps) {
3936 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003937 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 }
3939 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003940 if (bp != null && bp.packageSetting != null) {
3941 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003943 boolean allowedSig = false;
3944 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3945 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003947 } else if (bp.packageSetting == null) {
3948 // This permission is invalid; skip it.
3949 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003950 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3951 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003952 allowed = (checkSignaturesLP(
3953 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003955 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003957 if (!allowed && bp.protectionLevel
3958 == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003959 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 // For updated system applications, the signatureOrSystem permission
3961 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003962 if (isUpdatedSystemApp(pkg)) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003963 PackageSetting sysPs = mSettings.getDisabledSystemPkg(
3964 pkg.packageName);
3965 final GrantedPermissions origGp = sysPs.sharedUser != null
3966 ? sysPs.sharedUser : sysPs;
3967 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 allowed = true;
3969 } else {
3970 allowed = false;
3971 }
3972 } else {
3973 allowed = true;
3974 }
3975 }
3976 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003977 if (allowed) {
3978 allowedSig = true;
3979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 } else {
3981 allowed = false;
3982 }
3983 if (false) {
3984 if (gp != ps) {
3985 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3986 }
3987 }
3988 if (allowed) {
3989 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3990 && ps.permissionsFixed) {
3991 // If this is an existing, non-system package, then
3992 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003993 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003995 // Except... if this is a permission that was added
3996 // to the platform (note: need to only do this when
3997 // updating the platform).
3998 final int NP = PackageParser.NEW_PERMISSIONS.length;
3999 for (int ip=0; ip<NP; ip++) {
4000 final PackageParser.NewPermissionInfo npi
4001 = PackageParser.NEW_PERMISSIONS[ip];
4002 if (npi.name.equals(perm)
4003 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4004 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004005 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004006 + pkg.packageName);
4007 break;
4008 }
4009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 }
4011 }
4012 if (allowed) {
4013 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004014 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 gp.grantedPermissions.add(perm);
4016 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004017 } else if (!ps.haveGids) {
4018 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 }
4020 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004021 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 + " to package " + pkg.packageName
4023 + " because it was previously installed without");
4024 }
4025 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004026 if (gp.grantedPermissions.remove(perm)) {
4027 changedPermission = true;
4028 gp.gids = removeInts(gp.gids, bp.gids);
4029 Slog.i(TAG, "Un-granting permission " + perm
4030 + " from package " + pkg.packageName
4031 + " (protectionLevel=" + bp.protectionLevel
4032 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4033 + ")");
4034 } else {
4035 Slog.w(TAG, "Not granting permission " + perm
4036 + " to package " + pkg.packageName
4037 + " (protectionLevel=" + bp.protectionLevel
4038 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4039 + ")");
4040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 }
4042 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004043 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 + " in package " + pkg.packageName);
4045 }
4046 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004047
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004048 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004049 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4050 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 // This is the first that we have heard about this package, so the
4052 // permissions we have now selected are fixed until explicitly
4053 // changed.
4054 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004056 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 private final class ActivityIntentResolver
4060 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004061 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004063 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 }
4065
Mihai Preda074edef2009-05-18 17:13:31 +02004066 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004068 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4070 }
4071
Mihai Predaeae850c2009-05-13 10:13:48 +02004072 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4073 ArrayList<PackageParser.Activity> packageActivities) {
4074 if (packageActivities == null) {
4075 return null;
4076 }
4077 mFlags = flags;
4078 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4079 int N = packageActivities.size();
4080 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4081 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004082
4083 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004084 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004085 intentFilters = packageActivities.get(i).intents;
4086 if (intentFilters != null && intentFilters.size() > 0) {
4087 listCut.add(intentFilters);
4088 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004089 }
4090 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4091 }
4092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004094 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 if (SHOW_INFO || Config.LOGV) Log.v(
4096 TAG, " " + type + " " +
4097 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4098 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4099 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004100 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4102 if (SHOW_INFO || Config.LOGV) {
4103 Log.v(TAG, " IntentFilter:");
4104 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4105 }
4106 if (!intent.debugCheck()) {
4107 Log.w(TAG, "==> For Activity " + a.info.name);
4108 }
4109 addFilter(intent);
4110 }
4111 }
4112
4113 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004114 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 if (SHOW_INFO || Config.LOGV) Log.v(
4116 TAG, " " + type + " " +
4117 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4118 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4119 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004120 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4122 if (SHOW_INFO || Config.LOGV) {
4123 Log.v(TAG, " IntentFilter:");
4124 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4125 }
4126 removeFilter(intent);
4127 }
4128 }
4129
4130 @Override
4131 protected boolean allowFilterResult(
4132 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4133 ActivityInfo filterAi = filter.activity.info;
4134 for (int i=dest.size()-1; i>=0; i--) {
4135 ActivityInfo destAi = dest.get(i).activityInfo;
4136 if (destAi.name == filterAi.name
4137 && destAi.packageName == filterAi.packageName) {
4138 return false;
4139 }
4140 }
4141 return true;
4142 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004145 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4146 return info.activity.owner.packageName;
4147 }
4148
4149 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4151 int match) {
4152 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4153 return null;
4154 }
4155 final PackageParser.Activity activity = info.activity;
4156 if (mSafeMode && (activity.info.applicationInfo.flags
4157 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4158 return null;
4159 }
4160 final ResolveInfo res = new ResolveInfo();
4161 res.activityInfo = PackageParser.generateActivityInfo(activity,
4162 mFlags);
4163 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4164 res.filter = info;
4165 }
4166 res.priority = info.getPriority();
4167 res.preferredOrder = activity.owner.mPreferredOrder;
4168 //System.out.println("Result: " + res.activityInfo.className +
4169 // " = " + res.priority);
4170 res.match = match;
4171 res.isDefault = info.hasDefault;
4172 res.labelRes = info.labelRes;
4173 res.nonLocalizedLabel = info.nonLocalizedLabel;
4174 res.icon = info.icon;
4175 return res;
4176 }
4177
4178 @Override
4179 protected void sortResults(List<ResolveInfo> results) {
4180 Collections.sort(results, mResolvePrioritySorter);
4181 }
4182
4183 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004184 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004186 out.print(prefix); out.print(
4187 Integer.toHexString(System.identityHashCode(filter.activity)));
4188 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004189 out.print(filter.activity.getComponentShortName());
4190 out.print(" filter ");
4191 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 }
4193
4194// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4195// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4196// final List<ResolveInfo> retList = Lists.newArrayList();
4197// while (i.hasNext()) {
4198// final ResolveInfo resolveInfo = i.next();
4199// if (isEnabledLP(resolveInfo.activityInfo)) {
4200// retList.add(resolveInfo);
4201// }
4202// }
4203// return retList;
4204// }
4205
4206 // Keys are String (activity class name), values are Activity.
4207 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4208 = new HashMap<ComponentName, PackageParser.Activity>();
4209 private int mFlags;
4210 }
4211
4212 private final class ServiceIntentResolver
4213 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004214 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004216 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 }
4218
Mihai Preda074edef2009-05-18 17:13:31 +02004219 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004221 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4223 }
4224
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004225 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4226 ArrayList<PackageParser.Service> packageServices) {
4227 if (packageServices == null) {
4228 return null;
4229 }
4230 mFlags = flags;
4231 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4232 int N = packageServices.size();
4233 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4234 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4235
4236 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4237 for (int i = 0; i < N; ++i) {
4238 intentFilters = packageServices.get(i).intents;
4239 if (intentFilters != null && intentFilters.size() > 0) {
4240 listCut.add(intentFilters);
4241 }
4242 }
4243 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4244 }
4245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004247 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 if (SHOW_INFO || Config.LOGV) Log.v(
4249 TAG, " " + (s.info.nonLocalizedLabel != null
4250 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4251 if (SHOW_INFO || Config.LOGV) Log.v(
4252 TAG, " Class=" + s.info.name);
4253 int NI = s.intents.size();
4254 int j;
4255 for (j=0; j<NI; j++) {
4256 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4257 if (SHOW_INFO || Config.LOGV) {
4258 Log.v(TAG, " IntentFilter:");
4259 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4260 }
4261 if (!intent.debugCheck()) {
4262 Log.w(TAG, "==> For Service " + s.info.name);
4263 }
4264 addFilter(intent);
4265 }
4266 }
4267
4268 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004269 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 if (SHOW_INFO || Config.LOGV) Log.v(
4271 TAG, " " + (s.info.nonLocalizedLabel != null
4272 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4273 if (SHOW_INFO || Config.LOGV) Log.v(
4274 TAG, " Class=" + s.info.name);
4275 int NI = s.intents.size();
4276 int j;
4277 for (j=0; j<NI; j++) {
4278 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4279 if (SHOW_INFO || Config.LOGV) {
4280 Log.v(TAG, " IntentFilter:");
4281 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4282 }
4283 removeFilter(intent);
4284 }
4285 }
4286
4287 @Override
4288 protected boolean allowFilterResult(
4289 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4290 ServiceInfo filterSi = filter.service.info;
4291 for (int i=dest.size()-1; i>=0; i--) {
4292 ServiceInfo destAi = dest.get(i).serviceInfo;
4293 if (destAi.name == filterSi.name
4294 && destAi.packageName == filterSi.packageName) {
4295 return false;
4296 }
4297 }
4298 return true;
4299 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004302 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4303 return info.service.owner.packageName;
4304 }
4305
4306 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4308 int match) {
4309 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4310 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4311 return null;
4312 }
4313 final PackageParser.Service service = info.service;
4314 if (mSafeMode && (service.info.applicationInfo.flags
4315 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4316 return null;
4317 }
4318 final ResolveInfo res = new ResolveInfo();
4319 res.serviceInfo = PackageParser.generateServiceInfo(service,
4320 mFlags);
4321 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4322 res.filter = filter;
4323 }
4324 res.priority = info.getPriority();
4325 res.preferredOrder = service.owner.mPreferredOrder;
4326 //System.out.println("Result: " + res.activityInfo.className +
4327 // " = " + res.priority);
4328 res.match = match;
4329 res.isDefault = info.hasDefault;
4330 res.labelRes = info.labelRes;
4331 res.nonLocalizedLabel = info.nonLocalizedLabel;
4332 res.icon = info.icon;
4333 return res;
4334 }
4335
4336 @Override
4337 protected void sortResults(List<ResolveInfo> results) {
4338 Collections.sort(results, mResolvePrioritySorter);
4339 }
4340
4341 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004342 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004344 out.print(prefix); out.print(
4345 Integer.toHexString(System.identityHashCode(filter.service)));
4346 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004347 out.print(filter.service.getComponentShortName());
4348 out.print(" filter ");
4349 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 }
4351
4352// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4353// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4354// final List<ResolveInfo> retList = Lists.newArrayList();
4355// while (i.hasNext()) {
4356// final ResolveInfo resolveInfo = (ResolveInfo) i;
4357// if (isEnabledLP(resolveInfo.serviceInfo)) {
4358// retList.add(resolveInfo);
4359// }
4360// }
4361// return retList;
4362// }
4363
4364 // Keys are String (activity class name), values are Activity.
4365 private final HashMap<ComponentName, PackageParser.Service> mServices
4366 = new HashMap<ComponentName, PackageParser.Service>();
4367 private int mFlags;
4368 };
4369
4370 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4371 new Comparator<ResolveInfo>() {
4372 public int compare(ResolveInfo r1, ResolveInfo r2) {
4373 int v1 = r1.priority;
4374 int v2 = r2.priority;
4375 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4376 if (v1 != v2) {
4377 return (v1 > v2) ? -1 : 1;
4378 }
4379 v1 = r1.preferredOrder;
4380 v2 = r2.preferredOrder;
4381 if (v1 != v2) {
4382 return (v1 > v2) ? -1 : 1;
4383 }
4384 if (r1.isDefault != r2.isDefault) {
4385 return r1.isDefault ? -1 : 1;
4386 }
4387 v1 = r1.match;
4388 v2 = r2.match;
4389 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4390 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4391 }
4392 };
4393
4394 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4395 new Comparator<ProviderInfo>() {
4396 public int compare(ProviderInfo p1, ProviderInfo p2) {
4397 final int v1 = p1.initOrder;
4398 final int v2 = p2.initOrder;
4399 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4400 }
4401 };
4402
Kenny Root93565c4b2010-06-18 15:46:06 -07004403 private static final boolean DEBUG_OBB = false;
4404
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004405 private static final void sendPackageBroadcast(String action, String pkg,
4406 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004407 IActivityManager am = ActivityManagerNative.getDefault();
4408 if (am != null) {
4409 try {
4410 final Intent intent = new Intent(action,
4411 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4412 if (extras != null) {
4413 intent.putExtras(extras);
4414 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004415 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004416 am.broadcastIntent(null, intent, null, finishedReceiver,
4417 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 } catch (RemoteException ex) {
4419 }
4420 }
4421 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004422
4423 public String nextPackageToClean(String lastPackage) {
4424 synchronized (mPackages) {
4425 if (!mMediaMounted) {
4426 // If the external storage is no longer mounted at this point,
4427 // the caller may not have been able to delete all of this
4428 // packages files and can not delete any more. Bail.
4429 return null;
4430 }
4431 if (lastPackage != null) {
4432 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4433 }
4434 return mSettings.mPackagesToBeCleaned.size() > 0
4435 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4436 }
4437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004438
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004439 void schedulePackageCleaning(String packageName) {
4440 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4441 }
4442
4443 void startCleaningPackages() {
4444 synchronized (mPackages) {
4445 if (!mMediaMounted) {
4446 return;
4447 }
4448 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4449 return;
4450 }
4451 }
4452 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4453 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4454 IActivityManager am = ActivityManagerNative.getDefault();
4455 if (am != null) {
4456 try {
4457 am.startService(null, intent, null);
4458 } catch (RemoteException e) {
4459 }
4460 }
4461 }
4462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 private final class AppDirObserver extends FileObserver {
4464 public AppDirObserver(String path, int mask, boolean isrom) {
4465 super(path, mask);
4466 mRootDir = path;
4467 mIsRom = isrom;
4468 }
4469
4470 public void onEvent(int event, String path) {
4471 String removedPackage = null;
4472 int removedUid = -1;
4473 String addedPackage = null;
4474 int addedUid = -1;
4475
4476 synchronized (mInstallLock) {
4477 String fullPathStr = null;
4478 File fullPath = null;
4479 if (path != null) {
4480 fullPath = new File(mRootDir, path);
4481 fullPathStr = fullPath.getPath();
4482 }
4483
4484 if (Config.LOGV) Log.v(
4485 TAG, "File " + fullPathStr + " changed: "
4486 + Integer.toHexString(event));
4487
4488 if (!isPackageFilename(path)) {
4489 if (Config.LOGV) Log.v(
4490 TAG, "Ignoring change of non-package file: " + fullPathStr);
4491 return;
4492 }
4493
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004494 // Ignore packages that are being installed or
4495 // have just been installed.
4496 if (ignoreCodePath(fullPathStr)) {
4497 return;
4498 }
4499 PackageParser.Package p = null;
4500 synchronized (mPackages) {
4501 p = mAppDirs.get(fullPathStr);
4502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004504 if (p != null) {
4505 removePackageLI(p, true);
4506 removedPackage = p.applicationInfo.packageName;
4507 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 }
4509 }
4510
4511 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004513 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004514 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4515 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 PackageParser.PARSE_CHATTY |
4517 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004518 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4519 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 if (p != null) {
4521 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004522 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004523 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524 }
4525 addedPackage = p.applicationInfo.packageName;
4526 addedUid = p.applicationInfo.uid;
4527 }
4528 }
4529 }
4530
4531 synchronized (mPackages) {
4532 mSettings.writeLP();
4533 }
4534 }
4535
4536 if (removedPackage != null) {
4537 Bundle extras = new Bundle(1);
4538 extras.putInt(Intent.EXTRA_UID, removedUid);
4539 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004540 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4541 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004542 }
4543 if (addedPackage != null) {
4544 Bundle extras = new Bundle(1);
4545 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004546 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4547 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004548 }
4549 }
4550
4551 private final String mRootDir;
4552 private final boolean mIsRom;
4553 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004555 /* Called when a downloaded package installation has been confirmed by the user */
4556 public void installPackage(
4557 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004558 installPackage(packageURI, observer, flags, null);
4559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004560
Jacek Surazski65e13172009-04-28 15:26:38 +02004561 /* Called when a downloaded package installation has been confirmed by the user */
4562 public void installPackage(
4563 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4564 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004565 mContext.enforceCallingOrSelfPermission(
4566 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004567
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004568 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004569 msg.obj = new InstallParams(packageURI, observer, flags,
4570 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004571 mHandler.sendMessage(msg);
4572 }
4573
Christopher Tate1bb69062010-02-19 17:02:12 -08004574 public void finishPackageInstall(int token) {
4575 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4576 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4577 mHandler.sendMessage(msg);
4578 }
4579
Kenny Root93565c4b2010-06-18 15:46:06 -07004580 public void setPackageObbPath(String packageName, String path) {
4581 if (DEBUG_OBB)
4582 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4583 PackageSetting pkgSetting;
4584 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004585 final int permission = mContext.checkCallingPermission(
4586 android.Manifest.permission.INSTALL_PACKAGES);
4587 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004588 synchronized (mPackages) {
4589 pkgSetting = mSettings.mPackages.get(packageName);
4590 if (pkgSetting == null) {
4591 throw new IllegalArgumentException("Unknown package: " + packageName);
4592 }
4593 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4594 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4595 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4596 + pkgSetting.userId);
4597 }
4598 pkgSetting.obbPathString = path;
4599 mSettings.writeLP();
4600 }
4601 }
4602
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004603 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 // Queue up an async operation since the package installation may take a little while.
4605 mHandler.post(new Runnable() {
4606 public void run() {
4607 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004608 // Result object to be returned
4609 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004610 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004611 res.uid = -1;
4612 res.pkg = null;
4613 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004614 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004615 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004616 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004617 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004618 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004619 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004621
4622 // A restore should be performed at this point if (a) the install
4623 // succeeded, (b) the operation is not an update, and (c) the new
4624 // package has a backupAgent defined.
4625 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004626 boolean doRestore = (!update
4627 && res.pkg != null
4628 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004629
4630 // Set up the post-install work request bookkeeping. This will be used
4631 // and cleaned up by the post-install event handling regardless of whether
4632 // there's a restore pass performed. Token values are >= 1.
4633 int token;
4634 if (mNextInstallToken < 0) mNextInstallToken = 1;
4635 token = mNextInstallToken++;
4636
4637 PostInstallData data = new PostInstallData(args, res);
4638 mRunningInstalls.put(token, data);
4639 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4640
4641 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4642 // Pass responsibility to the Backup Manager. It will perform a
4643 // restore if appropriate, then pass responsibility back to the
4644 // Package Manager to run the post-install observer callbacks
4645 // and broadcasts.
4646 IBackupManager bm = IBackupManager.Stub.asInterface(
4647 ServiceManager.getService(Context.BACKUP_SERVICE));
4648 if (bm != null) {
4649 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4650 + " to BM for possible restore");
4651 try {
4652 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4653 } catch (RemoteException e) {
4654 // can't happen; the backup manager is local
4655 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004656 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004657 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004658 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004659 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004660 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004661 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004664
4665 if (!doRestore) {
4666 // No restore possible, or the Backup Manager was mysteriously not
4667 // available -- just fire the post-install work request directly.
4668 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4669 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4670 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004672 }
4673 });
4674 }
4675
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004676 abstract class HandlerParams {
4677 final static int MAX_RETRIES = 4;
4678 int retry = 0;
4679 final void startCopy() {
4680 try {
4681 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4682 retry++;
4683 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004684 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004685 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4686 handleServiceError();
4687 return;
4688 } else {
4689 handleStartCopy();
4690 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4691 mHandler.sendEmptyMessage(MCS_UNBIND);
4692 }
4693 } catch (RemoteException e) {
4694 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4695 mHandler.sendEmptyMessage(MCS_RECONNECT);
4696 }
4697 handleReturnCode();
4698 }
4699
4700 final void serviceError() {
4701 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4702 handleServiceError();
4703 handleReturnCode();
4704 }
4705 abstract void handleStartCopy() throws RemoteException;
4706 abstract void handleServiceError();
4707 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004708 }
4709
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004710 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004711 final IPackageInstallObserver observer;
4712 int flags;
4713 final Uri packageURI;
4714 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004715 private InstallArgs mArgs;
4716 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004717 InstallParams(Uri packageURI,
4718 IPackageInstallObserver observer, int flags,
4719 String installerPackageName) {
4720 this.packageURI = packageURI;
4721 this.flags = flags;
4722 this.observer = observer;
4723 this.installerPackageName = installerPackageName;
4724 }
4725
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004726 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4727 String packageName = pkgLite.packageName;
4728 int installLocation = pkgLite.installLocation;
4729 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4730 synchronized (mPackages) {
4731 PackageParser.Package pkg = mPackages.get(packageName);
4732 if (pkg != null) {
4733 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4734 // Check for updated system application.
4735 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4736 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004737 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004738 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4739 }
4740 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4741 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004742 if (onSd) {
4743 // Install flag overrides everything.
4744 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4745 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004746 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004747 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4748 // Application explicitly specified internal.
4749 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4750 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4751 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004752 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004753 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004754 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004755 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4756 }
4757 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004758 }
4759 }
4760 } else {
4761 // Invalid install. Return error code
4762 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4763 }
4764 }
4765 }
4766 // All the special cases have been taken care of.
4767 // Return result based on recommended install location.
4768 if (onSd) {
4769 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4770 }
4771 return pkgLite.recommendedInstallLocation;
4772 }
4773
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004774 /*
4775 * Invoke remote method to get package information and install
4776 * location values. Override install location based on default
4777 * policy if needed and then create install arguments based
4778 * on the install location.
4779 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004780 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004781 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004782 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4783 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004784 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4785 if (onInt && onSd) {
4786 // Check if both bits are set.
4787 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4788 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4789 } else if (fwdLocked && onSd) {
4790 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004791 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004792 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004793 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004794 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07004795 final PackageInfoLite pkgLite;
4796 try {
4797 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4798 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4799 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
4800 } finally {
4801 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4802 }
4803
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004804 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004805 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4806 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4807 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4808 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4809 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004810 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4811 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4812 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004813 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4814 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004815 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004816 // Override with defaults if needed.
4817 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004818 if (!onSd && !onInt) {
4819 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004820 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4821 // Set the flag to install on external media.
4822 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004823 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004824 } else {
4825 // Make sure the flag for installing on external
4826 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004827 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004828 flags &= ~PackageManager.INSTALL_EXTERNAL;
4829 }
4830 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004831 }
4832 }
4833 // Create the file args now.
4834 mArgs = createInstallArgs(this);
4835 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4836 // Create copy only if we are not in an erroneous state.
4837 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004838 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004839 }
4840 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004841 }
4842
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004843 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004844 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004845 // If mArgs is null, then MCS couldn't be reached. When it
4846 // reconnects, it will try again to install. At that point, this
4847 // will succeed.
4848 if (mArgs != null) {
4849 processPendingInstall(mArgs, mRet);
4850 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004851 }
4852
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004853 @Override
4854 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004855 mArgs = createInstallArgs(this);
4856 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004857 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004858 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004859
4860 /*
4861 * Utility class used in movePackage api.
4862 * srcArgs and targetArgs are not set for invalid flags and make
4863 * sure to do null checks when invoking methods on them.
4864 * We probably want to return ErrorPrams for both failed installs
4865 * and moves.
4866 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004867 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004868 final IPackageMoveObserver observer;
4869 final int flags;
4870 final String packageName;
4871 final InstallArgs srcArgs;
4872 final InstallArgs targetArgs;
4873 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004874
4875 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4876 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004877 this.srcArgs = srcArgs;
4878 this.observer = observer;
4879 this.flags = flags;
4880 this.packageName = packageName;
4881 if (srcArgs != null) {
4882 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004883 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004884 } else {
4885 targetArgs = null;
4886 }
4887 }
4888
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004889 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004890 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4891 // Check for storage space on target medium
4892 if (!targetArgs.checkFreeStorage(mContainerService)) {
4893 Log.w(TAG, "Insufficient storage to install");
4894 return;
4895 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004896 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004897 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004898 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004899 if (DEBUG_SD_INSTALL) {
4900 StringBuilder builder = new StringBuilder();
4901 if (srcArgs != null) {
4902 builder.append("src: ");
4903 builder.append(srcArgs.getCodePath());
4904 }
4905 if (targetArgs != null) {
4906 builder.append(" target : ");
4907 builder.append(targetArgs.getCodePath());
4908 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004909 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004910 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004911 }
4912
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004913 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004914 void handleReturnCode() {
4915 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004916 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4917 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4918 currentStatus = PackageManager.MOVE_SUCCEEDED;
4919 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4920 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4921 }
4922 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004923 }
4924
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004925 @Override
4926 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004927 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004928 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004929 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004930
4931 private InstallArgs createInstallArgs(InstallParams params) {
4932 if (installOnSd(params.flags)) {
4933 return new SdInstallArgs(params);
4934 } else {
4935 return new FileInstallArgs(params);
4936 }
4937 }
4938
Kenny Root85387d72010-08-26 10:13:11 -07004939 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4940 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004941 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004942 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004943 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004944 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004945 }
4946 }
4947
Kenny Root85387d72010-08-26 10:13:11 -07004948 // Used by package mover
4949 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004950 if (installOnSd(flags)) {
4951 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4952 return new SdInstallArgs(packageURI, cid);
4953 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004954 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004955 }
4956 }
4957
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004958 static abstract class InstallArgs {
4959 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004960 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004961 final int flags;
4962 final Uri packageURI;
4963 final String installerPackageName;
4964
4965 InstallArgs(Uri packageURI,
4966 IPackageInstallObserver observer, int flags,
4967 String installerPackageName) {
4968 this.packageURI = packageURI;
4969 this.flags = flags;
4970 this.observer = observer;
4971 this.installerPackageName = installerPackageName;
4972 }
4973
4974 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004975 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004976 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004977 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004978 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004979 abstract String getCodePath();
4980 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004981 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004982 // Need installer lock especially for dex file removal.
4983 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004984 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004985 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004986 }
4987
4988 class FileInstallArgs extends InstallArgs {
4989 File installDir;
4990 String codeFileName;
4991 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004992 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004993 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004994
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004995 FileInstallArgs(InstallParams params) {
4996 super(params.packageURI, params.observer,
4997 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004998 }
4999
Kenny Root85387d72010-08-26 10:13:11 -07005000 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005001 super(null, null, 0, null);
5002 File codeFile = new File(fullCodePath);
5003 installDir = codeFile.getParentFile();
5004 codeFileName = fullCodePath;
5005 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07005006 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005007 }
5008
Kenny Root85387d72010-08-26 10:13:11 -07005009 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005010 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07005011 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005012 String apkName = getNextCodePath(null, pkgName, ".apk");
5013 codeFileName = new File(installDir, apkName + ".apk").getPath();
5014 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07005015 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005016 }
5017
Kenny Root11128572010-10-11 10:51:32 -07005018 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5019 try {
5020 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5021 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5022 return imcs.checkFreeStorage(false, packageURI);
5023 } finally {
5024 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5025 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005026 }
5027
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005028 String getCodePath() {
5029 return codeFileName;
5030 }
5031
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005032 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005033 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005034 codeFileName = createTempPackageFile(installDir).getPath();
5035 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005036 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005037 }
5038
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005039 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005040 if (temp) {
5041 // Generate temp file name
5042 createCopyFile();
5043 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005044 // Get a ParcelFileDescriptor to write to the output file
5045 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005046 if (!created) {
5047 try {
5048 codeFile.createNewFile();
5049 // Set permissions
5050 if (!setPermissions()) {
5051 // Failed setting permissions.
5052 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5053 }
5054 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005055 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005056 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5057 }
5058 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005059 ParcelFileDescriptor out = null;
5060 try {
Kenny Root85387d72010-08-26 10:13:11 -07005061 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005062 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005063 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005064 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5065 }
5066 // Copy the resource now
5067 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5068 try {
Kenny Root11128572010-10-11 10:51:32 -07005069 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5070 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005071 if (imcs.copyResource(packageURI, out)) {
5072 ret = PackageManager.INSTALL_SUCCEEDED;
5073 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005074 } finally {
5075 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005076 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005077 }
Kenny Root85387d72010-08-26 10:13:11 -07005078
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005079 return ret;
5080 }
5081
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005082 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005083 if (status != PackageManager.INSTALL_SUCCEEDED) {
5084 cleanUp();
5085 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005086 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005087 }
5088
5089 boolean doRename(int status, final String pkgName, String oldCodePath) {
5090 if (status != PackageManager.INSTALL_SUCCEEDED) {
5091 cleanUp();
5092 return false;
5093 } else {
5094 // Rename based on packageName
5095 File codeFile = new File(getCodePath());
5096 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5097 File desFile = new File(installDir, apkName + ".apk");
5098 if (!codeFile.renameTo(desFile)) {
5099 return false;
5100 }
5101 // Reset paths since the file has been renamed.
5102 codeFileName = desFile.getPath();
5103 resourceFileName = getResourcePathFromCodePath();
5104 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005105 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005106 // Failed setting permissions.
5107 return false;
5108 }
5109 return true;
5110 }
5111 }
5112
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005113 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005114 if (status != PackageManager.INSTALL_SUCCEEDED) {
5115 cleanUp();
5116 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005117 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005118 }
5119
5120 String getResourcePath() {
5121 return resourceFileName;
5122 }
5123
5124 String getResourcePathFromCodePath() {
5125 String codePath = getCodePath();
5126 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5127 String apkNameOnly = getApkName(codePath);
5128 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5129 } else {
5130 return codePath;
5131 }
5132 }
5133
Kenny Root85387d72010-08-26 10:13:11 -07005134 @Override
5135 String getNativeLibraryPath() {
5136 return libraryPath;
5137 }
5138
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005139 private boolean cleanUp() {
5140 boolean ret = true;
5141 String sourceDir = getCodePath();
5142 String publicSourceDir = getResourcePath();
5143 if (sourceDir != null) {
5144 File sourceFile = new File(sourceDir);
5145 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005146 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005147 ret = false;
5148 }
5149 // Delete application's code and resources
5150 sourceFile.delete();
5151 }
5152 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5153 final File publicSourceFile = new File(publicSourceDir);
5154 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005155 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005156 }
5157 if (publicSourceFile.exists()) {
5158 publicSourceFile.delete();
5159 }
5160 }
5161 return ret;
5162 }
5163
5164 void cleanUpResourcesLI() {
5165 String sourceDir = getCodePath();
5166 if (cleanUp() && mInstaller != null) {
5167 int retCode = mInstaller.rmdex(sourceDir);
5168 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005169 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005170 + " at location "
5171 + sourceDir + ", retcode=" + retCode);
5172 // we don't consider this to be a failure of the core package deletion
5173 }
5174 }
5175 }
5176
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005177 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005178 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005179 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005180 final int filePermissions =
5181 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5182 |FileUtils.S_IROTH;
5183 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5184 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005185 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005186 getCodePath()
5187 + ". The return code was: " + retCode);
5188 // TODO Define new internal error
5189 return false;
5190 }
5191 return true;
5192 }
5193 return true;
5194 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005195
5196 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005197 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005198 cleanUpResourcesLI();
5199 return true;
5200 }
Kenny Root85387d72010-08-26 10:13:11 -07005201
5202 private boolean isFwdLocked() {
5203 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5204 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005205 }
5206
5207 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005208 static final String RES_FILE_NAME = "pkg.apk";
5209
Kenny Root85387d72010-08-26 10:13:11 -07005210 String cid;
5211 String packagePath;
5212 String libraryPath;
5213
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005214 SdInstallArgs(InstallParams params) {
5215 super(params.packageURI, params.observer,
5216 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005217 }
5218
Kenny Root85387d72010-08-26 10:13:11 -07005219 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005220 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005221 // Extract cid from fullCodePath
5222 int eidx = fullCodePath.lastIndexOf("/");
5223 String subStr1 = fullCodePath.substring(0, eidx);
5224 int sidx = subStr1.lastIndexOf("/");
5225 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005226 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005227 }
5228
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005229 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005230 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5231 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005232 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005233 }
5234
5235 SdInstallArgs(Uri packageURI, String cid) {
5236 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005237 this.cid = cid;
5238 }
5239
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005240 void createCopyFile() {
5241 cid = getTempContainerId();
5242 }
5243
Kenny Root11128572010-10-11 10:51:32 -07005244 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5245 try {
5246 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5247 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5248 return imcs.checkFreeStorage(true, packageURI);
5249 } finally {
5250 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5251 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005252 }
5253
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005254 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005255 if (temp) {
5256 createCopyFile();
5257 }
Kenny Root11128572010-10-11 10:51:32 -07005258
5259 final String newCachePath;
5260 try {
5261 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5262 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5263 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5264 getEncryptKey(), RES_FILE_NAME);
5265 } finally {
5266 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5267 }
5268
Kenny Root85387d72010-08-26 10:13:11 -07005269 if (newCachePath != null) {
5270 setCachePath(newCachePath);
5271 return PackageManager.INSTALL_SUCCEEDED;
5272 } else {
5273 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5274 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005275 }
5276
5277 @Override
5278 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005279 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005280 }
5281
5282 @Override
5283 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005284 return packagePath;
5285 }
5286
5287 @Override
5288 String getNativeLibraryPath() {
5289 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005290 }
5291
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005292 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005293 if (status != PackageManager.INSTALL_SUCCEEDED) {
5294 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005295 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005296 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005297 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005298 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005299 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5300 Process.SYSTEM_UID);
5301 if (newCachePath != null) {
5302 setCachePath(newCachePath);
5303 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005304 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5305 }
5306 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005307 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005308 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005309 }
5310
5311 boolean doRename(int status, final String pkgName,
5312 String oldCodePath) {
5313 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005314 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005315 if (PackageHelper.isContainerMounted(cid)) {
5316 // Unmount the container
5317 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005318 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005319 return false;
5320 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005321 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005322 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005323 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5324 " which might be stale. Will try to clean up.");
5325 // Clean up the stale container and proceed to recreate.
5326 if (!PackageHelper.destroySdDir(newCacheId)) {
5327 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5328 return false;
5329 }
5330 // Successfully cleaned up stale container. Try to rename again.
5331 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5332 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5333 + " inspite of cleaning it up.");
5334 return false;
5335 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005336 }
5337 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005338 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005339 newCachePath = PackageHelper.mountSdDir(newCacheId,
5340 getEncryptKey(), Process.SYSTEM_UID);
5341 } else {
5342 newCachePath = PackageHelper.getSdDir(newCacheId);
5343 }
5344 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005345 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005346 return false;
5347 }
5348 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005349 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005350 " at new path: " + newCachePath);
5351 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005352 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005353 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005354 }
5355
Kenny Root85387d72010-08-26 10:13:11 -07005356 private void setCachePath(String newCachePath) {
5357 File cachePath = new File(newCachePath);
5358 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5359 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5360 }
5361
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005362 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005363 if (status != PackageManager.INSTALL_SUCCEEDED) {
5364 cleanUp();
5365 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005366 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005367 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005368 PackageHelper.mountSdDir(cid,
5369 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005370 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005372 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005373 }
5374
5375 private void cleanUp() {
5376 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005377 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005378 }
5379
5380 void cleanUpResourcesLI() {
5381 String sourceFile = getCodePath();
5382 // Remove dex file
5383 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005384 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005385 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005386 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005387 + " at location "
5388 + sourceFile.toString() + ", retcode=" + retCode);
5389 // we don't consider this to be a failure of the core package deletion
5390 }
5391 }
5392 cleanUp();
5393 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005394
5395 boolean matchContainer(String app) {
5396 if (cid.startsWith(app)) {
5397 return true;
5398 }
5399 return false;
5400 }
5401
5402 String getPackageName() {
5403 int idx = cid.lastIndexOf("-");
5404 if (idx == -1) {
5405 return cid;
5406 }
5407 return cid.substring(0, idx);
5408 }
5409
5410 boolean doPostDeleteLI(boolean delete) {
5411 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005412 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005413 if (mounted) {
5414 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005415 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005416 }
5417 if (ret && delete) {
5418 cleanUpResourcesLI();
5419 }
5420 return ret;
5421 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005422 };
5423
5424 // Utility method used to create code paths based on package name and available index.
5425 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5426 String idxStr = "";
5427 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005428 // Fall back to default value of idx=1 if prefix is not
5429 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005430 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005431 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005432 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005433 if (subStr.endsWith(suffix)) {
5434 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005435 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005436 // If oldCodePath already contains prefix find out the
5437 // ending index to either increment or decrement.
5438 int sidx = subStr.lastIndexOf(prefix);
5439 if (sidx != -1) {
5440 subStr = subStr.substring(sidx + prefix.length());
5441 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005442 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5443 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005444 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005445 try {
5446 idx = Integer.parseInt(subStr);
5447 if (idx <= 1) {
5448 idx++;
5449 } else {
5450 idx--;
5451 }
5452 } catch(NumberFormatException e) {
5453 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005454 }
5455 }
5456 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005457 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005458 return prefix + idxStr;
5459 }
5460
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005461 // Utility method used to ignore ADD/REMOVE events
5462 // by directory observer.
5463 private static boolean ignoreCodePath(String fullPathStr) {
5464 String apkName = getApkName(fullPathStr);
5465 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5466 if (idx != -1 && ((idx+1) < apkName.length())) {
5467 // Make sure the package ends with a numeral
5468 String version = apkName.substring(idx+1);
5469 try {
5470 Integer.parseInt(version);
5471 return true;
5472 } catch (NumberFormatException e) {}
5473 }
5474 return false;
5475 }
5476
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005477 // Utility method that returns the relative package path with respect
5478 // to the installation directory. Like say for /data/data/com.test-1.apk
5479 // string com.test-1 is returned.
5480 static String getApkName(String codePath) {
5481 if (codePath == null) {
5482 return null;
5483 }
5484 int sidx = codePath.lastIndexOf("/");
5485 int eidx = codePath.lastIndexOf(".");
5486 if (eidx == -1) {
5487 eidx = codePath.length();
5488 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005489 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005490 return null;
5491 }
5492 return codePath.substring(sidx+1, eidx);
5493 }
5494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 class PackageInstalledInfo {
5496 String name;
5497 int uid;
5498 PackageParser.Package pkg;
5499 int returnCode;
5500 PackageRemovedInfo removedInfo;
5501 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005503 /*
5504 * Install a non-existing package.
5505 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005506 private void installNewPackageLI(PackageParser.Package pkg,
5507 int parseFlags,
5508 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005509 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005511 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005512
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005513 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 res.name = pkgName;
5515 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005516 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5517 // A package with the same name is already installed, though
5518 // it has been renamed to an older name. The package we
5519 // are trying to install should be installed as an update to
5520 // the existing one, but that has not been requested, so bail.
5521 Slog.w(TAG, "Attempt to re-install " + pkgName
5522 + " without first uninstalling package running as "
5523 + mSettings.mRenamedPackages.get(pkgName));
5524 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5525 return;
5526 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005527 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005529 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 + " without first uninstalling.");
5531 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5532 return;
5533 }
5534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005536 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5537 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005539 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5541 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5542 }
5543 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005544 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005545 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 res);
5547 // delete the partially installed application. the data directory will have to be
5548 // restored if it was already existing
5549 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5550 // remove package from internal structures. Note that we want deletePackageX to
5551 // delete the package data and cache directories that it created in
5552 // scanPackageLocked, unless those directories existed before we even tried to
5553 // install.
5554 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005555 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005557 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 }
5559 }
5560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005561
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005562 private void replacePackageLI(PackageParser.Package pkg,
5563 int parseFlags,
5564 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005565 String installerPackageName, PackageInstalledInfo res) {
5566
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005567 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005568 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 // First find the old package info and check signatures
5570 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005571 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005572 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005573 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5575 return;
5576 }
5577 }
Kenny Root85387d72010-08-26 10:13:11 -07005578 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005579 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005580 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005582 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 }
5584 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005587 PackageParser.Package pkg,
5588 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005589 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 PackageParser.Package newPackage = null;
5591 String pkgName = deletedPackage.packageName;
5592 boolean deletedPkg = true;
5593 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005594
Jacek Surazski65e13172009-04-28 15:26:38 +02005595 String oldInstallerPackageName = null;
5596 synchronized (mPackages) {
5597 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5598 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005599
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005600 long origUpdateTime;
5601 if (pkg.mExtras != null) {
5602 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5603 } else {
5604 origUpdateTime = 0;
5605 }
5606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005608 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005609 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005610 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5612 deletedPkg = false;
5613 } else {
5614 // Successfully deleted the old package. Now proceed with re-installation
5615 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005616 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5617 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005619 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5621 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005622 }
5623 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005624 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005625 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 res);
5627 updatedSettings = true;
5628 }
5629 }
5630
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005631 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 // remove package from internal structures. Note that we want deletePackageX to
5633 // delete the package data and cache directories that it created in
5634 // scanPackageLocked, unless those directories existed before we even tried to
5635 // install.
5636 if(updatedSettings) {
5637 deletePackageLI(
5638 pkgName, true,
5639 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005640 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 }
5642 // Since we failed to install the new package we need to restore the old
5643 // package that we deleted.
5644 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005645 File restoreFile = new File(deletedPackage.mPath);
5646 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005647 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005648 return;
5649 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005650 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005651 boolean oldOnSd = isExternal(deletedPackage);
5652 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5653 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5654 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005655 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5656 | SCAN_UPDATE_TIME;
5657 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5658 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005659 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5660 return;
5661 }
5662 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005663 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005664 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005665 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005666 mSettings.writeLP();
5667 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005668 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 }
5670 }
5671 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005674 PackageParser.Package pkg,
5675 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005676 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 PackageParser.Package newPackage = null;
5678 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005679 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 PackageParser.PARSE_IS_SYSTEM;
5681 String packageName = deletedPackage.packageName;
5682 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5683 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005684 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 return;
5686 }
5687 PackageParser.Package oldPkg;
5688 PackageSetting oldPkgSetting;
5689 synchronized (mPackages) {
5690 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005691 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5693 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005694 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 return;
5696 }
5697 }
5698 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5699 res.removedInfo.removedPackage = packageName;
5700 // Remove existing system package
5701 removePackageLI(oldPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702
5703 // Successfully disabled the old package. Now proceed with re-installation
5704 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5705 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005706 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005708 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5710 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5711 }
5712 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005713 if (newPackage.mExtras != null) {
5714 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5715 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5716 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5717 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005718 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 updatedSettings = true;
5720 }
5721
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005722 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 // Re installation failed. Restore old information
5724 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005725 if (newPackage != null) {
5726 removePackageLI(newPackage, true);
5727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005729 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 // Restore the old system information in Settings
5731 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005732 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005734 mSettings.setInstallerPackageName(packageName,
5735 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 }
5737 mSettings.writeLP();
5738 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005739 } else {
5740 // If this is an update to an existing update, setup
5741 // to remove the existing update.
5742 synchronized (mPackages) {
5743 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5744 if (ps != null && ps.codePathString != null &&
5745 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005746 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005747 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005748 }
5749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 }
5751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005752
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005753 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005754 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005755 int retCode;
5756 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5757 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5758 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005759 if (mNoDexOpt) {
5760 /*
5761 * If we're in an engineering build, programs are lazily run
5762 * through dexopt. If the .dex file doesn't exist yet, it
5763 * will be created when the program is run next.
5764 */
5765 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5766 } else {
5767 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5768 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5769 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005770 }
5771 }
5772 return PackageManager.INSTALL_SUCCEEDED;
5773 }
5774
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005775 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005776 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005777 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 synchronized (mPackages) {
5779 //write settings. the installStatus will be incomplete at this stage.
5780 //note that the new package setting would have already been
5781 //added to mPackages. It hasn't been persisted yet.
5782 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5783 mSettings.writeLP();
5784 }
5785
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005786 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005787 != PackageManager.INSTALL_SUCCEEDED) {
5788 // Discontinue if moving dex files failed.
5789 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005791 if((res.returnCode = setPermissionsLI(newPackage))
5792 != PackageManager.INSTALL_SUCCEEDED) {
5793 if (mInstaller != null) {
5794 mInstaller.rmdex(newPackage.mScanPath);
5795 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005796 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005798 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005801 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005802 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 res.name = pkgName;
5804 res.uid = newPackage.applicationInfo.uid;
5805 res.pkg = newPackage;
5806 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005807 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5809 //to update install status
5810 mSettings.writeLP();
5811 }
5812 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005813
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005814 private void installPackageLI(InstallArgs args,
5815 boolean newInstall, PackageInstalledInfo res) {
5816 int pFlags = args.flags;
5817 String installerPackageName = args.installerPackageName;
5818 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005819 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005820 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005821 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005822 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005823 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005824 // Result object to be returned
5825 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5826
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005827 // Retrieve PackageSettings and parse package
5828 int parseFlags = PackageParser.PARSE_CHATTY |
5829 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5830 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5831 parseFlags |= mDefParseFlags;
5832 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5833 pp.setSeparateProcesses(mSeparateProcesses);
5834 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5835 null, mMetrics, parseFlags);
5836 if (pkg == null) {
5837 res.returnCode = pp.getParseError();
5838 return;
5839 }
5840 String pkgName = res.name = pkg.packageName;
5841 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5842 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5843 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5844 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005846 }
5847 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5848 res.returnCode = pp.getParseError();
5849 return;
5850 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005851 // Get rid of all references to package scan path via parser.
5852 pp = null;
5853 String oldCodePath = null;
5854 boolean systemApp = false;
5855 synchronized (mPackages) {
5856 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005857 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5858 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005859 if (pkg.mOriginalPackages != null
5860 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005861 && mPackages.containsKey(oldName)) {
5862 // This package is derived from an original package,
5863 // and this device has been updating from that original
5864 // name. We must continue using the original name, so
5865 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005866 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005867 pkgName = pkg.packageName;
5868 replace = true;
5869 } else if (mPackages.containsKey(pkgName)) {
5870 // This package, under its official name, already exists
5871 // on the device; we should replace it.
5872 replace = true;
5873 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005874 }
5875 PackageSetting ps = mSettings.mPackages.get(pkgName);
5876 if (ps != null) {
5877 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5878 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5879 systemApp = (ps.pkg.applicationInfo.flags &
5880 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005881 }
5882 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005883 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005884
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005885 if (systemApp && onSd) {
5886 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005887 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005888 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5889 return;
5890 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005891
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005892 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5893 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5894 return;
5895 }
5896 // Set application objects path explicitly after the rename
5897 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005898 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005899 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005900 replacePackageLI(pkg, parseFlags, scanMode,
5901 installerPackageName, res);
5902 } else {
5903 installNewPackageLI(pkg, parseFlags, scanMode,
5904 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 }
5906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005907
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005908 private int setPermissionsLI(PackageParser.Package newPackage) {
5909 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005910 int retCode = 0;
5911 // TODO Gross hack but fix later. Ideally move this to be a post installation
5912 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005913 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005914 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005915 try {
5916 extractPublicFiles(newPackage, destResourceFile);
5917 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005918 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 -08005919 " forward-locked app.");
5920 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5921 } finally {
5922 //TODO clean up the extracted public files
5923 }
5924 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005925 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926 newPackage.applicationInfo.uid);
5927 } else {
5928 final int filePermissions =
5929 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005930 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 newPackage.applicationInfo.uid);
5932 }
5933 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005934 // The permissions on the resource file was set when it was copied for
5935 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005936 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005939 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005940 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005941 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005942 // TODO Define new internal error
5943 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005944 }
5945 return PackageManager.INSTALL_SUCCEEDED;
5946 }
5947
Kenny Root85387d72010-08-26 10:13:11 -07005948 private static boolean isForwardLocked(PackageParser.Package pkg) {
5949 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 }
5951
Kenny Root85387d72010-08-26 10:13:11 -07005952 private static boolean isExternal(PackageParser.Package pkg) {
5953 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5954 }
5955
5956 private static boolean isSystemApp(PackageParser.Package pkg) {
5957 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5958 }
5959
5960 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5961 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005962 }
5963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005964 private void extractPublicFiles(PackageParser.Package newPackage,
5965 File publicZipFile) throws IOException {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07005966 final FileOutputStream fstr = new FileOutputStream(publicZipFile);
5967 final ZipOutputStream publicZipOutStream = new ZipOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5969
5970 // Copy manifest, resources.arsc and res directory to public zip
5971
5972 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5973 while (privateZipEntries.hasMoreElements()) {
5974 final ZipEntry zipEntry = privateZipEntries.nextElement();
5975 final String zipEntryName = zipEntry.getName();
5976 if ("AndroidManifest.xml".equals(zipEntryName)
5977 || "resources.arsc".equals(zipEntryName)
5978 || zipEntryName.startsWith("res/")) {
5979 try {
5980 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5981 } catch (IOException e) {
5982 try {
5983 publicZipOutStream.close();
5984 throw e;
5985 } finally {
5986 publicZipFile.delete();
5987 }
5988 }
5989 }
5990 }
5991
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07005992 publicZipOutStream.finish();
5993 publicZipOutStream.flush();
5994 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 publicZipOutStream.close();
5996 FileUtils.setPermissions(
5997 publicZipFile.getAbsolutePath(),
5998 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5999 -1, -1);
6000 }
6001
6002 private static void copyZipEntry(ZipEntry zipEntry,
6003 ZipFile inZipFile,
6004 ZipOutputStream outZipStream) throws IOException {
6005 byte[] buffer = new byte[4096];
6006 int num;
6007
6008 ZipEntry newEntry;
6009 if (zipEntry.getMethod() == ZipEntry.STORED) {
6010 // Preserve the STORED method of the input entry.
6011 newEntry = new ZipEntry(zipEntry);
6012 } else {
6013 // Create a new entry so that the compressed len is recomputed.
6014 newEntry = new ZipEntry(zipEntry.getName());
6015 }
6016 outZipStream.putNextEntry(newEntry);
6017
6018 InputStream data = inZipFile.getInputStream(zipEntry);
6019 while ((num = data.read(buffer)) > 0) {
6020 outZipStream.write(buffer, 0, num);
6021 }
6022 outZipStream.flush();
6023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 private void deleteTempPackageFiles() {
6026 FilenameFilter filter = new FilenameFilter() {
6027 public boolean accept(File dir, String name) {
6028 return name.startsWith("vmdl") && name.endsWith(".tmp");
6029 }
6030 };
6031 String tmpFilesList[] = mAppInstallDir.list(filter);
6032 if(tmpFilesList == null) {
6033 return;
6034 }
6035 for(int i = 0; i < tmpFilesList.length; i++) {
6036 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6037 tmpFile.delete();
6038 }
6039 }
6040
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006041 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 File tmpPackageFile;
6043 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006044 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006046 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 return null;
6048 }
6049 try {
6050 FileUtils.setPermissions(
6051 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6052 -1, -1);
6053 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006054 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 return null;
6056 }
6057 return tmpPackageFile;
6058 }
6059
6060 public void deletePackage(final String packageName,
6061 final IPackageDeleteObserver observer,
6062 final int flags) {
6063 mContext.enforceCallingOrSelfPermission(
6064 android.Manifest.permission.DELETE_PACKAGES, null);
6065 // Queue up an async operation since the package deletion may take a little while.
6066 mHandler.post(new Runnable() {
6067 public void run() {
6068 mHandler.removeCallbacks(this);
6069 final boolean succeded = deletePackageX(packageName, true, true, flags);
6070 if (observer != null) {
6071 try {
6072 observer.packageDeleted(succeded);
6073 } catch (RemoteException e) {
6074 Log.i(TAG, "Observer no longer exists.");
6075 } //end catch
6076 } //end if
6077 } //end run
6078 });
6079 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 /**
6082 * This method is an internal method that could be get invoked either
6083 * to delete an installed package or to clean up a failed installation.
6084 * After deleting an installed package, a broadcast is sent to notify any
6085 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006086 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 * installation wouldn't have sent the initial broadcast either
6088 * The key steps in deleting a package are
6089 * deleting the package information in internal structures like mPackages,
6090 * deleting the packages base directories through installd
6091 * updating mSettings to reflect current status
6092 * persisting settings for later use
6093 * sending a broadcast if necessary
6094 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6096 boolean deleteCodeAndResources, int flags) {
6097 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006098 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006100 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6101 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6102 try {
6103 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006104 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006105 return false;
6106 }
6107 } catch (RemoteException e) {
6108 }
6109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006111 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006112 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006116 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006117 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006118
6119 // If the removed package was a system update, the old system packaged
6120 // was re-enabled; we need to broadcast this information
6121 if (systemUpdate) {
6122 Bundle extras = new Bundle(1);
6123 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6124 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6125
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006126 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6127 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006130 // Force a gc here.
6131 Runtime.getRuntime().gc();
6132 // Delete the resources here after sending the broadcast to let
6133 // other processes clean up before deleting resources.
6134 if (info.args != null) {
6135 synchronized (mInstallLock) {
6136 info.args.doPostDeleteLI(deleteCodeAndResources);
6137 }
6138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 return res;
6140 }
6141
6142 static class PackageRemovedInfo {
6143 String removedPackage;
6144 int uid = -1;
6145 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006146 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006147 // Clean up resources deleted packages.
6148 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006149
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006150 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 Bundle extras = new Bundle(1);
6152 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6153 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6154 if (replacing) {
6155 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6156 }
6157 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006158 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006159 }
6160 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006161 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 }
6163 }
6164 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 /*
6167 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6168 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006169 * 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 -08006170 * delete a partially installed application.
6171 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006172 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006173 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006175 if (outInfo != null) {
6176 outInfo.removedPackage = packageName;
6177 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006178 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 // Retrieve object to delete permissions for shared user later on
6180 PackageSetting deletedPs;
6181 synchronized (mPackages) {
6182 deletedPs = mSettings.mPackages.get(packageName);
6183 }
6184 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006185 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006187 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006189 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 + packageName + ", retcode=" + retCode);
6191 // we don't consider this to be a failure of the core package deletion
6192 }
6193 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006194 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 PackageParser.Package pkg = mPackages.get(packageName);
6196 File dataDir = new File(pkg.applicationInfo.dataDir);
6197 dataDir.delete();
6198 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006199 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 }
6201 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006202 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006203 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6204 if (outInfo != null) {
6205 outInfo.removedUid = mSettings.removePackageLP(packageName);
6206 }
6207 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006208 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006209 if (deletedPs.sharedUser != null) {
6210 // remove permissions associated with package
6211 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6212 }
6213 }
6214 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006215 // remove from preferred activities.
6216 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6217 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6218 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6219 removed.add(pa);
6220 }
6221 }
6222 for (PreferredActivity pa : removed) {
6223 mSettings.mPreferredActivities.removeFilter(pa);
6224 }
6225 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006226 if (writeSettings) {
6227 // Save settings now
6228 mSettings.writeLP();
6229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 }
6231 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 /*
6234 * Tries to delete system package.
6235 */
6236 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006237 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 ApplicationInfo applicationInfo = p.applicationInfo;
6239 //applicable for non-partially installed applications only
6240 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006241 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 return false;
6243 }
6244 PackageSetting ps = null;
6245 // Confirm if the system package has been updated
6246 // An updated system app can be deleted. This will also have to restore
6247 // the system pkg from system partition
6248 synchronized (mPackages) {
6249 ps = mSettings.getDisabledSystemPkg(p.packageName);
6250 }
6251 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006252 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 return false;
6254 } else {
6255 Log.i(TAG, "Deleting system pkg from data partition");
6256 }
6257 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006258 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006259 final boolean deleteCodeAndResources;
6260 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006261 // Delete code and resources for downgrades
6262 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006263 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006264 } else {
6265 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006266 deleteCodeAndResources = false;
6267 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006268 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006269 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6270 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 if (!ret) {
6272 return false;
6273 }
6274 synchronized (mPackages) {
6275 // Reinstate the old system package
6276 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006277 // Remove any native libraries from the upgraded package.
6278 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 }
6280 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006281 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006283 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006286 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006287 return false;
6288 }
6289 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006290 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006291 if (writeSettings) {
6292 mSettings.writeLP();
6293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 }
6295 return true;
6296 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006299 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6300 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301 ApplicationInfo applicationInfo = p.applicationInfo;
6302 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006303 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 return false;
6305 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006306 if (outInfo != null) {
6307 outInfo.uid = applicationInfo.uid;
6308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309
6310 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006311 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312
6313 // Delete application code and resources
6314 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006315 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006316 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6317 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6318 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6319 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 }
6321 return true;
6322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 /*
6325 * This method handles package deletion in general
6326 */
6327 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006328 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6329 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006331 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 return false;
6333 }
6334 PackageParser.Package p;
6335 boolean dataOnly = false;
6336 synchronized (mPackages) {
6337 p = mPackages.get(packageName);
6338 if (p == null) {
6339 //this retrieves partially installed apps
6340 dataOnly = true;
6341 PackageSetting ps = mSettings.mPackages.get(packageName);
6342 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006343 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 return false;
6345 }
6346 p = ps.pkg;
6347 }
6348 }
6349 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006350 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 return false;
6352 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 if (dataOnly) {
6355 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006356 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 return true;
6358 }
6359 // At this point the package should have ApplicationInfo associated with it
6360 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006361 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 return false;
6363 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006364 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006365 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 Log.i(TAG, "Removing system package:"+p.packageName);
6367 // When an updated system application is deleted we delete the existing resources as well and
6368 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006369 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006370 } else {
6371 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006372 // Kill application pre-emptively especially for apps on sd.
6373 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006374 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6375 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006377 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 public void clearApplicationUserData(final String packageName,
6381 final IPackageDataObserver observer) {
6382 mContext.enforceCallingOrSelfPermission(
6383 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6384 // Queue up an async operation since the package deletion may take a little while.
6385 mHandler.post(new Runnable() {
6386 public void run() {
6387 mHandler.removeCallbacks(this);
6388 final boolean succeeded;
6389 synchronized (mInstallLock) {
6390 succeeded = clearApplicationUserDataLI(packageName);
6391 }
6392 if (succeeded) {
6393 // invoke DeviceStorageMonitor's update method to clear any notifications
6394 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6395 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6396 if (dsm != null) {
6397 dsm.updateMemory();
6398 }
6399 }
6400 if(observer != null) {
6401 try {
6402 observer.onRemoveCompleted(packageName, succeeded);
6403 } catch (RemoteException e) {
6404 Log.i(TAG, "Observer no longer exists.");
6405 }
6406 } //end if observer
6407 } //end run
6408 });
6409 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 private boolean clearApplicationUserDataLI(String packageName) {
6412 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006413 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 return false;
6415 }
6416 PackageParser.Package p;
6417 boolean dataOnly = false;
6418 synchronized (mPackages) {
6419 p = mPackages.get(packageName);
6420 if(p == null) {
6421 dataOnly = true;
6422 PackageSetting ps = mSettings.mPackages.get(packageName);
6423 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006424 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 return false;
6426 }
6427 p = ps.pkg;
6428 }
6429 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006430 boolean useEncryptedFSDir = false;
6431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006432 if(!dataOnly) {
6433 //need to check this only for fully installed applications
6434 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006435 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 return false;
6437 }
6438 final ApplicationInfo applicationInfo = p.applicationInfo;
6439 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006440 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 return false;
6442 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006443 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 }
6445 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006446 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006448 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 + packageName);
6450 return false;
6451 }
6452 }
6453 return true;
6454 }
6455
6456 public void deleteApplicationCacheFiles(final String packageName,
6457 final IPackageDataObserver observer) {
6458 mContext.enforceCallingOrSelfPermission(
6459 android.Manifest.permission.DELETE_CACHE_FILES, null);
6460 // Queue up an async operation since the package deletion may take a little while.
6461 mHandler.post(new Runnable() {
6462 public void run() {
6463 mHandler.removeCallbacks(this);
6464 final boolean succeded;
6465 synchronized (mInstallLock) {
6466 succeded = deleteApplicationCacheFilesLI(packageName);
6467 }
6468 if(observer != null) {
6469 try {
6470 observer.onRemoveCompleted(packageName, succeded);
6471 } catch (RemoteException e) {
6472 Log.i(TAG, "Observer no longer exists.");
6473 }
6474 } //end if observer
6475 } //end run
6476 });
6477 }
6478
6479 private boolean deleteApplicationCacheFilesLI(String packageName) {
6480 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006481 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 return false;
6483 }
6484 PackageParser.Package p;
6485 synchronized (mPackages) {
6486 p = mPackages.get(packageName);
6487 }
6488 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006489 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 return false;
6491 }
6492 final ApplicationInfo applicationInfo = p.applicationInfo;
6493 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006494 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 return false;
6496 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006497 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006499 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006501 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 + packageName);
6503 return false;
6504 }
6505 }
6506 return true;
6507 }
6508
6509 public void getPackageSizeInfo(final String packageName,
6510 final IPackageStatsObserver observer) {
6511 mContext.enforceCallingOrSelfPermission(
6512 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6513 // Queue up an async operation since the package deletion may take a little while.
6514 mHandler.post(new Runnable() {
6515 public void run() {
6516 mHandler.removeCallbacks(this);
6517 PackageStats lStats = new PackageStats(packageName);
6518 final boolean succeded;
6519 synchronized (mInstallLock) {
6520 succeded = getPackageSizeInfoLI(packageName, lStats);
6521 }
6522 if(observer != null) {
6523 try {
6524 observer.onGetStatsCompleted(lStats, succeded);
6525 } catch (RemoteException e) {
6526 Log.i(TAG, "Observer no longer exists.");
6527 }
6528 } //end if observer
6529 } //end run
6530 });
6531 }
6532
6533 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6534 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006535 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 return false;
6537 }
6538 PackageParser.Package p;
6539 boolean dataOnly = false;
6540 synchronized (mPackages) {
6541 p = mPackages.get(packageName);
6542 if(p == null) {
6543 dataOnly = true;
6544 PackageSetting ps = mSettings.mPackages.get(packageName);
6545 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006546 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006547 return false;
6548 }
6549 p = ps.pkg;
6550 }
6551 }
6552 String publicSrcDir = null;
6553 if(!dataOnly) {
6554 final ApplicationInfo applicationInfo = p.applicationInfo;
6555 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006556 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 return false;
6558 }
6559 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6560 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006561 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006562 if (mInstaller != null) {
6563 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006564 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 if (res < 0) {
6566 return false;
6567 } else {
6568 return true;
6569 }
6570 }
6571 return true;
6572 }
6573
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006576 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 }
6578
6579 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006580 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 }
6582
6583 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006584 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 }
6586
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006587 int getUidTargetSdkVersionLockedLP(int uid) {
6588 Object obj = mSettings.getUserIdLP(uid);
6589 if (obj instanceof SharedUserSetting) {
6590 SharedUserSetting sus = (SharedUserSetting)obj;
6591 final int N = sus.packages.size();
6592 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6593 Iterator<PackageSetting> it = sus.packages.iterator();
6594 int i=0;
6595 while (it.hasNext()) {
6596 PackageSetting ps = it.next();
6597 if (ps.pkg != null) {
6598 int v = ps.pkg.applicationInfo.targetSdkVersion;
6599 if (v < vers) vers = v;
6600 }
6601 }
6602 return vers;
6603 } else if (obj instanceof PackageSetting) {
6604 PackageSetting ps = (PackageSetting)obj;
6605 if (ps.pkg != null) {
6606 return ps.pkg.applicationInfo.targetSdkVersion;
6607 }
6608 }
6609 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6610 }
6611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 public void addPreferredActivity(IntentFilter filter, int match,
6613 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006615 if (mContext.checkCallingOrSelfPermission(
6616 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6617 != PackageManager.PERMISSION_GRANTED) {
6618 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6619 < Build.VERSION_CODES.FROYO) {
6620 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6621 + Binder.getCallingUid());
6622 return;
6623 }
6624 mContext.enforceCallingOrSelfPermission(
6625 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6626 }
6627
6628 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6630 mSettings.mPreferredActivities.addFilter(
6631 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006632 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 }
6634 }
6635
Satish Sampath8dbe6122009-06-02 23:35:54 +01006636 public void replacePreferredActivity(IntentFilter filter, int match,
6637 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006638 if (filter.countActions() != 1) {
6639 throw new IllegalArgumentException(
6640 "replacePreferredActivity expects filter to have only 1 action.");
6641 }
6642 if (filter.countCategories() != 1) {
6643 throw new IllegalArgumentException(
6644 "replacePreferredActivity expects filter to have only 1 category.");
6645 }
6646 if (filter.countDataAuthorities() != 0
6647 || filter.countDataPaths() != 0
6648 || filter.countDataSchemes() != 0
6649 || filter.countDataTypes() != 0) {
6650 throw new IllegalArgumentException(
6651 "replacePreferredActivity expects filter to have no data authorities, " +
6652 "paths, schemes or types.");
6653 }
6654 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006655 if (mContext.checkCallingOrSelfPermission(
6656 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6657 != PackageManager.PERMISSION_GRANTED) {
6658 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6659 < Build.VERSION_CODES.FROYO) {
6660 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6661 + Binder.getCallingUid());
6662 return;
6663 }
6664 mContext.enforceCallingOrSelfPermission(
6665 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6666 }
6667
Satish Sampath8dbe6122009-06-02 23:35:54 +01006668 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6669 String action = filter.getAction(0);
6670 String category = filter.getCategory(0);
6671 while (it.hasNext()) {
6672 PreferredActivity pa = it.next();
6673 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6674 it.remove();
6675 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6676 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6677 }
6678 }
6679 addPreferredActivity(filter, match, set, activity);
6680 }
6681 }
6682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006684 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006685 int uid = Binder.getCallingUid();
6686 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006687 if (pkg == null || pkg.applicationInfo.uid != uid) {
6688 if (mContext.checkCallingOrSelfPermission(
6689 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6690 != PackageManager.PERMISSION_GRANTED) {
6691 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6692 < Build.VERSION_CODES.FROYO) {
6693 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6694 + Binder.getCallingUid());
6695 return;
6696 }
6697 mContext.enforceCallingOrSelfPermission(
6698 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6699 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006700 }
6701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006703 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 }
6705 }
6706 }
6707
6708 boolean clearPackagePreferredActivitiesLP(String packageName) {
6709 boolean changed = false;
6710 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6711 while (it.hasNext()) {
6712 PreferredActivity pa = it.next();
6713 if (pa.mActivity.getPackageName().equals(packageName)) {
6714 it.remove();
6715 changed = true;
6716 }
6717 }
6718 return changed;
6719 }
6720
6721 public int getPreferredActivities(List<IntentFilter> outFilters,
6722 List<ComponentName> outActivities, String packageName) {
6723
6724 int num = 0;
6725 synchronized (mPackages) {
6726 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6727 while (it.hasNext()) {
6728 PreferredActivity pa = it.next();
6729 if (packageName == null
6730 || pa.mActivity.getPackageName().equals(packageName)) {
6731 if (outFilters != null) {
6732 outFilters.add(new IntentFilter(pa));
6733 }
6734 if (outActivities != null) {
6735 outActivities.add(pa.mActivity);
6736 }
6737 }
6738 }
6739 }
6740
6741 return num;
6742 }
6743
6744 public void setApplicationEnabledSetting(String appPackageName,
6745 int newState, int flags) {
6746 setEnabledSetting(appPackageName, null, newState, flags);
6747 }
6748
6749 public void setComponentEnabledSetting(ComponentName componentName,
6750 int newState, int flags) {
6751 setEnabledSetting(componentName.getPackageName(),
6752 componentName.getClassName(), newState, flags);
6753 }
6754
6755 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006756 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6758 || newState == COMPONENT_ENABLED_STATE_ENABLED
6759 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6760 throw new IllegalArgumentException("Invalid new component state: "
6761 + newState);
6762 }
6763 PackageSetting pkgSetting;
6764 final int uid = Binder.getCallingUid();
6765 final int permission = mContext.checkCallingPermission(
6766 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6767 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006768 boolean sendNow = false;
6769 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006770 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006772 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006774 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006776 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006778 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 }
6780 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006781 "Unknown component: " + packageName
6782 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 }
6784 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6785 throw new SecurityException(
6786 "Permission Denial: attempt to change component state from pid="
6787 + Binder.getCallingPid()
6788 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6789 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006790 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006791 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006792 if (pkgSetting.enabled == newState) {
6793 // Nothing to do
6794 return;
6795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006797 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006798 } else {
6799 // We're dealing with a component level state change
6800 switch (newState) {
6801 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006802 if (!pkgSetting.enableComponentLP(className)) {
6803 return;
6804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 break;
6806 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006807 if (!pkgSetting.disableComponentLP(className)) {
6808 return;
6809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006810 break;
6811 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006812 if (!pkgSetting.restoreComponentLP(className)) {
6813 return;
6814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 break;
6816 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006817 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006818 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006819 }
6820 }
6821 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006822 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006823 components = mPendingBroadcasts.get(packageName);
6824 boolean newPackage = components == null;
6825 if (newPackage) {
6826 components = new ArrayList<String>();
6827 }
6828 if (!components.contains(componentName)) {
6829 components.add(componentName);
6830 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006831 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6832 sendNow = true;
6833 // Purge entry from pending broadcast list if another one exists already
6834 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006835 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006836 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006837 if (newPackage) {
6838 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006839 }
6840 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6841 // Schedule a message
6842 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6843 }
6844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 long callingId = Binder.clearCallingIdentity();
6848 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006849 if (sendNow) {
6850 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006851 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006853 } finally {
6854 Binder.restoreCallingIdentity(callingId);
6855 }
6856 }
6857
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006858 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006859 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6860 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6861 + " components=" + componentNames);
6862 Bundle extras = new Bundle(4);
6863 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6864 String nameList[] = new String[componentNames.size()];
6865 componentNames.toArray(nameList);
6866 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006867 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6868 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006869 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006870 }
6871
Jacek Surazski65e13172009-04-28 15:26:38 +02006872 public String getInstallerPackageName(String packageName) {
6873 synchronized (mPackages) {
6874 PackageSetting pkg = mSettings.mPackages.get(packageName);
6875 if (pkg == null) {
6876 throw new IllegalArgumentException("Unknown package: " + packageName);
6877 }
6878 return pkg.installerPackageName;
6879 }
6880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 public int getApplicationEnabledSetting(String appPackageName) {
6883 synchronized (mPackages) {
6884 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6885 if (pkg == null) {
6886 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6887 }
6888 return pkg.enabled;
6889 }
6890 }
6891
6892 public int getComponentEnabledSetting(ComponentName componentName) {
6893 synchronized (mPackages) {
6894 final String packageNameStr = componentName.getPackageName();
6895 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6896 if (pkg == null) {
6897 throw new IllegalArgumentException("Unknown component: " + componentName);
6898 }
6899 final String classNameStr = componentName.getClassName();
6900 return pkg.currentEnabledStateLP(classNameStr);
6901 }
6902 }
6903
6904 public void enterSafeMode() {
6905 if (!mSystemReady) {
6906 mSafeMode = true;
6907 }
6908 }
6909
6910 public void systemReady() {
6911 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006912
6913 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006914 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006915 mContext.getContentResolver(),
6916 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006917 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006918 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006919 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006921 }
6922
6923 public boolean isSafeMode() {
6924 return mSafeMode;
6925 }
6926
6927 public boolean hasSystemUidErrors() {
6928 return mHasSystemUidErrors;
6929 }
6930
6931 static String arrayToString(int[] array) {
6932 StringBuffer buf = new StringBuffer(128);
6933 buf.append('[');
6934 if (array != null) {
6935 for (int i=0; i<array.length; i++) {
6936 if (i > 0) buf.append(", ");
6937 buf.append(array[i]);
6938 }
6939 }
6940 buf.append(']');
6941 return buf.toString();
6942 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 @Override
6945 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6946 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6947 != PackageManager.PERMISSION_GRANTED) {
6948 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6949 + Binder.getCallingPid()
6950 + ", uid=" + Binder.getCallingUid()
6951 + " without permission "
6952 + android.Manifest.permission.DUMP);
6953 return;
6954 }
6955
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006956 boolean dumpStar = true;
6957 boolean dumpLibs = false;
6958 boolean dumpFeatures = false;
6959 boolean dumpResolvers = false;
6960 boolean dumpPermissions = false;
6961 boolean dumpPackages = false;
6962 boolean dumpSharedUsers = false;
6963 boolean dumpMessages = false;
6964 boolean dumpProviders = false;
6965
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006966 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006967 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006968
6969 int opti = 0;
6970 while (opti < args.length) {
6971 String opt = args[opti];
6972 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6973 break;
6974 }
6975 opti++;
6976 if ("-a".equals(opt)) {
6977 // Right now we only know how to print all.
6978 } else if ("-h".equals(opt)) {
6979 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006980 pw.println(" [-h] [-f] [cmd] ...");
6981 pw.println(" -f: print details of intent filters");
6982 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006983 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006984 pw.println(" l[ibraries]: list known shared libraries");
6985 pw.println(" f[ibraries]: list device features");
6986 pw.println(" r[esolvers]: dump intent resolvers");
6987 pw.println(" perm[issions]: dump permissions");
6988 pw.println(" prov[iders]: dump content providers");
6989 pw.println(" p[ackages]: dump installed packages");
6990 pw.println(" s[hared-users]: dump shared user IDs");
6991 pw.println(" m[essages]: print collected runtime messages");
6992 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006993 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006994 } else if ("-f".equals(opt)) {
6995 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006996 } else {
6997 pw.println("Unknown argument: " + opt + "; use -h for help");
6998 }
6999 }
7000
7001 // Is the caller requesting to dump a particular piece of data?
7002 if (opti < args.length) {
7003 String cmd = args[opti];
7004 opti++;
7005 // Is this a package name?
7006 if ("android".equals(cmd) || cmd.contains(".")) {
7007 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007008 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
7009 dumpStar = false;
7010 dumpLibs = true;
7011 } else if ("f".equals(cmd) || "features".equals(cmd)) {
7012 dumpStar = false;
7013 dumpFeatures = true;
7014 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
7015 dumpStar = false;
7016 dumpResolvers = true;
7017 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
7018 dumpStar = false;
7019 dumpPermissions = true;
7020 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
7021 dumpStar = false;
7022 dumpPackages = true;
7023 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
7024 dumpStar = false;
7025 dumpSharedUsers = true;
7026 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
7027 dumpStar = false;
7028 dumpProviders = true;
7029 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
7030 dumpStar = false;
7031 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007032 }
7033 }
7034
7035 boolean printedTitle = false;
7036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007038 if ((dumpStar || dumpLibs) && packageName == null) {
7039 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007040 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007041 pw.println("Libraries:");
7042 Iterator<String> it = mSharedLibraries.keySet().iterator();
7043 while (it.hasNext()) {
7044 String name = it.next();
7045 pw.print(" ");
7046 pw.print(name);
7047 pw.print(" -> ");
7048 pw.println(mSharedLibraries.get(name));
7049 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007050 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007051
7052 if ((dumpStar || dumpFeatures) && packageName == null) {
7053 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007054 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007055 pw.println("Features:");
7056 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7057 while (it.hasNext()) {
7058 String name = it.next();
7059 pw.print(" ");
7060 pw.println(name);
7061 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007062 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007063
7064 if (dumpStar || dumpResolvers) {
7065 if (mActivities.dump(pw, printedTitle
7066 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7067 " ", packageName, showFilters)) {
7068 printedTitle = true;
7069 }
7070 if (mReceivers.dump(pw, printedTitle
7071 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7072 " ", packageName, showFilters)) {
7073 printedTitle = true;
7074 }
7075 if (mServices.dump(pw, printedTitle
7076 ? "\nService Resolver Table:" : "Service Resolver Table:",
7077 " ", packageName, showFilters)) {
7078 printedTitle = true;
7079 }
7080 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7081 ? "\nPreferred Activities:" : "Preferred Activities:",
7082 " ", packageName, showFilters)) {
7083 printedTitle = true;
7084 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007085 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007086
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007087 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007088 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007089 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007090 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7091 continue;
7092 }
7093 if (!printedSomething) {
7094 if (printedTitle) pw.println(" ");
7095 pw.println("Permissions:");
7096 printedSomething = true;
7097 printedTitle = true;
7098 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007099 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7100 pw.print(Integer.toHexString(System.identityHashCode(p)));
7101 pw.println("):");
7102 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7103 pw.print(" uid="); pw.print(p.uid);
7104 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007105 pw.print(" type="); pw.print(p.type);
7106 pw.print(" prot="); pw.println(p.protectionLevel);
7107 if (p.packageSetting != null) {
7108 pw.print(" packageSetting="); pw.println(p.packageSetting);
7109 }
7110 if (p.perm != null) {
7111 pw.print(" perm="); pw.println(p.perm);
7112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007113 }
7114 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007115
7116 if (dumpStar || dumpProviders) {
7117 printedSomething = false;
7118 for (PackageParser.Provider p : mProviders.values()) {
7119 if (packageName != null && !packageName.equals(p.info.packageName)) {
7120 continue;
7121 }
7122 if (!printedSomething) {
7123 if (printedTitle) pw.println(" ");
7124 pw.println("Registered ContentProviders:");
7125 printedSomething = true;
7126 printedTitle = true;
7127 }
7128 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7129 pw.println(p.toString());
7130 }
7131 }
7132
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007133 printedSomething = false;
7134 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007135 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007136 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7137 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007138 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007139 if (packageName != null && !packageName.equals(ps.realName)
7140 && !packageName.equals(ps.name)) {
7141 continue;
7142 }
7143 if (!printedSomething) {
7144 if (printedTitle) pw.println(" ");
7145 pw.println("Packages:");
7146 printedSomething = true;
7147 printedTitle = true;
7148 }
7149 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007150 pw.print(" Package [");
7151 pw.print(ps.realName != null ? ps.realName : ps.name);
7152 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007153 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7154 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007155 if (ps.realName != null) {
7156 pw.print(" compat name="); pw.println(ps.name);
7157 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007158 pw.print(" userId="); pw.print(ps.userId);
7159 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7160 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7161 pw.print(" pkg="); pw.println(ps.pkg);
7162 pw.print(" codePath="); pw.println(ps.codePathString);
7163 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007164 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007165 pw.print(" obbPath="); pw.println(ps.obbPathString);
Kenny Root70fc04c2010-10-22 10:07:11 -07007166 pw.print(" versionCode="); pw.println(ps.versionCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007167 if (ps.pkg != null) {
Kenny Root70fc04c2010-10-22 10:07:11 -07007168 pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007169 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007170 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007171 if (ps.pkg.mOperationPending) {
7172 pw.println(" mOperationPending=true");
7173 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007174 pw.print(" supportsScreens=[");
7175 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007176 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007177 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7178 if (!first) pw.print(", ");
7179 first = false;
7180 pw.print("small");
7181 }
7182 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007183 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007184 if (!first) pw.print(", ");
7185 first = false;
7186 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007187 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007188 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007189 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007190 if (!first) pw.print(", ");
7191 first = false;
7192 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007193 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007194 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007195 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007196 if (!first) pw.print(", ");
7197 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007198 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007200 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007201 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007202 if (!first) pw.print(", ");
7203 first = false;
7204 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007205 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007206 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007207 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7208 if (!first) pw.print(", ");
7209 first = false;
7210 pw.print("anyDensity");
7211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007213 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007214 pw.print(" timeStamp=");
7215 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7216 pw.print(" firstInstallTime=");
7217 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7218 pw.print(" lastUpdateTime=");
7219 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007220 pw.print(" signatures="); pw.println(ps.signatures);
7221 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007222 pw.print(" haveGids="); pw.println(ps.haveGids);
7223 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007224 pw.print(" installStatus="); pw.print(ps.installStatus);
7225 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007226 if (ps.disabledComponents.size() > 0) {
7227 pw.println(" disabledComponents:");
7228 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007229 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007230 }
7231 }
7232 if (ps.enabledComponents.size() > 0) {
7233 pw.println(" enabledComponents:");
7234 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007235 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007236 }
7237 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007238 if (ps.grantedPermissions.size() > 0) {
7239 pw.println(" grantedPermissions:");
7240 for (String s : ps.grantedPermissions) {
7241 pw.print(" "); pw.println(s);
7242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007244 }
7245 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007246 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007247 if (dumpStar || dumpPackages) {
7248 if (mSettings.mRenamedPackages.size() > 0) {
7249 for (HashMap.Entry<String, String> e
7250 : mSettings.mRenamedPackages.entrySet()) {
7251 if (packageName != null && !packageName.equals(e.getKey())
7252 && !packageName.equals(e.getValue())) {
7253 continue;
7254 }
7255 if (!printedSomething) {
7256 if (printedTitle) pw.println(" ");
7257 pw.println("Renamed packages:");
7258 printedSomething = true;
7259 printedTitle = true;
7260 }
7261 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7262 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007263 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007264 }
7265 printedSomething = false;
7266 if (mSettings.mDisabledSysPackages.size() > 0) {
7267 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7268 if (packageName != null && !packageName.equals(ps.realName)
7269 && !packageName.equals(ps.name)) {
7270 continue;
7271 }
7272 if (!printedSomething) {
7273 if (printedTitle) pw.println(" ");
7274 pw.println("Hidden system packages:");
7275 printedSomething = true;
7276 printedTitle = true;
7277 }
7278 pw.print(" Package [");
7279 pw.print(ps.realName != null ? ps.realName : ps.name);
7280 pw.print("] (");
7281 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7282 pw.println("):");
7283 if (ps.realName != null) {
7284 pw.print(" compat name="); pw.println(ps.name);
7285 }
7286 pw.print(" userId="); pw.println(ps.userId);
7287 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7288 pw.print(" codePath="); pw.println(ps.codePathString);
7289 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007290 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007291 }
7292 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007293 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007294 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007296 if (packageName != null && su != packageSharedUser) {
7297 continue;
7298 }
7299 if (!printedSomething) {
7300 if (printedTitle) pw.println(" ");
7301 pw.println("Shared users:");
7302 printedSomething = true;
7303 printedTitle = true;
7304 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007305 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7306 pw.print(Integer.toHexString(System.identityHashCode(su)));
7307 pw.println("):");
7308 pw.print(" userId="); pw.print(su.userId);
7309 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 pw.println(" grantedPermissions:");
7311 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007312 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 }
7315 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007316
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007317 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007318 if (printedTitle) pw.println(" ");
7319 printedTitle = true;
7320 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007321 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007322
7323 pw.println(" ");
7324 pw.println("Package warning messages:");
7325 File fname = getSettingsProblemFile();
7326 FileInputStream in;
7327 try {
7328 in = new FileInputStream(fname);
7329 int avail = in.available();
7330 byte[] data = new byte[avail];
7331 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007332 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007333 } catch (FileNotFoundException e) {
7334 } catch (IOException e) {
7335 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 }
7338 }
7339
7340 static final class BasePermission {
7341 final static int TYPE_NORMAL = 0;
7342 final static int TYPE_BUILTIN = 1;
7343 final static int TYPE_DYNAMIC = 2;
7344
7345 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007346 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007347 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007349 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007350 PackageParser.Permission perm;
7351 PermissionInfo pendingInfo;
7352 int uid;
7353 int[] gids;
7354
7355 BasePermission(String _name, String _sourcePackage, int _type) {
7356 name = _name;
7357 sourcePackage = _sourcePackage;
7358 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007359 // Default to most conservative protection level.
7360 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7361 }
7362
7363 public String toString() {
7364 return "BasePermission{"
7365 + Integer.toHexString(System.identityHashCode(this))
7366 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 }
7368 }
7369
7370 static class PackageSignatures {
7371 private Signature[] mSignatures;
7372
7373 PackageSignatures(Signature[] sigs) {
7374 assignSignatures(sigs);
7375 }
7376
7377 PackageSignatures() {
7378 }
7379
7380 void writeXml(XmlSerializer serializer, String tagName,
7381 ArrayList<Signature> pastSignatures) throws IOException {
7382 if (mSignatures == null) {
7383 return;
7384 }
7385 serializer.startTag(null, tagName);
7386 serializer.attribute(null, "count",
7387 Integer.toString(mSignatures.length));
7388 for (int i=0; i<mSignatures.length; i++) {
7389 serializer.startTag(null, "cert");
7390 final Signature sig = mSignatures[i];
7391 final int sigHash = sig.hashCode();
7392 final int numPast = pastSignatures.size();
7393 int j;
7394 for (j=0; j<numPast; j++) {
7395 Signature pastSig = pastSignatures.get(j);
7396 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7397 serializer.attribute(null, "index", Integer.toString(j));
7398 break;
7399 }
7400 }
7401 if (j >= numPast) {
7402 pastSignatures.add(sig);
7403 serializer.attribute(null, "index", Integer.toString(numPast));
7404 serializer.attribute(null, "key", sig.toCharsString());
7405 }
7406 serializer.endTag(null, "cert");
7407 }
7408 serializer.endTag(null, tagName);
7409 }
7410
7411 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7412 throws IOException, XmlPullParserException {
7413 String countStr = parser.getAttributeValue(null, "count");
7414 if (countStr == null) {
7415 reportSettingsProblem(Log.WARN,
7416 "Error in package manager settings: <signatures> has"
7417 + " no count at " + parser.getPositionDescription());
7418 XmlUtils.skipCurrentTag(parser);
7419 }
7420 final int count = Integer.parseInt(countStr);
7421 mSignatures = new Signature[count];
7422 int pos = 0;
7423
7424 int outerDepth = parser.getDepth();
7425 int type;
7426 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7427 && (type != XmlPullParser.END_TAG
7428 || parser.getDepth() > outerDepth)) {
7429 if (type == XmlPullParser.END_TAG
7430 || type == XmlPullParser.TEXT) {
7431 continue;
7432 }
7433
7434 String tagName = parser.getName();
7435 if (tagName.equals("cert")) {
7436 if (pos < count) {
7437 String index = parser.getAttributeValue(null, "index");
7438 if (index != null) {
7439 try {
7440 int idx = Integer.parseInt(index);
7441 String key = parser.getAttributeValue(null, "key");
7442 if (key == null) {
7443 if (idx >= 0 && idx < pastSignatures.size()) {
7444 Signature sig = pastSignatures.get(idx);
7445 if (sig != null) {
7446 mSignatures[pos] = pastSignatures.get(idx);
7447 pos++;
7448 } else {
7449 reportSettingsProblem(Log.WARN,
7450 "Error in package manager settings: <cert> "
7451 + "index " + index + " is not defined at "
7452 + parser.getPositionDescription());
7453 }
7454 } else {
7455 reportSettingsProblem(Log.WARN,
7456 "Error in package manager settings: <cert> "
7457 + "index " + index + " is out of bounds at "
7458 + parser.getPositionDescription());
7459 }
7460 } else {
7461 while (pastSignatures.size() <= idx) {
7462 pastSignatures.add(null);
7463 }
7464 Signature sig = new Signature(key);
7465 pastSignatures.set(idx, sig);
7466 mSignatures[pos] = sig;
7467 pos++;
7468 }
7469 } catch (NumberFormatException e) {
7470 reportSettingsProblem(Log.WARN,
7471 "Error in package manager settings: <cert> "
7472 + "index " + index + " is not a number at "
7473 + parser.getPositionDescription());
7474 }
7475 } else {
7476 reportSettingsProblem(Log.WARN,
7477 "Error in package manager settings: <cert> has"
7478 + " no index at " + parser.getPositionDescription());
7479 }
7480 } else {
7481 reportSettingsProblem(Log.WARN,
7482 "Error in package manager settings: too "
7483 + "many <cert> tags, expected " + count
7484 + " at " + parser.getPositionDescription());
7485 }
7486 } else {
7487 reportSettingsProblem(Log.WARN,
7488 "Unknown element under <cert>: "
7489 + parser.getName());
7490 }
7491 XmlUtils.skipCurrentTag(parser);
7492 }
7493
7494 if (pos < count) {
7495 // Should never happen -- there is an error in the written
7496 // settings -- but if it does we don't want to generate
7497 // a bad array.
7498 Signature[] newSigs = new Signature[pos];
7499 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7500 mSignatures = newSigs;
7501 }
7502 }
7503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007504 private void assignSignatures(Signature[] sigs) {
7505 if (sigs == null) {
7506 mSignatures = null;
7507 return;
7508 }
7509 mSignatures = new Signature[sigs.length];
7510 for (int i=0; i<sigs.length; i++) {
7511 mSignatures[i] = sigs[i];
7512 }
7513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007515 @Override
7516 public String toString() {
7517 StringBuffer buf = new StringBuffer(128);
7518 buf.append("PackageSignatures{");
7519 buf.append(Integer.toHexString(System.identityHashCode(this)));
7520 buf.append(" [");
7521 if (mSignatures != null) {
7522 for (int i=0; i<mSignatures.length; i++) {
7523 if (i > 0) buf.append(", ");
7524 buf.append(Integer.toHexString(
7525 System.identityHashCode(mSignatures[i])));
7526 }
7527 }
7528 buf.append("]}");
7529 return buf.toString();
7530 }
7531 }
7532
7533 static class PreferredActivity extends IntentFilter {
7534 final int mMatch;
7535 final String[] mSetPackages;
7536 final String[] mSetClasses;
7537 final String[] mSetComponents;
7538 final ComponentName mActivity;
7539 final String mShortActivity;
7540 String mParseError;
7541
7542 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7543 ComponentName activity) {
7544 super(filter);
7545 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7546 mActivity = activity;
7547 mShortActivity = activity.flattenToShortString();
7548 mParseError = null;
7549 if (set != null) {
7550 final int N = set.length;
7551 String[] myPackages = new String[N];
7552 String[] myClasses = new String[N];
7553 String[] myComponents = new String[N];
7554 for (int i=0; i<N; i++) {
7555 ComponentName cn = set[i];
7556 if (cn == null) {
7557 mSetPackages = null;
7558 mSetClasses = null;
7559 mSetComponents = null;
7560 return;
7561 }
7562 myPackages[i] = cn.getPackageName().intern();
7563 myClasses[i] = cn.getClassName().intern();
7564 myComponents[i] = cn.flattenToShortString().intern();
7565 }
7566 mSetPackages = myPackages;
7567 mSetClasses = myClasses;
7568 mSetComponents = myComponents;
7569 } else {
7570 mSetPackages = null;
7571 mSetClasses = null;
7572 mSetComponents = null;
7573 }
7574 }
7575
7576 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7577 IOException {
7578 mShortActivity = parser.getAttributeValue(null, "name");
7579 mActivity = ComponentName.unflattenFromString(mShortActivity);
7580 if (mActivity == null) {
7581 mParseError = "Bad activity name " + mShortActivity;
7582 }
7583 String matchStr = parser.getAttributeValue(null, "match");
7584 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7585 String setCountStr = parser.getAttributeValue(null, "set");
7586 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7587
7588 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7589 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7590 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7591
7592 int setPos = 0;
7593
7594 int outerDepth = parser.getDepth();
7595 int type;
7596 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7597 && (type != XmlPullParser.END_TAG
7598 || parser.getDepth() > outerDepth)) {
7599 if (type == XmlPullParser.END_TAG
7600 || type == XmlPullParser.TEXT) {
7601 continue;
7602 }
7603
7604 String tagName = parser.getName();
7605 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7606 // + parser.getDepth() + " tag=" + tagName);
7607 if (tagName.equals("set")) {
7608 String name = parser.getAttributeValue(null, "name");
7609 if (name == null) {
7610 if (mParseError == null) {
7611 mParseError = "No name in set tag in preferred activity "
7612 + mShortActivity;
7613 }
7614 } else if (setPos >= setCount) {
7615 if (mParseError == null) {
7616 mParseError = "Too many set tags in preferred activity "
7617 + mShortActivity;
7618 }
7619 } else {
7620 ComponentName cn = ComponentName.unflattenFromString(name);
7621 if (cn == null) {
7622 if (mParseError == null) {
7623 mParseError = "Bad set name " + name + " in preferred activity "
7624 + mShortActivity;
7625 }
7626 } else {
7627 myPackages[setPos] = cn.getPackageName();
7628 myClasses[setPos] = cn.getClassName();
7629 myComponents[setPos] = name;
7630 setPos++;
7631 }
7632 }
7633 XmlUtils.skipCurrentTag(parser);
7634 } else if (tagName.equals("filter")) {
7635 //Log.i(TAG, "Starting to parse filter...");
7636 readFromXml(parser);
7637 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7638 // + parser.getDepth() + " tag=" + parser.getName());
7639 } else {
7640 reportSettingsProblem(Log.WARN,
7641 "Unknown element under <preferred-activities>: "
7642 + parser.getName());
7643 XmlUtils.skipCurrentTag(parser);
7644 }
7645 }
7646
7647 if (setPos != setCount) {
7648 if (mParseError == null) {
7649 mParseError = "Not enough set tags (expected " + setCount
7650 + " but found " + setPos + ") in " + mShortActivity;
7651 }
7652 }
7653
7654 mSetPackages = myPackages;
7655 mSetClasses = myClasses;
7656 mSetComponents = myComponents;
7657 }
7658
7659 public void writeToXml(XmlSerializer serializer) throws IOException {
7660 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7661 serializer.attribute(null, "name", mShortActivity);
7662 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7663 serializer.attribute(null, "set", Integer.toString(NS));
7664 for (int s=0; s<NS; s++) {
7665 serializer.startTag(null, "set");
7666 serializer.attribute(null, "name", mSetComponents[s]);
7667 serializer.endTag(null, "set");
7668 }
7669 serializer.startTag(null, "filter");
7670 super.writeToXml(serializer);
7671 serializer.endTag(null, "filter");
7672 }
7673
7674 boolean sameSet(List<ResolveInfo> query, int priority) {
7675 if (mSetPackages == null) return false;
7676 final int NQ = query.size();
7677 final int NS = mSetPackages.length;
7678 int numMatch = 0;
7679 for (int i=0; i<NQ; i++) {
7680 ResolveInfo ri = query.get(i);
7681 if (ri.priority != priority) continue;
7682 ActivityInfo ai = ri.activityInfo;
7683 boolean good = false;
7684 for (int j=0; j<NS; j++) {
7685 if (mSetPackages[j].equals(ai.packageName)
7686 && mSetClasses[j].equals(ai.name)) {
7687 numMatch++;
7688 good = true;
7689 break;
7690 }
7691 }
7692 if (!good) return false;
7693 }
7694 return numMatch == NS;
7695 }
7696 }
7697
7698 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007699 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 HashSet<String> grantedPermissions = new HashSet<String>();
7702 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007705 setFlags(pkgFlags);
7706 }
7707
7708 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007709 this.pkgFlags = pkgFlags & (
7710 ApplicationInfo.FLAG_SYSTEM |
7711 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007712 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007713 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 }
7715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 /**
7718 * Settings base class for pending and resolved classes.
7719 */
7720 static class PackageSettingBase extends GrantedPermissions {
7721 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007722 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007723 File codePath;
7724 String codePathString;
7725 File resourcePath;
7726 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007727 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007728 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007729 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007730 long firstInstallTime;
7731 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007732 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007733
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007734 boolean uidError;
7735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 PackageSignatures signatures = new PackageSignatures();
7737
7738 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007739 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 /* Explicitly disabled components */
7742 HashSet<String> disabledComponents = new HashSet<String>(0);
7743 /* Explicitly enabled components */
7744 HashSet<String> enabledComponents = new HashSet<String>(0);
7745 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7746 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007747
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007748 PackageSettingBase origPackage;
7749
Jacek Surazski65e13172009-04-28 15:26:38 +02007750 /* package name of the app that installed this package */
7751 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007753 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007754 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 super(pkgFlags);
7756 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007757 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007758 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007759 }
7760
Kenny Root806cc132010-09-12 08:34:19 -07007761 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7762 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 this.codePath = codePath;
7764 this.codePathString = codePath.toString();
7765 this.resourcePath = resourcePath;
7766 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007767 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007768 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 }
Kenny Root85387d72010-08-26 10:13:11 -07007770
Jacek Surazski65e13172009-04-28 15:26:38 +02007771 public void setInstallerPackageName(String packageName) {
7772 installerPackageName = packageName;
7773 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007774
Jacek Surazski65e13172009-04-28 15:26:38 +02007775 String getInstallerPackageName() {
7776 return installerPackageName;
7777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 public void setInstallStatus(int newStatus) {
7780 installStatus = newStatus;
7781 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 public int getInstallStatus() {
7784 return installStatus;
7785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007789 }
7790
7791 public void copyFrom(PackageSettingBase base) {
7792 grantedPermissions = base.grantedPermissions;
7793 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007796 firstInstallTime = base.firstInstallTime;
7797 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007798 signatures = base.signatures;
7799 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007800 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 disabledComponents = base.disabledComponents;
7802 enabledComponents = base.enabledComponents;
7803 enabled = base.enabled;
7804 installStatus = base.installStatus;
7805 }
7806
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007807 boolean enableComponentLP(String componentClassName) {
7808 boolean changed = disabledComponents.remove(componentClassName);
7809 changed |= enabledComponents.add(componentClassName);
7810 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 }
7812
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007813 boolean disableComponentLP(String componentClassName) {
7814 boolean changed = enabledComponents.remove(componentClassName);
7815 changed |= disabledComponents.add(componentClassName);
7816 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 }
7818
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007819 boolean restoreComponentLP(String componentClassName) {
7820 boolean changed = enabledComponents.remove(componentClassName);
7821 changed |= disabledComponents.remove(componentClassName);
7822 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 }
7824
7825 int currentEnabledStateLP(String componentName) {
7826 if (enabledComponents.contains(componentName)) {
7827 return COMPONENT_ENABLED_STATE_ENABLED;
7828 } else if (disabledComponents.contains(componentName)) {
7829 return COMPONENT_ENABLED_STATE_DISABLED;
7830 } else {
7831 return COMPONENT_ENABLED_STATE_DEFAULT;
7832 }
7833 }
7834 }
7835
7836 /**
7837 * Settings data for a particular package we know about.
7838 */
7839 static final class PackageSetting extends PackageSettingBase {
7840 int userId;
7841 PackageParser.Package pkg;
7842 SharedUserSetting sharedUser;
7843
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007844 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007845 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7846 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7847 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 @Override
7851 public String toString() {
7852 return "PackageSetting{"
7853 + Integer.toHexString(System.identityHashCode(this))
7854 + " " + name + "/" + userId + "}";
7855 }
7856 }
7857
7858 /**
7859 * Settings data for a particular shared user ID we know about.
7860 */
7861 static final class SharedUserSetting extends GrantedPermissions {
7862 final String name;
7863 int userId;
7864 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7865 final PackageSignatures signatures = new PackageSignatures();
7866
7867 SharedUserSetting(String _name, int _pkgFlags) {
7868 super(_pkgFlags);
7869 name = _name;
7870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 @Override
7873 public String toString() {
7874 return "SharedUserSetting{"
7875 + Integer.toHexString(System.identityHashCode(this))
7876 + " " + name + "/" + userId + "}";
7877 }
7878 }
7879
7880 /**
7881 * Holds information about dynamic settings.
7882 */
7883 private static final class Settings {
7884 private final File mSettingsFilename;
7885 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007886 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 private final HashMap<String, PackageSetting> mPackages =
7888 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 // List of replaced system applications
7890 final HashMap<String, PackageSetting> mDisabledSysPackages =
7891 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007892
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007893 // These are the last platform API version we were using for
7894 // the apps installed on internal and external storage. It is
7895 // used to grant newer permissions one time during a system upgrade.
7896 int mInternalSdkPlatform;
7897 int mExternalSdkPlatform;
7898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 // The user's preferred activities associated with particular intent
7900 // filters.
7901 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7902 new IntentResolver<PreferredActivity, PreferredActivity>() {
7903 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007904 protected String packageForFilter(PreferredActivity filter) {
7905 return filter.mActivity.getPackageName();
7906 }
7907 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007908 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007910 out.print(prefix); out.print(
7911 Integer.toHexString(System.identityHashCode(filter)));
7912 out.print(' ');
7913 out.print(filter.mActivity.flattenToShortString());
7914 out.print(" match=0x");
7915 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007917 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007918 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007919 out.print(prefix); out.print(" ");
7920 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 }
7922 }
7923 }
7924 };
7925 private final HashMap<String, SharedUserSetting> mSharedUsers =
7926 new HashMap<String, SharedUserSetting>();
7927 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7928 private final SparseArray<Object> mOtherUserIds =
7929 new SparseArray<Object>();
7930
7931 // For reading/writing settings file.
7932 private final ArrayList<Signature> mPastSignatures =
7933 new ArrayList<Signature>();
7934
7935 // Mapping from permission names to info about them.
7936 final HashMap<String, BasePermission> mPermissions =
7937 new HashMap<String, BasePermission>();
7938
7939 // Mapping from permission tree names to info about them.
7940 final HashMap<String, BasePermission> mPermissionTrees =
7941 new HashMap<String, BasePermission>();
7942
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007943 // Packages that have been uninstalled and still need their external
7944 // storage data deleted.
7945 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7946
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007947 // Packages that have been renamed since they were first installed.
7948 // Keys are the new names of the packages, values are the original
7949 // names. The packages appear everwhere else under their original
7950 // names.
7951 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 private final StringBuilder mReadMessages = new StringBuilder();
7954
7955 private static final class PendingPackage extends PackageSettingBase {
7956 final int sharedId;
7957
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007958 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007959 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7960 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7961 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007962 this.sharedId = sharedId;
7963 }
7964 }
7965 private final ArrayList<PendingPackage> mPendingPackages
7966 = new ArrayList<PendingPackage>();
7967
7968 Settings() {
7969 File dataDir = Environment.getDataDirectory();
7970 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007971 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7972 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007974 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 FileUtils.setPermissions(systemDir.toString(),
7976 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7977 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7978 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007979 FileUtils.setPermissions(systemSecureDir.toString(),
7980 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7981 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7982 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 mSettingsFilename = new File(systemDir, "packages.xml");
7984 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007985 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 }
7987
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007988 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007989 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007990 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007992 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007993 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994 return p;
7995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007996
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007997 PackageSetting peekPackageLP(String name) {
7998 return mPackages.get(name);
7999 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 PackageSetting p = mPackages.get(name);
8001 if (p != null && p.codePath.getPath().equals(codePath)) {
8002 return p;
8003 }
8004 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008005 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008008 void setInstallStatus(String pkgName, int status) {
8009 PackageSetting p = mPackages.get(pkgName);
8010 if(p != null) {
8011 if(p.getInstallStatus() != status) {
8012 p.setInstallStatus(status);
8013 }
8014 }
8015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008016
Jacek Surazski65e13172009-04-28 15:26:38 +02008017 void setInstallerPackageName(String pkgName,
8018 String installerPkgName) {
8019 PackageSetting p = mPackages.get(pkgName);
8020 if(p != null) {
8021 p.setInstallerPackageName(installerPkgName);
8022 }
8023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008024
Jacek Surazski65e13172009-04-28 15:26:38 +02008025 String getInstallerPackageName(String pkgName) {
8026 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008027 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008028 }
8029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008030 int getInstallStatus(String pkgName) {
8031 PackageSetting p = mPackages.get(pkgName);
8032 if(p != null) {
8033 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 return -1;
8036 }
8037
8038 SharedUserSetting getSharedUserLP(String name,
8039 int pkgFlags, boolean create) {
8040 SharedUserSetting s = mSharedUsers.get(name);
8041 if (s == null) {
8042 if (!create) {
8043 return null;
8044 }
8045 s = new SharedUserSetting(name, pkgFlags);
8046 if (MULTIPLE_APPLICATION_UIDS) {
8047 s.userId = newUserIdLP(s);
8048 } else {
8049 s.userId = FIRST_APPLICATION_UID;
8050 }
8051 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8052 // < 0 means we couldn't assign a userid; fall out and return
8053 // s, which is currently null
8054 if (s.userId >= 0) {
8055 mSharedUsers.put(name, s);
8056 }
8057 }
8058
8059 return s;
8060 }
8061
8062 int disableSystemPackageLP(String name) {
8063 PackageSetting p = mPackages.get(name);
8064 if(p == null) {
8065 Log.w(TAG, "Package:"+name+" is not an installed package");
8066 return -1;
8067 }
8068 PackageSetting dp = mDisabledSysPackages.get(name);
8069 // always make sure the system package code and resource paths dont change
8070 if(dp == null) {
8071 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8072 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8073 }
8074 mDisabledSysPackages.put(name, p);
8075 }
8076 return removePackageLP(name);
8077 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 PackageSetting enableSystemPackageLP(String name) {
8080 PackageSetting p = mDisabledSysPackages.get(name);
8081 if(p == null) {
8082 Log.w(TAG, "Package:"+name+" is not disabled");
8083 return null;
8084 }
8085 // Reset flag in ApplicationInfo object
8086 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8087 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8088 }
Kenny Root806cc132010-09-12 08:34:19 -07008089 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8090 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008091 mDisabledSysPackages.remove(name);
8092 return ret;
8093 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008094
Kenny Root806cc132010-09-12 08:34:19 -07008095 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8096 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 PackageSetting p = mPackages.get(name);
8098 if (p != null) {
8099 if (p.userId == uid) {
8100 return p;
8101 }
8102 reportSettingsProblem(Log.ERROR,
8103 "Adding duplicate package, keeping first: " + name);
8104 return null;
8105 }
Kenny Root806cc132010-09-12 08:34:19 -07008106 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8107 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 p.userId = uid;
8109 if (addUserIdLP(uid, p, name)) {
8110 mPackages.put(name, p);
8111 return p;
8112 }
8113 return null;
8114 }
8115
8116 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8117 SharedUserSetting s = mSharedUsers.get(name);
8118 if (s != null) {
8119 if (s.userId == uid) {
8120 return s;
8121 }
8122 reportSettingsProblem(Log.ERROR,
8123 "Adding duplicate shared user, keeping first: " + name);
8124 return null;
8125 }
8126 s = new SharedUserSetting(name, pkgFlags);
8127 s.userId = uid;
8128 if (addUserIdLP(uid, s, name)) {
8129 mSharedUsers.put(name, s);
8130 return s;
8131 }
8132 return null;
8133 }
8134
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008135 // Transfer ownership of permissions from one package to another.
8136 private void transferPermissions(String origPkg, String newPkg) {
8137 // Transfer ownership of permissions to the new package.
8138 for (int i=0; i<2; i++) {
8139 HashMap<String, BasePermission> permissions =
8140 i == 0 ? mPermissionTrees : mPermissions;
8141 for (BasePermission bp : permissions.values()) {
8142 if (origPkg.equals(bp.sourcePackage)) {
8143 if (DEBUG_UPGRADE) Log.v(TAG,
8144 "Moving permission " + bp.name
8145 + " from pkg " + bp.sourcePackage
8146 + " to " + newPkg);
8147 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008148 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008149 bp.perm = null;
8150 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008151 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008152 }
8153 bp.uid = 0;
8154 bp.gids = null;
8155 }
8156 }
8157 }
8158 }
8159
8160 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008161 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008162 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 PackageSetting p = mPackages.get(name);
8164 if (p != null) {
8165 if (!p.codePath.equals(codePath)) {
8166 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008167 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008168 // This is an updated system app with versions in both system
8169 // and data partition. Just let the most recent version
8170 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008171 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008172 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008173 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008174 // Just a change in the code path is not an issue, but
8175 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008176 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008177 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008178 /*
8179 * Since we've changed paths, we need to prefer the new
8180 * native library path over the one stored in the
8181 * package settings since we might have moved from
8182 * internal to external storage or vice versa.
8183 */
8184 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008186 }
8187 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008188 reportSettingsProblem(Log.WARN,
8189 "Package " + name + " shared user changed from "
8190 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8191 + " to "
8192 + (sharedUser != null ? sharedUser.name : "<nothing>")
8193 + "; replacing with new");
8194 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008195 } else {
8196 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8197 // If what we are scanning is a system package, then
8198 // make it so, regardless of whether it was previously
8199 // installed only in the data partition.
8200 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008202 }
8203 }
8204 if (p == null) {
8205 // Create a new PackageSettings entry. this can end up here because
8206 // of code path mismatch or user id mismatch of an updated system partition
8207 if (!create) {
8208 return null;
8209 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008210 if (origPackage != null) {
8211 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008212 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8213 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008214 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8215 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008216 // Note that we will retain the new package's signature so
8217 // that we can keep its data.
8218 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008219 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008220 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008221 p.sharedUser = origPackage.sharedUser;
8222 p.userId = origPackage.userId;
8223 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008224 mRenamedPackages.put(name, origPackage.name);
8225 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008226 // Update new package state.
8227 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008229 p = new PackageSetting(name, realName, codePath, resourcePath,
8230 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008231 p.setTimeStamp(codePath.lastModified());
8232 p.sharedUser = sharedUser;
8233 if (sharedUser != null) {
8234 p.userId = sharedUser.userId;
8235 } else if (MULTIPLE_APPLICATION_UIDS) {
8236 // Clone the setting here for disabled system packages
8237 PackageSetting dis = mDisabledSysPackages.get(name);
8238 if (dis != null) {
8239 // For disabled packages a new setting is created
8240 // from the existing user id. This still has to be
8241 // added to list of user id's
8242 // Copy signatures from previous setting
8243 if (dis.signatures.mSignatures != null) {
8244 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8245 }
8246 p.userId = dis.userId;
8247 // Clone permissions
8248 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008249 // Clone component info
8250 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8251 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8252 // Add new setting to list of user ids
8253 addUserIdLP(p.userId, p, name);
8254 } else {
8255 // Assign new user id
8256 p.userId = newUserIdLP(p);
8257 }
8258 } else {
8259 p.userId = FIRST_APPLICATION_UID;
8260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008261 }
8262 if (p.userId < 0) {
8263 reportSettingsProblem(Log.WARN,
8264 "Package " + name + " could not be assigned a valid uid");
8265 return null;
8266 }
8267 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008268 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008269 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008270 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 }
8272 }
8273 return p;
8274 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008275
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008276 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008277 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008278 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008279 final String codePath = pkg.applicationInfo.sourceDir;
8280 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008281 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008282 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008283 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008284 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008285 p.codePath = new File(codePath);
8286 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008287 }
8288 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008289 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008290 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008291 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008292 p.resourcePath = new File(resourcePath);
8293 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008294 }
Kenny Root85387d72010-08-26 10:13:11 -07008295 // Update the native library path if needed
8296 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8297 if (nativeLibraryPath != null
8298 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8299 p.nativeLibraryPathString = nativeLibraryPath;
8300 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008301 // Update version code if needed
8302 if (pkg.mVersionCode != p.versionCode) {
8303 p.versionCode = pkg.mVersionCode;
8304 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008305 // Update signatures if needed.
8306 if (p.signatures.mSignatures == null) {
8307 p.signatures.assignSignatures(pkg.mSignatures);
8308 }
8309 // If this app defines a shared user id initialize
8310 // the shared user signatures as well.
8311 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8312 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8313 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008314 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8315 }
8316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317 // Utility method that adds a PackageSetting to mPackages and
8318 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008319 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 SharedUserSetting sharedUser) {
8321 mPackages.put(name, p);
8322 if (sharedUser != null) {
8323 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8324 reportSettingsProblem(Log.ERROR,
8325 "Package " + p.name + " was user "
8326 + p.sharedUser + " but is now " + sharedUser
8327 + "; I am not changing its files so it will probably fail!");
8328 p.sharedUser.packages.remove(p);
8329 } else if (p.userId != sharedUser.userId) {
8330 reportSettingsProblem(Log.ERROR,
8331 "Package " + p.name + " was user id " + p.userId
8332 + " but is now user " + sharedUser
8333 + " with id " + sharedUser.userId
8334 + "; I am not changing its files so it will probably fail!");
8335 }
8336
8337 sharedUser.packages.add(p);
8338 p.sharedUser = sharedUser;
8339 p.userId = sharedUser.userId;
8340 }
8341 }
8342
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008343 /*
8344 * Update the shared user setting when a package using
8345 * specifying the shared user id is removed. The gids
8346 * associated with each permission of the deleted package
8347 * are removed from the shared user's gid list only if its
8348 * not in use by other permissions of packages in the
8349 * shared user setting.
8350 */
8351 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008353 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 return;
8355 }
8356 // No sharedUserId
8357 if (deletedPs.sharedUser == null) {
8358 return;
8359 }
8360 SharedUserSetting sus = deletedPs.sharedUser;
8361 // Update permissions
8362 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8363 boolean used = false;
8364 if (!sus.grantedPermissions.contains (eachPerm)) {
8365 continue;
8366 }
8367 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008368 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008369 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008370 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 used = true;
8372 break;
8373 }
8374 }
8375 if (!used) {
8376 // can safely delete this permission from list
8377 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008378 }
8379 }
8380 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008381 int newGids[] = globalGids;
8382 for (String eachPerm : sus.grantedPermissions) {
8383 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008384 if (bp != null) {
8385 newGids = appendInts(newGids, bp.gids);
8386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008387 }
8388 sus.gids = newGids;
8389 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008391 private int removePackageLP(String name) {
8392 PackageSetting p = mPackages.get(name);
8393 if (p != null) {
8394 mPackages.remove(name);
8395 if (p.sharedUser != null) {
8396 p.sharedUser.packages.remove(p);
8397 if (p.sharedUser.packages.size() == 0) {
8398 mSharedUsers.remove(p.sharedUser.name);
8399 removeUserIdLP(p.sharedUser.userId);
8400 return p.sharedUser.userId;
8401 }
8402 } else {
8403 removeUserIdLP(p.userId);
8404 return p.userId;
8405 }
8406 }
8407 return -1;
8408 }
8409
8410 private boolean addUserIdLP(int uid, Object obj, Object name) {
8411 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8412 return false;
8413 }
8414
8415 if (uid >= FIRST_APPLICATION_UID) {
8416 int N = mUserIds.size();
8417 final int index = uid - FIRST_APPLICATION_UID;
8418 while (index >= N) {
8419 mUserIds.add(null);
8420 N++;
8421 }
8422 if (mUserIds.get(index) != null) {
8423 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008424 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008425 + " name=" + name);
8426 return false;
8427 }
8428 mUserIds.set(index, obj);
8429 } else {
8430 if (mOtherUserIds.get(uid) != null) {
8431 reportSettingsProblem(Log.ERROR,
8432 "Adding duplicate shared id: " + uid
8433 + " name=" + name);
8434 return false;
8435 }
8436 mOtherUserIds.put(uid, obj);
8437 }
8438 return true;
8439 }
8440
8441 public Object getUserIdLP(int uid) {
8442 if (uid >= FIRST_APPLICATION_UID) {
8443 int N = mUserIds.size();
8444 final int index = uid - FIRST_APPLICATION_UID;
8445 return index < N ? mUserIds.get(index) : null;
8446 } else {
8447 return mOtherUserIds.get(uid);
8448 }
8449 }
8450
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008451 private Set<String> findPackagesWithFlag(int flag) {
8452 Set<String> ret = new HashSet<String>();
8453 for (PackageSetting ps : mPackages.values()) {
8454 // Has to match atleast all the flag bits set on flag
8455 if ((ps.pkgFlags & flag) == flag) {
8456 ret.add(ps.name);
8457 }
8458 }
8459 return ret;
8460 }
8461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008462 private void removeUserIdLP(int uid) {
8463 if (uid >= FIRST_APPLICATION_UID) {
8464 int N = mUserIds.size();
8465 final int index = uid - FIRST_APPLICATION_UID;
8466 if (index < N) mUserIds.set(index, null);
8467 } else {
8468 mOtherUserIds.remove(uid);
8469 }
8470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008472 void writeLP() {
8473 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8474
8475 // Keep the old settings around until we know the new ones have
8476 // been successfully written.
8477 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008478 // Presence of backup settings file indicates that we failed
8479 // to persist settings earlier. So preserve the older
8480 // backup for future reference since the current settings
8481 // might have been corrupted.
8482 if (!mBackupSettingsFilename.exists()) {
8483 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008484 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008485 return;
8486 }
8487 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008488 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008489 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008491 }
8492
8493 mPastSignatures.clear();
8494
8495 try {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008496 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
8497 BufferedOutputStream str = new BufferedOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008498
8499 //XmlSerializer serializer = XmlUtils.serializerInstance();
8500 XmlSerializer serializer = new FastXmlSerializer();
8501 serializer.setOutput(str, "utf-8");
8502 serializer.startDocument(null, true);
8503 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8504
8505 serializer.startTag(null, "packages");
8506
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008507 serializer.startTag(null, "last-platform-version");
8508 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8509 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8510 serializer.endTag(null, "last-platform-version");
8511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008512 serializer.startTag(null, "permission-trees");
8513 for (BasePermission bp : mPermissionTrees.values()) {
8514 writePermission(serializer, bp);
8515 }
8516 serializer.endTag(null, "permission-trees");
8517
8518 serializer.startTag(null, "permissions");
8519 for (BasePermission bp : mPermissions.values()) {
8520 writePermission(serializer, bp);
8521 }
8522 serializer.endTag(null, "permissions");
8523
8524 for (PackageSetting pkg : mPackages.values()) {
8525 writePackage(serializer, pkg);
8526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8529 writeDisabledSysPackage(serializer, pkg);
8530 }
8531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008532 serializer.startTag(null, "preferred-activities");
8533 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8534 serializer.startTag(null, "item");
8535 pa.writeToXml(serializer);
8536 serializer.endTag(null, "item");
8537 }
8538 serializer.endTag(null, "preferred-activities");
8539
8540 for (SharedUserSetting usr : mSharedUsers.values()) {
8541 serializer.startTag(null, "shared-user");
8542 serializer.attribute(null, "name", usr.name);
8543 serializer.attribute(null, "userId",
8544 Integer.toString(usr.userId));
8545 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8546 serializer.startTag(null, "perms");
8547 for (String name : usr.grantedPermissions) {
8548 serializer.startTag(null, "item");
8549 serializer.attribute(null, "name", name);
8550 serializer.endTag(null, "item");
8551 }
8552 serializer.endTag(null, "perms");
8553 serializer.endTag(null, "shared-user");
8554 }
8555
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008556 if (mPackagesToBeCleaned.size() > 0) {
8557 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8558 serializer.startTag(null, "cleaning-package");
8559 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8560 serializer.endTag(null, "cleaning-package");
8561 }
8562 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008563
8564 if (mRenamedPackages.size() > 0) {
8565 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8566 serializer.startTag(null, "renamed-package");
8567 serializer.attribute(null, "new", e.getKey());
8568 serializer.attribute(null, "old", e.getValue());
8569 serializer.endTag(null, "renamed-package");
8570 }
8571 }
8572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 serializer.endTag(null, "packages");
8574
8575 serializer.endDocument();
8576
8577 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008578 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 str.close();
8580
8581 // New settings successfully written, old ones are no longer
8582 // needed.
8583 mBackupSettingsFilename.delete();
8584 FileUtils.setPermissions(mSettingsFilename.toString(),
8585 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8586 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8587 |FileUtils.S_IROTH,
8588 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008589
8590 // Write package list file now, use a JournaledFile.
8591 //
8592 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8593 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8594
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008595 fstr = new FileOutputStream(journal.chooseForWrite());
8596 str = new BufferedOutputStream(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008597 try {
8598 StringBuilder sb = new StringBuilder();
8599 for (PackageSetting pkg : mPackages.values()) {
8600 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008601 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008602 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8603
8604 // Avoid any application that has a space in its path
8605 // or that is handled by the system.
8606 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8607 continue;
8608
8609 // we store on each line the following information for now:
8610 //
8611 // pkgName - package name
8612 // userId - application-specific user id
8613 // debugFlag - 0 or 1 if the package is debuggable.
8614 // dataPath - path to package's data path
8615 //
8616 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8617 //
8618 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8619 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8620 // system/core/run-as/run-as.c
8621 //
8622 sb.setLength(0);
8623 sb.append(ai.packageName);
8624 sb.append(" ");
8625 sb.append((int)ai.uid);
8626 sb.append(isDebug ? " 1 " : " 0 ");
8627 sb.append(dataPath);
8628 sb.append("\n");
8629 str.write(sb.toString().getBytes());
8630 }
8631 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008632 FileUtils.sync(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008633 str.close();
8634 journal.commit();
8635 }
8636 catch (Exception e) {
8637 journal.rollback();
8638 }
8639
8640 FileUtils.setPermissions(mPackageListFilename.toString(),
8641 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8642 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8643 |FileUtils.S_IROTH,
8644 -1, -1);
8645
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008646 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008647
8648 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008649 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 -08008650 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008651 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 -08008652 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008653 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008654 if (mSettingsFilename.exists()) {
8655 if (!mSettingsFilename.delete()) {
8656 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8657 }
8658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008659 //Debug.stopMethodTracing();
8660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008661
8662 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008663 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 serializer.startTag(null, "updated-package");
8665 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008666 if (pkg.realName != null) {
8667 serializer.attribute(null, "realName", pkg.realName);
8668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008670 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8671 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8672 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008673 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008674 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8675 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8676 }
Kenny Root85387d72010-08-26 10:13:11 -07008677 if (pkg.nativeLibraryPathString != null) {
8678 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 if (pkg.sharedUser == null) {
8681 serializer.attribute(null, "userId",
8682 Integer.toString(pkg.userId));
8683 } else {
8684 serializer.attribute(null, "sharedUserId",
8685 Integer.toString(pkg.userId));
8686 }
8687 serializer.startTag(null, "perms");
8688 if (pkg.sharedUser == null) {
8689 // If this is a shared user, the permissions will
8690 // be written there. We still need to write an
8691 // empty permissions list so permissionsFixed will
8692 // be set.
8693 for (final String name : pkg.grantedPermissions) {
8694 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008695 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 // We only need to write signature or system permissions but this wont
8697 // match the semantics of grantedPermissions. So write all permissions.
8698 serializer.startTag(null, "item");
8699 serializer.attribute(null, "name", name);
8700 serializer.endTag(null, "item");
8701 }
8702 }
8703 }
8704 serializer.endTag(null, "perms");
8705 serializer.endTag(null, "updated-package");
8706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008707
8708 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008709 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 serializer.startTag(null, "package");
8711 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008712 if (pkg.realName != null) {
8713 serializer.attribute(null, "realName", pkg.realName);
8714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 serializer.attribute(null, "codePath", pkg.codePathString);
8716 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8717 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8718 }
Kenny Root85387d72010-08-26 10:13:11 -07008719 if (pkg.nativeLibraryPathString != null) {
8720 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8721 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008722 serializer.attribute(null, "flags",
8723 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008724 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8725 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8726 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008727 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 if (pkg.sharedUser == null) {
8729 serializer.attribute(null, "userId",
8730 Integer.toString(pkg.userId));
8731 } else {
8732 serializer.attribute(null, "sharedUserId",
8733 Integer.toString(pkg.userId));
8734 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008735 if (pkg.uidError) {
8736 serializer.attribute(null, "uidError", "true");
8737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8739 serializer.attribute(null, "enabled",
8740 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8741 ? "true" : "false");
8742 }
8743 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8744 serializer.attribute(null, "installStatus", "false");
8745 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008746 if (pkg.installerPackageName != null) {
8747 serializer.attribute(null, "installer", pkg.installerPackageName);
8748 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008749 if (pkg.obbPathString != null) {
8750 serializer.attribute(null, "obbPath", pkg.obbPathString);
8751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8753 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8754 serializer.startTag(null, "perms");
8755 if (pkg.sharedUser == null) {
8756 // If this is a shared user, the permissions will
8757 // be written there. We still need to write an
8758 // empty permissions list so permissionsFixed will
8759 // be set.
8760 for (final String name : pkg.grantedPermissions) {
8761 serializer.startTag(null, "item");
8762 serializer.attribute(null, "name", name);
8763 serializer.endTag(null, "item");
8764 }
8765 }
8766 serializer.endTag(null, "perms");
8767 }
8768 if (pkg.disabledComponents.size() > 0) {
8769 serializer.startTag(null, "disabled-components");
8770 for (final String name : pkg.disabledComponents) {
8771 serializer.startTag(null, "item");
8772 serializer.attribute(null, "name", name);
8773 serializer.endTag(null, "item");
8774 }
8775 serializer.endTag(null, "disabled-components");
8776 }
8777 if (pkg.enabledComponents.size() > 0) {
8778 serializer.startTag(null, "enabled-components");
8779 for (final String name : pkg.enabledComponents) {
8780 serializer.startTag(null, "item");
8781 serializer.attribute(null, "name", name);
8782 serializer.endTag(null, "item");
8783 }
8784 serializer.endTag(null, "enabled-components");
8785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 serializer.endTag(null, "package");
8788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 void writePermission(XmlSerializer serializer, BasePermission bp)
8791 throws XmlPullParserException, java.io.IOException {
8792 if (bp.type != BasePermission.TYPE_BUILTIN
8793 && bp.sourcePackage != null) {
8794 serializer.startTag(null, "item");
8795 serializer.attribute(null, "name", bp.name);
8796 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008797 if (bp.protectionLevel !=
8798 PermissionInfo.PROTECTION_NORMAL) {
8799 serializer.attribute(null, "protection",
8800 Integer.toString(bp.protectionLevel));
8801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802 if (DEBUG_SETTINGS) Log.v(TAG,
8803 "Writing perm: name=" + bp.name + " type=" + bp.type);
8804 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8805 PermissionInfo pi = bp.perm != null ? bp.perm.info
8806 : bp.pendingInfo;
8807 if (pi != null) {
8808 serializer.attribute(null, "type", "dynamic");
8809 if (pi.icon != 0) {
8810 serializer.attribute(null, "icon",
8811 Integer.toString(pi.icon));
8812 }
8813 if (pi.nonLocalizedLabel != null) {
8814 serializer.attribute(null, "label",
8815 pi.nonLocalizedLabel.toString());
8816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008817 }
8818 }
8819 serializer.endTag(null, "item");
8820 }
8821 }
8822
8823 String getReadMessagesLP() {
8824 return mReadMessages.toString();
8825 }
8826
Oscar Montemayora8529f62009-11-18 10:14:20 -08008827 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008828 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8829 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008830 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 while(its.hasNext()) {
8832 String key = its.next();
8833 PackageSetting ps = mPackages.get(key);
8834 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008835 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 }
8837 }
8838 return ret;
8839 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008841 boolean readLP() {
8842 FileInputStream str = null;
8843 if (mBackupSettingsFilename.exists()) {
8844 try {
8845 str = new FileInputStream(mBackupSettingsFilename);
8846 mReadMessages.append("Reading from backup settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008847 reportSettingsProblem(Log.INFO, "Need to read from backup settings file");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008848 if (mSettingsFilename.exists()) {
8849 // If both the backup and settings file exist, we
8850 // ignore the settings since it might have been
8851 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008852 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008853 mSettingsFilename.delete();
8854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008855 } catch (java.io.IOException e) {
8856 // We'll try for the normal settings file.
8857 }
8858 }
8859
8860 mPastSignatures.clear();
8861
8862 try {
8863 if (str == null) {
8864 if (!mSettingsFilename.exists()) {
8865 mReadMessages.append("No settings file found\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008866 reportSettingsProblem(Log.INFO, "No settings file; creating initial state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 return false;
8868 }
8869 str = new FileInputStream(mSettingsFilename);
8870 }
8871 XmlPullParser parser = Xml.newPullParser();
8872 parser.setInput(str, null);
8873
8874 int type;
8875 while ((type=parser.next()) != XmlPullParser.START_TAG
8876 && type != XmlPullParser.END_DOCUMENT) {
8877 ;
8878 }
8879
8880 if (type != XmlPullParser.START_TAG) {
8881 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008882 reportSettingsProblem(Log.WARN, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 return false;
8884 }
8885
8886 int outerDepth = parser.getDepth();
8887 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8888 && (type != XmlPullParser.END_TAG
8889 || parser.getDepth() > outerDepth)) {
8890 if (type == XmlPullParser.END_TAG
8891 || type == XmlPullParser.TEXT) {
8892 continue;
8893 }
8894
8895 String tagName = parser.getName();
8896 if (tagName.equals("package")) {
8897 readPackageLP(parser);
8898 } else if (tagName.equals("permissions")) {
8899 readPermissionsLP(mPermissions, parser);
8900 } else if (tagName.equals("permission-trees")) {
8901 readPermissionsLP(mPermissionTrees, parser);
8902 } else if (tagName.equals("shared-user")) {
8903 readSharedUserLP(parser);
8904 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008905 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 } else if (tagName.equals("preferred-activities")) {
8907 readPreferredActivitiesLP(parser);
8908 } else if(tagName.equals("updated-package")) {
8909 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008910 } else if (tagName.equals("cleaning-package")) {
8911 String name = parser.getAttributeValue(null, "name");
8912 if (name != null) {
8913 mPackagesToBeCleaned.add(name);
8914 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008915 } else if (tagName.equals("renamed-package")) {
8916 String nname = parser.getAttributeValue(null, "new");
8917 String oname = parser.getAttributeValue(null, "old");
8918 if (nname != null && oname != null) {
8919 mRenamedPackages.put(nname, oname);
8920 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008921 } else if (tagName.equals("last-platform-version")) {
8922 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8923 try {
8924 String internal = parser.getAttributeValue(null, "internal");
8925 if (internal != null) {
8926 mInternalSdkPlatform = Integer.parseInt(internal);
8927 }
8928 String external = parser.getAttributeValue(null, "external");
8929 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008930 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008931 }
8932 } catch (NumberFormatException e) {
8933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008935 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 + parser.getName());
8937 XmlUtils.skipCurrentTag(parser);
8938 }
8939 }
8940
8941 str.close();
8942
8943 } catch(XmlPullParserException e) {
8944 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07008945 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008946 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947
8948 } catch(java.io.IOException e) {
8949 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07008950 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008951 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952
8953 }
8954
8955 int N = mPendingPackages.size();
8956 for (int i=0; i<N; i++) {
8957 final PendingPackage pp = mPendingPackages.get(i);
8958 Object idObj = getUserIdLP(pp.sharedId);
8959 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008960 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008961 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8962 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008963 if (p == null) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07008964 reportSettingsProblem(Log.WARN, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 + pp.name);
8966 continue;
8967 }
8968 p.copyFrom(pp);
8969 } else if (idObj != null) {
8970 String msg = "Bad package setting: package " + pp.name
8971 + " has shared uid " + pp.sharedId
8972 + " that is not a shared uid\n";
8973 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07008974 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975 } else {
8976 String msg = "Bad package setting: package " + pp.name
8977 + " has shared uid " + pp.sharedId
8978 + " that is not defined\n";
8979 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07008980 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 }
8982 }
8983 mPendingPackages.clear();
8984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 mReadMessages.append("Read completed successfully: "
8986 + mPackages.size() + " packages, "
8987 + mSharedUsers.size() + " shared uids\n");
8988
8989 return true;
8990 }
8991
8992 private int readInt(XmlPullParser parser, String ns, String name,
8993 int defValue) {
8994 String v = parser.getAttributeValue(ns, name);
8995 try {
8996 if (v == null) {
8997 return defValue;
8998 }
8999 return Integer.parseInt(v);
9000 } catch (NumberFormatException e) {
9001 reportSettingsProblem(Log.WARN,
9002 "Error in package manager settings: attribute " +
9003 name + " has bad integer value " + v + " at "
9004 + parser.getPositionDescription());
9005 }
9006 return defValue;
9007 }
9008
9009 private void readPermissionsLP(HashMap<String, BasePermission> out,
9010 XmlPullParser parser)
9011 throws IOException, XmlPullParserException {
9012 int outerDepth = parser.getDepth();
9013 int type;
9014 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9015 && (type != XmlPullParser.END_TAG
9016 || parser.getDepth() > outerDepth)) {
9017 if (type == XmlPullParser.END_TAG
9018 || type == XmlPullParser.TEXT) {
9019 continue;
9020 }
9021
9022 String tagName = parser.getName();
9023 if (tagName.equals("item")) {
9024 String name = parser.getAttributeValue(null, "name");
9025 String sourcePackage = parser.getAttributeValue(null, "package");
9026 String ptype = parser.getAttributeValue(null, "type");
9027 if (name != null && sourcePackage != null) {
9028 boolean dynamic = "dynamic".equals(ptype);
9029 BasePermission bp = new BasePermission(name, sourcePackage,
9030 dynamic
9031 ? BasePermission.TYPE_DYNAMIC
9032 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009033 bp.protectionLevel = readInt(parser, null, "protection",
9034 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 if (dynamic) {
9036 PermissionInfo pi = new PermissionInfo();
9037 pi.packageName = sourcePackage.intern();
9038 pi.name = name.intern();
9039 pi.icon = readInt(parser, null, "icon", 0);
9040 pi.nonLocalizedLabel = parser.getAttributeValue(
9041 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009042 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009043 bp.pendingInfo = pi;
9044 }
9045 out.put(bp.name, bp);
9046 } else {
9047 reportSettingsProblem(Log.WARN,
9048 "Error in package manager settings: permissions has"
9049 + " no name at " + parser.getPositionDescription());
9050 }
9051 } else {
9052 reportSettingsProblem(Log.WARN,
9053 "Unknown element reading permissions: "
9054 + parser.getName() + " at "
9055 + parser.getPositionDescription());
9056 }
9057 XmlUtils.skipCurrentTag(parser);
9058 }
9059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009062 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009063 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009064 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 String codePathStr = parser.getAttributeValue(null, "codePath");
9066 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009067 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009068 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009069 resourcePathStr = codePathStr;
9070 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009071 String version = parser.getAttributeValue(null, "version");
9072 int versionCode = 0;
9073 if (version != null) {
9074 try {
9075 versionCode = Integer.parseInt(version);
9076 } catch (NumberFormatException e) {
9077 }
9078 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009080 int pkgFlags = 0;
9081 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009082 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9083 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009084 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009085 if (timeStampStr != null) {
9086 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009087 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009088 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009089 } catch (NumberFormatException e) {
9090 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009091 } else {
9092 timeStampStr = parser.getAttributeValue(null, "ts");
9093 if (timeStampStr != null) {
9094 try {
9095 long timeStamp = Long.parseLong(timeStampStr);
9096 ps.setTimeStamp(timeStamp);
9097 } catch (NumberFormatException e) {
9098 }
9099 }
9100 }
9101 timeStampStr = parser.getAttributeValue(null, "it");
9102 if (timeStampStr != null) {
9103 try {
9104 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9105 } catch (NumberFormatException e) {
9106 }
9107 }
9108 timeStampStr = parser.getAttributeValue(null, "ut");
9109 if (timeStampStr != null) {
9110 try {
9111 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9112 } catch (NumberFormatException e) {
9113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009114 }
9115 String idStr = parser.getAttributeValue(null, "userId");
9116 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9117 if(ps.userId <= 0) {
9118 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9119 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9120 }
9121 int outerDepth = parser.getDepth();
9122 int type;
9123 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9124 && (type != XmlPullParser.END_TAG
9125 || parser.getDepth() > outerDepth)) {
9126 if (type == XmlPullParser.END_TAG
9127 || type == XmlPullParser.TEXT) {
9128 continue;
9129 }
9130
9131 String tagName = parser.getName();
9132 if (tagName.equals("perms")) {
9133 readGrantedPermissionsLP(parser,
9134 ps.grantedPermissions);
9135 } else {
9136 reportSettingsProblem(Log.WARN,
9137 "Unknown element under <updated-package>: "
9138 + parser.getName());
9139 XmlUtils.skipCurrentTag(parser);
9140 }
9141 }
9142 mDisabledSysPackages.put(name, ps);
9143 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009145 private void readPackageLP(XmlPullParser parser)
9146 throws XmlPullParserException, IOException {
9147 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009148 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 String idStr = null;
9150 String sharedIdStr = null;
9151 String codePathStr = null;
9152 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009153 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009154 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009155 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009156 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009157 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009158 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009159 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009160 long firstInstallTime = 0;
9161 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009162 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009163 String version = null;
9164 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009165 try {
9166 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009167 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009168 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009169 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009170 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9171 codePathStr = parser.getAttributeValue(null, "codePath");
9172 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009173 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009174 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009175 version = parser.getAttributeValue(null, "version");
9176 if (version != null) {
9177 try {
9178 versionCode = Integer.parseInt(version);
9179 } catch (NumberFormatException e) {
9180 }
9181 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009182 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009183
9184 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009185 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009186 try {
9187 pkgFlags = Integer.parseInt(systemStr);
9188 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009189 }
9190 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009191 // For backward compatibility
9192 systemStr = parser.getAttributeValue(null, "system");
9193 if (systemStr != null) {
9194 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9195 } else {
9196 // Old settings that don't specify system... just treat
9197 // them as system, good enough.
9198 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009200 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009201 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009202 if (timeStampStr != null) {
9203 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009204 timeStamp = Long.parseLong(timeStampStr, 16);
9205 } catch (NumberFormatException e) {
9206 }
9207 } else {
9208 timeStampStr = parser.getAttributeValue(null, "ts");
9209 if (timeStampStr != null) {
9210 try {
9211 timeStamp = Long.parseLong(timeStampStr);
9212 } catch (NumberFormatException e) {
9213 }
9214 }
9215 }
9216 timeStampStr = parser.getAttributeValue(null, "it");
9217 if (timeStampStr != null) {
9218 try {
9219 firstInstallTime = Long.parseLong(timeStampStr, 16);
9220 } catch (NumberFormatException e) {
9221 }
9222 }
9223 timeStampStr = parser.getAttributeValue(null, "ut");
9224 if (timeStampStr != null) {
9225 try {
9226 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009227 } catch (NumberFormatException e) {
9228 }
9229 }
9230 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9231 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9232 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9233 if (resourcePathStr == null) {
9234 resourcePathStr = codePathStr;
9235 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009236 if (realName != null) {
9237 realName = realName.intern();
9238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009239 if (name == null) {
9240 reportSettingsProblem(Log.WARN,
9241 "Error in package manager settings: <package> has no name at "
9242 + parser.getPositionDescription());
9243 } else if (codePathStr == null) {
9244 reportSettingsProblem(Log.WARN,
9245 "Error in package manager settings: <package> has no codePath at "
9246 + parser.getPositionDescription());
9247 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009248 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9249 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9250 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009251 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9252 + ": userId=" + userId + " pkg=" + packageSetting);
9253 if (packageSetting == null) {
9254 reportSettingsProblem(Log.ERROR,
9255 "Failure adding uid " + userId
9256 + " while parsing settings at "
9257 + parser.getPositionDescription());
9258 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009259 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009260 packageSetting.firstInstallTime = firstInstallTime;
9261 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009262 }
9263 } else if (sharedIdStr != null) {
9264 userId = sharedIdStr != null
9265 ? Integer.parseInt(sharedIdStr) : 0;
9266 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009267 packageSetting = new PendingPackage(name.intern(), realName,
9268 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009269 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009270 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009271 packageSetting.firstInstallTime = firstInstallTime;
9272 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273 mPendingPackages.add((PendingPackage) packageSetting);
9274 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9275 + ": sharedUserId=" + userId + " pkg="
9276 + packageSetting);
9277 } else {
9278 reportSettingsProblem(Log.WARN,
9279 "Error in package manager settings: package "
9280 + name + " has bad sharedId " + sharedIdStr
9281 + " at " + parser.getPositionDescription());
9282 }
9283 } else {
9284 reportSettingsProblem(Log.WARN,
9285 "Error in package manager settings: package "
9286 + name + " has bad userId " + idStr + " at "
9287 + parser.getPositionDescription());
9288 }
9289 } catch (NumberFormatException e) {
9290 reportSettingsProblem(Log.WARN,
9291 "Error in package manager settings: package "
9292 + name + " has bad userId " + idStr + " at "
9293 + parser.getPositionDescription());
9294 }
9295 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009296 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009297 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009298 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009299 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009300 final String enabledStr = parser.getAttributeValue(null, "enabled");
9301 if (enabledStr != null) {
9302 if (enabledStr.equalsIgnoreCase("true")) {
9303 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9304 } else if (enabledStr.equalsIgnoreCase("false")) {
9305 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9306 } else if (enabledStr.equalsIgnoreCase("default")) {
9307 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9308 } else {
9309 reportSettingsProblem(Log.WARN,
9310 "Error in package manager settings: package "
9311 + name + " has bad enabled value: " + idStr
9312 + " at " + parser.getPositionDescription());
9313 }
9314 } else {
9315 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9316 }
9317 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9318 if (installStatusStr != null) {
9319 if (installStatusStr.equalsIgnoreCase("false")) {
9320 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9321 } else {
9322 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9323 }
9324 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009326 int outerDepth = parser.getDepth();
9327 int type;
9328 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9329 && (type != XmlPullParser.END_TAG
9330 || parser.getDepth() > outerDepth)) {
9331 if (type == XmlPullParser.END_TAG
9332 || type == XmlPullParser.TEXT) {
9333 continue;
9334 }
9335
9336 String tagName = parser.getName();
9337 if (tagName.equals("disabled-components")) {
9338 readDisabledComponentsLP(packageSetting, parser);
9339 } else if (tagName.equals("enabled-components")) {
9340 readEnabledComponentsLP(packageSetting, parser);
9341 } else if (tagName.equals("sigs")) {
9342 packageSetting.signatures.readXml(parser, mPastSignatures);
9343 } else if (tagName.equals("perms")) {
9344 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009345 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 packageSetting.permissionsFixed = true;
9347 } else {
9348 reportSettingsProblem(Log.WARN,
9349 "Unknown element under <package>: "
9350 + parser.getName());
9351 XmlUtils.skipCurrentTag(parser);
9352 }
9353 }
9354 } else {
9355 XmlUtils.skipCurrentTag(parser);
9356 }
9357 }
9358
9359 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9360 XmlPullParser parser)
9361 throws IOException, XmlPullParserException {
9362 int outerDepth = parser.getDepth();
9363 int type;
9364 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9365 && (type != XmlPullParser.END_TAG
9366 || parser.getDepth() > outerDepth)) {
9367 if (type == XmlPullParser.END_TAG
9368 || type == XmlPullParser.TEXT) {
9369 continue;
9370 }
9371
9372 String tagName = parser.getName();
9373 if (tagName.equals("item")) {
9374 String name = parser.getAttributeValue(null, "name");
9375 if (name != null) {
9376 packageSetting.disabledComponents.add(name.intern());
9377 } else {
9378 reportSettingsProblem(Log.WARN,
9379 "Error in package manager settings: <disabled-components> has"
9380 + " no name at " + parser.getPositionDescription());
9381 }
9382 } else {
9383 reportSettingsProblem(Log.WARN,
9384 "Unknown element under <disabled-components>: "
9385 + parser.getName());
9386 }
9387 XmlUtils.skipCurrentTag(parser);
9388 }
9389 }
9390
9391 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9392 XmlPullParser parser)
9393 throws IOException, XmlPullParserException {
9394 int outerDepth = parser.getDepth();
9395 int type;
9396 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9397 && (type != XmlPullParser.END_TAG
9398 || parser.getDepth() > outerDepth)) {
9399 if (type == XmlPullParser.END_TAG
9400 || type == XmlPullParser.TEXT) {
9401 continue;
9402 }
9403
9404 String tagName = parser.getName();
9405 if (tagName.equals("item")) {
9406 String name = parser.getAttributeValue(null, "name");
9407 if (name != null) {
9408 packageSetting.enabledComponents.add(name.intern());
9409 } else {
9410 reportSettingsProblem(Log.WARN,
9411 "Error in package manager settings: <enabled-components> has"
9412 + " no name at " + parser.getPositionDescription());
9413 }
9414 } else {
9415 reportSettingsProblem(Log.WARN,
9416 "Unknown element under <enabled-components>: "
9417 + parser.getName());
9418 }
9419 XmlUtils.skipCurrentTag(parser);
9420 }
9421 }
9422
9423 private void readSharedUserLP(XmlPullParser parser)
9424 throws XmlPullParserException, IOException {
9425 String name = null;
9426 String idStr = null;
9427 int pkgFlags = 0;
9428 SharedUserSetting su = null;
9429 try {
9430 name = parser.getAttributeValue(null, "name");
9431 idStr = parser.getAttributeValue(null, "userId");
9432 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9433 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9434 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9435 }
9436 if (name == null) {
9437 reportSettingsProblem(Log.WARN,
9438 "Error in package manager settings: <shared-user> has no name at "
9439 + parser.getPositionDescription());
9440 } else if (userId == 0) {
9441 reportSettingsProblem(Log.WARN,
9442 "Error in package manager settings: shared-user "
9443 + name + " has bad userId " + idStr + " at "
9444 + parser.getPositionDescription());
9445 } else {
9446 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9447 reportSettingsProblem(Log.ERROR,
9448 "Occurred while parsing settings at "
9449 + parser.getPositionDescription());
9450 }
9451 }
9452 } catch (NumberFormatException e) {
9453 reportSettingsProblem(Log.WARN,
9454 "Error in package manager settings: package "
9455 + name + " has bad userId " + idStr + " at "
9456 + parser.getPositionDescription());
9457 };
9458
9459 if (su != null) {
9460 int outerDepth = parser.getDepth();
9461 int type;
9462 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9463 && (type != XmlPullParser.END_TAG
9464 || parser.getDepth() > outerDepth)) {
9465 if (type == XmlPullParser.END_TAG
9466 || type == XmlPullParser.TEXT) {
9467 continue;
9468 }
9469
9470 String tagName = parser.getName();
9471 if (tagName.equals("sigs")) {
9472 su.signatures.readXml(parser, mPastSignatures);
9473 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009474 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009475 } else {
9476 reportSettingsProblem(Log.WARN,
9477 "Unknown element under <shared-user>: "
9478 + parser.getName());
9479 XmlUtils.skipCurrentTag(parser);
9480 }
9481 }
9482
9483 } else {
9484 XmlUtils.skipCurrentTag(parser);
9485 }
9486 }
9487
9488 private void readGrantedPermissionsLP(XmlPullParser parser,
9489 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9490 int outerDepth = parser.getDepth();
9491 int type;
9492 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9493 && (type != XmlPullParser.END_TAG
9494 || parser.getDepth() > outerDepth)) {
9495 if (type == XmlPullParser.END_TAG
9496 || type == XmlPullParser.TEXT) {
9497 continue;
9498 }
9499
9500 String tagName = parser.getName();
9501 if (tagName.equals("item")) {
9502 String name = parser.getAttributeValue(null, "name");
9503 if (name != null) {
9504 outPerms.add(name.intern());
9505 } else {
9506 reportSettingsProblem(Log.WARN,
9507 "Error in package manager settings: <perms> has"
9508 + " no name at " + parser.getPositionDescription());
9509 }
9510 } else {
9511 reportSettingsProblem(Log.WARN,
9512 "Unknown element under <perms>: "
9513 + parser.getName());
9514 }
9515 XmlUtils.skipCurrentTag(parser);
9516 }
9517 }
9518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009519 private void readPreferredActivitiesLP(XmlPullParser parser)
9520 throws XmlPullParserException, IOException {
9521 int outerDepth = parser.getDepth();
9522 int type;
9523 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9524 && (type != XmlPullParser.END_TAG
9525 || parser.getDepth() > outerDepth)) {
9526 if (type == XmlPullParser.END_TAG
9527 || type == XmlPullParser.TEXT) {
9528 continue;
9529 }
9530
9531 String tagName = parser.getName();
9532 if (tagName.equals("item")) {
9533 PreferredActivity pa = new PreferredActivity(parser);
9534 if (pa.mParseError == null) {
9535 mPreferredActivities.addFilter(pa);
9536 } else {
9537 reportSettingsProblem(Log.WARN,
9538 "Error in package manager settings: <preferred-activity> "
9539 + pa.mParseError + " at "
9540 + parser.getPositionDescription());
9541 }
9542 } else {
9543 reportSettingsProblem(Log.WARN,
9544 "Unknown element under <preferred-activities>: "
9545 + parser.getName());
9546 XmlUtils.skipCurrentTag(parser);
9547 }
9548 }
9549 }
9550
9551 // Returns -1 if we could not find an available UserId to assign
9552 private int newUserIdLP(Object obj) {
9553 // Let's be stupidly inefficient for now...
9554 final int N = mUserIds.size();
9555 for (int i=0; i<N; i++) {
9556 if (mUserIds.get(i) == null) {
9557 mUserIds.set(i, obj);
9558 return FIRST_APPLICATION_UID + i;
9559 }
9560 }
9561
9562 // None left?
9563 if (N >= MAX_APPLICATION_UIDS) {
9564 return -1;
9565 }
9566
9567 mUserIds.add(obj);
9568 return FIRST_APPLICATION_UID + N;
9569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009571 public PackageSetting getDisabledSystemPkg(String name) {
9572 synchronized(mPackages) {
9573 PackageSetting ps = mDisabledSysPackages.get(name);
9574 return ps;
9575 }
9576 }
9577
9578 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009579 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9580 return true;
9581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009582 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9583 if (Config.LOGV) {
9584 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9585 + " componentName = " + componentInfo.name);
9586 Log.v(TAG, "enabledComponents: "
9587 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9588 Log.v(TAG, "disabledComponents: "
9589 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9590 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009591 if (packageSettings == null) {
9592 if (false) {
9593 Log.w(TAG, "WAITING FOR DEBUGGER");
9594 Debug.waitForDebugger();
9595 Log.i(TAG, "We will crash!");
9596 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009597 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009598 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009599 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9600 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9601 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9602 return false;
9603 }
9604 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9605 return true;
9606 }
9607 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9608 return false;
9609 }
9610 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009611 }
9612 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009613
9614 // ------- apps on sdcard specific code -------
9615 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009616 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9617 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9618 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009619 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009620
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009621 private String getEncryptKey() {
9622 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009623 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9624 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009625 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009626 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9627 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009628 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009629 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009630 return null;
9631 }
9632 }
9633 return sdEncKey;
9634 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009635 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009636 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009637 } catch (IOException ioe) {
9638 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9639 + ioe);
9640 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009641 }
Rich Cannings8d578832010-09-09 15:12:40 -07009642
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009643 }
9644
Kenny Rootc78a8072010-07-27 15:18:38 -07009645 /* package */ static String getTempContainerId() {
9646 int tmpIdx = 1;
9647 String list[] = PackageHelper.getSecureContainerList();
9648 if (list != null) {
9649 for (final String name : list) {
9650 // Ignore null and non-temporary container entries
9651 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9652 continue;
9653 }
9654
9655 String subStr = name.substring(mTempContainerPrefix.length());
9656 try {
9657 int cid = Integer.parseInt(subStr);
9658 if (cid >= tmpIdx) {
9659 tmpIdx = cid + 1;
9660 }
9661 } catch (NumberFormatException e) {
9662 }
9663 }
9664 }
9665 return mTempContainerPrefix + tmpIdx;
9666 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009667
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009668 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009669 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009670 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009671 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9672 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9673 throw new SecurityException("Media status can only be updated by the system");
9674 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009675 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009676 Log.i(TAG, "Updating external media status from " +
9677 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9678 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009679 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9680 mediaStatus+", mMediaMounted=" + mMediaMounted);
9681 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009682 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9683 reportStatus ? 1 : 0, -1);
9684 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009685 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009686 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009687 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009688 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009689 // Queue up an async operation since the package installation may take a little while.
9690 mHandler.post(new Runnable() {
9691 public void run() {
9692 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009693 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009694 }
9695 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009696 }
9697
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009698 /*
9699 * Collect information of applications on external media, map them
9700 * against existing containers and update information based on current
9701 * mount status. Please note that we always have to report status
9702 * if reportStatus has been set to true especially when unloading packages.
9703 */
9704 private void updateExternalMediaStatusInner(boolean mediaStatus,
9705 boolean reportStatus) {
9706 // Collection of uids
9707 int uidArr[] = null;
9708 // Collection of stale containers
9709 HashSet<String> removeCids = new HashSet<String>();
9710 // Collection of packages on external media with valid containers.
9711 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9712 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009713 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009714 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009715 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009716 } else {
9717 // Process list of secure containers and categorize them
9718 // as active or stale based on their package internal state.
9719 int uidList[] = new int[list.length];
9720 int num = 0;
9721 synchronized (mPackages) {
9722 for (String cid : list) {
9723 SdInstallArgs args = new SdInstallArgs(cid);
9724 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009725 String pkgName = args.getPackageName();
9726 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009727 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9728 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009729 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009730 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009731 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9732 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009733 // The package status is changed only if the code path
9734 // matches between settings and the container id.
9735 if (ps != null && ps.codePathString != null &&
9736 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009737 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9738 " corresponds to pkg : " + pkgName +
9739 " at code path: " + ps.codePathString);
9740 // We do have a valid package installed on sdcard
9741 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009742 int uid = ps.userId;
9743 if (uid != -1) {
9744 uidList[num++] = uid;
9745 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009746 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009747 // Stale container on sdcard. Just delete
9748 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9749 removeCids.add(cid);
9750 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009751 }
9752 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009753
9754 if (num > 0) {
9755 // Sort uid list
9756 Arrays.sort(uidList, 0, num);
9757 // Throw away duplicates
9758 uidArr = new int[num];
9759 uidArr[0] = uidList[0];
9760 int di = 0;
9761 for (int i = 1; i < num; i++) {
9762 if (uidList[i-1] != uidList[i]) {
9763 uidArr[di++] = uidList[i];
9764 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009765 }
9766 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009767 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009768 // Process packages with valid entries.
9769 if (mediaStatus) {
9770 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009771 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009772 startCleaningPackages();
9773 } else {
9774 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009775 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009776 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009777 }
9778
9779 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009780 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009781 int size = pkgList.size();
9782 if (size > 0) {
9783 // Send broadcasts here
9784 Bundle extras = new Bundle();
9785 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9786 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009787 if (uidArr != null) {
9788 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9789 }
9790 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9791 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009792 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009793 }
9794 }
9795
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009796 /*
9797 * Look at potentially valid container ids from processCids
9798 * If package information doesn't match the one on record
9799 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009800 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009801 */
9802 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009803 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009804 ArrayList<String> pkgList = new ArrayList<String>();
9805 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009806 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009807 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009808 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009809 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9810 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009811 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009812 try {
9813 // Make sure there are no container errors first.
9814 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9815 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009816 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009817 " when installing from sdcard");
9818 continue;
9819 }
9820 // Check code path here.
9821 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009822 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009823 " does not match one in settings " + codePath);
9824 continue;
9825 }
9826 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009827 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009828 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009829 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009830 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009831 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009832 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009833 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009834 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009835 retCode = PackageManager.INSTALL_SUCCEEDED;
9836 pkgList.add(pkg.packageName);
9837 // Post process args
9838 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9839 }
9840 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009841 Slog.i(TAG, "Failed to install pkg from " +
9842 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009843 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009844 }
9845
9846 } finally {
9847 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9848 // Don't destroy container here. Wait till gc clears things up.
9849 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009850 }
9851 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009852 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009853 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009854 // If the platform SDK has changed since the last time we booted,
9855 // we need to re-grant app permission to catch any new ones that
9856 // appear. This is really a hack, and means that apps can in some
9857 // cases get permissions that the user didn't initially explicitly
9858 // allow... it would be nice to have some better way to handle
9859 // this situation.
9860 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9861 != mSdkVersion;
9862 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9863 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9864 + "; regranting permissions for external storage");
9865 mSettings.mExternalSdkPlatform = mSdkVersion;
9866
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009867 // Make sure group IDs have been assigned, and any permission
9868 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009869 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009870 // Persist settings
9871 mSettings.writeLP();
9872 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009873 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009874 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009875 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009876 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009877 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009878 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009879 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009880 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009881 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009882 if (removeCids != null) {
9883 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009884 if (cid.startsWith(mTempContainerPrefix)) {
9885 Log.i(TAG, "Destroying stale temporary container " + cid);
9886 PackageHelper.destroySdDir(cid);
9887 } else {
9888 Log.w(TAG, "Container " + cid + " is stale");
9889 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009890 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009891 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009892 }
9893
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009894 /*
9895 * Utility method to unload a list of specified containers
9896 */
9897 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9898 // Just unmount all valid containers.
9899 for (SdInstallArgs arg : cidArgs) {
9900 synchronized (mInstallLock) {
9901 arg.doPostDeleteLI(false);
9902 }
9903 }
9904 }
9905
9906 /*
9907 * Unload packages mounted on external media. This involves deleting
9908 * package data from internal structures, sending broadcasts about
9909 * diabled packages, gc'ing to free up references, unmounting all
9910 * secure containers corresponding to packages on external media, and
9911 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9912 * Please note that we always have to post this message if status has
9913 * been requested no matter what.
9914 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009915 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009916 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009917 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009918 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009919 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009920 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009921 for (SdInstallArgs args : keys) {
9922 String cid = args.cid;
9923 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009924 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009925 // Delete package internally
9926 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9927 synchronized (mInstallLock) {
9928 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009929 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009930 if (res) {
9931 pkgList.add(pkgName);
9932 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009933 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009934 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009935 }
9936 }
9937 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009938
9939 synchronized (mPackages) {
9940 // We didn't update the settings after removing each package;
9941 // write them now for all packages.
9942 mSettings.writeLP();
9943 }
9944
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009945 // We have to absolutely send UPDATED_MEDIA_STATUS only
9946 // after confirming that all the receivers processed the ordered
9947 // broadcast when packages get disabled, force a gc to clean things up.
9948 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009949 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009950 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9951 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9952 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009953 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9954 reportStatus ? 1 : 0, 1, keys);
9955 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009956 }
9957 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009958 } else {
9959 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9960 reportStatus ? 1 : 0, -1, keys);
9961 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009962 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009963 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009964
9965 public void movePackage(final String packageName,
9966 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009967 mContext.enforceCallingOrSelfPermission(
9968 android.Manifest.permission.MOVE_PACKAGE, null);
9969 int returnCode = PackageManager.MOVE_SUCCEEDED;
9970 int currFlags = 0;
9971 int newFlags = 0;
9972 synchronized (mPackages) {
9973 PackageParser.Package pkg = mPackages.get(packageName);
9974 if (pkg == null) {
9975 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009976 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009977 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009978 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009979 Slog.w(TAG, "Cannot move system application");
9980 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009981 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009982 Slog.w(TAG, "Cannot move forward locked app.");
9983 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009984 } else if (pkg.mOperationPending) {
9985 Slog.w(TAG, "Attempt to move package which has pending operations");
9986 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009987 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009988 // Find install location first
9989 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9990 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9991 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009992 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009993 } else {
9994 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9995 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009996 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9997 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009998 if (newFlags == currFlags) {
9999 Slog.w(TAG, "No move required. Trying to move to same location");
10000 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
10001 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010002 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010003 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10004 pkg.mOperationPending = true;
10005 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010006 }
10007 }
10008 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -070010009 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010010 } else {
10011 Message msg = mHandler.obtainMessage(INIT_COPY);
10012 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -070010013 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
10014 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
10015 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010016 msg.obj = mp;
10017 mHandler.sendMessage(msg);
10018 }
10019 }
10020 }
10021
10022 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10023 // Queue up an async operation since the package deletion may take a little while.
10024 mHandler.post(new Runnable() {
10025 public void run() {
10026 mHandler.removeCallbacks(this);
10027 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010028 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10029 int uidArr[] = null;
10030 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010031 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010032 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010033 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010034 Slog.w(TAG, " Package " + mp.packageName +
10035 " doesn't exist. Aborting move");
10036 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10037 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10038 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10039 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10040 " Aborting move and returning error");
10041 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10042 } else {
10043 uidArr = new int[] { pkg.applicationInfo.uid };
10044 pkgList = new ArrayList<String>();
10045 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010046 }
10047 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010048 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10049 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010050 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010051 // Update package code and resource paths
10052 synchronized (mInstallLock) {
10053 synchronized (mPackages) {
10054 PackageParser.Package pkg = mPackages.get(mp.packageName);
10055 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010056 if (pkg == null) {
10057 Slog.w(TAG, " Package " + mp.packageName
10058 + " doesn't exist. Aborting move");
10059 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010060 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10061 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10062 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10063 " Aborting move and returning error");
10064 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10065 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010066 final String oldCodePath = pkg.mPath;
10067 final String newCodePath = mp.targetArgs.getCodePath();
10068 final String newResPath = mp.targetArgs.getResourcePath();
10069 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010070
10071 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10072 if (mInstaller
10073 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10074 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10075 } else {
10076 NativeLibraryHelper.copyNativeBinariesLI(
10077 new File(newCodePath), new File(newNativePath));
10078 }
10079 } else {
10080 if (mInstaller.linkNativeLibraryDirectory(
10081 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10082 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10083 }
10084 }
10085
10086 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10087 pkg.mPath = newCodePath;
10088 // Move dex files around
10089 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10090 // Moving of dex files failed. Set
10091 // error code and abort move.
10092 pkg.mPath = pkg.mScanPath;
10093 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10094 }
10095 }
10096
10097 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010098 pkg.mScanPath = newCodePath;
10099 pkg.applicationInfo.sourceDir = newCodePath;
10100 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010101 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010102 PackageSetting ps = (PackageSetting) pkg.mExtras;
10103 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10104 ps.codePathString = ps.codePath.getPath();
10105 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10106 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010107 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010108 // Set the application info flag correctly.
10109 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10110 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10111 } else {
10112 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10113 }
10114 ps.setFlags(pkg.applicationInfo.flags);
10115 mAppDirs.remove(oldCodePath);
10116 mAppDirs.put(newCodePath, pkg);
10117 // Persist settings
10118 mSettings.writeLP();
10119 }
10120 }
10121 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010122 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010123 // Send resources available broadcast
10124 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010125 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010126 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010127 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010128 // Clean up failed installation
10129 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010130 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010131 }
10132 } else {
10133 // Force a gc to clear things up.
10134 Runtime.getRuntime().gc();
10135 // Delete older code
10136 synchronized (mInstallLock) {
10137 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010138 }
10139 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010140
10141 // Allow more operations on this file if we didn't fail because
10142 // an operation was already pending for this package.
10143 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10144 synchronized (mPackages) {
10145 PackageParser.Package pkg = mPackages.get(mp.packageName);
10146 if (pkg != null) {
10147 pkg.mOperationPending = false;
10148 }
10149 }
10150 }
10151
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010152 IPackageMoveObserver observer = mp.observer;
10153 if (observer != null) {
10154 try {
10155 observer.packageMoved(mp.packageName, returnCode);
10156 } catch (RemoteException e) {
10157 Log.i(TAG, "Observer no longer exists.");
10158 }
10159 }
10160 }
10161 });
10162 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010163
10164 public boolean setInstallLocation(int loc) {
10165 mContext.enforceCallingOrSelfPermission(
10166 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10167 if (getInstallLocation() == loc) {
10168 return true;
10169 }
10170 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10171 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10172 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10173 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10174 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10175 return true;
10176 }
10177 return false;
10178 }
10179
10180 public int getInstallLocation() {
10181 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10182 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010184}