blob: 4707bbfd988d07fefb362647b4de2df3cf3438d7 [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 Pellycd0e8392010-10-13 17:25:24 -0700147 private static final int NFC_UID = Process.NFC_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private static final int FIRST_APPLICATION_UID =
149 Process.FIRST_APPLICATION_UID;
150 private static final int MAX_APPLICATION_UIDS = 1000;
151
152 private static final boolean SHOW_INFO = false;
153
154 private static final boolean GET_CERTIFICATES = true;
155
Oscar Montemayora8529f62009-11-18 10:14:20 -0800156 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private static final int REMOVE_EVENTS =
159 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
160 private static final int ADD_EVENTS =
161 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
162
163 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800164 // Suffix used during package installation when copying/moving
165 // package apks to install directory.
166 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800168 /**
169 * Indicates the state of installation. Used by PackageManager to
170 * figure out incomplete installations. Say a package is being installed
171 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
172 * the package installation is successful or unsuccesful lin which case
173 * the PackageManager will no longer maintain state information associated
174 * with the package. If some exception(like device freeze or battery being
175 * pulled out) occurs during installation of a package, the PackageManager
176 * needs this information to clean up the previously failed installation.
177 */
178 private static final int PKG_INSTALL_INCOMPLETE = 0;
179 private static final int PKG_INSTALL_COMPLETE = 1;
180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final int SCAN_MONITOR = 1<<0;
182 static final int SCAN_NO_DEX = 1<<1;
183 static final int SCAN_FORCE_DEX = 1<<2;
184 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800185 static final int SCAN_NEW_INSTALL = 1<<4;
186 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700187 static final int SCAN_UPDATE_TIME = 1<<6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700189 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700190
191 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
192
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800193 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700194 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800195 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700196
Kenny Root85387d72010-08-26 10:13:11 -0700197 private static final String LIB_DIR_NAME = "lib";
198
Kenny Rootc78a8072010-07-27 15:18:38 -0700199 static final String mTempContainerPrefix = "smdl2tmp";
200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
202 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700203 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Dianne Hackborn851a5412009-05-08 12:06:44 -0700205 final int mSdkVersion = Build.VERSION.SDK_INT;
206 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
207 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 final Context mContext;
210 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700211 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 final DisplayMetrics mMetrics;
213 final int mDefParseFlags;
214 final String[] mSeparateProcesses;
215
216 // This is where all application persistent data goes.
217 final File mAppDataDir;
218
Oscar Montemayora8529f62009-11-18 10:14:20 -0800219 // If Encrypted File System feature is enabled, all application persistent data
220 // should go here instead.
221 final File mSecureAppDataDir;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // This is the object monitoring the framework dir.
224 final FileObserver mFrameworkInstallObserver;
225
226 // This is the object monitoring the system app dir.
227 final FileObserver mSystemInstallObserver;
228
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700229 // This is the object monitoring the system app dir.
230 final FileObserver mVendorInstallObserver;
231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // This is the object monitoring mAppInstallDir.
233 final FileObserver mAppInstallObserver;
234
235 // This is the object monitoring mDrmAppPrivateInstallDir.
236 final FileObserver mDrmAppInstallObserver;
237
238 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
239 // LOCK HELD. Can be called with mInstallLock held.
240 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 final File mFrameworkDir;
243 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700244 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700246 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
249 // apps.
250 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // Lock for state used when installing and doing other long running
255 // operations. Methods that must be called with this lock held have
256 // the prefix "LI".
257 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 // These are the directories in the 3rd party applications installed dir
260 // that we have currently loaded packages from. Keys are the application's
261 // installed zip file (absolute codePath), and values are Package.
262 final HashMap<String, PackageParser.Package> mAppDirs =
263 new HashMap<String, PackageParser.Package>();
264
265 // Information for the parser to write more useful error messages.
266 File mScanningPath;
267 int mLastScanError;
268
269 final int[] mOutPermissions = new int[3];
270
271 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 // Keys are String (package name), values are Package. This also serves
274 // as the lock for the global state. Methods that must be called with
275 // this lock held have the prefix "LP".
276 final HashMap<String, PackageParser.Package> mPackages =
277 new HashMap<String, PackageParser.Package>();
278
279 final Settings mSettings;
280 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281
282 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
283 int[] mGlobalGids;
284
285 // These are the built-in uid -> permission mappings that were read from the
286 // etc/permissions.xml file.
287 final SparseArray<HashSet<String>> mSystemPermissions =
288 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 // These are the built-in shared libraries that were read from the
291 // etc/permissions.xml file.
292 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
Dianne Hackborn49237342009-08-27 20:08:01 -0700294 // Temporary for building the final shared libraries for an .apk.
295 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800296
Dianne Hackborn49237342009-08-27 20:08:01 -0700297 // These are the features this devices supports that were read from the
298 // etc/permissions.xml file.
299 final HashMap<String, FeatureInfo> mAvailableFeatures =
300 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 // All available activities, for your resolving pleasure.
303 final ActivityIntentResolver mActivities =
304 new ActivityIntentResolver();
305
306 // All available receivers, for your resolving pleasure.
307 final ActivityIntentResolver mReceivers =
308 new ActivityIntentResolver();
309
310 // All available services, for your resolving pleasure.
311 final ServiceIntentResolver mServices = new ServiceIntentResolver();
312
313 // Keys are String (provider class name), values are Provider.
314 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
315 new HashMap<ComponentName, PackageParser.Provider>();
316
317 // Mapping from provider base names (first directory in content URI codePath)
318 // to the provider information.
319 final HashMap<String, PackageParser.Provider> mProviders =
320 new HashMap<String, PackageParser.Provider>();
321
322 // Mapping from instrumentation class names to info about them.
323 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
324 new HashMap<ComponentName, PackageParser.Instrumentation>();
325
326 // Mapping from permission names to info about them.
327 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
328 new HashMap<String, PackageParser.PermissionGroup>();
329
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800330 // Packages whose data we have transfered into another package, thus
331 // should no longer exist.
332 final HashSet<String> mTransferedPackages = new HashSet<String>();
333
Dianne Hackborn854060af2009-07-09 18:14:31 -0700334 // Broadcast actions that are only available to the system.
335 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 boolean mSystemReady;
338 boolean mSafeMode;
339 boolean mHasSystemUidErrors;
340
341 ApplicationInfo mAndroidApplication;
342 final ActivityInfo mResolveActivity = new ActivityInfo();
343 final ResolveInfo mResolveInfo = new ResolveInfo();
344 ComponentName mResolveComponentName;
345 PackageParser.Package mPlatformPackage;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800348 final HashMap<String, ArrayList<String>> mPendingBroadcasts
349 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800350 // Service Connection to remote media container service to copy
351 // package uri's from external media onto secure containers
352 // or internal storage.
353 private IMediaContainerService mContainerService = null;
354
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700355 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800356 static final int MCS_BOUND = 3;
357 static final int END_COPY = 4;
358 static final int INIT_COPY = 5;
359 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800360 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800361 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800362 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800363 static final int MCS_RECONNECT = 10;
364 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700365 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700366 static final int WRITE_SETTINGS = 13;
367
368 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700370 // Delay time in millisecs
371 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372 final private DefaultContainerConnection mDefContainerConn =
373 new DefaultContainerConnection();
374 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800375 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800376 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800377 IMediaContainerService imcs =
378 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800379 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800380 }
381
382 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800383 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800384 }
385 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700386
Christopher Tate1bb69062010-02-19 17:02:12 -0800387 // Recordkeeping of restore-after-install operations that are currently in flight
388 // between the Package Manager and the Backup Manager
389 class PostInstallData {
390 public InstallArgs args;
391 public PackageInstalledInfo res;
392
393 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
394 args = _a;
395 res = _r;
396 }
397 };
398 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
399 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
400
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700401 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800403 final ArrayList<HandlerParams> mPendingInstalls =
404 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800405
406 private boolean connectToService() {
407 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
408 " DefaultContainerService");
409 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700410 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800411 if (mContext.bindService(service, mDefContainerConn,
412 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800414 mBound = true;
415 return true;
416 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700417 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800418 return false;
419 }
420
421 private void disconnectService() {
422 mContainerService = null;
423 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700424 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800425 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800427 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800428
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700429 PackageHandler(Looper looper) {
430 super(looper);
431 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700432
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700433 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700434 try {
435 doHandleMessage(msg);
436 } finally {
437 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
438 }
439 }
440
441 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700442 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800443 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800444 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800445 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800446 int idx = mPendingInstalls.size();
447 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
448 // If a bind was already initiated we dont really
449 // need to do anything. The pending install
450 // will be processed later on.
451 if (!mBound) {
452 // If this is the only one pending we might
453 // have to bind to the service again.
454 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800455 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800456 params.serviceError();
457 return;
458 } else {
459 // Once we bind to the service, the first
460 // pending request will be processed.
461 mPendingInstalls.add(idx, params);
462 }
463 } else {
464 mPendingInstalls.add(idx, params);
465 // Already bound to the service. Just make
466 // sure we trigger off processing the first request.
467 if (idx == 0) {
468 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800469 }
470 }
471 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800472 }
473 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800474 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800475 if (msg.obj != null) {
476 mContainerService = (IMediaContainerService) msg.obj;
477 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 if (mContainerService == null) {
479 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800480 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 for (HandlerParams params : mPendingInstalls) {
482 mPendingInstalls.remove(0);
483 // Indicate service bind error
484 params.serviceError();
485 }
486 mPendingInstalls.clear();
487 } else if (mPendingInstalls.size() > 0) {
488 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800489 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800490 params.startCopy();
491 }
492 } else {
493 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800494 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800495 }
496 break;
497 }
498 case MCS_RECONNECT : {
499 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
500 if (mPendingInstalls.size() > 0) {
501 if (mBound) {
502 disconnectService();
503 }
504 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800505 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800506 for (HandlerParams params : mPendingInstalls) {
507 mPendingInstalls.remove(0);
508 // Indicate service bind error
509 params.serviceError();
510 }
511 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800512 }
513 }
514 break;
515 }
516 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800517 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
518 // Delete pending install
519 if (mPendingInstalls.size() > 0) {
520 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800521 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800522 if (mPendingInstalls.size() == 0) {
523 if (mBound) {
524 disconnectService();
525 }
526 } else {
527 // There are more pending requests in queue.
528 // Just post MCS_BOUND message to trigger processing
529 // of next pending install.
530 mHandler.sendEmptyMessage(MCS_BOUND);
531 }
532 break;
533 }
534 case MCS_GIVE_UP: {
535 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
536 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800537 break;
538 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800540 String packages[];
541 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700543 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700544 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700545 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800546 if (mPendingBroadcasts == null) {
547 return;
548 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700549 size = mPendingBroadcasts.size();
550 if (size <= 0) {
551 // Nothing to be done. Just return
552 return;
553 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 packages = new String[size];
555 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700556 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800557 Iterator<HashMap.Entry<String, ArrayList<String>>>
558 it = mPendingBroadcasts.entrySet().iterator();
559 int i = 0;
560 while (it.hasNext() && i < size) {
561 HashMap.Entry<String, ArrayList<String>> ent = it.next();
562 packages[i] = ent.getKey();
563 components[i] = ent.getValue();
564 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700565 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800566 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700567 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800568 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700569 mPendingBroadcasts.clear();
570 }
571 // Send broadcasts
572 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800573 sendPackageChangedBroadcast(packages[i], true,
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 Pellycd0e8392010-10-13 17:25:24 -0700744 mSettings.addSharedUserLP("android.uid.nfc",
745 MULTIPLE_APPLICATION_UIDS
746 ? NFC_UID : FIRST_APPLICATION_UID,
747 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748
749 String separateProcesses = SystemProperties.get("debug.separate_processes");
750 if (separateProcesses != null && separateProcesses.length() > 0) {
751 if ("*".equals(separateProcesses)) {
752 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
753 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800754 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 } else {
756 mDefParseFlags = 0;
757 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800758 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 + separateProcesses);
760 }
761 } else {
762 mDefParseFlags = 0;
763 mSeparateProcesses = null;
764 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 Installer installer = new Installer();
767 // Little hacky thing to check if installd is here, to determine
768 // whether we are running on the simulator and thus need to take
769 // care of building the /data file structure ourself.
770 // (apparently the sim now has a working installer)
771 if (installer.ping() && Process.supportsProcesses()) {
772 mInstaller = installer;
773 } else {
774 mInstaller = null;
775 }
776
777 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
778 Display d = wm.getDefaultDisplay();
779 d.getMetrics(mMetrics);
780
781 synchronized (mInstallLock) {
782 synchronized (mPackages) {
783 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700784 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 File dataDir = Environment.getDataDirectory();
787 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800788 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
790
791 if (mInstaller == null) {
792 // Make sure these dirs exist, when we are running in
793 // the simulator.
794 // Make a wide-open directory for random misc stuff.
795 File miscDir = new File(dataDir, "misc");
796 miscDir.mkdirs();
797 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800798 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 mDrmAppPrivateInstallDir.mkdirs();
800 }
801
802 readPermissions();
803
804 mRestoredSettings = mSettings.readLP();
805 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806
807 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800809
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800810 // Set flag to monitor and not change apk file paths when
811 // scanning install directories.
812 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700813 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800814 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700821 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700824 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 /**
827 * Out of paranoia, ensure that everything in the boot class
828 * path has been dexed.
829 */
830 String bootClassPath = System.getProperty("java.boot.class.path");
831 if (bootClassPath != null) {
832 String[] paths = splitString(bootClassPath, ':');
833 for (int i=0; i<paths.length; i++) {
834 try {
835 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
836 libFiles.add(paths[i]);
837 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700838 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
840 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800841 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800843 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845 }
846 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800847 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 /**
851 * Also ensure all external libraries have had dexopt run on them.
852 */
853 if (mSharedLibraries.size() > 0) {
854 Iterator<String> libs = mSharedLibraries.values().iterator();
855 while (libs.hasNext()) {
856 String lib = libs.next();
857 try {
858 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
859 libFiles.add(lib);
860 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700861 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
863 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800864 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800866 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
868 }
869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 // Gross hack for now: we know this file doesn't contain any
872 // code, so don't dexopt it to avoid the resulting log spew.
873 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 /**
876 * And there are a number of commands implemented in Java, which
877 * we currently need to do the dexopt on so that they can be
878 * run from a non-root shell.
879 */
880 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700881 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 for (int i=0; i<frameworkFiles.length; i++) {
883 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
884 String path = libPath.getPath();
885 // Skip the file if we alrady did it.
886 if (libFiles.contains(path)) {
887 continue;
888 }
889 // Skip the file if it is not a type we want to dexopt.
890 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
891 continue;
892 }
893 try {
894 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
895 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700896 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 }
898 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800899 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800901 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
903 }
904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800905
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700906 if (didDexOpt) {
907 // If we had to do a dexopt of one of the previous
908 // things, then something on the system has changed.
909 // Consider this significant, and wipe away all other
910 // existing dexopt files to ensure we don't leave any
911 // dangling around.
912 String[] files = mDalvikCacheDir.list();
913 if (files != null) {
914 for (int i=0; i<files.length; i++) {
915 String fn = files[i];
916 if (fn.startsWith("data@app@")
917 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800918 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700919 (new File(mDalvikCacheDir, fn)).delete();
920 }
921 }
922 }
923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800925
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800926 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 mFrameworkInstallObserver = new AppDirObserver(
928 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
929 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700930 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
931 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700932 scanMode | SCAN_NO_DEX, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800933
934 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
936 mSystemInstallObserver = new AppDirObserver(
937 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
938 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700939 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700940 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800941
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700942 // Collect all vendor packages.
943 mVendorAppDir = new File("/vendor/app");
944 mVendorInstallObserver = new AppDirObserver(
945 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
946 mVendorInstallObserver.startWatching();
947 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700948 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700949
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800950 if (mInstaller != null) {
951 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
952 mInstaller.moveFiles();
953 }
954
955 // Prune any system packages that no longer exist.
956 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
957 while (psit.hasNext()) {
958 PackageSetting ps = psit.next();
959 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800960 && !mPackages.containsKey(ps.name)
961 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800962 psit.remove();
963 String msg = "System package " + ps.name
964 + " no longer exists; wiping its data";
965 reportSettingsProblem(Log.WARN, msg);
966 if (mInstaller != null) {
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 }
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001228 permReader.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001230 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001232 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
1234 }
1235
1236 void readPermission(XmlPullParser parser, String name)
1237 throws IOException, XmlPullParserException {
1238
1239 name = name.intern();
1240
1241 BasePermission bp = mSettings.mPermissions.get(name);
1242 if (bp == null) {
1243 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1244 mSettings.mPermissions.put(name, bp);
1245 }
1246 int outerDepth = parser.getDepth();
1247 int type;
1248 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1249 && (type != XmlPullParser.END_TAG
1250 || parser.getDepth() > outerDepth)) {
1251 if (type == XmlPullParser.END_TAG
1252 || type == XmlPullParser.TEXT) {
1253 continue;
1254 }
1255
1256 String tagName = parser.getName();
1257 if ("group".equals(tagName)) {
1258 String gidStr = parser.getAttributeValue(null, "gid");
1259 if (gidStr != null) {
1260 int gid = Process.getGidForName(gidStr);
1261 bp.gids = appendInt(bp.gids, gid);
1262 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001263 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 + parser.getPositionDescription());
1265 }
1266 }
1267 XmlUtils.skipCurrentTag(parser);
1268 }
1269 }
1270
1271 static int[] appendInt(int[] cur, int val) {
1272 if (cur == null) {
1273 return new int[] { val };
1274 }
1275 final int N = cur.length;
1276 for (int i=0; i<N; i++) {
1277 if (cur[i] == val) {
1278 return cur;
1279 }
1280 }
1281 int[] ret = new int[N+1];
1282 System.arraycopy(cur, 0, ret, 0, N);
1283 ret[N] = val;
1284 return ret;
1285 }
1286
1287 static int[] appendInts(int[] cur, int[] add) {
1288 if (add == null) return cur;
1289 if (cur == null) return add;
1290 final int N = add.length;
1291 for (int i=0; i<N; i++) {
1292 cur = appendInt(cur, add[i]);
1293 }
1294 return cur;
1295 }
1296
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001297 static int[] removeInt(int[] cur, int val) {
1298 if (cur == null) {
1299 return null;
1300 }
1301 final int N = cur.length;
1302 for (int i=0; i<N; i++) {
1303 if (cur[i] == val) {
1304 int[] ret = new int[N-1];
1305 if (i > 0) {
1306 System.arraycopy(cur, 0, ret, 0, i);
1307 }
1308 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001309 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001310 }
1311 return ret;
1312 }
1313 }
1314 return cur;
1315 }
1316
1317 static int[] removeInts(int[] cur, int[] rem) {
1318 if (rem == null) return cur;
1319 if (cur == null) return cur;
1320 final int N = rem.length;
1321 for (int i=0; i<N; i++) {
1322 cur = removeInt(cur, rem[i]);
1323 }
1324 return cur;
1325 }
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001328 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1329 // The package has been uninstalled but has retained data and resources.
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001330 return PackageParser.generatePackageInfo(p, null, flags, 0, 0);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 final PackageSetting ps = (PackageSetting)p.mExtras;
1333 if (ps == null) {
1334 return null;
1335 }
1336 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001337 return PackageParser.generatePackageInfo(p, gp.gids, flags,
1338 ps.firstInstallTime, ps.lastUpdateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340
1341 public PackageInfo getPackageInfo(String packageName, int flags) {
1342 synchronized (mPackages) {
1343 PackageParser.Package p = mPackages.get(packageName);
1344 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001345 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 + ": " + p);
1347 if (p != null) {
1348 return generatePackageInfo(p, flags);
1349 }
1350 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1351 return generatePackageInfoFromSettingsLP(packageName, flags);
1352 }
1353 }
1354 return null;
1355 }
1356
Dianne Hackborn47096932010-02-11 15:57:09 -08001357 public String[] currentToCanonicalPackageNames(String[] names) {
1358 String[] out = new String[names.length];
1359 synchronized (mPackages) {
1360 for (int i=names.length-1; i>=0; i--) {
1361 PackageSetting ps = mSettings.mPackages.get(names[i]);
1362 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1363 }
1364 }
1365 return out;
1366 }
1367
1368 public String[] canonicalToCurrentPackageNames(String[] names) {
1369 String[] out = new String[names.length];
1370 synchronized (mPackages) {
1371 for (int i=names.length-1; i>=0; i--) {
1372 String cur = mSettings.mRenamedPackages.get(names[i]);
1373 out[i] = cur != null ? cur : names[i];
1374 }
1375 }
1376 return out;
1377 }
1378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 public int getPackageUid(String packageName) {
1380 synchronized (mPackages) {
1381 PackageParser.Package p = mPackages.get(packageName);
1382 if(p != null) {
1383 return p.applicationInfo.uid;
1384 }
1385 PackageSetting ps = mSettings.mPackages.get(packageName);
1386 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1387 return -1;
1388 }
1389 p = ps.pkg;
1390 return p != null ? p.applicationInfo.uid : -1;
1391 }
1392 }
1393
1394 public int[] getPackageGids(String packageName) {
1395 synchronized (mPackages) {
1396 PackageParser.Package p = mPackages.get(packageName);
1397 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001398 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 + ": " + p);
1400 if (p != null) {
1401 final PackageSetting ps = (PackageSetting)p.mExtras;
1402 final SharedUserSetting suid = ps.sharedUser;
1403 return suid != null ? suid.gids : ps.gids;
1404 }
1405 }
1406 // stupid thing to indicate an error.
1407 return new int[0];
1408 }
1409
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001410 static final PermissionInfo generatePermissionInfo(
1411 BasePermission bp, int flags) {
1412 if (bp.perm != null) {
1413 return PackageParser.generatePermissionInfo(bp.perm, flags);
1414 }
1415 PermissionInfo pi = new PermissionInfo();
1416 pi.name = bp.name;
1417 pi.packageName = bp.sourcePackage;
1418 pi.nonLocalizedLabel = bp.name;
1419 pi.protectionLevel = bp.protectionLevel;
1420 return pi;
1421 }
1422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 public PermissionInfo getPermissionInfo(String name, int flags) {
1424 synchronized (mPackages) {
1425 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001426 if (p != null) {
1427 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 return null;
1430 }
1431 }
1432
1433 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1434 synchronized (mPackages) {
1435 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1436 for (BasePermission p : mSettings.mPermissions.values()) {
1437 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001438 if (p.perm == null || p.perm.info.group == null) {
1439 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001442 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1444 }
1445 }
1446 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 if (out.size() > 0) {
1449 return out;
1450 }
1451 return mPermissionGroups.containsKey(group) ? out : null;
1452 }
1453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1456 synchronized (mPackages) {
1457 return PackageParser.generatePermissionGroupInfo(
1458 mPermissionGroups.get(name), flags);
1459 }
1460 }
1461
1462 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1463 synchronized (mPackages) {
1464 final int N = mPermissionGroups.size();
1465 ArrayList<PermissionGroupInfo> out
1466 = new ArrayList<PermissionGroupInfo>(N);
1467 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1468 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1469 }
1470 return out;
1471 }
1472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1475 PackageSetting ps = mSettings.mPackages.get(packageName);
1476 if(ps != null) {
1477 if(ps.pkg == null) {
1478 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1479 if(pInfo != null) {
1480 return pInfo.applicationInfo;
1481 }
1482 return null;
1483 }
1484 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1485 }
1486 return null;
1487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1490 PackageSetting ps = mSettings.mPackages.get(packageName);
1491 if(ps != null) {
1492 if(ps.pkg == null) {
1493 ps.pkg = new PackageParser.Package(packageName);
1494 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001495 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1496 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1497 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1498 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001499 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001500 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502 return generatePackageInfo(ps.pkg, flags);
1503 }
1504 return null;
1505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1508 synchronized (mPackages) {
1509 PackageParser.Package p = mPackages.get(packageName);
1510 if (Config.LOGV) Log.v(
1511 TAG, "getApplicationInfo " + packageName
1512 + ": " + p);
1513 if (p != null) {
1514 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001515 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517 if ("android".equals(packageName)||"system".equals(packageName)) {
1518 return mAndroidApplication;
1519 }
1520 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1521 return generateApplicationInfoFromSettingsLP(packageName, flags);
1522 }
1523 }
1524 return null;
1525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001526
1527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1529 mContext.enforceCallingOrSelfPermission(
1530 android.Manifest.permission.CLEAR_APP_CACHE, null);
1531 // Queue up an async operation since clearing cache may take a little while.
1532 mHandler.post(new Runnable() {
1533 public void run() {
1534 mHandler.removeCallbacks(this);
1535 int retCode = -1;
1536 if (mInstaller != null) {
1537 retCode = mInstaller.freeCache(freeStorageSize);
1538 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001539 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541 } //end if mInstaller
1542 if (observer != null) {
1543 try {
1544 observer.onRemoveCompleted(null, (retCode >= 0));
1545 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001546 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
1549 }
1550 });
1551 }
1552
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001553 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001554 mContext.enforceCallingOrSelfPermission(
1555 android.Manifest.permission.CLEAR_APP_CACHE, null);
1556 // Queue up an async operation since clearing cache may take a little while.
1557 mHandler.post(new Runnable() {
1558 public void run() {
1559 mHandler.removeCallbacks(this);
1560 int retCode = -1;
1561 if (mInstaller != null) {
1562 retCode = mInstaller.freeCache(freeStorageSize);
1563 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001564 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001565 }
1566 }
1567 if(pi != null) {
1568 try {
1569 // Callback via pending intent
1570 int code = (retCode >= 0) ? 1 : 0;
1571 pi.sendIntent(null, code, null,
1572 null, null);
1573 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001574 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001575 }
1576 }
1577 }
1578 });
1579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1582 synchronized (mPackages) {
1583 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001584
1585 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001587 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 }
1589 if (mResolveComponentName.equals(component)) {
1590 return mResolveActivity;
1591 }
1592 }
1593 return null;
1594 }
1595
1596 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1597 synchronized (mPackages) {
1598 PackageParser.Activity a = mReceivers.mActivities.get(component);
1599 if (Config.LOGV) Log.v(
1600 TAG, "getReceiverInfo " + component + ": " + a);
1601 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1602 return PackageParser.generateActivityInfo(a, flags);
1603 }
1604 }
1605 return null;
1606 }
1607
1608 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1609 synchronized (mPackages) {
1610 PackageParser.Service s = mServices.mServices.get(component);
1611 if (Config.LOGV) Log.v(
1612 TAG, "getServiceInfo " + component + ": " + s);
1613 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1614 return PackageParser.generateServiceInfo(s, flags);
1615 }
1616 }
1617 return null;
1618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001619
Dianne Hackborn361199b2010-08-30 17:42:07 -07001620 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1621 synchronized (mPackages) {
1622 PackageParser.Provider p = mProvidersByComponent.get(component);
1623 if (Config.LOGV) Log.v(
1624 TAG, "getProviderInfo " + component + ": " + p);
1625 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1626 return PackageParser.generateProviderInfo(p, flags);
1627 }
1628 }
1629 return null;
1630 }
1631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 public String[] getSystemSharedLibraryNames() {
1633 Set<String> libSet;
1634 synchronized (mPackages) {
1635 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001636 int size = libSet.size();
1637 if (size > 0) {
1638 String[] libs = new String[size];
1639 libSet.toArray(libs);
1640 return libs;
1641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001643 return null;
1644 }
1645
1646 public FeatureInfo[] getSystemAvailableFeatures() {
1647 Collection<FeatureInfo> featSet;
1648 synchronized (mPackages) {
1649 featSet = mAvailableFeatures.values();
1650 int size = featSet.size();
1651 if (size > 0) {
1652 FeatureInfo[] features = new FeatureInfo[size+1];
1653 featSet.toArray(features);
1654 FeatureInfo fi = new FeatureInfo();
1655 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1656 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1657 features[size] = fi;
1658 return features;
1659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 return null;
1662 }
1663
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001664 public boolean hasSystemFeature(String name) {
1665 synchronized (mPackages) {
1666 return mAvailableFeatures.containsKey(name);
1667 }
1668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 public int checkPermission(String permName, String pkgName) {
1671 synchronized (mPackages) {
1672 PackageParser.Package p = mPackages.get(pkgName);
1673 if (p != null && p.mExtras != null) {
1674 PackageSetting ps = (PackageSetting)p.mExtras;
1675 if (ps.sharedUser != null) {
1676 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1677 return PackageManager.PERMISSION_GRANTED;
1678 }
1679 } else if (ps.grantedPermissions.contains(permName)) {
1680 return PackageManager.PERMISSION_GRANTED;
1681 }
1682 }
1683 }
1684 return PackageManager.PERMISSION_DENIED;
1685 }
1686
1687 public int checkUidPermission(String permName, int uid) {
1688 synchronized (mPackages) {
1689 Object obj = mSettings.getUserIdLP(uid);
1690 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001691 GrantedPermissions gp = (GrantedPermissions)obj;
1692 if (gp.grantedPermissions.contains(permName)) {
1693 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695 } else {
1696 HashSet<String> perms = mSystemPermissions.get(uid);
1697 if (perms != null && perms.contains(permName)) {
1698 return PackageManager.PERMISSION_GRANTED;
1699 }
1700 }
1701 }
1702 return PackageManager.PERMISSION_DENIED;
1703 }
1704
1705 private BasePermission findPermissionTreeLP(String permName) {
1706 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1707 if (permName.startsWith(bp.name) &&
1708 permName.length() > bp.name.length() &&
1709 permName.charAt(bp.name.length()) == '.') {
1710 return bp;
1711 }
1712 }
1713 return null;
1714 }
1715
1716 private BasePermission checkPermissionTreeLP(String permName) {
1717 if (permName != null) {
1718 BasePermission bp = findPermissionTreeLP(permName);
1719 if (bp != null) {
1720 if (bp.uid == Binder.getCallingUid()) {
1721 return bp;
1722 }
1723 throw new SecurityException("Calling uid "
1724 + Binder.getCallingUid()
1725 + " is not allowed to add to permission tree "
1726 + bp.name + " owned by uid " + bp.uid);
1727 }
1728 }
1729 throw new SecurityException("No permission tree found for " + permName);
1730 }
1731
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001732 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1733 if (s1 == null) {
1734 return s2 == null;
1735 }
1736 if (s2 == null) {
1737 return false;
1738 }
1739 if (s1.getClass() != s2.getClass()) {
1740 return false;
1741 }
1742 return s1.equals(s2);
1743 }
1744
1745 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1746 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001747 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001748 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1749 if (!compareStrings(pi1.name, pi2.name)) return false;
1750 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1751 // We'll take care of setting this one.
1752 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1753 // These are not currently stored in settings.
1754 //if (!compareStrings(pi1.group, pi2.group)) return false;
1755 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1756 //if (pi1.labelRes != pi2.labelRes) return false;
1757 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1758 return true;
1759 }
1760
1761 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1762 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1763 throw new SecurityException("Label must be specified in permission");
1764 }
1765 BasePermission tree = checkPermissionTreeLP(info.name);
1766 BasePermission bp = mSettings.mPermissions.get(info.name);
1767 boolean added = bp == null;
1768 boolean changed = true;
1769 if (added) {
1770 bp = new BasePermission(info.name, tree.sourcePackage,
1771 BasePermission.TYPE_DYNAMIC);
1772 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1773 throw new SecurityException(
1774 "Not allowed to modify non-dynamic permission "
1775 + info.name);
1776 } else {
1777 if (bp.protectionLevel == info.protectionLevel
1778 && bp.perm.owner.equals(tree.perm.owner)
1779 && bp.uid == tree.uid
1780 && comparePermissionInfos(bp.perm.info, info)) {
1781 changed = false;
1782 }
1783 }
1784 bp.protectionLevel = info.protectionLevel;
1785 bp.perm = new PackageParser.Permission(tree.perm.owner,
1786 new PermissionInfo(info));
1787 bp.perm.info.packageName = tree.perm.info.packageName;
1788 bp.uid = tree.uid;
1789 if (added) {
1790 mSettings.mPermissions.put(info.name, bp);
1791 }
1792 if (changed) {
1793 if (!async) {
1794 mSettings.writeLP();
1795 } else {
1796 scheduleWriteSettingsLocked();
1797 }
1798 }
1799 return added;
1800 }
1801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 public boolean addPermission(PermissionInfo info) {
1803 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001804 return addPermissionLocked(info, false);
1805 }
1806 }
1807
1808 public boolean addPermissionAsync(PermissionInfo info) {
1809 synchronized (mPackages) {
1810 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
1812 }
1813
1814 public void removePermission(String name) {
1815 synchronized (mPackages) {
1816 checkPermissionTreeLP(name);
1817 BasePermission bp = mSettings.mPermissions.get(name);
1818 if (bp != null) {
1819 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1820 throw new SecurityException(
1821 "Not allowed to modify non-dynamic permission "
1822 + name);
1823 }
1824 mSettings.mPermissions.remove(name);
1825 mSettings.writeLP();
1826 }
1827 }
1828 }
1829
Dianne Hackborn854060af2009-07-09 18:14:31 -07001830 public boolean isProtectedBroadcast(String actionName) {
1831 synchronized (mPackages) {
1832 return mProtectedBroadcasts.contains(actionName);
1833 }
1834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 public int checkSignatures(String pkg1, String pkg2) {
1837 synchronized (mPackages) {
1838 PackageParser.Package p1 = mPackages.get(pkg1);
1839 PackageParser.Package p2 = mPackages.get(pkg2);
1840 if (p1 == null || p1.mExtras == null
1841 || p2 == null || p2.mExtras == null) {
1842 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1843 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001844 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846 }
1847
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001848 public int checkUidSignatures(int uid1, int uid2) {
1849 synchronized (mPackages) {
1850 Signature[] s1;
1851 Signature[] s2;
1852 Object obj = mSettings.getUserIdLP(uid1);
1853 if (obj != null) {
1854 if (obj instanceof SharedUserSetting) {
1855 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1856 } else if (obj instanceof PackageSetting) {
1857 s1 = ((PackageSetting)obj).signatures.mSignatures;
1858 } else {
1859 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1860 }
1861 } else {
1862 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1863 }
1864 obj = mSettings.getUserIdLP(uid2);
1865 if (obj != null) {
1866 if (obj instanceof SharedUserSetting) {
1867 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1868 } else if (obj instanceof PackageSetting) {
1869 s2 = ((PackageSetting)obj).signatures.mSignatures;
1870 } else {
1871 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1872 }
1873 } else {
1874 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1875 }
1876 return checkSignaturesLP(s1, s2);
1877 }
1878 }
1879
1880 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1881 if (s1 == null) {
1882 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1884 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1885 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001886 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1888 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001889 HashSet<Signature> set1 = new HashSet<Signature>();
1890 for (Signature sig : s1) {
1891 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001893 HashSet<Signature> set2 = new HashSet<Signature>();
1894 for (Signature sig : s2) {
1895 set2.add(sig);
1896 }
1897 // Make sure s2 contains all signatures in s1.
1898 if (set1.equals(set2)) {
1899 return PackageManager.SIGNATURE_MATCH;
1900 }
1901 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
1904 public String[] getPackagesForUid(int uid) {
1905 synchronized (mPackages) {
1906 Object obj = mSettings.getUserIdLP(uid);
1907 if (obj instanceof SharedUserSetting) {
1908 SharedUserSetting sus = (SharedUserSetting)obj;
1909 final int N = sus.packages.size();
1910 String[] res = new String[N];
1911 Iterator<PackageSetting> it = sus.packages.iterator();
1912 int i=0;
1913 while (it.hasNext()) {
1914 res[i++] = it.next().name;
1915 }
1916 return res;
1917 } else if (obj instanceof PackageSetting) {
1918 PackageSetting ps = (PackageSetting)obj;
1919 return new String[] { ps.name };
1920 }
1921 }
1922 return null;
1923 }
1924
1925 public String getNameForUid(int uid) {
1926 synchronized (mPackages) {
1927 Object obj = mSettings.getUserIdLP(uid);
1928 if (obj instanceof SharedUserSetting) {
1929 SharedUserSetting sus = (SharedUserSetting)obj;
1930 return sus.name + ":" + sus.userId;
1931 } else if (obj instanceof PackageSetting) {
1932 PackageSetting ps = (PackageSetting)obj;
1933 return ps.name;
1934 }
1935 }
1936 return null;
1937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 public int getUidForSharedUser(String sharedUserName) {
1940 if(sharedUserName == null) {
1941 return -1;
1942 }
1943 synchronized (mPackages) {
1944 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1945 if(suid == null) {
1946 return -1;
1947 }
1948 return suid.userId;
1949 }
1950 }
1951
1952 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1953 int flags) {
1954 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001955 return chooseBestActivity(intent, resolvedType, flags, query);
1956 }
1957
Mihai Predaeae850c2009-05-13 10:13:48 +02001958 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1959 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 if (query != null) {
1961 final int N = query.size();
1962 if (N == 1) {
1963 return query.get(0);
1964 } else if (N > 1) {
1965 // If there is more than one activity with the same priority,
1966 // then let the user decide between them.
1967 ResolveInfo r0 = query.get(0);
1968 ResolveInfo r1 = query.get(1);
1969 if (false) {
1970 System.out.println(r0.activityInfo.name +
1971 "=" + r0.priority + " vs " +
1972 r1.activityInfo.name +
1973 "=" + r1.priority);
1974 }
1975 // If the first activity has a higher priority, or a different
1976 // default, then it is always desireable to pick it.
1977 if (r0.priority != r1.priority
1978 || r0.preferredOrder != r1.preferredOrder
1979 || r0.isDefault != r1.isDefault) {
1980 return query.get(0);
1981 }
1982 // If we have saved a preference for a preferred activity for
1983 // this Intent, use that.
1984 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1985 flags, query, r0.priority);
1986 if (ri != null) {
1987 return ri;
1988 }
1989 return mResolveInfo;
1990 }
1991 }
1992 return null;
1993 }
1994
1995 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1996 int flags, List<ResolveInfo> query, int priority) {
1997 synchronized (mPackages) {
1998 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1999 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02002000 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2002 if (prefs != null && prefs.size() > 0) {
2003 // First figure out how good the original match set is.
2004 // We will only allow preferred activities that came
2005 // from the same match quality.
2006 int match = 0;
2007 final int N = query.size();
2008 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2009 for (int j=0; j<N; j++) {
2010 ResolveInfo ri = query.get(j);
2011 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2012 + ": 0x" + Integer.toHexString(match));
2013 if (ri.match > match) match = ri.match;
2014 }
2015 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2016 + Integer.toHexString(match));
2017 match &= IntentFilter.MATCH_CATEGORY_MASK;
2018 final int M = prefs.size();
2019 for (int i=0; i<M; i++) {
2020 PreferredActivity pa = prefs.get(i);
2021 if (pa.mMatch != match) {
2022 continue;
2023 }
2024 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2025 if (DEBUG_PREFERRED) {
2026 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002027 if (ai != null) {
2028 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2029 } else {
2030 Log.v(TAG, " null");
2031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033 if (ai != null) {
2034 for (int j=0; j<N; j++) {
2035 ResolveInfo ri = query.get(j);
2036 if (!ri.activityInfo.applicationInfo.packageName
2037 .equals(ai.applicationInfo.packageName)) {
2038 continue;
2039 }
2040 if (!ri.activityInfo.name.equals(ai.name)) {
2041 continue;
2042 }
2043
2044 // Okay we found a previously set preferred app.
2045 // If the result set is different from when this
2046 // was created, we need to clear it and re-ask the
2047 // user their preference.
2048 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002049 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 + intent + " type " + resolvedType);
2051 mSettings.mPreferredActivities.removeFilter(pa);
2052 return null;
2053 }
2054
2055 // Yay!
2056 return ri;
2057 }
2058 }
2059 }
2060 }
2061 }
2062 return null;
2063 }
2064
2065 public List<ResolveInfo> queryIntentActivities(Intent intent,
2066 String resolvedType, int flags) {
2067 ComponentName comp = intent.getComponent();
2068 if (comp != null) {
2069 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2070 ActivityInfo ai = getActivityInfo(comp, flags);
2071 if (ai != null) {
2072 ResolveInfo ri = new ResolveInfo();
2073 ri.activityInfo = ai;
2074 list.add(ri);
2075 }
2076 return list;
2077 }
2078
2079 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002080 String pkgName = intent.getPackage();
2081 if (pkgName == null) {
2082 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2083 resolvedType, flags);
2084 }
2085 PackageParser.Package pkg = mPackages.get(pkgName);
2086 if (pkg != null) {
2087 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2088 resolvedType, flags, pkg.activities);
2089 }
2090 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
2093
2094 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2095 Intent[] specifics, String[] specificTypes, Intent intent,
2096 String resolvedType, int flags) {
2097 final String resultsAction = intent.getAction();
2098
2099 List<ResolveInfo> results = queryIntentActivities(
2100 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2101 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2102
2103 int specificsPos = 0;
2104 int N;
2105
2106 // todo: note that the algorithm used here is O(N^2). This
2107 // isn't a problem in our current environment, but if we start running
2108 // into situations where we have more than 5 or 10 matches then this
2109 // should probably be changed to something smarter...
2110
2111 // First we go through and resolve each of the specific items
2112 // that were supplied, taking care of removing any corresponding
2113 // duplicate items in the generic resolve list.
2114 if (specifics != null) {
2115 for (int i=0; i<specifics.length; i++) {
2116 final Intent sintent = specifics[i];
2117 if (sintent == null) {
2118 continue;
2119 }
2120
2121 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2122 String action = sintent.getAction();
2123 if (resultsAction != null && resultsAction.equals(action)) {
2124 // If this action was explicitly requested, then don't
2125 // remove things that have it.
2126 action = null;
2127 }
2128 ComponentName comp = sintent.getComponent();
2129 ResolveInfo ri = null;
2130 ActivityInfo ai = null;
2131 if (comp == null) {
2132 ri = resolveIntent(
2133 sintent,
2134 specificTypes != null ? specificTypes[i] : null,
2135 flags);
2136 if (ri == null) {
2137 continue;
2138 }
2139 if (ri == mResolveInfo) {
2140 // ACK! Must do something better with this.
2141 }
2142 ai = ri.activityInfo;
2143 comp = new ComponentName(ai.applicationInfo.packageName,
2144 ai.name);
2145 } else {
2146 ai = getActivityInfo(comp, flags);
2147 if (ai == null) {
2148 continue;
2149 }
2150 }
2151
2152 // Look for any generic query activities that are duplicates
2153 // of this specific one, and remove them from the results.
2154 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2155 N = results.size();
2156 int j;
2157 for (j=specificsPos; j<N; j++) {
2158 ResolveInfo sri = results.get(j);
2159 if ((sri.activityInfo.name.equals(comp.getClassName())
2160 && sri.activityInfo.applicationInfo.packageName.equals(
2161 comp.getPackageName()))
2162 || (action != null && sri.filter.matchAction(action))) {
2163 results.remove(j);
2164 if (Config.LOGV) Log.v(
2165 TAG, "Removing duplicate item from " + j
2166 + " due to specific " + specificsPos);
2167 if (ri == null) {
2168 ri = sri;
2169 }
2170 j--;
2171 N--;
2172 }
2173 }
2174
2175 // Add this specific item to its proper place.
2176 if (ri == null) {
2177 ri = new ResolveInfo();
2178 ri.activityInfo = ai;
2179 }
2180 results.add(specificsPos, ri);
2181 ri.specificIndex = i;
2182 specificsPos++;
2183 }
2184 }
2185
2186 // Now we go through the remaining generic results and remove any
2187 // duplicate actions that are found here.
2188 N = results.size();
2189 for (int i=specificsPos; i<N-1; i++) {
2190 final ResolveInfo rii = results.get(i);
2191 if (rii.filter == null) {
2192 continue;
2193 }
2194
2195 // Iterate over all of the actions of this result's intent
2196 // filter... typically this should be just one.
2197 final Iterator<String> it = rii.filter.actionsIterator();
2198 if (it == null) {
2199 continue;
2200 }
2201 while (it.hasNext()) {
2202 final String action = it.next();
2203 if (resultsAction != null && resultsAction.equals(action)) {
2204 // If this action was explicitly requested, then don't
2205 // remove things that have it.
2206 continue;
2207 }
2208 for (int j=i+1; j<N; j++) {
2209 final ResolveInfo rij = results.get(j);
2210 if (rij.filter != null && rij.filter.hasAction(action)) {
2211 results.remove(j);
2212 if (Config.LOGV) Log.v(
2213 TAG, "Removing duplicate item from " + j
2214 + " due to action " + action + " at " + i);
2215 j--;
2216 N--;
2217 }
2218 }
2219 }
2220
2221 // If the caller didn't request filter information, drop it now
2222 // so we don't have to marshall/unmarshall it.
2223 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2224 rii.filter = null;
2225 }
2226 }
2227
2228 // Filter out the caller activity if so requested.
2229 if (caller != null) {
2230 N = results.size();
2231 for (int i=0; i<N; i++) {
2232 ActivityInfo ainfo = results.get(i).activityInfo;
2233 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2234 && caller.getClassName().equals(ainfo.name)) {
2235 results.remove(i);
2236 break;
2237 }
2238 }
2239 }
2240
2241 // If the caller didn't request filter information,
2242 // drop them now so we don't have to
2243 // marshall/unmarshall it.
2244 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2245 N = results.size();
2246 for (int i=0; i<N; i++) {
2247 results.get(i).filter = null;
2248 }
2249 }
2250
2251 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2252 return results;
2253 }
2254
2255 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2256 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002257 ComponentName comp = intent.getComponent();
2258 if (comp != null) {
2259 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2260 ActivityInfo ai = getReceiverInfo(comp, flags);
2261 if (ai != null) {
2262 ResolveInfo ri = new ResolveInfo();
2263 ri.activityInfo = ai;
2264 list.add(ri);
2265 }
2266 return list;
2267 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002270 String pkgName = intent.getPackage();
2271 if (pkgName == null) {
2272 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2273 resolvedType, flags);
2274 }
2275 PackageParser.Package pkg = mPackages.get(pkgName);
2276 if (pkg != null) {
2277 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2278 resolvedType, flags, pkg.receivers);
2279 }
2280 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
2282 }
2283
2284 public ResolveInfo resolveService(Intent intent, String resolvedType,
2285 int flags) {
2286 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2287 flags);
2288 if (query != null) {
2289 if (query.size() >= 1) {
2290 // If there is more than one service with the same priority,
2291 // just arbitrarily pick the first one.
2292 return query.get(0);
2293 }
2294 }
2295 return null;
2296 }
2297
2298 public List<ResolveInfo> queryIntentServices(Intent intent,
2299 String resolvedType, int flags) {
2300 ComponentName comp = intent.getComponent();
2301 if (comp != null) {
2302 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2303 ServiceInfo si = getServiceInfo(comp, flags);
2304 if (si != null) {
2305 ResolveInfo ri = new ResolveInfo();
2306 ri.serviceInfo = si;
2307 list.add(ri);
2308 }
2309 return list;
2310 }
2311
2312 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002313 String pkgName = intent.getPackage();
2314 if (pkgName == null) {
2315 return (List<ResolveInfo>)mServices.queryIntent(intent,
2316 resolvedType, flags);
2317 }
2318 PackageParser.Package pkg = mPackages.get(pkgName);
2319 if (pkg != null) {
2320 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2321 resolvedType, flags, pkg.services);
2322 }
2323 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 }
2325 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 public List<PackageInfo> getInstalledPackages(int flags) {
2328 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2329
2330 synchronized (mPackages) {
2331 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2332 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2333 while (i.hasNext()) {
2334 final PackageSetting ps = i.next();
2335 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2336 if(psPkg != null) {
2337 finalList.add(psPkg);
2338 }
2339 }
2340 }
2341 else {
2342 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2343 while (i.hasNext()) {
2344 final PackageParser.Package p = i.next();
2345 if (p.applicationInfo != null) {
2346 PackageInfo pi = generatePackageInfo(p, flags);
2347 if(pi != null) {
2348 finalList.add(pi);
2349 }
2350 }
2351 }
2352 }
2353 }
2354 return finalList;
2355 }
2356
2357 public List<ApplicationInfo> getInstalledApplications(int flags) {
2358 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2359 synchronized(mPackages) {
2360 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2361 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2362 while (i.hasNext()) {
2363 final PackageSetting ps = i.next();
2364 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2365 if(ai != null) {
2366 finalList.add(ai);
2367 }
2368 }
2369 }
2370 else {
2371 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2372 while (i.hasNext()) {
2373 final PackageParser.Package p = i.next();
2374 if (p.applicationInfo != null) {
2375 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2376 if(ai != null) {
2377 finalList.add(ai);
2378 }
2379 }
2380 }
2381 }
2382 }
2383 return finalList;
2384 }
2385
2386 public List<ApplicationInfo> getPersistentApplications(int flags) {
2387 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2388
2389 synchronized (mPackages) {
2390 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2391 while (i.hasNext()) {
2392 PackageParser.Package p = i.next();
2393 if (p.applicationInfo != null
2394 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002395 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002396 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
2398 }
2399 }
2400
2401 return finalList;
2402 }
2403
2404 public ProviderInfo resolveContentProvider(String name, int flags) {
2405 synchronized (mPackages) {
2406 final PackageParser.Provider provider = mProviders.get(name);
2407 return provider != null
2408 && mSettings.isEnabledLP(provider.info, flags)
2409 && (!mSafeMode || (provider.info.applicationInfo.flags
2410 &ApplicationInfo.FLAG_SYSTEM) != 0)
2411 ? PackageParser.generateProviderInfo(provider, flags)
2412 : null;
2413 }
2414 }
2415
Fred Quintana718d8a22009-04-29 17:53:20 -07002416 /**
2417 * @deprecated
2418 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 public void querySyncProviders(List outNames, List outInfo) {
2420 synchronized (mPackages) {
2421 Iterator<Map.Entry<String, PackageParser.Provider>> i
2422 = mProviders.entrySet().iterator();
2423
2424 while (i.hasNext()) {
2425 Map.Entry<String, PackageParser.Provider> entry = i.next();
2426 PackageParser.Provider p = entry.getValue();
2427
2428 if (p.syncable
2429 && (!mSafeMode || (p.info.applicationInfo.flags
2430 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2431 outNames.add(entry.getKey());
2432 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2433 }
2434 }
2435 }
2436 }
2437
2438 public List<ProviderInfo> queryContentProviders(String processName,
2439 int uid, int flags) {
2440 ArrayList<ProviderInfo> finalList = null;
2441
2442 synchronized (mPackages) {
2443 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2444 while (i.hasNext()) {
2445 PackageParser.Provider p = i.next();
2446 if (p.info.authority != null
2447 && (processName == null ||
2448 (p.info.processName.equals(processName)
2449 && p.info.applicationInfo.uid == uid))
2450 && mSettings.isEnabledLP(p.info, flags)
2451 && (!mSafeMode || (p.info.applicationInfo.flags
2452 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2453 if (finalList == null) {
2454 finalList = new ArrayList<ProviderInfo>(3);
2455 }
2456 finalList.add(PackageParser.generateProviderInfo(p,
2457 flags));
2458 }
2459 }
2460 }
2461
2462 if (finalList != null) {
2463 Collections.sort(finalList, mProviderInitOrderSorter);
2464 }
2465
2466 return finalList;
2467 }
2468
2469 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2470 int flags) {
2471 synchronized (mPackages) {
2472 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2473 return PackageParser.generateInstrumentationInfo(i, flags);
2474 }
2475 }
2476
2477 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2478 int flags) {
2479 ArrayList<InstrumentationInfo> finalList =
2480 new ArrayList<InstrumentationInfo>();
2481
2482 synchronized (mPackages) {
2483 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2484 while (i.hasNext()) {
2485 PackageParser.Instrumentation p = i.next();
2486 if (targetPackage == null
2487 || targetPackage.equals(p.info.targetPackage)) {
2488 finalList.add(PackageParser.generateInstrumentationInfo(p,
2489 flags));
2490 }
2491 }
2492 }
2493
2494 return finalList;
2495 }
2496
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002497 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002499 if (files == null) {
2500 Log.d(TAG, "No files in app dir " + dir);
2501 return;
2502 }
2503
Joe Onorato431bb222010-10-18 19:13:23 -04002504 if (false) {
2505 Log.d(TAG, "Scanning app dir " + dir);
2506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507
2508 int i;
2509 for (i=0; i<files.length; i++) {
2510 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002511 if (!isPackageFilename(files[i])) {
2512 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002513 continue;
2514 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002515 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002516 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002517 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002518 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2519 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002520 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002521 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002522 file.delete();
2523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 }
2525 }
2526
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002527 private static File getSettingsProblemFile() {
2528 File dataDir = Environment.getDataDirectory();
2529 File systemDir = new File(dataDir, "system");
2530 File fname = new File(systemDir, "uiderrors.txt");
2531 return fname;
2532 }
2533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 private static void reportSettingsProblem(int priority, String msg) {
2535 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002536 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 FileOutputStream out = new FileOutputStream(fname, true);
2538 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002539 SimpleDateFormat formatter = new SimpleDateFormat();
2540 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2541 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 pw.close();
2543 FileUtils.setPermissions(
2544 fname.toString(),
2545 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2546 -1, -1);
2547 } catch (java.io.IOException e) {
2548 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002549 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 }
2551
2552 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2553 PackageParser.Package pkg, File srcFile, int parseFlags) {
2554 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002555 if (ps != null
2556 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002557 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002558 if (ps.signatures.mSignatures != null
2559 && ps.signatures.mSignatures.length != 0) {
2560 // Optimization: reuse the existing cached certificates
2561 // if the package appears to be unchanged.
2562 pkg.mSignatures = ps.signatures.mSignatures;
2563 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
Jeff Browne7600722010-04-07 18:28:23 -07002565
2566 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002567 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002568 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2569 }
2570
2571 if (!pp.collectCertificates(pkg, parseFlags)) {
2572 mLastScanError = pp.getParseError();
2573 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 }
2576 return true;
2577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 /*
2580 * Scan a package and return the newly parsed package.
2581 * Returns null in case of errors and the error code is stored in mLastScanError
2582 */
2583 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002584 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002586 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002588 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 if (pkg == null) {
2593 mLastScanError = pp.getParseError();
2594 return null;
2595 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002596 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 PackageSetting updatedPkg;
2598 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002599 // Look to see if we already know about this package.
2600 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002601 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002602 // This package has been renamed to its original name. Let's
2603 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002604 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002605 }
2606 // If there was no original package, see one for the real package name.
2607 if (ps == null) {
2608 ps = mSettings.peekPackageLP(pkg.packageName);
2609 }
2610 // Check to see if this package could be hiding/updating a system
2611 // package. Must look for it either under the original or real
2612 // package name depending on our state.
2613 updatedPkg = mSettings.mDisabledSysPackages.get(
2614 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 // First check if this is a system package that may involve an update
2617 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002618 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 // The path has changed from what was last scanned... check the
2620 // version of the new path against what we have stored to determine
2621 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002622 if (pkg.mVersionCode < ps.versionCode) {
2623 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002624 // Ignore entry. Skip it.
2625 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002626 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002627 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002628 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2629 return null;
2630 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002631 // The current app on the system partion is better than
2632 // what we have updated to on the data partition; switch
2633 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002634 // At this point, its safely assumed that package installation for
2635 // apps in system partition will go through. If not there won't be a working
2636 // version of the app
2637 synchronized (mPackages) {
2638 // Just remove the loaded entries from package lists.
2639 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002640 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002641 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002642 + "reverting from " + ps.codePathString
2643 + ": new version " + pkg.mVersionCode
2644 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002645 InstallArgs args = new FileInstallArgs(ps.codePathString,
2646 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002647 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002648 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 }
2651 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002652 if (updatedPkg != null) {
2653 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2654 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2655 }
2656 // Verify certificates against what was last scanned
2657 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002658 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002659 return null;
2660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 // The apk is forward locked (not public) if its code and resources
2662 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002663 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002665 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002666 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002667
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002668 String codePath = null;
2669 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002670 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2671 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002672 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002673 } else {
2674 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002675 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002676 }
2677 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002678 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002679 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002680 codePath = pkg.mScanPath;
2681 // Set application objects path explicitly.
2682 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002684 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 }
2686
Kenny Root85387d72010-08-26 10:13:11 -07002687 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2688 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002689 pkg.mPath = pkg.mScanPath = destCodePath;
2690 pkg.applicationInfo.sourceDir = destCodePath;
2691 pkg.applicationInfo.publicSourceDir = destResPath;
2692 }
2693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 private static String fixProcessName(String defProcessName,
2695 String processName, int uid) {
2696 if (processName == null) {
2697 return defProcessName;
2698 }
2699 return processName;
2700 }
2701
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002702 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002703 PackageParser.Package pkg) {
2704 if (pkgSetting.signatures.mSignatures != null) {
2705 // Already existing package. Make sure signatures match
2706 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2707 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002708 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002709 + " signatures do not match the previously installed version; ignoring!");
2710 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 return false;
2712 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002713 }
2714 // Check for shared user signatures
2715 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2716 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2717 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2718 Slog.e(TAG, "Package " + pkg.packageName
2719 + " has no signatures that match those in shared user "
2720 + pkgSetting.sharedUser.name + "; ignoring!");
2721 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2722 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
2725 return true;
2726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002727
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002728 public boolean performDexOpt(String packageName) {
2729 if (!mNoDexOpt) {
2730 return false;
2731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002733 PackageParser.Package p;
2734 synchronized (mPackages) {
2735 p = mPackages.get(packageName);
2736 if (p == null || p.mDidDexOpt) {
2737 return false;
2738 }
2739 }
2740 synchronized (mInstallLock) {
2741 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2742 }
2743 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002744
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002745 static final int DEX_OPT_SKIPPED = 0;
2746 static final int DEX_OPT_PERFORMED = 1;
2747 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002748
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002749 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2750 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002751 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002752 String path = pkg.mScanPath;
2753 int ret = 0;
2754 try {
2755 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002756 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002757 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002758 pkg.mDidDexOpt = true;
2759 performed = true;
2760 }
2761 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002762 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002763 ret = -1;
2764 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002765 Slog.w(TAG, "IOException reading apk: " + path, e);
2766 ret = -1;
2767 } catch (dalvik.system.StaleDexCacheError e) {
2768 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2769 ret = -1;
2770 } catch (Exception e) {
2771 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002772 ret = -1;
2773 }
2774 if (ret < 0) {
2775 //error from installer
2776 return DEX_OPT_FAILED;
2777 }
2778 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002779
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002780 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2781 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002782
2783 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2784 return Environment.isEncryptedFilesystemEnabled() &&
2785 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2786 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002787
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002788 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2789 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002790 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002791 + " to " + newPkg.packageName
2792 + ": old package not in system partition");
2793 return false;
2794 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002795 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002796 + " to " + newPkg.packageName
2797 + ": old package still exists");
2798 return false;
2799 }
2800 return true;
2801 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002802
2803 private File getDataPathForPackage(PackageParser.Package pkg) {
2804 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2805 File dataPath;
2806 if (useEncryptedFSDir) {
2807 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2808 } else {
2809 dataPath = new File(mAppDataDir, pkg.packageName);
2810 }
2811 return dataPath;
2812 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002813
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002814 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002815 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002816 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002817 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2818 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002819 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002820 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002821 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2822 return null;
2823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 mScanningPath = scanFile;
2825 if (pkg == null) {
2826 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2827 return null;
2828 }
2829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2831 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2832 }
2833
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002834 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 synchronized (mPackages) {
2836 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002837 Slog.w(TAG, "*************************************************");
2838 Slog.w(TAG, "Core android package being redefined. Skipping.");
2839 Slog.w(TAG, " file=" + mScanningPath);
2840 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2842 return null;
2843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 // Set up information for our fall-back user intent resolution
2846 // activity.
2847 mPlatformPackage = pkg;
2848 pkg.mVersionCode = mSdkVersion;
2849 mAndroidApplication = pkg.applicationInfo;
2850 mResolveActivity.applicationInfo = mAndroidApplication;
2851 mResolveActivity.name = ResolverActivity.class.getName();
2852 mResolveActivity.packageName = mAndroidApplication.packageName;
2853 mResolveActivity.processName = mAndroidApplication.processName;
2854 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2855 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
Joe Onorato646f46e2010-11-08 15:08:56 -08002856 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 mResolveActivity.exported = true;
2858 mResolveActivity.enabled = true;
2859 mResolveInfo.activityInfo = mResolveActivity;
2860 mResolveInfo.priority = 0;
2861 mResolveInfo.preferredOrder = 0;
2862 mResolveInfo.match = 0;
2863 mResolveComponentName = new ComponentName(
2864 mAndroidApplication.packageName, mResolveActivity.name);
2865 }
2866 }
2867
2868 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002869 TAG, "Scanning package " + pkg.packageName);
2870 if (mPackages.containsKey(pkg.packageName)
2871 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002872 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2875 return null;
2876 }
2877
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002878 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002879 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2880 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 SharedUserSetting suid = null;
2883 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002884
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002885 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2886 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002887 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002888 pkg.mRealPackage = null;
2889 pkg.mAdoptPermissions = null;
2890 }
2891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 synchronized (mPackages) {
2893 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002894 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2895 if (mTmpSharedLibraries == null ||
2896 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2897 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2898 }
2899 int num = 0;
2900 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2901 for (int i=0; i<N; i++) {
2902 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002904 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002906 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2908 return null;
2909 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002910 mTmpSharedLibraries[num] = file;
2911 num++;
2912 }
2913 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2914 for (int i=0; i<N; i++) {
2915 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2916 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002917 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002918 + " desires unavailable shared library "
2919 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2920 } else {
2921 mTmpSharedLibraries[num] = file;
2922 num++;
2923 }
2924 }
2925 if (num > 0) {
2926 pkg.usesLibraryFiles = new String[num];
2927 System.arraycopy(mTmpSharedLibraries, 0,
2928 pkg.usesLibraryFiles, 0, num);
2929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002930
Dianne Hackborn49237342009-08-27 20:08:01 -07002931 if (pkg.reqFeatures != null) {
2932 N = pkg.reqFeatures.size();
2933 for (int i=0; i<N; i++) {
2934 FeatureInfo fi = pkg.reqFeatures.get(i);
2935 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2936 // Don't care.
2937 continue;
2938 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002939
Dianne Hackborn49237342009-08-27 20:08:01 -07002940 if (fi.name != null) {
2941 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002942 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002943 + " requires unavailable feature "
2944 + fi.name + "; failing!");
2945 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2946 return null;
2947 }
2948 }
2949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
2951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 if (pkg.mSharedUserId != null) {
2954 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2955 pkg.applicationInfo.flags, true);
2956 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002957 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 + " for shared user failed");
2959 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2960 return null;
2961 }
2962 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2963 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2964 + suid.userId + "): packages=" + suid.packages);
2965 }
2966 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002967
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002968 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002969 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002970 Log.w(TAG, "WAITING FOR DEBUGGER");
2971 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002972 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2973 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002974 }
2975 }
2976
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002977 // Check if we are renaming from an original package name.
2978 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002979 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002980 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002981 // This package may need to be renamed to a previously
2982 // installed name. Let's check on that...
2983 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002984 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002985 // This package had originally been installed as the
2986 // original name, and we have already taken care of
2987 // transitioning to the new one. Just update the new
2988 // one to continue using the old name.
2989 realName = pkg.mRealPackage;
2990 if (!pkg.packageName.equals(renamed)) {
2991 // Callers into this function may have already taken
2992 // care of renaming the package; only do it here if
2993 // it is not already done.
2994 pkg.setPackageName(renamed);
2995 }
2996
Dianne Hackbornc1552392010-03-03 16:19:01 -08002997 } else {
2998 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2999 if ((origPackage=mSettings.peekPackageLP(
3000 pkg.mOriginalPackages.get(i))) != null) {
3001 // We do have the package already installed under its
3002 // original name... should we use it?
3003 if (!verifyPackageUpdate(origPackage, pkg)) {
3004 // New package is not compatible with original.
3005 origPackage = null;
3006 continue;
3007 } else if (origPackage.sharedUser != null) {
3008 // Make sure uid is compatible between packages.
3009 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003010 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003011 + " to " + pkg.packageName + ": old uid "
3012 + origPackage.sharedUser.name
3013 + " differs from " + pkg.mSharedUserId);
3014 origPackage = null;
3015 continue;
3016 }
3017 } else {
3018 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3019 + pkg.packageName + " to old name " + origPackage.name);
3020 }
3021 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003022 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003023 }
3024 }
3025 }
3026
3027 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003028 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003029 + " was transferred to another, but its .apk remains");
3030 }
3031
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003032 // Just create the setting, don't add it yet. For already existing packages
3033 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003034 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003035 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3036 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003038 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3040 return null;
3041 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003042
3043 if (pkgSetting.origPackage != null) {
3044 // If we are first transitioning from an original package,
3045 // fix up the new package's name now. We need to do this after
3046 // looking up the package under its new name, so getPackageLP
3047 // can take care of fiddling things correctly.
3048 pkg.setPackageName(origPackage.name);
3049
3050 // File a report about this.
3051 String msg = "New package " + pkgSetting.realName
3052 + " renamed to replace old package " + pkgSetting.name;
3053 reportSettingsProblem(Log.WARN, msg);
3054
3055 // Make a note of it.
3056 mTransferedPackages.add(origPackage.name);
3057
3058 // No longer need to retain this.
3059 pkgSetting.origPackage = null;
3060 }
3061
3062 if (realName != null) {
3063 // Make a note of it.
3064 mTransferedPackages.add(pkg.packageName);
3065 }
3066
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003067 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3069 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 pkg.applicationInfo.uid = pkgSetting.userId;
3072 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003073
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003074 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003075 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 return null;
3077 }
3078 // The signature has changed, but this package is in the system
3079 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003080 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 // However... if this package is part of a shared user, but it
3082 // doesn't match the signature of the shared user, let's fail.
3083 // What this means is that you can't change the signatures
3084 // associated with an overall shared user, which doesn't seem all
3085 // that unreasonable.
3086 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003087 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3088 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3089 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3091 return null;
3092 }
3093 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003094 // File a report about this.
3095 String msg = "System package " + pkg.packageName
3096 + " signature changed; retaining data.";
3097 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003099
The Android Open Source Project10592532009-03-18 17:39:46 -07003100 // Verify that this new package doesn't have any content providers
3101 // that conflict with existing packages. Only do this if the
3102 // package isn't already installed, since we don't want to break
3103 // things that are installed.
3104 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3105 int N = pkg.providers.size();
3106 int i;
3107 for (i=0; i<N; i++) {
3108 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003109 if (p.info.authority != null) {
3110 String names[] = p.info.authority.split(";");
3111 for (int j = 0; j < names.length; j++) {
3112 if (mProviders.containsKey(names[j])) {
3113 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003114 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003115 " (in package " + pkg.applicationInfo.packageName +
3116 ") is already used by "
3117 + ((other != null && other.getComponentName() != null)
3118 ? other.getComponentName().getPackageName() : "?"));
3119 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3120 return null;
3121 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003122 }
3123 }
3124 }
3125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 }
3127
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003128 final String pkgName = pkg.packageName;
3129
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003130 if (pkg.mAdoptPermissions != null) {
3131 // This package wants to adopt ownership of permissions from
3132 // another package.
3133 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3134 String origName = pkg.mAdoptPermissions.get(i);
3135 PackageSetting orig = mSettings.peekPackageLP(origName);
3136 if (orig != null) {
3137 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003138 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003139 + origName + " to " + pkg.packageName);
3140 mSettings.transferPermissions(origName, pkg.packageName);
3141 }
3142 }
3143 }
3144 }
3145
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003146 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003148 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 pkg.applicationInfo.processName = fixProcessName(
3150 pkg.applicationInfo.packageName,
3151 pkg.applicationInfo.processName,
3152 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003153
3154 File dataPath;
3155 if (mPlatformPackage == pkg) {
3156 // The system package is special.
3157 dataPath = new File (Environment.getDataDirectory(), "system");
3158 pkg.applicationInfo.dataDir = dataPath.getPath();
3159 } else {
3160 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003161 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003162 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003163
3164 boolean uidError = false;
3165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 if (dataPath.exists()) {
3167 mOutPermissions[1] = 0;
3168 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003169
3170 // If we have mismatched owners for the data path, we have a
3171 // problem (unless we're running in the simulator.)
3172 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 boolean recovered = false;
3174 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3175 // If this is a system app, we can at least delete its
3176 // current data so the application will still work.
3177 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003178 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003179 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 // Old data gone!
3181 String msg = "System package " + pkg.packageName
3182 + " has changed from uid: "
3183 + mOutPermissions[1] + " to "
3184 + pkg.applicationInfo.uid + "; old data erased";
3185 reportSettingsProblem(Log.WARN, msg);
3186 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003189 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 pkg.applicationInfo.uid);
3191 if (ret == -1) {
3192 // Ack should not happen!
3193 msg = "System package " + pkg.packageName
3194 + " could not have data directory re-created after delete.";
3195 reportSettingsProblem(Log.WARN, msg);
3196 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3197 return null;
3198 }
3199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 if (!recovered) {
3202 mHasSystemUidErrors = true;
3203 }
3204 }
3205 if (!recovered) {
3206 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3207 + pkg.applicationInfo.uid + "/fs_"
3208 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003209 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 String msg = "Package " + pkg.packageName
3211 + " has mismatched uid: "
3212 + mOutPermissions[1] + " on disk, "
3213 + pkg.applicationInfo.uid + " in settings";
3214 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003215 mSettings.mReadMessages.append(msg);
3216 mSettings.mReadMessages.append('\n');
3217 uidError = true;
3218 if (!pkgSetting.uidError) {
3219 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 }
3222 }
3223 }
3224 pkg.applicationInfo.dataDir = dataPath.getPath();
3225 } else {
3226 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3227 Log.v(TAG, "Want this data dir: " + dataPath);
3228 //invoke installer to do the actual installation
3229 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003230 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 pkg.applicationInfo.uid);
3232 if(ret < 0) {
3233 // Error from installer
3234 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3235 return null;
3236 }
3237 } else {
3238 dataPath.mkdirs();
3239 if (dataPath.exists()) {
3240 FileUtils.setPermissions(
3241 dataPath.toString(),
3242 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3243 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3244 }
3245 }
3246 if (dataPath.exists()) {
3247 pkg.applicationInfo.dataDir = dataPath.getPath();
3248 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003249 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 pkg.applicationInfo.dataDir = null;
3251 }
3252 }
Kenny Root85387d72010-08-26 10:13:11 -07003253
3254 /*
3255 * Set the data dir to the default "/data/data/<package name>/lib"
3256 * if we got here without anyone telling us different (e.g., apps
3257 * stored on SD card have their native libraries stored in the ASEC
3258 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003259 *
3260 * This happens during an upgrade from a package settings file that
3261 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003262 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003263 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3264 if (pkgSetting.nativeLibraryPathString == null) {
3265 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3266 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3267 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3268 } else {
3269 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3270 }
Kenny Root85387d72010-08-26 10:13:11 -07003271 }
3272
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003273 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 }
3275
Kenny Root85387d72010-08-26 10:13:11 -07003276 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 if (mInstaller != null) {
3278 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003279 /* Note: We don't want to unpack the native binaries for
3280 * system applications, unless they have been updated
3281 * (the binaries are already under /system/lib).
3282 * Also, don't unpack libs for apps on the external card
3283 * since they should have their libraries in the ASEC
3284 * container already.
3285 *
3286 * In other words, we're going to unpack the binaries
3287 * only for non-system apps and system app upgrades.
3288 */
Kenny Root831baa22010-10-05 12:29:25 -07003289 if (pkg.applicationInfo.nativeLibraryDir != null) {
Kenny Roote68d58a2010-10-18 16:08:54 -07003290 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3291 final String dataPathString = dataPath.getPath();
3292
Kenny Root831baa22010-10-05 12:29:25 -07003293 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3294 /*
3295 * Upgrading from a previous version of the OS sometimes
3296 * leaves native libraries in the /data/data/<app>/lib
3297 * directory for system apps even when they shouldn't be.
3298 * Recent changes in the JNI library search path
3299 * necessitates we remove those to match previous behavior.
3300 */
Kenny Roote68d58a2010-10-18 16:08:54 -07003301 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Kenny Root831baa22010-10-05 12:29:25 -07003302 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3303 }
Kenny Roote68d58a2010-10-18 16:08:54 -07003304 } else if (nativeLibraryDir.getParent().equals(dataPathString)) {
3305 /*
3306 * If this is an internal application or our
3307 * nativeLibraryPath points to our data directory, unpack
3308 * the libraries. The native library path pointing to the
3309 * data directory for an application in an ASEC container
3310 * can happen for older apps that existed before an OTA to
3311 * Gingerbread.
3312 */
3313 Slog.i(TAG, "Unpacking native libraries for " + path);
3314 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
3315 NativeLibraryHelper.copyNativeBinariesLI(scanFile, nativeLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003316 } else {
Kenny Roote68d58a2010-10-18 16:08:54 -07003317 Slog.i(TAG, "Linking native library dir for " + path);
3318 mInstaller.linkNativeLibraryDirectory(dataPathString,
Kenny Root6a6b0072010-10-07 16:46:10 -07003319 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003322 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003323
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003324 if ((scanMode&SCAN_NO_DEX) == 0) {
3325 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3327 return null;
3328 }
3329 }
3330 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 if (mFactoryTest && pkg.requestedPermissions.contains(
3333 android.Manifest.permission.FACTORY_TEST)) {
3334 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3335 }
3336
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003337 // Request the ActivityManager to kill the process(only for existing packages)
3338 // so that we do not end up in a confused state while the user is still using the older
3339 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003340 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003341 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003342 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003343 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003346 // We don't expect installation to fail beyond this point,
3347 if ((scanMode&SCAN_MONITOR) != 0) {
3348 mAppDirs.put(pkg.mPath, pkg);
3349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003351 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003353 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003354 // Make sure we don't accidentally delete its data.
3355 mSettings.mPackagesToBeCleaned.remove(pkgName);
3356
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003357 // Take care of first install / last update times.
3358 if (currentTime != 0) {
3359 if (pkgSetting.firstInstallTime == 0) {
3360 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3361 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3362 pkgSetting.lastUpdateTime = currentTime;
3363 }
3364 } else if (pkgSetting.firstInstallTime == 0) {
3365 // We need *something*. Take time time stamp of the file.
3366 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3367 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3368 if (scanFileTime != pkgSetting.timeStamp) {
3369 // A package on the system image has changed; consider this
3370 // to be an update.
3371 pkgSetting.lastUpdateTime = scanFileTime;
3372 }
3373 }
3374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 int N = pkg.providers.size();
3376 StringBuilder r = null;
3377 int i;
3378 for (i=0; i<N; i++) {
3379 PackageParser.Provider p = pkg.providers.get(i);
3380 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3381 p.info.processName, pkg.applicationInfo.uid);
3382 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3383 p.info.name), p);
3384 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003385 if (p.info.authority != null) {
3386 String names[] = p.info.authority.split(";");
3387 p.info.authority = null;
3388 for (int j = 0; j < names.length; j++) {
3389 if (j == 1 && p.syncable) {
3390 // We only want the first authority for a provider to possibly be
3391 // syncable, so if we already added this provider using a different
3392 // authority clear the syncable flag. We copy the provider before
3393 // changing it because the mProviders object contains a reference
3394 // to a provider that we don't want to change.
3395 // Only do this for the second authority since the resulting provider
3396 // object can be the same for all future authorities for this provider.
3397 p = new PackageParser.Provider(p);
3398 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003400 if (!mProviders.containsKey(names[j])) {
3401 mProviders.put(names[j], p);
3402 if (p.info.authority == null) {
3403 p.info.authority = names[j];
3404 } else {
3405 p.info.authority = p.info.authority + ";" + names[j];
3406 }
3407 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3408 Log.d(TAG, "Registered content provider: " + names[j] +
3409 ", className = " + p.info.name +
3410 ", isSyncable = " + p.info.isSyncable);
3411 } else {
3412 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003413 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003414 " (in package " + pkg.applicationInfo.packageName +
3415 "): name already used by "
3416 + ((other != null && other.getComponentName() != null)
3417 ? other.getComponentName().getPackageName() : "?"));
3418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 }
3420 }
3421 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3422 if (r == null) {
3423 r = new StringBuilder(256);
3424 } else {
3425 r.append(' ');
3426 }
3427 r.append(p.info.name);
3428 }
3429 }
3430 if (r != null) {
3431 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3432 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 N = pkg.services.size();
3435 r = null;
3436 for (i=0; i<N; i++) {
3437 PackageParser.Service s = pkg.services.get(i);
3438 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3439 s.info.processName, pkg.applicationInfo.uid);
3440 mServices.addService(s);
3441 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3442 if (r == null) {
3443 r = new StringBuilder(256);
3444 } else {
3445 r.append(' ');
3446 }
3447 r.append(s.info.name);
3448 }
3449 }
3450 if (r != null) {
3451 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 N = pkg.receivers.size();
3455 r = null;
3456 for (i=0; i<N; i++) {
3457 PackageParser.Activity a = pkg.receivers.get(i);
3458 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3459 a.info.processName, pkg.applicationInfo.uid);
3460 mReceivers.addActivity(a, "receiver");
3461 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3462 if (r == null) {
3463 r = new StringBuilder(256);
3464 } else {
3465 r.append(' ');
3466 }
3467 r.append(a.info.name);
3468 }
3469 }
3470 if (r != null) {
3471 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 N = pkg.activities.size();
3475 r = null;
3476 for (i=0; i<N; i++) {
3477 PackageParser.Activity a = pkg.activities.get(i);
3478 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3479 a.info.processName, pkg.applicationInfo.uid);
3480 mActivities.addActivity(a, "activity");
3481 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3482 if (r == null) {
3483 r = new StringBuilder(256);
3484 } else {
3485 r.append(' ');
3486 }
3487 r.append(a.info.name);
3488 }
3489 }
3490 if (r != null) {
3491 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 N = pkg.permissionGroups.size();
3495 r = null;
3496 for (i=0; i<N; i++) {
3497 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3498 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3499 if (cur == null) {
3500 mPermissionGroups.put(pg.info.name, pg);
3501 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3502 if (r == null) {
3503 r = new StringBuilder(256);
3504 } else {
3505 r.append(' ');
3506 }
3507 r.append(pg.info.name);
3508 }
3509 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003510 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 + pg.info.packageName + " ignored: original from "
3512 + cur.info.packageName);
3513 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3514 if (r == null) {
3515 r = new StringBuilder(256);
3516 } else {
3517 r.append(' ');
3518 }
3519 r.append("DUP:");
3520 r.append(pg.info.name);
3521 }
3522 }
3523 }
3524 if (r != null) {
3525 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 N = pkg.permissions.size();
3529 r = null;
3530 for (i=0; i<N; i++) {
3531 PackageParser.Permission p = pkg.permissions.get(i);
3532 HashMap<String, BasePermission> permissionMap =
3533 p.tree ? mSettings.mPermissionTrees
3534 : mSettings.mPermissions;
3535 p.group = mPermissionGroups.get(p.info.group);
3536 if (p.info.group == null || p.group != null) {
3537 BasePermission bp = permissionMap.get(p.info.name);
3538 if (bp == null) {
3539 bp = new BasePermission(p.info.name, p.info.packageName,
3540 BasePermission.TYPE_NORMAL);
3541 permissionMap.put(p.info.name, bp);
3542 }
3543 if (bp.perm == null) {
3544 if (bp.sourcePackage == null
3545 || bp.sourcePackage.equals(p.info.packageName)) {
3546 BasePermission tree = findPermissionTreeLP(p.info.name);
3547 if (tree == null
3548 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003549 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 bp.perm = p;
3551 bp.uid = pkg.applicationInfo.uid;
3552 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3553 if (r == null) {
3554 r = new StringBuilder(256);
3555 } else {
3556 r.append(' ');
3557 }
3558 r.append(p.info.name);
3559 }
3560 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003561 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 + p.info.packageName + " ignored: base tree "
3563 + tree.name + " is from package "
3564 + tree.sourcePackage);
3565 }
3566 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003567 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 + p.info.packageName + " ignored: original from "
3569 + bp.sourcePackage);
3570 }
3571 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3572 if (r == null) {
3573 r = new StringBuilder(256);
3574 } else {
3575 r.append(' ');
3576 }
3577 r.append("DUP:");
3578 r.append(p.info.name);
3579 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003580 if (bp.perm == p) {
3581 bp.protectionLevel = p.info.protectionLevel;
3582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003584 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 + p.info.packageName + " ignored: no group "
3586 + p.group);
3587 }
3588 }
3589 if (r != null) {
3590 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3591 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 N = pkg.instrumentation.size();
3594 r = null;
3595 for (i=0; i<N; i++) {
3596 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3597 a.info.packageName = pkg.applicationInfo.packageName;
3598 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3599 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3600 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003601 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003602 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003603 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3604 if (r == null) {
3605 r = new StringBuilder(256);
3606 } else {
3607 r.append(' ');
3608 }
3609 r.append(a.info.name);
3610 }
3611 }
3612 if (r != null) {
3613 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3614 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003615
Dianne Hackborn854060af2009-07-09 18:14:31 -07003616 if (pkg.protectedBroadcasts != null) {
3617 N = pkg.protectedBroadcasts.size();
3618 for (i=0; i<N; i++) {
3619 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3620 }
3621 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 pkgSetting.setTimeStamp(scanFileTime);
3624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 return pkg;
3627 }
3628
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003629 private void killApplication(String pkgName, int uid) {
3630 // Request the ActivityManager to kill the process(only for existing packages)
3631 // so that we do not end up in a confused state while the user is still using the older
3632 // version of the application while the new one gets installed.
3633 IActivityManager am = ActivityManagerNative.getDefault();
3634 if (am != null) {
3635 try {
3636 am.killApplicationWithUid(pkgName, uid);
3637 } catch (RemoteException e) {
3638 }
3639 }
3640 }
3641
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003642 // Return the path of the directory that will contain the native binaries
3643 // of a given installed package. This is relative to the data path.
3644 //
Kenny Root85387d72010-08-26 10:13:11 -07003645 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3646 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3647 if (nativeLibraryDir != null) {
3648 return new File(nativeLibraryDir);
3649 } else {
3650 // Fall back for old packages
3651 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3652 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003653 }
3654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3656 if (chatty && Config.LOGD) Log.d(
3657 TAG, "Removing package " + pkg.applicationInfo.packageName );
3658
3659 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 mPackages.remove(pkg.applicationInfo.packageName);
3663 if (pkg.mPath != null) {
3664 mAppDirs.remove(pkg.mPath);
3665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 PackageSetting ps = (PackageSetting)pkg.mExtras;
3668 if (ps != null && ps.sharedUser != null) {
3669 // XXX don't do this until the data is removed.
3670 if (false) {
3671 ps.sharedUser.packages.remove(ps);
3672 if (ps.sharedUser.packages.size() == 0) {
3673 // Remove.
3674 }
3675 }
3676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 int N = pkg.providers.size();
3679 StringBuilder r = null;
3680 int i;
3681 for (i=0; i<N; i++) {
3682 PackageParser.Provider p = pkg.providers.get(i);
3683 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3684 p.info.name));
3685 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 /* The is another ContentProvider with this authority when
3688 * this app was installed so this authority is null,
3689 * Ignore it as we don't have to unregister the provider.
3690 */
3691 continue;
3692 }
3693 String names[] = p.info.authority.split(";");
3694 for (int j = 0; j < names.length; j++) {
3695 if (mProviders.get(names[j]) == p) {
3696 mProviders.remove(names[j]);
3697 if (chatty && Config.LOGD) Log.d(
3698 TAG, "Unregistered content provider: " + names[j] +
3699 ", className = " + p.info.name +
3700 ", isSyncable = " + p.info.isSyncable);
3701 }
3702 }
3703 if (chatty) {
3704 if (r == null) {
3705 r = new StringBuilder(256);
3706 } else {
3707 r.append(' ');
3708 }
3709 r.append(p.info.name);
3710 }
3711 }
3712 if (r != null) {
3713 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 N = pkg.services.size();
3717 r = null;
3718 for (i=0; i<N; i++) {
3719 PackageParser.Service s = pkg.services.get(i);
3720 mServices.removeService(s);
3721 if (chatty) {
3722 if (r == null) {
3723 r = new StringBuilder(256);
3724 } else {
3725 r.append(' ');
3726 }
3727 r.append(s.info.name);
3728 }
3729 }
3730 if (r != null) {
3731 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 N = pkg.receivers.size();
3735 r = null;
3736 for (i=0; i<N; i++) {
3737 PackageParser.Activity a = pkg.receivers.get(i);
3738 mReceivers.removeActivity(a, "receiver");
3739 if (chatty) {
3740 if (r == null) {
3741 r = new StringBuilder(256);
3742 } else {
3743 r.append(' ');
3744 }
3745 r.append(a.info.name);
3746 }
3747 }
3748 if (r != null) {
3749 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 N = pkg.activities.size();
3753 r = null;
3754 for (i=0; i<N; i++) {
3755 PackageParser.Activity a = pkg.activities.get(i);
3756 mActivities.removeActivity(a, "activity");
3757 if (chatty) {
3758 if (r == null) {
3759 r = new StringBuilder(256);
3760 } else {
3761 r.append(' ');
3762 }
3763 r.append(a.info.name);
3764 }
3765 }
3766 if (r != null) {
3767 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 N = pkg.permissions.size();
3771 r = null;
3772 for (i=0; i<N; i++) {
3773 PackageParser.Permission p = pkg.permissions.get(i);
3774 boolean tree = false;
3775 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3776 if (bp == null) {
3777 tree = true;
3778 bp = mSettings.mPermissionTrees.get(p.info.name);
3779 }
3780 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003781 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 if (chatty) {
3783 if (r == null) {
3784 r = new StringBuilder(256);
3785 } else {
3786 r.append(' ');
3787 }
3788 r.append(p.info.name);
3789 }
3790 }
3791 }
3792 if (r != null) {
3793 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3794 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 N = pkg.instrumentation.size();
3797 r = null;
3798 for (i=0; i<N; i++) {
3799 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003800 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 if (chatty) {
3802 if (r == null) {
3803 r = new StringBuilder(256);
3804 } else {
3805 r.append(' ');
3806 }
3807 r.append(a.info.name);
3808 }
3809 }
3810 if (r != null) {
3811 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3812 }
3813 }
3814 }
3815
3816 private static final boolean isPackageFilename(String name) {
3817 return name != null && name.endsWith(".apk");
3818 }
3819
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003820 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3821 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3822 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3823 return true;
3824 }
3825 }
3826 return false;
3827 }
3828
3829 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003830 PackageParser.Package pkgInfo, boolean grantPermissions,
3831 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 // Make sure there are no dangling permission trees.
3833 Iterator<BasePermission> it = mSettings.mPermissionTrees
3834 .values().iterator();
3835 while (it.hasNext()) {
3836 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003837 if (bp.packageSetting == null) {
3838 // We may not yet have parsed the package, so just see if
3839 // we still know about its settings.
3840 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3841 }
3842 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003843 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 + " from package " + bp.sourcePackage);
3845 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003846 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3847 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3848 Slog.i(TAG, "Removing old permission tree: " + bp.name
3849 + " from package " + bp.sourcePackage);
3850 grantPermissions = true;
3851 it.remove();
3852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 }
3854 }
3855
3856 // Make sure all dynamic permissions have been assigned to a package,
3857 // and make sure there are no dangling permissions.
3858 it = mSettings.mPermissions.values().iterator();
3859 while (it.hasNext()) {
3860 BasePermission bp = it.next();
3861 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3862 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3863 + bp.name + " pkg=" + bp.sourcePackage
3864 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003865 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 BasePermission tree = findPermissionTreeLP(bp.name);
3867 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003868 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 bp.perm = new PackageParser.Permission(tree.perm.owner,
3870 new PermissionInfo(bp.pendingInfo));
3871 bp.perm.info.packageName = tree.perm.info.packageName;
3872 bp.perm.info.name = bp.name;
3873 bp.uid = tree.uid;
3874 }
3875 }
3876 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003877 if (bp.packageSetting == null) {
3878 // We may not yet have parsed the package, so just see if
3879 // we still know about its settings.
3880 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3881 }
3882 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003883 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 + " from package " + bp.sourcePackage);
3885 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003886 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3887 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3888 Slog.i(TAG, "Removing old permission: " + bp.name
3889 + " from package " + bp.sourcePackage);
3890 grantPermissions = true;
3891 it.remove();
3892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 }
3894 }
3895
3896 // Now update the permissions for all packages, in particular
3897 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003898 if (grantPermissions) {
3899 for (PackageParser.Package pkg : mPackages.values()) {
3900 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003901 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003902 }
3903 }
3904 }
3905
3906 if (pkgInfo != null) {
3907 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3912 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3913 if (ps == null) {
3914 return;
3915 }
3916 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003917 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 if (replace) {
3920 ps.permissionsFixed = false;
3921 if (gp == ps) {
3922 gp.grantedPermissions.clear();
3923 gp.gids = mGlobalGids;
3924 }
3925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 if (gp.gids == null) {
3928 gp.gids = mGlobalGids;
3929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 final int N = pkg.requestedPermissions.size();
3932 for (int i=0; i<N; i++) {
3933 String name = pkg.requestedPermissions.get(i);
3934 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 if (false) {
3936 if (gp != ps) {
3937 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003938 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 }
3940 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003941 if (bp != null && bp.packageSetting != null) {
3942 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003944 boolean allowedSig = false;
3945 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3946 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003948 } else if (bp.packageSetting == null) {
3949 // This permission is invalid; skip it.
3950 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003951 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3952 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003953 allowed = (checkSignaturesLP(
3954 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003956 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003958 if (!allowed && bp.protectionLevel
3959 == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003960 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 // For updated system applications, the signatureOrSystem permission
3962 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003963 if (isUpdatedSystemApp(pkg)) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003964 PackageSetting sysPs = mSettings.getDisabledSystemPkg(
3965 pkg.packageName);
3966 final GrantedPermissions origGp = sysPs.sharedUser != null
3967 ? sysPs.sharedUser : sysPs;
3968 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 allowed = true;
3970 } else {
3971 allowed = false;
3972 }
3973 } else {
3974 allowed = true;
3975 }
3976 }
3977 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003978 if (allowed) {
3979 allowedSig = true;
3980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 } else {
3982 allowed = false;
3983 }
3984 if (false) {
3985 if (gp != ps) {
3986 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3987 }
3988 }
3989 if (allowed) {
3990 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3991 && ps.permissionsFixed) {
3992 // If this is an existing, non-system package, then
3993 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003994 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003996 // Except... if this is a permission that was added
3997 // to the platform (note: need to only do this when
3998 // updating the platform).
3999 final int NP = PackageParser.NEW_PERMISSIONS.length;
4000 for (int ip=0; ip<NP; ip++) {
4001 final PackageParser.NewPermissionInfo npi
4002 = PackageParser.NEW_PERMISSIONS[ip];
4003 if (npi.name.equals(perm)
4004 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4005 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004006 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004007 + pkg.packageName);
4008 break;
4009 }
4010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 }
4012 }
4013 if (allowed) {
4014 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004015 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 gp.grantedPermissions.add(perm);
4017 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004018 } else if (!ps.haveGids) {
4019 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 }
4021 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004022 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 + " to package " + pkg.packageName
4024 + " because it was previously installed without");
4025 }
4026 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004027 if (gp.grantedPermissions.remove(perm)) {
4028 changedPermission = true;
4029 gp.gids = removeInts(gp.gids, bp.gids);
4030 Slog.i(TAG, "Un-granting permission " + perm
4031 + " from package " + pkg.packageName
4032 + " (protectionLevel=" + bp.protectionLevel
4033 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4034 + ")");
4035 } else {
4036 Slog.w(TAG, "Not granting permission " + perm
4037 + " to package " + pkg.packageName
4038 + " (protectionLevel=" + bp.protectionLevel
4039 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4040 + ")");
4041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 }
4043 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004044 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 + " in package " + pkg.packageName);
4046 }
4047 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004048
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004049 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004050 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4051 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 // This is the first that we have heard about this package, so the
4053 // permissions we have now selected are fixed until explicitly
4054 // changed.
4055 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004057 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 private final class ActivityIntentResolver
4061 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004062 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004064 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 }
4066
Mihai Preda074edef2009-05-18 17:13:31 +02004067 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004069 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4071 }
4072
Mihai Predaeae850c2009-05-13 10:13:48 +02004073 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4074 ArrayList<PackageParser.Activity> packageActivities) {
4075 if (packageActivities == null) {
4076 return null;
4077 }
4078 mFlags = flags;
4079 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4080 int N = packageActivities.size();
4081 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4082 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004083
4084 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004085 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004086 intentFilters = packageActivities.get(i).intents;
4087 if (intentFilters != null && intentFilters.size() > 0) {
4088 listCut.add(intentFilters);
4089 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004090 }
4091 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4092 }
4093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004095 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 if (SHOW_INFO || Config.LOGV) Log.v(
4097 TAG, " " + type + " " +
4098 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4099 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4100 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004101 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4103 if (SHOW_INFO || Config.LOGV) {
4104 Log.v(TAG, " IntentFilter:");
4105 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4106 }
4107 if (!intent.debugCheck()) {
4108 Log.w(TAG, "==> For Activity " + a.info.name);
4109 }
4110 addFilter(intent);
4111 }
4112 }
4113
4114 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004115 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 if (SHOW_INFO || Config.LOGV) Log.v(
4117 TAG, " " + type + " " +
4118 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4119 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4120 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004121 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4123 if (SHOW_INFO || Config.LOGV) {
4124 Log.v(TAG, " IntentFilter:");
4125 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4126 }
4127 removeFilter(intent);
4128 }
4129 }
4130
4131 @Override
4132 protected boolean allowFilterResult(
4133 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4134 ActivityInfo filterAi = filter.activity.info;
4135 for (int i=dest.size()-1; i>=0; i--) {
4136 ActivityInfo destAi = dest.get(i).activityInfo;
4137 if (destAi.name == filterAi.name
4138 && destAi.packageName == filterAi.packageName) {
4139 return false;
4140 }
4141 }
4142 return true;
4143 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004146 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4147 return info.activity.owner.packageName;
4148 }
4149
4150 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4152 int match) {
4153 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4154 return null;
4155 }
4156 final PackageParser.Activity activity = info.activity;
4157 if (mSafeMode && (activity.info.applicationInfo.flags
4158 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4159 return null;
4160 }
4161 final ResolveInfo res = new ResolveInfo();
4162 res.activityInfo = PackageParser.generateActivityInfo(activity,
4163 mFlags);
4164 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4165 res.filter = info;
4166 }
4167 res.priority = info.getPriority();
4168 res.preferredOrder = activity.owner.mPreferredOrder;
4169 //System.out.println("Result: " + res.activityInfo.className +
4170 // " = " + res.priority);
4171 res.match = match;
4172 res.isDefault = info.hasDefault;
4173 res.labelRes = info.labelRes;
4174 res.nonLocalizedLabel = info.nonLocalizedLabel;
4175 res.icon = info.icon;
4176 return res;
4177 }
4178
4179 @Override
4180 protected void sortResults(List<ResolveInfo> results) {
4181 Collections.sort(results, mResolvePrioritySorter);
4182 }
4183
4184 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004185 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004187 out.print(prefix); out.print(
4188 Integer.toHexString(System.identityHashCode(filter.activity)));
4189 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004190 out.print(filter.activity.getComponentShortName());
4191 out.print(" filter ");
4192 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 }
4194
4195// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4196// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4197// final List<ResolveInfo> retList = Lists.newArrayList();
4198// while (i.hasNext()) {
4199// final ResolveInfo resolveInfo = i.next();
4200// if (isEnabledLP(resolveInfo.activityInfo)) {
4201// retList.add(resolveInfo);
4202// }
4203// }
4204// return retList;
4205// }
4206
4207 // Keys are String (activity class name), values are Activity.
4208 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4209 = new HashMap<ComponentName, PackageParser.Activity>();
4210 private int mFlags;
4211 }
4212
4213 private final class ServiceIntentResolver
4214 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004215 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004217 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 }
4219
Mihai Preda074edef2009-05-18 17:13:31 +02004220 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004222 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4224 }
4225
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004226 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4227 ArrayList<PackageParser.Service> packageServices) {
4228 if (packageServices == null) {
4229 return null;
4230 }
4231 mFlags = flags;
4232 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4233 int N = packageServices.size();
4234 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4235 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4236
4237 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4238 for (int i = 0; i < N; ++i) {
4239 intentFilters = packageServices.get(i).intents;
4240 if (intentFilters != null && intentFilters.size() > 0) {
4241 listCut.add(intentFilters);
4242 }
4243 }
4244 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4245 }
4246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004248 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 if (SHOW_INFO || Config.LOGV) Log.v(
4250 TAG, " " + (s.info.nonLocalizedLabel != null
4251 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4252 if (SHOW_INFO || Config.LOGV) Log.v(
4253 TAG, " Class=" + s.info.name);
4254 int NI = s.intents.size();
4255 int j;
4256 for (j=0; j<NI; j++) {
4257 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4258 if (SHOW_INFO || Config.LOGV) {
4259 Log.v(TAG, " IntentFilter:");
4260 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4261 }
4262 if (!intent.debugCheck()) {
4263 Log.w(TAG, "==> For Service " + s.info.name);
4264 }
4265 addFilter(intent);
4266 }
4267 }
4268
4269 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004270 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 if (SHOW_INFO || Config.LOGV) Log.v(
4272 TAG, " " + (s.info.nonLocalizedLabel != null
4273 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4274 if (SHOW_INFO || Config.LOGV) Log.v(
4275 TAG, " Class=" + s.info.name);
4276 int NI = s.intents.size();
4277 int j;
4278 for (j=0; j<NI; j++) {
4279 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4280 if (SHOW_INFO || Config.LOGV) {
4281 Log.v(TAG, " IntentFilter:");
4282 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4283 }
4284 removeFilter(intent);
4285 }
4286 }
4287
4288 @Override
4289 protected boolean allowFilterResult(
4290 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4291 ServiceInfo filterSi = filter.service.info;
4292 for (int i=dest.size()-1; i>=0; i--) {
4293 ServiceInfo destAi = dest.get(i).serviceInfo;
4294 if (destAi.name == filterSi.name
4295 && destAi.packageName == filterSi.packageName) {
4296 return false;
4297 }
4298 }
4299 return true;
4300 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004303 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4304 return info.service.owner.packageName;
4305 }
4306
4307 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4309 int match) {
4310 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4311 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4312 return null;
4313 }
4314 final PackageParser.Service service = info.service;
4315 if (mSafeMode && (service.info.applicationInfo.flags
4316 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4317 return null;
4318 }
4319 final ResolveInfo res = new ResolveInfo();
4320 res.serviceInfo = PackageParser.generateServiceInfo(service,
4321 mFlags);
4322 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4323 res.filter = filter;
4324 }
4325 res.priority = info.getPriority();
4326 res.preferredOrder = service.owner.mPreferredOrder;
4327 //System.out.println("Result: " + res.activityInfo.className +
4328 // " = " + res.priority);
4329 res.match = match;
4330 res.isDefault = info.hasDefault;
4331 res.labelRes = info.labelRes;
4332 res.nonLocalizedLabel = info.nonLocalizedLabel;
4333 res.icon = info.icon;
4334 return res;
4335 }
4336
4337 @Override
4338 protected void sortResults(List<ResolveInfo> results) {
4339 Collections.sort(results, mResolvePrioritySorter);
4340 }
4341
4342 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004343 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004345 out.print(prefix); out.print(
4346 Integer.toHexString(System.identityHashCode(filter.service)));
4347 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004348 out.print(filter.service.getComponentShortName());
4349 out.print(" filter ");
4350 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 }
4352
4353// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4354// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4355// final List<ResolveInfo> retList = Lists.newArrayList();
4356// while (i.hasNext()) {
4357// final ResolveInfo resolveInfo = (ResolveInfo) i;
4358// if (isEnabledLP(resolveInfo.serviceInfo)) {
4359// retList.add(resolveInfo);
4360// }
4361// }
4362// return retList;
4363// }
4364
4365 // Keys are String (activity class name), values are Activity.
4366 private final HashMap<ComponentName, PackageParser.Service> mServices
4367 = new HashMap<ComponentName, PackageParser.Service>();
4368 private int mFlags;
4369 };
4370
4371 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4372 new Comparator<ResolveInfo>() {
4373 public int compare(ResolveInfo r1, ResolveInfo r2) {
4374 int v1 = r1.priority;
4375 int v2 = r2.priority;
4376 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4377 if (v1 != v2) {
4378 return (v1 > v2) ? -1 : 1;
4379 }
4380 v1 = r1.preferredOrder;
4381 v2 = r2.preferredOrder;
4382 if (v1 != v2) {
4383 return (v1 > v2) ? -1 : 1;
4384 }
4385 if (r1.isDefault != r2.isDefault) {
4386 return r1.isDefault ? -1 : 1;
4387 }
4388 v1 = r1.match;
4389 v2 = r2.match;
4390 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4391 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4392 }
4393 };
4394
4395 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4396 new Comparator<ProviderInfo>() {
4397 public int compare(ProviderInfo p1, ProviderInfo p2) {
4398 final int v1 = p1.initOrder;
4399 final int v2 = p2.initOrder;
4400 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4401 }
4402 };
4403
Kenny Root93565c4b2010-06-18 15:46:06 -07004404 private static final boolean DEBUG_OBB = false;
4405
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004406 private static final void sendPackageBroadcast(String action, String pkg,
4407 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004408 IActivityManager am = ActivityManagerNative.getDefault();
4409 if (am != null) {
4410 try {
4411 final Intent intent = new Intent(action,
4412 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4413 if (extras != null) {
4414 intent.putExtras(extras);
4415 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004416 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004417 am.broadcastIntent(null, intent, null, finishedReceiver,
4418 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004419 } catch (RemoteException ex) {
4420 }
4421 }
4422 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004423
4424 public String nextPackageToClean(String lastPackage) {
4425 synchronized (mPackages) {
4426 if (!mMediaMounted) {
4427 // If the external storage is no longer mounted at this point,
4428 // the caller may not have been able to delete all of this
4429 // packages files and can not delete any more. Bail.
4430 return null;
4431 }
4432 if (lastPackage != null) {
4433 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4434 }
4435 return mSettings.mPackagesToBeCleaned.size() > 0
4436 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4437 }
4438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004439
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004440 void schedulePackageCleaning(String packageName) {
4441 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4442 }
4443
4444 void startCleaningPackages() {
4445 synchronized (mPackages) {
4446 if (!mMediaMounted) {
4447 return;
4448 }
4449 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4450 return;
4451 }
4452 }
4453 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4454 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4455 IActivityManager am = ActivityManagerNative.getDefault();
4456 if (am != null) {
4457 try {
4458 am.startService(null, intent, null);
4459 } catch (RemoteException e) {
4460 }
4461 }
4462 }
4463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 private final class AppDirObserver extends FileObserver {
4465 public AppDirObserver(String path, int mask, boolean isrom) {
4466 super(path, mask);
4467 mRootDir = path;
4468 mIsRom = isrom;
4469 }
4470
4471 public void onEvent(int event, String path) {
4472 String removedPackage = null;
4473 int removedUid = -1;
4474 String addedPackage = null;
4475 int addedUid = -1;
4476
4477 synchronized (mInstallLock) {
4478 String fullPathStr = null;
4479 File fullPath = null;
4480 if (path != null) {
4481 fullPath = new File(mRootDir, path);
4482 fullPathStr = fullPath.getPath();
4483 }
4484
4485 if (Config.LOGV) Log.v(
4486 TAG, "File " + fullPathStr + " changed: "
4487 + Integer.toHexString(event));
4488
4489 if (!isPackageFilename(path)) {
4490 if (Config.LOGV) Log.v(
4491 TAG, "Ignoring change of non-package file: " + fullPathStr);
4492 return;
4493 }
4494
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004495 // Ignore packages that are being installed or
4496 // have just been installed.
4497 if (ignoreCodePath(fullPathStr)) {
4498 return;
4499 }
4500 PackageParser.Package p = null;
4501 synchronized (mPackages) {
4502 p = mAppDirs.get(fullPathStr);
4503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004505 if (p != null) {
4506 removePackageLI(p, true);
4507 removedPackage = p.applicationInfo.packageName;
4508 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 }
4510 }
4511
4512 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004514 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004515 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4516 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 PackageParser.PARSE_CHATTY |
4518 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004519 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4520 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004521 if (p != null) {
4522 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004523 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004524 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 }
4526 addedPackage = p.applicationInfo.packageName;
4527 addedUid = p.applicationInfo.uid;
4528 }
4529 }
4530 }
4531
4532 synchronized (mPackages) {
4533 mSettings.writeLP();
4534 }
4535 }
4536
4537 if (removedPackage != null) {
4538 Bundle extras = new Bundle(1);
4539 extras.putInt(Intent.EXTRA_UID, removedUid);
4540 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004541 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4542 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 }
4544 if (addedPackage != null) {
4545 Bundle extras = new Bundle(1);
4546 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004547 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4548 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004549 }
4550 }
4551
4552 private final String mRootDir;
4553 private final boolean mIsRom;
4554 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 /* Called when a downloaded package installation has been confirmed by the user */
4557 public void installPackage(
4558 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004559 installPackage(packageURI, observer, flags, null);
4560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004561
Jacek Surazski65e13172009-04-28 15:26:38 +02004562 /* Called when a downloaded package installation has been confirmed by the user */
4563 public void installPackage(
4564 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4565 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 mContext.enforceCallingOrSelfPermission(
4567 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004568
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004569 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004570 msg.obj = new InstallParams(packageURI, observer, flags,
4571 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004572 mHandler.sendMessage(msg);
4573 }
4574
Christopher Tate1bb69062010-02-19 17:02:12 -08004575 public void finishPackageInstall(int token) {
4576 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4577 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4578 mHandler.sendMessage(msg);
4579 }
4580
Kenny Root93565c4b2010-06-18 15:46:06 -07004581 public void setPackageObbPath(String packageName, String path) {
4582 if (DEBUG_OBB)
4583 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4584 PackageSetting pkgSetting;
4585 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004586 final int permission = mContext.checkCallingPermission(
4587 android.Manifest.permission.INSTALL_PACKAGES);
4588 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004589 synchronized (mPackages) {
4590 pkgSetting = mSettings.mPackages.get(packageName);
4591 if (pkgSetting == null) {
4592 throw new IllegalArgumentException("Unknown package: " + packageName);
4593 }
4594 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4595 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4596 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4597 + pkgSetting.userId);
4598 }
4599 pkgSetting.obbPathString = path;
4600 mSettings.writeLP();
4601 }
4602 }
4603
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004604 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 // Queue up an async operation since the package installation may take a little while.
4606 mHandler.post(new Runnable() {
4607 public void run() {
4608 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004609 // Result object to be returned
4610 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004611 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004612 res.uid = -1;
4613 res.pkg = null;
4614 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004615 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004616 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004617 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004618 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004619 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004620 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004622
4623 // A restore should be performed at this point if (a) the install
4624 // succeeded, (b) the operation is not an update, and (c) the new
4625 // package has a backupAgent defined.
4626 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004627 boolean doRestore = (!update
4628 && res.pkg != null
4629 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004630
4631 // Set up the post-install work request bookkeeping. This will be used
4632 // and cleaned up by the post-install event handling regardless of whether
4633 // there's a restore pass performed. Token values are >= 1.
4634 int token;
4635 if (mNextInstallToken < 0) mNextInstallToken = 1;
4636 token = mNextInstallToken++;
4637
4638 PostInstallData data = new PostInstallData(args, res);
4639 mRunningInstalls.put(token, data);
4640 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4641
4642 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4643 // Pass responsibility to the Backup Manager. It will perform a
4644 // restore if appropriate, then pass responsibility back to the
4645 // Package Manager to run the post-install observer callbacks
4646 // and broadcasts.
4647 IBackupManager bm = IBackupManager.Stub.asInterface(
4648 ServiceManager.getService(Context.BACKUP_SERVICE));
4649 if (bm != null) {
4650 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4651 + " to BM for possible restore");
4652 try {
4653 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4654 } catch (RemoteException e) {
4655 // can't happen; the backup manager is local
4656 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004657 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004658 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004659 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004660 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004661 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004662 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004664 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004665
4666 if (!doRestore) {
4667 // No restore possible, or the Backup Manager was mysteriously not
4668 // available -- just fire the post-install work request directly.
4669 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4670 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4671 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 }
4674 });
4675 }
4676
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004677 abstract class HandlerParams {
4678 final static int MAX_RETRIES = 4;
4679 int retry = 0;
4680 final void startCopy() {
4681 try {
4682 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4683 retry++;
4684 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004685 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004686 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4687 handleServiceError();
4688 return;
4689 } else {
4690 handleStartCopy();
4691 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4692 mHandler.sendEmptyMessage(MCS_UNBIND);
4693 }
4694 } catch (RemoteException e) {
4695 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4696 mHandler.sendEmptyMessage(MCS_RECONNECT);
4697 }
4698 handleReturnCode();
4699 }
4700
4701 final void serviceError() {
4702 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4703 handleServiceError();
4704 handleReturnCode();
4705 }
4706 abstract void handleStartCopy() throws RemoteException;
4707 abstract void handleServiceError();
4708 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004709 }
4710
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004711 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004712 final IPackageInstallObserver observer;
4713 int flags;
4714 final Uri packageURI;
4715 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004716 private InstallArgs mArgs;
4717 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004718 InstallParams(Uri packageURI,
4719 IPackageInstallObserver observer, int flags,
4720 String installerPackageName) {
4721 this.packageURI = packageURI;
4722 this.flags = flags;
4723 this.observer = observer;
4724 this.installerPackageName = installerPackageName;
4725 }
4726
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004727 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4728 String packageName = pkgLite.packageName;
4729 int installLocation = pkgLite.installLocation;
4730 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4731 synchronized (mPackages) {
4732 PackageParser.Package pkg = mPackages.get(packageName);
4733 if (pkg != null) {
4734 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4735 // Check for updated system application.
4736 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4737 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004738 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004739 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4740 }
4741 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4742 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004743 if (onSd) {
4744 // Install flag overrides everything.
4745 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4746 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004747 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004748 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4749 // Application explicitly specified internal.
4750 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4751 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4752 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004753 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004754 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004755 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004756 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4757 }
4758 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004759 }
4760 }
4761 } else {
4762 // Invalid install. Return error code
4763 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4764 }
4765 }
4766 }
4767 // All the special cases have been taken care of.
4768 // Return result based on recommended install location.
4769 if (onSd) {
4770 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4771 }
4772 return pkgLite.recommendedInstallLocation;
4773 }
4774
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004775 /*
4776 * Invoke remote method to get package information and install
4777 * location values. Override install location based on default
4778 * policy if needed and then create install arguments based
4779 * on the install location.
4780 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004781 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004782 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004783 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4784 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004785 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4786 if (onInt && onSd) {
4787 // Check if both bits are set.
4788 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4789 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4790 } else if (fwdLocked && onSd) {
4791 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004792 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004793 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004794 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004795 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07004796 final PackageInfoLite pkgLite;
4797 try {
4798 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4799 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4800 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
4801 } finally {
4802 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4803 }
4804
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004805 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004806 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4807 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4808 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4809 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4810 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004811 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4812 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4813 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004814 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4815 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004816 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004817 // Override with defaults if needed.
4818 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004819 if (!onSd && !onInt) {
4820 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004821 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4822 // Set the flag to install on external media.
4823 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004824 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004825 } else {
4826 // Make sure the flag for installing on external
4827 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004828 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004829 flags &= ~PackageManager.INSTALL_EXTERNAL;
4830 }
4831 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004832 }
4833 }
4834 // Create the file args now.
4835 mArgs = createInstallArgs(this);
4836 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4837 // Create copy only if we are not in an erroneous state.
4838 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004839 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004840 }
4841 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004842 }
4843
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004844 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004845 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004846 // If mArgs is null, then MCS couldn't be reached. When it
4847 // reconnects, it will try again to install. At that point, this
4848 // will succeed.
4849 if (mArgs != null) {
4850 processPendingInstall(mArgs, mRet);
4851 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004852 }
4853
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004854 @Override
4855 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004856 mArgs = createInstallArgs(this);
4857 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004859 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004860
4861 /*
4862 * Utility class used in movePackage api.
4863 * srcArgs and targetArgs are not set for invalid flags and make
4864 * sure to do null checks when invoking methods on them.
4865 * We probably want to return ErrorPrams for both failed installs
4866 * and moves.
4867 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004868 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004869 final IPackageMoveObserver observer;
4870 final int flags;
4871 final String packageName;
4872 final InstallArgs srcArgs;
4873 final InstallArgs targetArgs;
4874 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004875
4876 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4877 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004878 this.srcArgs = srcArgs;
4879 this.observer = observer;
4880 this.flags = flags;
4881 this.packageName = packageName;
4882 if (srcArgs != null) {
4883 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004884 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004885 } else {
4886 targetArgs = null;
4887 }
4888 }
4889
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004890 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004891 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4892 // Check for storage space on target medium
4893 if (!targetArgs.checkFreeStorage(mContainerService)) {
4894 Log.w(TAG, "Insufficient storage to install");
4895 return;
4896 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004897 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004898 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004899 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004900 if (DEBUG_SD_INSTALL) {
4901 StringBuilder builder = new StringBuilder();
4902 if (srcArgs != null) {
4903 builder.append("src: ");
4904 builder.append(srcArgs.getCodePath());
4905 }
4906 if (targetArgs != null) {
4907 builder.append(" target : ");
4908 builder.append(targetArgs.getCodePath());
4909 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004910 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004911 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004912 }
4913
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004914 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004915 void handleReturnCode() {
4916 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004917 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4918 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4919 currentStatus = PackageManager.MOVE_SUCCEEDED;
4920 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4921 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4922 }
4923 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004924 }
4925
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004926 @Override
4927 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004928 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004929 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004930 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004931
4932 private InstallArgs createInstallArgs(InstallParams params) {
4933 if (installOnSd(params.flags)) {
4934 return new SdInstallArgs(params);
4935 } else {
4936 return new FileInstallArgs(params);
4937 }
4938 }
4939
Kenny Root85387d72010-08-26 10:13:11 -07004940 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4941 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004942 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004943 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004944 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004945 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004946 }
4947 }
4948
Kenny Root85387d72010-08-26 10:13:11 -07004949 // Used by package mover
4950 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004951 if (installOnSd(flags)) {
4952 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4953 return new SdInstallArgs(packageURI, cid);
4954 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004955 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004956 }
4957 }
4958
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004959 static abstract class InstallArgs {
4960 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004962 final int flags;
4963 final Uri packageURI;
4964 final String installerPackageName;
4965
4966 InstallArgs(Uri packageURI,
4967 IPackageInstallObserver observer, int flags,
4968 String installerPackageName) {
4969 this.packageURI = packageURI;
4970 this.flags = flags;
4971 this.observer = observer;
4972 this.installerPackageName = installerPackageName;
4973 }
4974
4975 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004976 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004977 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004978 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004979 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004980 abstract String getCodePath();
4981 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004982 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004983 // Need installer lock especially for dex file removal.
4984 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004985 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004986 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004987 }
4988
4989 class FileInstallArgs extends InstallArgs {
4990 File installDir;
4991 String codeFileName;
4992 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004993 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004994 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004995
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004996 FileInstallArgs(InstallParams params) {
4997 super(params.packageURI, params.observer,
4998 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004999 }
5000
Kenny Root85387d72010-08-26 10:13:11 -07005001 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005002 super(null, null, 0, null);
5003 File codeFile = new File(fullCodePath);
5004 installDir = codeFile.getParentFile();
5005 codeFileName = fullCodePath;
5006 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07005007 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005008 }
5009
Kenny Root85387d72010-08-26 10:13:11 -07005010 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005011 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07005012 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005013 String apkName = getNextCodePath(null, pkgName, ".apk");
5014 codeFileName = new File(installDir, apkName + ".apk").getPath();
5015 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07005016 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005017 }
5018
Kenny Root11128572010-10-11 10:51:32 -07005019 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5020 try {
5021 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5022 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5023 return imcs.checkFreeStorage(false, packageURI);
5024 } finally {
5025 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5026 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005027 }
5028
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005029 String getCodePath() {
5030 return codeFileName;
5031 }
5032
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005033 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005034 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005035 codeFileName = createTempPackageFile(installDir).getPath();
5036 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005037 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005038 }
5039
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005040 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005041 if (temp) {
5042 // Generate temp file name
5043 createCopyFile();
5044 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005045 // Get a ParcelFileDescriptor to write to the output file
5046 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005047 if (!created) {
5048 try {
5049 codeFile.createNewFile();
5050 // Set permissions
5051 if (!setPermissions()) {
5052 // Failed setting permissions.
5053 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5054 }
5055 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005056 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005057 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5058 }
5059 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005060 ParcelFileDescriptor out = null;
5061 try {
Kenny Root85387d72010-08-26 10:13:11 -07005062 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005064 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005065 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5066 }
5067 // Copy the resource now
5068 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5069 try {
Kenny Root11128572010-10-11 10:51:32 -07005070 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5071 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005072 if (imcs.copyResource(packageURI, out)) {
5073 ret = PackageManager.INSTALL_SUCCEEDED;
5074 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005075 } finally {
5076 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005077 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005078 }
Kenny Root85387d72010-08-26 10:13:11 -07005079
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005080 return ret;
5081 }
5082
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005083 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005084 if (status != PackageManager.INSTALL_SUCCEEDED) {
5085 cleanUp();
5086 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005087 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005088 }
5089
5090 boolean doRename(int status, final String pkgName, String oldCodePath) {
5091 if (status != PackageManager.INSTALL_SUCCEEDED) {
5092 cleanUp();
5093 return false;
5094 } else {
5095 // Rename based on packageName
5096 File codeFile = new File(getCodePath());
5097 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5098 File desFile = new File(installDir, apkName + ".apk");
5099 if (!codeFile.renameTo(desFile)) {
5100 return false;
5101 }
5102 // Reset paths since the file has been renamed.
5103 codeFileName = desFile.getPath();
5104 resourceFileName = getResourcePathFromCodePath();
5105 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005106 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 // Failed setting permissions.
5108 return false;
5109 }
5110 return true;
5111 }
5112 }
5113
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005114 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005115 if (status != PackageManager.INSTALL_SUCCEEDED) {
5116 cleanUp();
5117 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005118 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005119 }
5120
5121 String getResourcePath() {
5122 return resourceFileName;
5123 }
5124
5125 String getResourcePathFromCodePath() {
5126 String codePath = getCodePath();
5127 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5128 String apkNameOnly = getApkName(codePath);
5129 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5130 } else {
5131 return codePath;
5132 }
5133 }
5134
Kenny Root85387d72010-08-26 10:13:11 -07005135 @Override
5136 String getNativeLibraryPath() {
5137 return libraryPath;
5138 }
5139
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005140 private boolean cleanUp() {
5141 boolean ret = true;
5142 String sourceDir = getCodePath();
5143 String publicSourceDir = getResourcePath();
5144 if (sourceDir != null) {
5145 File sourceFile = new File(sourceDir);
5146 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005147 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005148 ret = false;
5149 }
5150 // Delete application's code and resources
5151 sourceFile.delete();
5152 }
5153 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5154 final File publicSourceFile = new File(publicSourceDir);
5155 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005156 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005157 }
5158 if (publicSourceFile.exists()) {
5159 publicSourceFile.delete();
5160 }
5161 }
5162 return ret;
5163 }
5164
5165 void cleanUpResourcesLI() {
5166 String sourceDir = getCodePath();
5167 if (cleanUp() && mInstaller != null) {
5168 int retCode = mInstaller.rmdex(sourceDir);
5169 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005170 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005171 + " at location "
5172 + sourceDir + ", retcode=" + retCode);
5173 // we don't consider this to be a failure of the core package deletion
5174 }
5175 }
5176 }
5177
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005178 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005179 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005180 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005181 final int filePermissions =
5182 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5183 |FileUtils.S_IROTH;
5184 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5185 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005186 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005187 getCodePath()
5188 + ". The return code was: " + retCode);
5189 // TODO Define new internal error
5190 return false;
5191 }
5192 return true;
5193 }
5194 return true;
5195 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005196
5197 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005198 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005199 cleanUpResourcesLI();
5200 return true;
5201 }
Kenny Root85387d72010-08-26 10:13:11 -07005202
5203 private boolean isFwdLocked() {
5204 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5205 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005206 }
5207
5208 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005209 static final String RES_FILE_NAME = "pkg.apk";
5210
Kenny Root85387d72010-08-26 10:13:11 -07005211 String cid;
5212 String packagePath;
5213 String libraryPath;
5214
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005215 SdInstallArgs(InstallParams params) {
5216 super(params.packageURI, params.observer,
5217 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005218 }
5219
Kenny Root85387d72010-08-26 10:13:11 -07005220 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005221 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005222 // Extract cid from fullCodePath
5223 int eidx = fullCodePath.lastIndexOf("/");
5224 String subStr1 = fullCodePath.substring(0, eidx);
5225 int sidx = subStr1.lastIndexOf("/");
5226 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005227 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005228 }
5229
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005230 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005231 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5232 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005233 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005234 }
5235
5236 SdInstallArgs(Uri packageURI, String cid) {
5237 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005238 this.cid = cid;
5239 }
5240
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 void createCopyFile() {
5242 cid = getTempContainerId();
5243 }
5244
Kenny Root11128572010-10-11 10:51:32 -07005245 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5246 try {
5247 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5248 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5249 return imcs.checkFreeStorage(true, packageURI);
5250 } finally {
5251 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5252 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005253 }
5254
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005255 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005256 if (temp) {
5257 createCopyFile();
5258 }
Kenny Root11128572010-10-11 10:51:32 -07005259
5260 final String newCachePath;
5261 try {
5262 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5263 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5264 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5265 getEncryptKey(), RES_FILE_NAME);
5266 } finally {
5267 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5268 }
5269
Kenny Root85387d72010-08-26 10:13:11 -07005270 if (newCachePath != null) {
5271 setCachePath(newCachePath);
5272 return PackageManager.INSTALL_SUCCEEDED;
5273 } else {
5274 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5275 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005276 }
5277
5278 @Override
5279 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005280 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005281 }
5282
5283 @Override
5284 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005285 return packagePath;
5286 }
5287
5288 @Override
5289 String getNativeLibraryPath() {
5290 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005291 }
5292
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005293 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005294 if (status != PackageManager.INSTALL_SUCCEEDED) {
5295 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005296 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005297 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005298 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005299 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005300 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5301 Process.SYSTEM_UID);
5302 if (newCachePath != null) {
5303 setCachePath(newCachePath);
5304 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005305 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5306 }
5307 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005308 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005309 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005310 }
5311
5312 boolean doRename(int status, final String pkgName,
5313 String oldCodePath) {
5314 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005315 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005316 if (PackageHelper.isContainerMounted(cid)) {
5317 // Unmount the container
5318 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005319 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005320 return false;
5321 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005322 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005323 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005324 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5325 " which might be stale. Will try to clean up.");
5326 // Clean up the stale container and proceed to recreate.
5327 if (!PackageHelper.destroySdDir(newCacheId)) {
5328 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5329 return false;
5330 }
5331 // Successfully cleaned up stale container. Try to rename again.
5332 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5333 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5334 + " inspite of cleaning it up.");
5335 return false;
5336 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005337 }
5338 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005339 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005340 newCachePath = PackageHelper.mountSdDir(newCacheId,
5341 getEncryptKey(), Process.SYSTEM_UID);
5342 } else {
5343 newCachePath = PackageHelper.getSdDir(newCacheId);
5344 }
5345 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005346 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005347 return false;
5348 }
5349 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005350 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005351 " at new path: " + newCachePath);
5352 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005353 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005354 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005355 }
5356
Kenny Root85387d72010-08-26 10:13:11 -07005357 private void setCachePath(String newCachePath) {
5358 File cachePath = new File(newCachePath);
5359 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5360 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5361 }
5362
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005363 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005364 if (status != PackageManager.INSTALL_SUCCEEDED) {
5365 cleanUp();
5366 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005367 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005368 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005369 PackageHelper.mountSdDir(cid,
5370 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005371 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005372 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005373 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005374 }
5375
5376 private void cleanUp() {
5377 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005378 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005379 }
5380
5381 void cleanUpResourcesLI() {
5382 String sourceFile = getCodePath();
5383 // Remove dex file
5384 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005385 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005386 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005387 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005388 + " at location "
5389 + sourceFile.toString() + ", retcode=" + retCode);
5390 // we don't consider this to be a failure of the core package deletion
5391 }
5392 }
5393 cleanUp();
5394 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005395
5396 boolean matchContainer(String app) {
5397 if (cid.startsWith(app)) {
5398 return true;
5399 }
5400 return false;
5401 }
5402
5403 String getPackageName() {
5404 int idx = cid.lastIndexOf("-");
5405 if (idx == -1) {
5406 return cid;
5407 }
5408 return cid.substring(0, idx);
5409 }
5410
5411 boolean doPostDeleteLI(boolean delete) {
5412 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005413 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005414 if (mounted) {
5415 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005416 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005417 }
5418 if (ret && delete) {
5419 cleanUpResourcesLI();
5420 }
5421 return ret;
5422 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005423 };
5424
5425 // Utility method used to create code paths based on package name and available index.
5426 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5427 String idxStr = "";
5428 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005429 // Fall back to default value of idx=1 if prefix is not
5430 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005431 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005432 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005433 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005434 if (subStr.endsWith(suffix)) {
5435 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005436 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005437 // If oldCodePath already contains prefix find out the
5438 // ending index to either increment or decrement.
5439 int sidx = subStr.lastIndexOf(prefix);
5440 if (sidx != -1) {
5441 subStr = subStr.substring(sidx + prefix.length());
5442 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005443 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5444 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005445 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005446 try {
5447 idx = Integer.parseInt(subStr);
5448 if (idx <= 1) {
5449 idx++;
5450 } else {
5451 idx--;
5452 }
5453 } catch(NumberFormatException e) {
5454 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005455 }
5456 }
5457 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005458 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005459 return prefix + idxStr;
5460 }
5461
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005462 // Utility method used to ignore ADD/REMOVE events
5463 // by directory observer.
5464 private static boolean ignoreCodePath(String fullPathStr) {
5465 String apkName = getApkName(fullPathStr);
5466 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5467 if (idx != -1 && ((idx+1) < apkName.length())) {
5468 // Make sure the package ends with a numeral
5469 String version = apkName.substring(idx+1);
5470 try {
5471 Integer.parseInt(version);
5472 return true;
5473 } catch (NumberFormatException e) {}
5474 }
5475 return false;
5476 }
5477
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005478 // Utility method that returns the relative package path with respect
5479 // to the installation directory. Like say for /data/data/com.test-1.apk
5480 // string com.test-1 is returned.
5481 static String getApkName(String codePath) {
5482 if (codePath == null) {
5483 return null;
5484 }
5485 int sidx = codePath.lastIndexOf("/");
5486 int eidx = codePath.lastIndexOf(".");
5487 if (eidx == -1) {
5488 eidx = codePath.length();
5489 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005490 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005491 return null;
5492 }
5493 return codePath.substring(sidx+1, eidx);
5494 }
5495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 class PackageInstalledInfo {
5497 String name;
5498 int uid;
5499 PackageParser.Package pkg;
5500 int returnCode;
5501 PackageRemovedInfo removedInfo;
5502 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 /*
5505 * Install a non-existing package.
5506 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005507 private void installNewPackageLI(PackageParser.Package pkg,
5508 int parseFlags,
5509 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005510 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005511 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005512 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005513
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005514 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 res.name = pkgName;
5516 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005517 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5518 // A package with the same name is already installed, though
5519 // it has been renamed to an older name. The package we
5520 // are trying to install should be installed as an update to
5521 // the existing one, but that has not been requested, so bail.
5522 Slog.w(TAG, "Attempt to re-install " + pkgName
5523 + " without first uninstalling package running as "
5524 + mSettings.mRenamedPackages.get(pkgName));
5525 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5526 return;
5527 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005528 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005530 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005531 + " without first uninstalling.");
5532 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5533 return;
5534 }
5535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005537 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5538 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005540 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5542 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5543 }
5544 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005545 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005546 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 res);
5548 // delete the partially installed application. the data directory will have to be
5549 // restored if it was already existing
5550 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5551 // remove package from internal structures. Note that we want deletePackageX to
5552 // delete the package data and cache directories that it created in
5553 // scanPackageLocked, unless those directories existed before we even tried to
5554 // install.
5555 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005556 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005558 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 }
5560 }
5561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005562
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005563 private void replacePackageLI(PackageParser.Package pkg,
5564 int parseFlags,
5565 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005566 String installerPackageName, PackageInstalledInfo res) {
5567
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005568 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005569 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 // First find the old package info and check signatures
5571 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005572 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005573 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005574 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5576 return;
5577 }
5578 }
Kenny Root85387d72010-08-26 10:13:11 -07005579 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005580 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005581 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005583 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 }
5585 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005588 PackageParser.Package pkg,
5589 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005590 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 PackageParser.Package newPackage = null;
5592 String pkgName = deletedPackage.packageName;
5593 boolean deletedPkg = true;
5594 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005595
Jacek Surazski65e13172009-04-28 15:26:38 +02005596 String oldInstallerPackageName = null;
5597 synchronized (mPackages) {
5598 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5599 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005600
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005601 long origUpdateTime;
5602 if (pkg.mExtras != null) {
5603 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5604 } else {
5605 origUpdateTime = 0;
5606 }
5607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005609 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005610 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005611 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5613 deletedPkg = false;
5614 } else {
5615 // Successfully deleted the old package. Now proceed with re-installation
5616 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005617 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5618 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005620 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5622 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005623 }
5624 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005625 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005626 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 res);
5628 updatedSettings = true;
5629 }
5630 }
5631
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005632 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 // remove package from internal structures. Note that we want deletePackageX to
5634 // delete the package data and cache directories that it created in
5635 // scanPackageLocked, unless those directories existed before we even tried to
5636 // install.
5637 if(updatedSettings) {
5638 deletePackageLI(
5639 pkgName, true,
5640 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005641 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 }
5643 // Since we failed to install the new package we need to restore the old
5644 // package that we deleted.
5645 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005646 File restoreFile = new File(deletedPackage.mPath);
5647 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005648 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005649 return;
5650 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005651 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005652 boolean oldOnSd = isExternal(deletedPackage);
5653 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5654 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5655 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005656 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5657 | SCAN_UPDATE_TIME;
5658 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5659 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005660 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5661 return;
5662 }
5663 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005664 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005665 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005666 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005667 mSettings.writeLP();
5668 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005669 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 }
5671 }
5672 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005675 PackageParser.Package pkg,
5676 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005677 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 PackageParser.Package newPackage = null;
5679 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005680 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 PackageParser.PARSE_IS_SYSTEM;
5682 String packageName = deletedPackage.packageName;
5683 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5684 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005685 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 return;
5687 }
5688 PackageParser.Package oldPkg;
5689 PackageSetting oldPkgSetting;
5690 synchronized (mPackages) {
5691 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005692 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005693 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5694 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005695 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 return;
5697 }
5698 }
5699 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5700 res.removedInfo.removedPackage = packageName;
5701 // Remove existing system package
5702 removePackageLI(oldPkg, true);
5703 synchronized (mPackages) {
5704 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5705 }
5706
5707 // Successfully disabled the old package. Now proceed with re-installation
5708 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5709 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005710 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005712 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5714 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5715 }
5716 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005717 if (newPackage.mExtras != null) {
5718 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5719 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5720 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5721 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005722 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 updatedSettings = true;
5724 }
5725
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005726 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 // Re installation failed. Restore old information
5728 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005729 if (newPackage != null) {
5730 removePackageLI(newPackage, true);
5731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005733 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 // Restore the old system information in Settings
5735 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005736 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005738 mSettings.setInstallerPackageName(packageName,
5739 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 }
5741 mSettings.writeLP();
5742 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005743 } else {
5744 // If this is an update to an existing update, setup
5745 // to remove the existing update.
5746 synchronized (mPackages) {
5747 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5748 if (ps != null && ps.codePathString != null &&
5749 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005750 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005751 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005752 }
5753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 }
5755 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005756
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005757 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005758 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005759 int retCode;
5760 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5761 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5762 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005763 if (mNoDexOpt) {
5764 /*
5765 * If we're in an engineering build, programs are lazily run
5766 * through dexopt. If the .dex file doesn't exist yet, it
5767 * will be created when the program is run next.
5768 */
5769 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5770 } else {
5771 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5772 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5773 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005774 }
5775 }
5776 return PackageManager.INSTALL_SUCCEEDED;
5777 }
5778
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005779 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005780 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005781 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 synchronized (mPackages) {
5783 //write settings. the installStatus will be incomplete at this stage.
5784 //note that the new package setting would have already been
5785 //added to mPackages. It hasn't been persisted yet.
5786 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5787 mSettings.writeLP();
5788 }
5789
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005790 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005791 != PackageManager.INSTALL_SUCCEEDED) {
5792 // Discontinue if moving dex files failed.
5793 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005795 if((res.returnCode = setPermissionsLI(newPackage))
5796 != PackageManager.INSTALL_SUCCEEDED) {
5797 if (mInstaller != null) {
5798 mInstaller.rmdex(newPackage.mScanPath);
5799 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005800 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005802 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005805 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005806 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 res.name = pkgName;
5808 res.uid = newPackage.applicationInfo.uid;
5809 res.pkg = newPackage;
5810 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005811 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5813 //to update install status
5814 mSettings.writeLP();
5815 }
5816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005817
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005818 private void installPackageLI(InstallArgs args,
5819 boolean newInstall, PackageInstalledInfo res) {
5820 int pFlags = args.flags;
5821 String installerPackageName = args.installerPackageName;
5822 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005823 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005824 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005825 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005826 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005827 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005828 // Result object to be returned
5829 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5830
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005831 // Retrieve PackageSettings and parse package
5832 int parseFlags = PackageParser.PARSE_CHATTY |
5833 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5834 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5835 parseFlags |= mDefParseFlags;
5836 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5837 pp.setSeparateProcesses(mSeparateProcesses);
5838 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5839 null, mMetrics, parseFlags);
5840 if (pkg == null) {
5841 res.returnCode = pp.getParseError();
5842 return;
5843 }
5844 String pkgName = res.name = pkg.packageName;
5845 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5846 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5847 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5848 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005850 }
5851 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5852 res.returnCode = pp.getParseError();
5853 return;
5854 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005855 // Get rid of all references to package scan path via parser.
5856 pp = null;
5857 String oldCodePath = null;
5858 boolean systemApp = false;
5859 synchronized (mPackages) {
5860 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005861 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5862 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005863 if (pkg.mOriginalPackages != null
5864 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005865 && mPackages.containsKey(oldName)) {
5866 // This package is derived from an original package,
5867 // and this device has been updating from that original
5868 // name. We must continue using the original name, so
5869 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005870 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005871 pkgName = pkg.packageName;
5872 replace = true;
5873 } else if (mPackages.containsKey(pkgName)) {
5874 // This package, under its official name, already exists
5875 // on the device; we should replace it.
5876 replace = true;
5877 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005878 }
5879 PackageSetting ps = mSettings.mPackages.get(pkgName);
5880 if (ps != null) {
5881 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5882 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5883 systemApp = (ps.pkg.applicationInfo.flags &
5884 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005885 }
5886 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005887 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005888
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005889 if (systemApp && onSd) {
5890 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005891 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005892 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5893 return;
5894 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005895
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005896 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5897 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5898 return;
5899 }
5900 // Set application objects path explicitly after the rename
5901 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005902 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005903 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005904 replacePackageLI(pkg, parseFlags, scanMode,
5905 installerPackageName, res);
5906 } else {
5907 installNewPackageLI(pkg, parseFlags, scanMode,
5908 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 }
5910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005911
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005912 private int setPermissionsLI(PackageParser.Package newPackage) {
5913 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005914 int retCode = 0;
5915 // TODO Gross hack but fix later. Ideally move this to be a post installation
5916 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005917 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005918 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005919 try {
5920 extractPublicFiles(newPackage, destResourceFile);
5921 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005922 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 -08005923 " forward-locked app.");
5924 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5925 } finally {
5926 //TODO clean up the extracted public files
5927 }
5928 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005929 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 newPackage.applicationInfo.uid);
5931 } else {
5932 final int filePermissions =
5933 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005934 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935 newPackage.applicationInfo.uid);
5936 }
5937 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005938 // The permissions on the resource file was set when it was copied for
5939 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005943 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005944 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005946 // TODO Define new internal error
5947 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005948 }
5949 return PackageManager.INSTALL_SUCCEEDED;
5950 }
5951
Kenny Root85387d72010-08-26 10:13:11 -07005952 private static boolean isForwardLocked(PackageParser.Package pkg) {
5953 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 }
5955
Kenny Root85387d72010-08-26 10:13:11 -07005956 private static boolean isExternal(PackageParser.Package pkg) {
5957 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5958 }
5959
5960 private static boolean isSystemApp(PackageParser.Package pkg) {
5961 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5962 }
5963
5964 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5965 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005966 }
5967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 private void extractPublicFiles(PackageParser.Package newPackage,
5969 File publicZipFile) throws IOException {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07005970 final FileOutputStream fstr = new FileOutputStream(publicZipFile);
5971 final ZipOutputStream publicZipOutStream = new ZipOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5973
5974 // Copy manifest, resources.arsc and res directory to public zip
5975
5976 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5977 while (privateZipEntries.hasMoreElements()) {
5978 final ZipEntry zipEntry = privateZipEntries.nextElement();
5979 final String zipEntryName = zipEntry.getName();
5980 if ("AndroidManifest.xml".equals(zipEntryName)
5981 || "resources.arsc".equals(zipEntryName)
5982 || zipEntryName.startsWith("res/")) {
5983 try {
5984 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5985 } catch (IOException e) {
5986 try {
5987 publicZipOutStream.close();
5988 throw e;
5989 } finally {
5990 publicZipFile.delete();
5991 }
5992 }
5993 }
5994 }
5995
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07005996 publicZipOutStream.finish();
5997 publicZipOutStream.flush();
5998 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 publicZipOutStream.close();
6000 FileUtils.setPermissions(
6001 publicZipFile.getAbsolutePath(),
6002 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6003 -1, -1);
6004 }
6005
6006 private static void copyZipEntry(ZipEntry zipEntry,
6007 ZipFile inZipFile,
6008 ZipOutputStream outZipStream) throws IOException {
6009 byte[] buffer = new byte[4096];
6010 int num;
6011
6012 ZipEntry newEntry;
6013 if (zipEntry.getMethod() == ZipEntry.STORED) {
6014 // Preserve the STORED method of the input entry.
6015 newEntry = new ZipEntry(zipEntry);
6016 } else {
6017 // Create a new entry so that the compressed len is recomputed.
6018 newEntry = new ZipEntry(zipEntry.getName());
6019 }
6020 outZipStream.putNextEntry(newEntry);
6021
6022 InputStream data = inZipFile.getInputStream(zipEntry);
6023 while ((num = data.read(buffer)) > 0) {
6024 outZipStream.write(buffer, 0, num);
6025 }
6026 outZipStream.flush();
6027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 private void deleteTempPackageFiles() {
6030 FilenameFilter filter = new FilenameFilter() {
6031 public boolean accept(File dir, String name) {
6032 return name.startsWith("vmdl") && name.endsWith(".tmp");
6033 }
6034 };
6035 String tmpFilesList[] = mAppInstallDir.list(filter);
6036 if(tmpFilesList == null) {
6037 return;
6038 }
6039 for(int i = 0; i < tmpFilesList.length; i++) {
6040 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6041 tmpFile.delete();
6042 }
6043 }
6044
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006045 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 File tmpPackageFile;
6047 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006048 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006050 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 return null;
6052 }
6053 try {
6054 FileUtils.setPermissions(
6055 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6056 -1, -1);
6057 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006058 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 return null;
6060 }
6061 return tmpPackageFile;
6062 }
6063
6064 public void deletePackage(final String packageName,
6065 final IPackageDeleteObserver observer,
6066 final int flags) {
6067 mContext.enforceCallingOrSelfPermission(
6068 android.Manifest.permission.DELETE_PACKAGES, null);
6069 // Queue up an async operation since the package deletion may take a little while.
6070 mHandler.post(new Runnable() {
6071 public void run() {
6072 mHandler.removeCallbacks(this);
6073 final boolean succeded = deletePackageX(packageName, true, true, flags);
6074 if (observer != null) {
6075 try {
6076 observer.packageDeleted(succeded);
6077 } catch (RemoteException e) {
6078 Log.i(TAG, "Observer no longer exists.");
6079 } //end catch
6080 } //end if
6081 } //end run
6082 });
6083 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 /**
6086 * This method is an internal method that could be get invoked either
6087 * to delete an installed package or to clean up a failed installation.
6088 * After deleting an installed package, a broadcast is sent to notify any
6089 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006090 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 * installation wouldn't have sent the initial broadcast either
6092 * The key steps in deleting a package are
6093 * deleting the package information in internal structures like mPackages,
6094 * deleting the packages base directories through installd
6095 * updating mSettings to reflect current status
6096 * persisting settings for later use
6097 * sending a broadcast if necessary
6098 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6100 boolean deleteCodeAndResources, int flags) {
6101 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006102 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006104 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6105 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6106 try {
6107 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006108 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006109 return false;
6110 }
6111 } catch (RemoteException e) {
6112 }
6113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006115 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006116 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006120 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006121 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006122
6123 // If the removed package was a system update, the old system packaged
6124 // was re-enabled; we need to broadcast this information
6125 if (systemUpdate) {
6126 Bundle extras = new Bundle(1);
6127 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6128 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6129
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006130 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6131 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006134 // Force a gc here.
6135 Runtime.getRuntime().gc();
6136 // Delete the resources here after sending the broadcast to let
6137 // other processes clean up before deleting resources.
6138 if (info.args != null) {
6139 synchronized (mInstallLock) {
6140 info.args.doPostDeleteLI(deleteCodeAndResources);
6141 }
6142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 return res;
6144 }
6145
6146 static class PackageRemovedInfo {
6147 String removedPackage;
6148 int uid = -1;
6149 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006150 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006151 // Clean up resources deleted packages.
6152 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006153
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006154 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 Bundle extras = new Bundle(1);
6156 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6157 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6158 if (replacing) {
6159 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6160 }
6161 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006162 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 }
6164 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006165 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 }
6167 }
6168 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 /*
6171 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6172 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006173 * 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 -08006174 * delete a partially installed application.
6175 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006176 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006177 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006179 if (outInfo != null) {
6180 outInfo.removedPackage = packageName;
6181 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006182 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 // Retrieve object to delete permissions for shared user later on
6184 PackageSetting deletedPs;
6185 synchronized (mPackages) {
6186 deletedPs = mSettings.mPackages.get(packageName);
6187 }
6188 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006189 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006191 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006193 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 + packageName + ", retcode=" + retCode);
6195 // we don't consider this to be a failure of the core package deletion
6196 }
6197 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006198 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 PackageParser.Package pkg = mPackages.get(packageName);
6200 File dataDir = new File(pkg.applicationInfo.dataDir);
6201 dataDir.delete();
6202 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006203 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 }
6205 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006206 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006207 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6208 if (outInfo != null) {
6209 outInfo.removedUid = mSettings.removePackageLP(packageName);
6210 }
6211 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006212 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006213 if (deletedPs.sharedUser != null) {
6214 // remove permissions associated with package
6215 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6216 }
6217 }
6218 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006219 // remove from preferred activities.
6220 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6221 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6222 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6223 removed.add(pa);
6224 }
6225 }
6226 for (PreferredActivity pa : removed) {
6227 mSettings.mPreferredActivities.removeFilter(pa);
6228 }
6229 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006230 if (writeSettings) {
6231 // Save settings now
6232 mSettings.writeLP();
6233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 }
6235 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 /*
6238 * Tries to delete system package.
6239 */
6240 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006241 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 ApplicationInfo applicationInfo = p.applicationInfo;
6243 //applicable for non-partially installed applications only
6244 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006245 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 return false;
6247 }
6248 PackageSetting ps = null;
6249 // Confirm if the system package has been updated
6250 // An updated system app can be deleted. This will also have to restore
6251 // the system pkg from system partition
6252 synchronized (mPackages) {
6253 ps = mSettings.getDisabledSystemPkg(p.packageName);
6254 }
6255 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006256 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 return false;
6258 } else {
6259 Log.i(TAG, "Deleting system pkg from data partition");
6260 }
6261 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006262 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006263 final boolean deleteCodeAndResources;
6264 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006265 // Delete code and resources for downgrades
6266 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006267 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006268 } else {
6269 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006270 deleteCodeAndResources = false;
6271 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006272 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006273 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6274 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 if (!ret) {
6276 return false;
6277 }
6278 synchronized (mPackages) {
6279 // Reinstate the old system package
6280 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006281 // Remove any native libraries from the upgraded package.
6282 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 }
6284 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006285 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006287 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006290 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 return false;
6292 }
6293 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006294 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006295 if (writeSettings) {
6296 mSettings.writeLP();
6297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 }
6299 return true;
6300 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006303 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6304 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 ApplicationInfo applicationInfo = p.applicationInfo;
6306 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006307 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 return false;
6309 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006310 if (outInfo != null) {
6311 outInfo.uid = applicationInfo.uid;
6312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313
6314 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006315 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316
6317 // Delete application code and resources
6318 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006319 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006320 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6321 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6322 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6323 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 }
6325 return true;
6326 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 /*
6329 * This method handles package deletion in general
6330 */
6331 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006332 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6333 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006335 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 return false;
6337 }
6338 PackageParser.Package p;
6339 boolean dataOnly = false;
6340 synchronized (mPackages) {
6341 p = mPackages.get(packageName);
6342 if (p == null) {
6343 //this retrieves partially installed apps
6344 dataOnly = true;
6345 PackageSetting ps = mSettings.mPackages.get(packageName);
6346 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006347 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 return false;
6349 }
6350 p = ps.pkg;
6351 }
6352 }
6353 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006354 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 return false;
6356 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 if (dataOnly) {
6359 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006360 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006361 return true;
6362 }
6363 // At this point the package should have ApplicationInfo associated with it
6364 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006365 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 return false;
6367 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006368 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006369 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 Log.i(TAG, "Removing system package:"+p.packageName);
6371 // When an updated system application is deleted we delete the existing resources as well and
6372 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006373 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006374 } else {
6375 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006376 // Kill application pre-emptively especially for apps on sd.
6377 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006378 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6379 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006381 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 public void clearApplicationUserData(final String packageName,
6385 final IPackageDataObserver observer) {
6386 mContext.enforceCallingOrSelfPermission(
6387 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6388 // Queue up an async operation since the package deletion may take a little while.
6389 mHandler.post(new Runnable() {
6390 public void run() {
6391 mHandler.removeCallbacks(this);
6392 final boolean succeeded;
6393 synchronized (mInstallLock) {
6394 succeeded = clearApplicationUserDataLI(packageName);
6395 }
6396 if (succeeded) {
6397 // invoke DeviceStorageMonitor's update method to clear any notifications
6398 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6399 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6400 if (dsm != null) {
6401 dsm.updateMemory();
6402 }
6403 }
6404 if(observer != null) {
6405 try {
6406 observer.onRemoveCompleted(packageName, succeeded);
6407 } catch (RemoteException e) {
6408 Log.i(TAG, "Observer no longer exists.");
6409 }
6410 } //end if observer
6411 } //end run
6412 });
6413 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 private boolean clearApplicationUserDataLI(String packageName) {
6416 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006417 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 return false;
6419 }
6420 PackageParser.Package p;
6421 boolean dataOnly = false;
6422 synchronized (mPackages) {
6423 p = mPackages.get(packageName);
6424 if(p == null) {
6425 dataOnly = true;
6426 PackageSetting ps = mSettings.mPackages.get(packageName);
6427 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006428 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006429 return false;
6430 }
6431 p = ps.pkg;
6432 }
6433 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006434 boolean useEncryptedFSDir = false;
6435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 if(!dataOnly) {
6437 //need to check this only for fully installed applications
6438 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006439 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 return false;
6441 }
6442 final ApplicationInfo applicationInfo = p.applicationInfo;
6443 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006444 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 return false;
6446 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006447 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 }
6449 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006450 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006452 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 + packageName);
6454 return false;
6455 }
6456 }
6457 return true;
6458 }
6459
6460 public void deleteApplicationCacheFiles(final String packageName,
6461 final IPackageDataObserver observer) {
6462 mContext.enforceCallingOrSelfPermission(
6463 android.Manifest.permission.DELETE_CACHE_FILES, null);
6464 // Queue up an async operation since the package deletion may take a little while.
6465 mHandler.post(new Runnable() {
6466 public void run() {
6467 mHandler.removeCallbacks(this);
6468 final boolean succeded;
6469 synchronized (mInstallLock) {
6470 succeded = deleteApplicationCacheFilesLI(packageName);
6471 }
6472 if(observer != null) {
6473 try {
6474 observer.onRemoveCompleted(packageName, succeded);
6475 } catch (RemoteException e) {
6476 Log.i(TAG, "Observer no longer exists.");
6477 }
6478 } //end if observer
6479 } //end run
6480 });
6481 }
6482
6483 private boolean deleteApplicationCacheFilesLI(String packageName) {
6484 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006485 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 return false;
6487 }
6488 PackageParser.Package p;
6489 synchronized (mPackages) {
6490 p = mPackages.get(packageName);
6491 }
6492 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006493 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 return false;
6495 }
6496 final ApplicationInfo applicationInfo = p.applicationInfo;
6497 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006498 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 return false;
6500 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006501 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006503 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006505 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 + packageName);
6507 return false;
6508 }
6509 }
6510 return true;
6511 }
6512
6513 public void getPackageSizeInfo(final String packageName,
6514 final IPackageStatsObserver observer) {
6515 mContext.enforceCallingOrSelfPermission(
6516 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6517 // Queue up an async operation since the package deletion may take a little while.
6518 mHandler.post(new Runnable() {
6519 public void run() {
6520 mHandler.removeCallbacks(this);
6521 PackageStats lStats = new PackageStats(packageName);
6522 final boolean succeded;
6523 synchronized (mInstallLock) {
6524 succeded = getPackageSizeInfoLI(packageName, lStats);
6525 }
6526 if(observer != null) {
6527 try {
6528 observer.onGetStatsCompleted(lStats, succeded);
6529 } catch (RemoteException e) {
6530 Log.i(TAG, "Observer no longer exists.");
6531 }
6532 } //end if observer
6533 } //end run
6534 });
6535 }
6536
6537 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6538 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006539 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 return false;
6541 }
6542 PackageParser.Package p;
6543 boolean dataOnly = false;
6544 synchronized (mPackages) {
6545 p = mPackages.get(packageName);
6546 if(p == null) {
6547 dataOnly = true;
6548 PackageSetting ps = mSettings.mPackages.get(packageName);
6549 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006550 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006551 return false;
6552 }
6553 p = ps.pkg;
6554 }
6555 }
6556 String publicSrcDir = null;
6557 if(!dataOnly) {
6558 final ApplicationInfo applicationInfo = p.applicationInfo;
6559 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006560 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 return false;
6562 }
6563 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6564 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006565 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 if (mInstaller != null) {
6567 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006568 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006569 if (res < 0) {
6570 return false;
6571 } else {
6572 return true;
6573 }
6574 }
6575 return true;
6576 }
6577
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006580 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 }
6582
6583 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006584 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 }
6586
6587 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006588 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 }
6590
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006591 int getUidTargetSdkVersionLockedLP(int uid) {
6592 Object obj = mSettings.getUserIdLP(uid);
6593 if (obj instanceof SharedUserSetting) {
6594 SharedUserSetting sus = (SharedUserSetting)obj;
6595 final int N = sus.packages.size();
6596 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6597 Iterator<PackageSetting> it = sus.packages.iterator();
6598 int i=0;
6599 while (it.hasNext()) {
6600 PackageSetting ps = it.next();
6601 if (ps.pkg != null) {
6602 int v = ps.pkg.applicationInfo.targetSdkVersion;
6603 if (v < vers) vers = v;
6604 }
6605 }
6606 return vers;
6607 } else if (obj instanceof PackageSetting) {
6608 PackageSetting ps = (PackageSetting)obj;
6609 if (ps.pkg != null) {
6610 return ps.pkg.applicationInfo.targetSdkVersion;
6611 }
6612 }
6613 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6614 }
6615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 public void addPreferredActivity(IntentFilter filter, int match,
6617 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006619 if (mContext.checkCallingOrSelfPermission(
6620 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6621 != PackageManager.PERMISSION_GRANTED) {
6622 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6623 < Build.VERSION_CODES.FROYO) {
6624 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6625 + Binder.getCallingUid());
6626 return;
6627 }
6628 mContext.enforceCallingOrSelfPermission(
6629 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6630 }
6631
6632 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6634 mSettings.mPreferredActivities.addFilter(
6635 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006636 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 }
6638 }
6639
Satish Sampath8dbe6122009-06-02 23:35:54 +01006640 public void replacePreferredActivity(IntentFilter filter, int match,
6641 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006642 if (filter.countActions() != 1) {
6643 throw new IllegalArgumentException(
6644 "replacePreferredActivity expects filter to have only 1 action.");
6645 }
6646 if (filter.countCategories() != 1) {
6647 throw new IllegalArgumentException(
6648 "replacePreferredActivity expects filter to have only 1 category.");
6649 }
6650 if (filter.countDataAuthorities() != 0
6651 || filter.countDataPaths() != 0
6652 || filter.countDataSchemes() != 0
6653 || filter.countDataTypes() != 0) {
6654 throw new IllegalArgumentException(
6655 "replacePreferredActivity expects filter to have no data authorities, " +
6656 "paths, schemes or types.");
6657 }
6658 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006659 if (mContext.checkCallingOrSelfPermission(
6660 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6661 != PackageManager.PERMISSION_GRANTED) {
6662 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6663 < Build.VERSION_CODES.FROYO) {
6664 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6665 + Binder.getCallingUid());
6666 return;
6667 }
6668 mContext.enforceCallingOrSelfPermission(
6669 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6670 }
6671
Satish Sampath8dbe6122009-06-02 23:35:54 +01006672 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6673 String action = filter.getAction(0);
6674 String category = filter.getCategory(0);
6675 while (it.hasNext()) {
6676 PreferredActivity pa = it.next();
6677 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6678 it.remove();
6679 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6680 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6681 }
6682 }
6683 addPreferredActivity(filter, match, set, activity);
6684 }
6685 }
6686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006689 int uid = Binder.getCallingUid();
6690 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006691 if (pkg == null || pkg.applicationInfo.uid != uid) {
6692 if (mContext.checkCallingOrSelfPermission(
6693 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6694 != PackageManager.PERMISSION_GRANTED) {
6695 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6696 < Build.VERSION_CODES.FROYO) {
6697 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6698 + Binder.getCallingUid());
6699 return;
6700 }
6701 mContext.enforceCallingOrSelfPermission(
6702 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6703 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006704 }
6705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006707 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 }
6709 }
6710 }
6711
6712 boolean clearPackagePreferredActivitiesLP(String packageName) {
6713 boolean changed = false;
6714 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6715 while (it.hasNext()) {
6716 PreferredActivity pa = it.next();
6717 if (pa.mActivity.getPackageName().equals(packageName)) {
6718 it.remove();
6719 changed = true;
6720 }
6721 }
6722 return changed;
6723 }
6724
6725 public int getPreferredActivities(List<IntentFilter> outFilters,
6726 List<ComponentName> outActivities, String packageName) {
6727
6728 int num = 0;
6729 synchronized (mPackages) {
6730 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6731 while (it.hasNext()) {
6732 PreferredActivity pa = it.next();
6733 if (packageName == null
6734 || pa.mActivity.getPackageName().equals(packageName)) {
6735 if (outFilters != null) {
6736 outFilters.add(new IntentFilter(pa));
6737 }
6738 if (outActivities != null) {
6739 outActivities.add(pa.mActivity);
6740 }
6741 }
6742 }
6743 }
6744
6745 return num;
6746 }
6747
6748 public void setApplicationEnabledSetting(String appPackageName,
6749 int newState, int flags) {
6750 setEnabledSetting(appPackageName, null, newState, flags);
6751 }
6752
6753 public void setComponentEnabledSetting(ComponentName componentName,
6754 int newState, int flags) {
6755 setEnabledSetting(componentName.getPackageName(),
6756 componentName.getClassName(), newState, flags);
6757 }
6758
6759 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006760 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6762 || newState == COMPONENT_ENABLED_STATE_ENABLED
6763 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6764 throw new IllegalArgumentException("Invalid new component state: "
6765 + newState);
6766 }
6767 PackageSetting pkgSetting;
6768 final int uid = Binder.getCallingUid();
6769 final int permission = mContext.checkCallingPermission(
6770 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6771 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006772 boolean sendNow = false;
6773 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006774 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006776 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006778 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006780 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006782 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 }
6784 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006785 "Unknown component: " + packageName
6786 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 }
6788 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6789 throw new SecurityException(
6790 "Permission Denial: attempt to change component state from pid="
6791 + Binder.getCallingPid()
6792 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6793 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006794 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006795 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006796 if (pkgSetting.enabled == newState) {
6797 // Nothing to do
6798 return;
6799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006801 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 } else {
6803 // We're dealing with a component level state change
6804 switch (newState) {
6805 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006806 if (!pkgSetting.enableComponentLP(className)) {
6807 return;
6808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 break;
6810 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006811 if (!pkgSetting.disableComponentLP(className)) {
6812 return;
6813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006814 break;
6815 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006816 if (!pkgSetting.restoreComponentLP(className)) {
6817 return;
6818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006819 break;
6820 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006821 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006822 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 }
6824 }
6825 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006826 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006827 components = mPendingBroadcasts.get(packageName);
6828 boolean newPackage = components == null;
6829 if (newPackage) {
6830 components = new ArrayList<String>();
6831 }
6832 if (!components.contains(componentName)) {
6833 components.add(componentName);
6834 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006835 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6836 sendNow = true;
6837 // Purge entry from pending broadcast list if another one exists already
6838 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006839 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006840 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006841 if (newPackage) {
6842 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006843 }
6844 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6845 // Schedule a message
6846 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6847 }
6848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006849 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006851 long callingId = Binder.clearCallingIdentity();
6852 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006853 if (sendNow) {
6854 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006855 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 } finally {
6858 Binder.restoreCallingIdentity(callingId);
6859 }
6860 }
6861
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006862 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006863 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6864 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6865 + " components=" + componentNames);
6866 Bundle extras = new Bundle(4);
6867 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6868 String nameList[] = new String[componentNames.size()];
6869 componentNames.toArray(nameList);
6870 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006871 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6872 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006873 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006874 }
6875
Jacek Surazski65e13172009-04-28 15:26:38 +02006876 public String getInstallerPackageName(String packageName) {
6877 synchronized (mPackages) {
6878 PackageSetting pkg = mSettings.mPackages.get(packageName);
6879 if (pkg == null) {
6880 throw new IllegalArgumentException("Unknown package: " + packageName);
6881 }
6882 return pkg.installerPackageName;
6883 }
6884 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 public int getApplicationEnabledSetting(String appPackageName) {
6887 synchronized (mPackages) {
6888 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6889 if (pkg == null) {
6890 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6891 }
6892 return pkg.enabled;
6893 }
6894 }
6895
6896 public int getComponentEnabledSetting(ComponentName componentName) {
6897 synchronized (mPackages) {
6898 final String packageNameStr = componentName.getPackageName();
6899 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6900 if (pkg == null) {
6901 throw new IllegalArgumentException("Unknown component: " + componentName);
6902 }
6903 final String classNameStr = componentName.getClassName();
6904 return pkg.currentEnabledStateLP(classNameStr);
6905 }
6906 }
6907
6908 public void enterSafeMode() {
6909 if (!mSystemReady) {
6910 mSafeMode = true;
6911 }
6912 }
6913
6914 public void systemReady() {
6915 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006916
6917 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006918 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006919 mContext.getContentResolver(),
6920 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006921 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006922 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006923 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 }
6926
6927 public boolean isSafeMode() {
6928 return mSafeMode;
6929 }
6930
6931 public boolean hasSystemUidErrors() {
6932 return mHasSystemUidErrors;
6933 }
6934
6935 static String arrayToString(int[] array) {
6936 StringBuffer buf = new StringBuffer(128);
6937 buf.append('[');
6938 if (array != null) {
6939 for (int i=0; i<array.length; i++) {
6940 if (i > 0) buf.append(", ");
6941 buf.append(array[i]);
6942 }
6943 }
6944 buf.append(']');
6945 return buf.toString();
6946 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 @Override
6949 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6950 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6951 != PackageManager.PERMISSION_GRANTED) {
6952 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6953 + Binder.getCallingPid()
6954 + ", uid=" + Binder.getCallingUid()
6955 + " without permission "
6956 + android.Manifest.permission.DUMP);
6957 return;
6958 }
6959
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006960 boolean dumpStar = true;
6961 boolean dumpLibs = false;
6962 boolean dumpFeatures = false;
6963 boolean dumpResolvers = false;
6964 boolean dumpPermissions = false;
6965 boolean dumpPackages = false;
6966 boolean dumpSharedUsers = false;
6967 boolean dumpMessages = false;
6968 boolean dumpProviders = false;
6969
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006970 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006971 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006972
6973 int opti = 0;
6974 while (opti < args.length) {
6975 String opt = args[opti];
6976 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6977 break;
6978 }
6979 opti++;
6980 if ("-a".equals(opt)) {
6981 // Right now we only know how to print all.
6982 } else if ("-h".equals(opt)) {
6983 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006984 pw.println(" [-h] [-f] [cmd] ...");
6985 pw.println(" -f: print details of intent filters");
6986 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006987 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006988 pw.println(" l[ibraries]: list known shared libraries");
6989 pw.println(" f[ibraries]: list device features");
6990 pw.println(" r[esolvers]: dump intent resolvers");
6991 pw.println(" perm[issions]: dump permissions");
6992 pw.println(" prov[iders]: dump content providers");
6993 pw.println(" p[ackages]: dump installed packages");
6994 pw.println(" s[hared-users]: dump shared user IDs");
6995 pw.println(" m[essages]: print collected runtime messages");
6996 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006997 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006998 } else if ("-f".equals(opt)) {
6999 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007000 } else {
7001 pw.println("Unknown argument: " + opt + "; use -h for help");
7002 }
7003 }
7004
7005 // Is the caller requesting to dump a particular piece of data?
7006 if (opti < args.length) {
7007 String cmd = args[opti];
7008 opti++;
7009 // Is this a package name?
7010 if ("android".equals(cmd) || cmd.contains(".")) {
7011 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007012 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
7013 dumpStar = false;
7014 dumpLibs = true;
7015 } else if ("f".equals(cmd) || "features".equals(cmd)) {
7016 dumpStar = false;
7017 dumpFeatures = true;
7018 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
7019 dumpStar = false;
7020 dumpResolvers = true;
7021 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
7022 dumpStar = false;
7023 dumpPermissions = true;
7024 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
7025 dumpStar = false;
7026 dumpPackages = true;
7027 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
7028 dumpStar = false;
7029 dumpSharedUsers = true;
7030 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
7031 dumpStar = false;
7032 dumpProviders = true;
7033 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
7034 dumpStar = false;
7035 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007036 }
7037 }
7038
7039 boolean printedTitle = false;
7040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007042 if ((dumpStar || dumpLibs) && packageName == null) {
7043 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007044 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007045 pw.println("Libraries:");
7046 Iterator<String> it = mSharedLibraries.keySet().iterator();
7047 while (it.hasNext()) {
7048 String name = it.next();
7049 pw.print(" ");
7050 pw.print(name);
7051 pw.print(" -> ");
7052 pw.println(mSharedLibraries.get(name));
7053 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007054 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007055
7056 if ((dumpStar || dumpFeatures) && packageName == null) {
7057 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007058 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007059 pw.println("Features:");
7060 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7061 while (it.hasNext()) {
7062 String name = it.next();
7063 pw.print(" ");
7064 pw.println(name);
7065 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007066 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007067
7068 if (dumpStar || dumpResolvers) {
7069 if (mActivities.dump(pw, printedTitle
7070 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7071 " ", packageName, showFilters)) {
7072 printedTitle = true;
7073 }
7074 if (mReceivers.dump(pw, printedTitle
7075 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7076 " ", packageName, showFilters)) {
7077 printedTitle = true;
7078 }
7079 if (mServices.dump(pw, printedTitle
7080 ? "\nService Resolver Table:" : "Service Resolver Table:",
7081 " ", packageName, showFilters)) {
7082 printedTitle = true;
7083 }
7084 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7085 ? "\nPreferred Activities:" : "Preferred Activities:",
7086 " ", packageName, showFilters)) {
7087 printedTitle = true;
7088 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007089 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007090
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007091 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007092 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007093 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007094 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7095 continue;
7096 }
7097 if (!printedSomething) {
7098 if (printedTitle) pw.println(" ");
7099 pw.println("Permissions:");
7100 printedSomething = true;
7101 printedTitle = true;
7102 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007103 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7104 pw.print(Integer.toHexString(System.identityHashCode(p)));
7105 pw.println("):");
7106 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7107 pw.print(" uid="); pw.print(p.uid);
7108 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007109 pw.print(" type="); pw.print(p.type);
7110 pw.print(" prot="); pw.println(p.protectionLevel);
7111 if (p.packageSetting != null) {
7112 pw.print(" packageSetting="); pw.println(p.packageSetting);
7113 }
7114 if (p.perm != null) {
7115 pw.print(" perm="); pw.println(p.perm);
7116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 }
7118 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007119
7120 if (dumpStar || dumpProviders) {
7121 printedSomething = false;
7122 for (PackageParser.Provider p : mProviders.values()) {
7123 if (packageName != null && !packageName.equals(p.info.packageName)) {
7124 continue;
7125 }
7126 if (!printedSomething) {
7127 if (printedTitle) pw.println(" ");
7128 pw.println("Registered ContentProviders:");
7129 printedSomething = true;
7130 printedTitle = true;
7131 }
7132 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7133 pw.println(p.toString());
7134 }
7135 }
7136
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007137 printedSomething = false;
7138 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007139 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007140 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7141 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007143 if (packageName != null && !packageName.equals(ps.realName)
7144 && !packageName.equals(ps.name)) {
7145 continue;
7146 }
7147 if (!printedSomething) {
7148 if (printedTitle) pw.println(" ");
7149 pw.println("Packages:");
7150 printedSomething = true;
7151 printedTitle = true;
7152 }
7153 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007154 pw.print(" Package [");
7155 pw.print(ps.realName != null ? ps.realName : ps.name);
7156 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007157 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7158 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007159 if (ps.realName != null) {
7160 pw.print(" compat name="); pw.println(ps.name);
7161 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007162 pw.print(" userId="); pw.print(ps.userId);
7163 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7164 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7165 pw.print(" pkg="); pw.println(ps.pkg);
7166 pw.print(" codePath="); pw.println(ps.codePathString);
7167 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007168 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007169 pw.print(" obbPath="); pw.println(ps.obbPathString);
Kenny Root1174f712010-10-22 10:07:11 -07007170 pw.print(" versionCode="); pw.println(ps.versionCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007171 if (ps.pkg != null) {
Kenny Root1174f712010-10-22 10:07:11 -07007172 pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007173 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007174 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007175 if (ps.pkg.mOperationPending) {
7176 pw.println(" mOperationPending=true");
7177 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007178 pw.print(" supportsScreens=[");
7179 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007180 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007181 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7182 if (!first) pw.print(", ");
7183 first = false;
7184 pw.print("small");
7185 }
7186 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007187 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007188 if (!first) pw.print(", ");
7189 first = false;
7190 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007192 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007193 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007194 if (!first) pw.print(", ");
7195 first = false;
7196 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007198 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007199 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007200 if (!first) pw.print(", ");
7201 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007202 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007203 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007204 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007205 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007206 if (!first) pw.print(", ");
7207 first = false;
7208 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007209 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007210 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007211 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7212 if (!first) pw.print(", ");
7213 first = false;
7214 pw.print("anyDensity");
7215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007216 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007217 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007218 pw.print(" timeStamp=");
7219 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7220 pw.print(" firstInstallTime=");
7221 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7222 pw.print(" lastUpdateTime=");
7223 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007224 pw.print(" signatures="); pw.println(ps.signatures);
7225 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007226 pw.print(" haveGids="); pw.println(ps.haveGids);
7227 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007228 pw.print(" installStatus="); pw.print(ps.installStatus);
7229 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007230 if (ps.disabledComponents.size() > 0) {
7231 pw.println(" disabledComponents:");
7232 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007233 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 }
7235 }
7236 if (ps.enabledComponents.size() > 0) {
7237 pw.println(" enabledComponents:");
7238 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007239 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 }
7241 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007242 if (ps.grantedPermissions.size() > 0) {
7243 pw.println(" grantedPermissions:");
7244 for (String s : ps.grantedPermissions) {
7245 pw.print(" "); pw.println(s);
7246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007248 }
7249 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007250 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007251 if (dumpStar || dumpPackages) {
7252 if (mSettings.mRenamedPackages.size() > 0) {
7253 for (HashMap.Entry<String, String> e
7254 : mSettings.mRenamedPackages.entrySet()) {
7255 if (packageName != null && !packageName.equals(e.getKey())
7256 && !packageName.equals(e.getValue())) {
7257 continue;
7258 }
7259 if (!printedSomething) {
7260 if (printedTitle) pw.println(" ");
7261 pw.println("Renamed packages:");
7262 printedSomething = true;
7263 printedTitle = true;
7264 }
7265 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7266 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007267 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007268 }
7269 printedSomething = false;
7270 if (mSettings.mDisabledSysPackages.size() > 0) {
7271 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7272 if (packageName != null && !packageName.equals(ps.realName)
7273 && !packageName.equals(ps.name)) {
7274 continue;
7275 }
7276 if (!printedSomething) {
7277 if (printedTitle) pw.println(" ");
7278 pw.println("Hidden system packages:");
7279 printedSomething = true;
7280 printedTitle = true;
7281 }
7282 pw.print(" Package [");
7283 pw.print(ps.realName != null ? ps.realName : ps.name);
7284 pw.print("] (");
7285 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7286 pw.println("):");
7287 if (ps.realName != null) {
7288 pw.print(" compat name="); pw.println(ps.name);
7289 }
7290 pw.print(" userId="); pw.println(ps.userId);
7291 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7292 pw.print(" codePath="); pw.println(ps.codePathString);
7293 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007294 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007295 }
7296 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007297 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007298 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007300 if (packageName != null && su != packageSharedUser) {
7301 continue;
7302 }
7303 if (!printedSomething) {
7304 if (printedTitle) pw.println(" ");
7305 pw.println("Shared users:");
7306 printedSomething = true;
7307 printedTitle = true;
7308 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007309 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7310 pw.print(Integer.toHexString(System.identityHashCode(su)));
7311 pw.println("):");
7312 pw.print(" userId="); pw.print(su.userId);
7313 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 pw.println(" grantedPermissions:");
7315 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007316 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007318 }
7319 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007320
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007321 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007322 if (printedTitle) pw.println(" ");
7323 printedTitle = true;
7324 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007325 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007326
7327 pw.println(" ");
7328 pw.println("Package warning messages:");
7329 File fname = getSettingsProblemFile();
7330 FileInputStream in;
7331 try {
7332 in = new FileInputStream(fname);
7333 int avail = in.available();
7334 byte[] data = new byte[avail];
7335 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007336 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007337 } catch (FileNotFoundException e) {
7338 } catch (IOException e) {
7339 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007341 }
7342 }
7343
7344 static final class BasePermission {
7345 final static int TYPE_NORMAL = 0;
7346 final static int TYPE_BUILTIN = 1;
7347 final static int TYPE_DYNAMIC = 2;
7348
7349 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007350 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007351 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007353 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007354 PackageParser.Permission perm;
7355 PermissionInfo pendingInfo;
7356 int uid;
7357 int[] gids;
7358
7359 BasePermission(String _name, String _sourcePackage, int _type) {
7360 name = _name;
7361 sourcePackage = _sourcePackage;
7362 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007363 // Default to most conservative protection level.
7364 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7365 }
7366
7367 public String toString() {
7368 return "BasePermission{"
7369 + Integer.toHexString(System.identityHashCode(this))
7370 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 }
7372 }
7373
7374 static class PackageSignatures {
7375 private Signature[] mSignatures;
7376
7377 PackageSignatures(Signature[] sigs) {
7378 assignSignatures(sigs);
7379 }
7380
7381 PackageSignatures() {
7382 }
7383
7384 void writeXml(XmlSerializer serializer, String tagName,
7385 ArrayList<Signature> pastSignatures) throws IOException {
7386 if (mSignatures == null) {
7387 return;
7388 }
7389 serializer.startTag(null, tagName);
7390 serializer.attribute(null, "count",
7391 Integer.toString(mSignatures.length));
7392 for (int i=0; i<mSignatures.length; i++) {
7393 serializer.startTag(null, "cert");
7394 final Signature sig = mSignatures[i];
7395 final int sigHash = sig.hashCode();
7396 final int numPast = pastSignatures.size();
7397 int j;
7398 for (j=0; j<numPast; j++) {
7399 Signature pastSig = pastSignatures.get(j);
7400 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7401 serializer.attribute(null, "index", Integer.toString(j));
7402 break;
7403 }
7404 }
7405 if (j >= numPast) {
7406 pastSignatures.add(sig);
7407 serializer.attribute(null, "index", Integer.toString(numPast));
7408 serializer.attribute(null, "key", sig.toCharsString());
7409 }
7410 serializer.endTag(null, "cert");
7411 }
7412 serializer.endTag(null, tagName);
7413 }
7414
7415 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7416 throws IOException, XmlPullParserException {
7417 String countStr = parser.getAttributeValue(null, "count");
7418 if (countStr == null) {
7419 reportSettingsProblem(Log.WARN,
7420 "Error in package manager settings: <signatures> has"
7421 + " no count at " + parser.getPositionDescription());
7422 XmlUtils.skipCurrentTag(parser);
7423 }
7424 final int count = Integer.parseInt(countStr);
7425 mSignatures = new Signature[count];
7426 int pos = 0;
7427
7428 int outerDepth = parser.getDepth();
7429 int type;
7430 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7431 && (type != XmlPullParser.END_TAG
7432 || parser.getDepth() > outerDepth)) {
7433 if (type == XmlPullParser.END_TAG
7434 || type == XmlPullParser.TEXT) {
7435 continue;
7436 }
7437
7438 String tagName = parser.getName();
7439 if (tagName.equals("cert")) {
7440 if (pos < count) {
7441 String index = parser.getAttributeValue(null, "index");
7442 if (index != null) {
7443 try {
7444 int idx = Integer.parseInt(index);
7445 String key = parser.getAttributeValue(null, "key");
7446 if (key == null) {
7447 if (idx >= 0 && idx < pastSignatures.size()) {
7448 Signature sig = pastSignatures.get(idx);
7449 if (sig != null) {
7450 mSignatures[pos] = pastSignatures.get(idx);
7451 pos++;
7452 } else {
7453 reportSettingsProblem(Log.WARN,
7454 "Error in package manager settings: <cert> "
7455 + "index " + index + " is not defined at "
7456 + parser.getPositionDescription());
7457 }
7458 } else {
7459 reportSettingsProblem(Log.WARN,
7460 "Error in package manager settings: <cert> "
7461 + "index " + index + " is out of bounds at "
7462 + parser.getPositionDescription());
7463 }
7464 } else {
7465 while (pastSignatures.size() <= idx) {
7466 pastSignatures.add(null);
7467 }
7468 Signature sig = new Signature(key);
7469 pastSignatures.set(idx, sig);
7470 mSignatures[pos] = sig;
7471 pos++;
7472 }
7473 } catch (NumberFormatException e) {
7474 reportSettingsProblem(Log.WARN,
7475 "Error in package manager settings: <cert> "
7476 + "index " + index + " is not a number at "
7477 + parser.getPositionDescription());
7478 }
7479 } else {
7480 reportSettingsProblem(Log.WARN,
7481 "Error in package manager settings: <cert> has"
7482 + " no index at " + parser.getPositionDescription());
7483 }
7484 } else {
7485 reportSettingsProblem(Log.WARN,
7486 "Error in package manager settings: too "
7487 + "many <cert> tags, expected " + count
7488 + " at " + parser.getPositionDescription());
7489 }
7490 } else {
7491 reportSettingsProblem(Log.WARN,
7492 "Unknown element under <cert>: "
7493 + parser.getName());
7494 }
7495 XmlUtils.skipCurrentTag(parser);
7496 }
7497
7498 if (pos < count) {
7499 // Should never happen -- there is an error in the written
7500 // settings -- but if it does we don't want to generate
7501 // a bad array.
7502 Signature[] newSigs = new Signature[pos];
7503 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7504 mSignatures = newSigs;
7505 }
7506 }
7507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007508 private void assignSignatures(Signature[] sigs) {
7509 if (sigs == null) {
7510 mSignatures = null;
7511 return;
7512 }
7513 mSignatures = new Signature[sigs.length];
7514 for (int i=0; i<sigs.length; i++) {
7515 mSignatures[i] = sigs[i];
7516 }
7517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007519 @Override
7520 public String toString() {
7521 StringBuffer buf = new StringBuffer(128);
7522 buf.append("PackageSignatures{");
7523 buf.append(Integer.toHexString(System.identityHashCode(this)));
7524 buf.append(" [");
7525 if (mSignatures != null) {
7526 for (int i=0; i<mSignatures.length; i++) {
7527 if (i > 0) buf.append(", ");
7528 buf.append(Integer.toHexString(
7529 System.identityHashCode(mSignatures[i])));
7530 }
7531 }
7532 buf.append("]}");
7533 return buf.toString();
7534 }
7535 }
7536
7537 static class PreferredActivity extends IntentFilter {
7538 final int mMatch;
7539 final String[] mSetPackages;
7540 final String[] mSetClasses;
7541 final String[] mSetComponents;
7542 final ComponentName mActivity;
7543 final String mShortActivity;
7544 String mParseError;
7545
7546 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7547 ComponentName activity) {
7548 super(filter);
7549 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7550 mActivity = activity;
7551 mShortActivity = activity.flattenToShortString();
7552 mParseError = null;
7553 if (set != null) {
7554 final int N = set.length;
7555 String[] myPackages = new String[N];
7556 String[] myClasses = new String[N];
7557 String[] myComponents = new String[N];
7558 for (int i=0; i<N; i++) {
7559 ComponentName cn = set[i];
7560 if (cn == null) {
7561 mSetPackages = null;
7562 mSetClasses = null;
7563 mSetComponents = null;
7564 return;
7565 }
7566 myPackages[i] = cn.getPackageName().intern();
7567 myClasses[i] = cn.getClassName().intern();
7568 myComponents[i] = cn.flattenToShortString().intern();
7569 }
7570 mSetPackages = myPackages;
7571 mSetClasses = myClasses;
7572 mSetComponents = myComponents;
7573 } else {
7574 mSetPackages = null;
7575 mSetClasses = null;
7576 mSetComponents = null;
7577 }
7578 }
7579
7580 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7581 IOException {
7582 mShortActivity = parser.getAttributeValue(null, "name");
7583 mActivity = ComponentName.unflattenFromString(mShortActivity);
7584 if (mActivity == null) {
7585 mParseError = "Bad activity name " + mShortActivity;
7586 }
7587 String matchStr = parser.getAttributeValue(null, "match");
7588 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7589 String setCountStr = parser.getAttributeValue(null, "set");
7590 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7591
7592 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7593 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7594 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7595
7596 int setPos = 0;
7597
7598 int outerDepth = parser.getDepth();
7599 int type;
7600 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7601 && (type != XmlPullParser.END_TAG
7602 || parser.getDepth() > outerDepth)) {
7603 if (type == XmlPullParser.END_TAG
7604 || type == XmlPullParser.TEXT) {
7605 continue;
7606 }
7607
7608 String tagName = parser.getName();
7609 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7610 // + parser.getDepth() + " tag=" + tagName);
7611 if (tagName.equals("set")) {
7612 String name = parser.getAttributeValue(null, "name");
7613 if (name == null) {
7614 if (mParseError == null) {
7615 mParseError = "No name in set tag in preferred activity "
7616 + mShortActivity;
7617 }
7618 } else if (setPos >= setCount) {
7619 if (mParseError == null) {
7620 mParseError = "Too many set tags in preferred activity "
7621 + mShortActivity;
7622 }
7623 } else {
7624 ComponentName cn = ComponentName.unflattenFromString(name);
7625 if (cn == null) {
7626 if (mParseError == null) {
7627 mParseError = "Bad set name " + name + " in preferred activity "
7628 + mShortActivity;
7629 }
7630 } else {
7631 myPackages[setPos] = cn.getPackageName();
7632 myClasses[setPos] = cn.getClassName();
7633 myComponents[setPos] = name;
7634 setPos++;
7635 }
7636 }
7637 XmlUtils.skipCurrentTag(parser);
7638 } else if (tagName.equals("filter")) {
7639 //Log.i(TAG, "Starting to parse filter...");
7640 readFromXml(parser);
7641 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7642 // + parser.getDepth() + " tag=" + parser.getName());
7643 } else {
7644 reportSettingsProblem(Log.WARN,
7645 "Unknown element under <preferred-activities>: "
7646 + parser.getName());
7647 XmlUtils.skipCurrentTag(parser);
7648 }
7649 }
7650
7651 if (setPos != setCount) {
7652 if (mParseError == null) {
7653 mParseError = "Not enough set tags (expected " + setCount
7654 + " but found " + setPos + ") in " + mShortActivity;
7655 }
7656 }
7657
7658 mSetPackages = myPackages;
7659 mSetClasses = myClasses;
7660 mSetComponents = myComponents;
7661 }
7662
7663 public void writeToXml(XmlSerializer serializer) throws IOException {
7664 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7665 serializer.attribute(null, "name", mShortActivity);
7666 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7667 serializer.attribute(null, "set", Integer.toString(NS));
7668 for (int s=0; s<NS; s++) {
7669 serializer.startTag(null, "set");
7670 serializer.attribute(null, "name", mSetComponents[s]);
7671 serializer.endTag(null, "set");
7672 }
7673 serializer.startTag(null, "filter");
7674 super.writeToXml(serializer);
7675 serializer.endTag(null, "filter");
7676 }
7677
7678 boolean sameSet(List<ResolveInfo> query, int priority) {
7679 if (mSetPackages == null) return false;
7680 final int NQ = query.size();
7681 final int NS = mSetPackages.length;
7682 int numMatch = 0;
7683 for (int i=0; i<NQ; i++) {
7684 ResolveInfo ri = query.get(i);
7685 if (ri.priority != priority) continue;
7686 ActivityInfo ai = ri.activityInfo;
7687 boolean good = false;
7688 for (int j=0; j<NS; j++) {
7689 if (mSetPackages[j].equals(ai.packageName)
7690 && mSetClasses[j].equals(ai.name)) {
7691 numMatch++;
7692 good = true;
7693 break;
7694 }
7695 }
7696 if (!good) return false;
7697 }
7698 return numMatch == NS;
7699 }
7700 }
7701
7702 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007703 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705 HashSet<String> grantedPermissions = new HashSet<String>();
7706 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007709 setFlags(pkgFlags);
7710 }
7711
7712 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007713 this.pkgFlags = pkgFlags & (
7714 ApplicationInfo.FLAG_SYSTEM |
7715 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007716 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007717 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 }
7719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721 /**
7722 * Settings base class for pending and resolved classes.
7723 */
7724 static class PackageSettingBase extends GrantedPermissions {
7725 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007726 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007727 File codePath;
7728 String codePathString;
7729 File resourcePath;
7730 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007731 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007732 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007733 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007734 long firstInstallTime;
7735 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007736 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007738 boolean uidError;
7739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 PackageSignatures signatures = new PackageSignatures();
7741
7742 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007743 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 /* Explicitly disabled components */
7746 HashSet<String> disabledComponents = new HashSet<String>(0);
7747 /* Explicitly enabled components */
7748 HashSet<String> enabledComponents = new HashSet<String>(0);
7749 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7750 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007751
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007752 PackageSettingBase origPackage;
7753
Jacek Surazski65e13172009-04-28 15:26:38 +02007754 /* package name of the app that installed this package */
7755 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007757 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007758 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007759 super(pkgFlags);
7760 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007761 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007762 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007763 }
7764
Kenny Root806cc132010-09-12 08:34:19 -07007765 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7766 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007767 this.codePath = codePath;
7768 this.codePathString = codePath.toString();
7769 this.resourcePath = resourcePath;
7770 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007771 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007772 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 }
Kenny Root85387d72010-08-26 10:13:11 -07007774
Jacek Surazski65e13172009-04-28 15:26:38 +02007775 public void setInstallerPackageName(String packageName) {
7776 installerPackageName = packageName;
7777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007778
Jacek Surazski65e13172009-04-28 15:26:38 +02007779 String getInstallerPackageName() {
7780 return installerPackageName;
7781 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 public void setInstallStatus(int newStatus) {
7784 installStatus = newStatus;
7785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 public int getInstallStatus() {
7788 return installStatus;
7789 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007792 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 }
7794
7795 public void copyFrom(PackageSettingBase base) {
7796 grantedPermissions = base.grantedPermissions;
7797 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007799 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007800 firstInstallTime = base.firstInstallTime;
7801 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 signatures = base.signatures;
7803 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007804 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 disabledComponents = base.disabledComponents;
7806 enabledComponents = base.enabledComponents;
7807 enabled = base.enabled;
7808 installStatus = base.installStatus;
7809 }
7810
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007811 boolean enableComponentLP(String componentClassName) {
7812 boolean changed = disabledComponents.remove(componentClassName);
7813 changed |= enabledComponents.add(componentClassName);
7814 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 }
7816
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007817 boolean disableComponentLP(String componentClassName) {
7818 boolean changed = enabledComponents.remove(componentClassName);
7819 changed |= disabledComponents.add(componentClassName);
7820 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 }
7822
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007823 boolean restoreComponentLP(String componentClassName) {
7824 boolean changed = enabledComponents.remove(componentClassName);
7825 changed |= disabledComponents.remove(componentClassName);
7826 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 }
7828
7829 int currentEnabledStateLP(String componentName) {
7830 if (enabledComponents.contains(componentName)) {
7831 return COMPONENT_ENABLED_STATE_ENABLED;
7832 } else if (disabledComponents.contains(componentName)) {
7833 return COMPONENT_ENABLED_STATE_DISABLED;
7834 } else {
7835 return COMPONENT_ENABLED_STATE_DEFAULT;
7836 }
7837 }
7838 }
7839
7840 /**
7841 * Settings data for a particular package we know about.
7842 */
7843 static final class PackageSetting extends PackageSettingBase {
7844 int userId;
7845 PackageParser.Package pkg;
7846 SharedUserSetting sharedUser;
7847
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007848 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007849 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7850 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7851 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 @Override
7855 public String toString() {
7856 return "PackageSetting{"
7857 + Integer.toHexString(System.identityHashCode(this))
7858 + " " + name + "/" + userId + "}";
7859 }
7860 }
7861
7862 /**
7863 * Settings data for a particular shared user ID we know about.
7864 */
7865 static final class SharedUserSetting extends GrantedPermissions {
7866 final String name;
7867 int userId;
7868 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7869 final PackageSignatures signatures = new PackageSignatures();
7870
7871 SharedUserSetting(String _name, int _pkgFlags) {
7872 super(_pkgFlags);
7873 name = _name;
7874 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007876 @Override
7877 public String toString() {
7878 return "SharedUserSetting{"
7879 + Integer.toHexString(System.identityHashCode(this))
7880 + " " + name + "/" + userId + "}";
7881 }
7882 }
7883
7884 /**
7885 * Holds information about dynamic settings.
7886 */
7887 private static final class Settings {
7888 private final File mSettingsFilename;
7889 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007890 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 private final HashMap<String, PackageSetting> mPackages =
7892 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 // List of replaced system applications
7894 final HashMap<String, PackageSetting> mDisabledSysPackages =
7895 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007896
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007897 // These are the last platform API version we were using for
7898 // the apps installed on internal and external storage. It is
7899 // used to grant newer permissions one time during a system upgrade.
7900 int mInternalSdkPlatform;
7901 int mExternalSdkPlatform;
7902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 // The user's preferred activities associated with particular intent
7904 // filters.
7905 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7906 new IntentResolver<PreferredActivity, PreferredActivity>() {
7907 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007908 protected String packageForFilter(PreferredActivity filter) {
7909 return filter.mActivity.getPackageName();
7910 }
7911 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007912 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007913 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007914 out.print(prefix); out.print(
7915 Integer.toHexString(System.identityHashCode(filter)));
7916 out.print(' ');
7917 out.print(filter.mActivity.flattenToShortString());
7918 out.print(" match=0x");
7919 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007920 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007921 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007922 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007923 out.print(prefix); out.print(" ");
7924 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 }
7926 }
7927 }
7928 };
7929 private final HashMap<String, SharedUserSetting> mSharedUsers =
7930 new HashMap<String, SharedUserSetting>();
7931 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7932 private final SparseArray<Object> mOtherUserIds =
7933 new SparseArray<Object>();
7934
7935 // For reading/writing settings file.
7936 private final ArrayList<Signature> mPastSignatures =
7937 new ArrayList<Signature>();
7938
7939 // Mapping from permission names to info about them.
7940 final HashMap<String, BasePermission> mPermissions =
7941 new HashMap<String, BasePermission>();
7942
7943 // Mapping from permission tree names to info about them.
7944 final HashMap<String, BasePermission> mPermissionTrees =
7945 new HashMap<String, BasePermission>();
7946
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007947 // Packages that have been uninstalled and still need their external
7948 // storage data deleted.
7949 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7950
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007951 // Packages that have been renamed since they were first installed.
7952 // Keys are the new names of the packages, values are the original
7953 // names. The packages appear everwhere else under their original
7954 // names.
7955 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 private final StringBuilder mReadMessages = new StringBuilder();
7958
7959 private static final class PendingPackage extends PackageSettingBase {
7960 final int sharedId;
7961
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007962 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007963 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7964 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7965 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 this.sharedId = sharedId;
7967 }
7968 }
7969 private final ArrayList<PendingPackage> mPendingPackages
7970 = new ArrayList<PendingPackage>();
7971
7972 Settings() {
7973 File dataDir = Environment.getDataDirectory();
7974 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007975 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7976 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007978 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 FileUtils.setPermissions(systemDir.toString(),
7980 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7981 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7982 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007983 FileUtils.setPermissions(systemSecureDir.toString(),
7984 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7985 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7986 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 mSettingsFilename = new File(systemDir, "packages.xml");
7988 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007989 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 }
7991
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007992 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007993 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007994 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007995 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007996 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007997 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 return p;
7999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008000
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008001 PackageSetting peekPackageLP(String name) {
8002 return mPackages.get(name);
8003 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008004 PackageSetting p = mPackages.get(name);
8005 if (p != null && p.codePath.getPath().equals(codePath)) {
8006 return p;
8007 }
8008 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008009 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 void setInstallStatus(String pkgName, int status) {
8013 PackageSetting p = mPackages.get(pkgName);
8014 if(p != null) {
8015 if(p.getInstallStatus() != status) {
8016 p.setInstallStatus(status);
8017 }
8018 }
8019 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008020
Jacek Surazski65e13172009-04-28 15:26:38 +02008021 void setInstallerPackageName(String pkgName,
8022 String installerPkgName) {
8023 PackageSetting p = mPackages.get(pkgName);
8024 if(p != null) {
8025 p.setInstallerPackageName(installerPkgName);
8026 }
8027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008028
Jacek Surazski65e13172009-04-28 15:26:38 +02008029 String getInstallerPackageName(String pkgName) {
8030 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008031 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008032 }
8033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 int getInstallStatus(String pkgName) {
8035 PackageSetting p = mPackages.get(pkgName);
8036 if(p != null) {
8037 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008039 return -1;
8040 }
8041
8042 SharedUserSetting getSharedUserLP(String name,
8043 int pkgFlags, boolean create) {
8044 SharedUserSetting s = mSharedUsers.get(name);
8045 if (s == null) {
8046 if (!create) {
8047 return null;
8048 }
8049 s = new SharedUserSetting(name, pkgFlags);
8050 if (MULTIPLE_APPLICATION_UIDS) {
8051 s.userId = newUserIdLP(s);
8052 } else {
8053 s.userId = FIRST_APPLICATION_UID;
8054 }
8055 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8056 // < 0 means we couldn't assign a userid; fall out and return
8057 // s, which is currently null
8058 if (s.userId >= 0) {
8059 mSharedUsers.put(name, s);
8060 }
8061 }
8062
8063 return s;
8064 }
8065
8066 int disableSystemPackageLP(String name) {
8067 PackageSetting p = mPackages.get(name);
8068 if(p == null) {
8069 Log.w(TAG, "Package:"+name+" is not an installed package");
8070 return -1;
8071 }
8072 PackageSetting dp = mDisabledSysPackages.get(name);
8073 // always make sure the system package code and resource paths dont change
8074 if(dp == null) {
8075 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8076 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8077 }
8078 mDisabledSysPackages.put(name, p);
8079 }
8080 return removePackageLP(name);
8081 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 PackageSetting enableSystemPackageLP(String name) {
8084 PackageSetting p = mDisabledSysPackages.get(name);
8085 if(p == null) {
8086 Log.w(TAG, "Package:"+name+" is not disabled");
8087 return null;
8088 }
8089 // Reset flag in ApplicationInfo object
8090 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8091 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8092 }
Kenny Root806cc132010-09-12 08:34:19 -07008093 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8094 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 mDisabledSysPackages.remove(name);
8096 return ret;
8097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008098
Kenny Root806cc132010-09-12 08:34:19 -07008099 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8100 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008101 PackageSetting p = mPackages.get(name);
8102 if (p != null) {
8103 if (p.userId == uid) {
8104 return p;
8105 }
8106 reportSettingsProblem(Log.ERROR,
8107 "Adding duplicate package, keeping first: " + name);
8108 return null;
8109 }
Kenny Root806cc132010-09-12 08:34:19 -07008110 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8111 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008112 p.userId = uid;
8113 if (addUserIdLP(uid, p, name)) {
8114 mPackages.put(name, p);
8115 return p;
8116 }
8117 return null;
8118 }
8119
8120 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8121 SharedUserSetting s = mSharedUsers.get(name);
8122 if (s != null) {
8123 if (s.userId == uid) {
8124 return s;
8125 }
8126 reportSettingsProblem(Log.ERROR,
8127 "Adding duplicate shared user, keeping first: " + name);
8128 return null;
8129 }
8130 s = new SharedUserSetting(name, pkgFlags);
8131 s.userId = uid;
8132 if (addUserIdLP(uid, s, name)) {
8133 mSharedUsers.put(name, s);
8134 return s;
8135 }
8136 return null;
8137 }
8138
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008139 // Transfer ownership of permissions from one package to another.
8140 private void transferPermissions(String origPkg, String newPkg) {
8141 // Transfer ownership of permissions to the new package.
8142 for (int i=0; i<2; i++) {
8143 HashMap<String, BasePermission> permissions =
8144 i == 0 ? mPermissionTrees : mPermissions;
8145 for (BasePermission bp : permissions.values()) {
8146 if (origPkg.equals(bp.sourcePackage)) {
8147 if (DEBUG_UPGRADE) Log.v(TAG,
8148 "Moving permission " + bp.name
8149 + " from pkg " + bp.sourcePackage
8150 + " to " + newPkg);
8151 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008152 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008153 bp.perm = null;
8154 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008155 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008156 }
8157 bp.uid = 0;
8158 bp.gids = null;
8159 }
8160 }
8161 }
8162 }
8163
8164 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008165 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008166 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008167 PackageSetting p = mPackages.get(name);
8168 if (p != null) {
8169 if (!p.codePath.equals(codePath)) {
8170 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008171 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008172 // This is an updated system app with versions in both system
8173 // and data partition. Just let the most recent version
8174 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008175 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008176 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008177 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008178 // Just a change in the code path is not an issue, but
8179 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008180 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008181 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008182 /*
8183 * Since we've changed paths, we need to prefer the new
8184 * native library path over the one stored in the
8185 * package settings since we might have moved from
8186 * internal to external storage or vice versa.
8187 */
8188 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008190 }
8191 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 reportSettingsProblem(Log.WARN,
8193 "Package " + name + " shared user changed from "
8194 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8195 + " to "
8196 + (sharedUser != null ? sharedUser.name : "<nothing>")
8197 + "; replacing with new");
8198 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008199 } else {
8200 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8201 // If what we are scanning is a system package, then
8202 // make it so, regardless of whether it was previously
8203 // installed only in the data partition.
8204 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008206 }
8207 }
8208 if (p == null) {
8209 // Create a new PackageSettings entry. this can end up here because
8210 // of code path mismatch or user id mismatch of an updated system partition
8211 if (!create) {
8212 return null;
8213 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008214 if (origPackage != null) {
8215 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008216 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8217 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008218 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8219 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008220 // Note that we will retain the new package's signature so
8221 // that we can keep its data.
8222 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008223 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008224 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008225 p.sharedUser = origPackage.sharedUser;
8226 p.userId = origPackage.userId;
8227 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008228 mRenamedPackages.put(name, origPackage.name);
8229 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008230 // Update new package state.
8231 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008233 p = new PackageSetting(name, realName, codePath, resourcePath,
8234 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008235 p.setTimeStamp(codePath.lastModified());
8236 p.sharedUser = sharedUser;
8237 if (sharedUser != null) {
8238 p.userId = sharedUser.userId;
8239 } else if (MULTIPLE_APPLICATION_UIDS) {
8240 // Clone the setting here for disabled system packages
8241 PackageSetting dis = mDisabledSysPackages.get(name);
8242 if (dis != null) {
8243 // For disabled packages a new setting is created
8244 // from the existing user id. This still has to be
8245 // added to list of user id's
8246 // Copy signatures from previous setting
8247 if (dis.signatures.mSignatures != null) {
8248 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8249 }
8250 p.userId = dis.userId;
8251 // Clone permissions
8252 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008253 // Clone component info
8254 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8255 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8256 // Add new setting to list of user ids
8257 addUserIdLP(p.userId, p, name);
8258 } else {
8259 // Assign new user id
8260 p.userId = newUserIdLP(p);
8261 }
8262 } else {
8263 p.userId = FIRST_APPLICATION_UID;
8264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008265 }
8266 if (p.userId < 0) {
8267 reportSettingsProblem(Log.WARN,
8268 "Package " + name + " could not be assigned a valid uid");
8269 return null;
8270 }
8271 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008272 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008274 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 }
8276 }
8277 return p;
8278 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008279
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008280 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008281 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008282 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008283 final String codePath = pkg.applicationInfo.sourceDir;
8284 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008285 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008286 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008287 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008288 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008289 p.codePath = new File(codePath);
8290 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008291 }
8292 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008293 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008294 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008295 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008296 p.resourcePath = new File(resourcePath);
8297 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008298 }
Kenny Root85387d72010-08-26 10:13:11 -07008299 // Update the native library path if needed
8300 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8301 if (nativeLibraryPath != null
8302 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8303 p.nativeLibraryPathString = nativeLibraryPath;
8304 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008305 // Update version code if needed
8306 if (pkg.mVersionCode != p.versionCode) {
8307 p.versionCode = pkg.mVersionCode;
8308 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008309 // Update signatures if needed.
8310 if (p.signatures.mSignatures == null) {
8311 p.signatures.assignSignatures(pkg.mSignatures);
8312 }
8313 // If this app defines a shared user id initialize
8314 // the shared user signatures as well.
8315 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8316 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8317 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008318 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8319 }
8320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008321 // Utility method that adds a PackageSetting to mPackages and
8322 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008323 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008324 SharedUserSetting sharedUser) {
8325 mPackages.put(name, p);
8326 if (sharedUser != null) {
8327 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8328 reportSettingsProblem(Log.ERROR,
8329 "Package " + p.name + " was user "
8330 + p.sharedUser + " but is now " + sharedUser
8331 + "; I am not changing its files so it will probably fail!");
8332 p.sharedUser.packages.remove(p);
8333 } else if (p.userId != sharedUser.userId) {
8334 reportSettingsProblem(Log.ERROR,
8335 "Package " + p.name + " was user id " + p.userId
8336 + " but is now user " + sharedUser
8337 + " with id " + sharedUser.userId
8338 + "; I am not changing its files so it will probably fail!");
8339 }
8340
8341 sharedUser.packages.add(p);
8342 p.sharedUser = sharedUser;
8343 p.userId = sharedUser.userId;
8344 }
8345 }
8346
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008347 /*
8348 * Update the shared user setting when a package using
8349 * specifying the shared user id is removed. The gids
8350 * associated with each permission of the deleted package
8351 * are removed from the shared user's gid list only if its
8352 * not in use by other permissions of packages in the
8353 * shared user setting.
8354 */
8355 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008356 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008357 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008358 return;
8359 }
8360 // No sharedUserId
8361 if (deletedPs.sharedUser == null) {
8362 return;
8363 }
8364 SharedUserSetting sus = deletedPs.sharedUser;
8365 // Update permissions
8366 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8367 boolean used = false;
8368 if (!sus.grantedPermissions.contains (eachPerm)) {
8369 continue;
8370 }
8371 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008372 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008373 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008374 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008375 used = true;
8376 break;
8377 }
8378 }
8379 if (!used) {
8380 // can safely delete this permission from list
8381 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008382 }
8383 }
8384 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008385 int newGids[] = globalGids;
8386 for (String eachPerm : sus.grantedPermissions) {
8387 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008388 if (bp != null) {
8389 newGids = appendInts(newGids, bp.gids);
8390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008391 }
8392 sus.gids = newGids;
8393 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008395 private int removePackageLP(String name) {
8396 PackageSetting p = mPackages.get(name);
8397 if (p != null) {
8398 mPackages.remove(name);
8399 if (p.sharedUser != null) {
8400 p.sharedUser.packages.remove(p);
8401 if (p.sharedUser.packages.size() == 0) {
8402 mSharedUsers.remove(p.sharedUser.name);
8403 removeUserIdLP(p.sharedUser.userId);
8404 return p.sharedUser.userId;
8405 }
8406 } else {
8407 removeUserIdLP(p.userId);
8408 return p.userId;
8409 }
8410 }
8411 return -1;
8412 }
8413
8414 private boolean addUserIdLP(int uid, Object obj, Object name) {
8415 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8416 return false;
8417 }
8418
8419 if (uid >= FIRST_APPLICATION_UID) {
8420 int N = mUserIds.size();
8421 final int index = uid - FIRST_APPLICATION_UID;
8422 while (index >= N) {
8423 mUserIds.add(null);
8424 N++;
8425 }
8426 if (mUserIds.get(index) != null) {
8427 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008428 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008429 + " name=" + name);
8430 return false;
8431 }
8432 mUserIds.set(index, obj);
8433 } else {
8434 if (mOtherUserIds.get(uid) != null) {
8435 reportSettingsProblem(Log.ERROR,
8436 "Adding duplicate shared id: " + uid
8437 + " name=" + name);
8438 return false;
8439 }
8440 mOtherUserIds.put(uid, obj);
8441 }
8442 return true;
8443 }
8444
8445 public Object getUserIdLP(int uid) {
8446 if (uid >= FIRST_APPLICATION_UID) {
8447 int N = mUserIds.size();
8448 final int index = uid - FIRST_APPLICATION_UID;
8449 return index < N ? mUserIds.get(index) : null;
8450 } else {
8451 return mOtherUserIds.get(uid);
8452 }
8453 }
8454
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008455 private Set<String> findPackagesWithFlag(int flag) {
8456 Set<String> ret = new HashSet<String>();
8457 for (PackageSetting ps : mPackages.values()) {
8458 // Has to match atleast all the flag bits set on flag
8459 if ((ps.pkgFlags & flag) == flag) {
8460 ret.add(ps.name);
8461 }
8462 }
8463 return ret;
8464 }
8465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 private void removeUserIdLP(int uid) {
8467 if (uid >= FIRST_APPLICATION_UID) {
8468 int N = mUserIds.size();
8469 final int index = uid - FIRST_APPLICATION_UID;
8470 if (index < N) mUserIds.set(index, null);
8471 } else {
8472 mOtherUserIds.remove(uid);
8473 }
8474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 void writeLP() {
8477 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8478
8479 // Keep the old settings around until we know the new ones have
8480 // been successfully written.
8481 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008482 // Presence of backup settings file indicates that we failed
8483 // to persist settings earlier. So preserve the older
8484 // backup for future reference since the current settings
8485 // might have been corrupted.
8486 if (!mBackupSettingsFilename.exists()) {
8487 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008488 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008489 return;
8490 }
8491 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008492 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008493 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 }
8496
8497 mPastSignatures.clear();
8498
8499 try {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008500 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
8501 BufferedOutputStream str = new BufferedOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502
8503 //XmlSerializer serializer = XmlUtils.serializerInstance();
8504 XmlSerializer serializer = new FastXmlSerializer();
8505 serializer.setOutput(str, "utf-8");
8506 serializer.startDocument(null, true);
8507 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8508
8509 serializer.startTag(null, "packages");
8510
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008511 serializer.startTag(null, "last-platform-version");
8512 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8513 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8514 serializer.endTag(null, "last-platform-version");
8515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 serializer.startTag(null, "permission-trees");
8517 for (BasePermission bp : mPermissionTrees.values()) {
8518 writePermission(serializer, bp);
8519 }
8520 serializer.endTag(null, "permission-trees");
8521
8522 serializer.startTag(null, "permissions");
8523 for (BasePermission bp : mPermissions.values()) {
8524 writePermission(serializer, bp);
8525 }
8526 serializer.endTag(null, "permissions");
8527
8528 for (PackageSetting pkg : mPackages.values()) {
8529 writePackage(serializer, pkg);
8530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008532 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8533 writeDisabledSysPackage(serializer, pkg);
8534 }
8535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008536 serializer.startTag(null, "preferred-activities");
8537 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8538 serializer.startTag(null, "item");
8539 pa.writeToXml(serializer);
8540 serializer.endTag(null, "item");
8541 }
8542 serializer.endTag(null, "preferred-activities");
8543
8544 for (SharedUserSetting usr : mSharedUsers.values()) {
8545 serializer.startTag(null, "shared-user");
8546 serializer.attribute(null, "name", usr.name);
8547 serializer.attribute(null, "userId",
8548 Integer.toString(usr.userId));
8549 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8550 serializer.startTag(null, "perms");
8551 for (String name : usr.grantedPermissions) {
8552 serializer.startTag(null, "item");
8553 serializer.attribute(null, "name", name);
8554 serializer.endTag(null, "item");
8555 }
8556 serializer.endTag(null, "perms");
8557 serializer.endTag(null, "shared-user");
8558 }
8559
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008560 if (mPackagesToBeCleaned.size() > 0) {
8561 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8562 serializer.startTag(null, "cleaning-package");
8563 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8564 serializer.endTag(null, "cleaning-package");
8565 }
8566 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008567
8568 if (mRenamedPackages.size() > 0) {
8569 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8570 serializer.startTag(null, "renamed-package");
8571 serializer.attribute(null, "new", e.getKey());
8572 serializer.attribute(null, "old", e.getValue());
8573 serializer.endTag(null, "renamed-package");
8574 }
8575 }
8576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 serializer.endTag(null, "packages");
8578
8579 serializer.endDocument();
8580
8581 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008582 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583 str.close();
8584
8585 // New settings successfully written, old ones are no longer
8586 // needed.
8587 mBackupSettingsFilename.delete();
8588 FileUtils.setPermissions(mSettingsFilename.toString(),
8589 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8590 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8591 |FileUtils.S_IROTH,
8592 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008593
8594 // Write package list file now, use a JournaledFile.
8595 //
8596 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8597 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8598
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008599 fstr = new FileOutputStream(journal.chooseForWrite());
8600 str = new BufferedOutputStream(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008601 try {
8602 StringBuilder sb = new StringBuilder();
8603 for (PackageSetting pkg : mPackages.values()) {
8604 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008605 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008606 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8607
8608 // Avoid any application that has a space in its path
8609 // or that is handled by the system.
8610 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8611 continue;
8612
8613 // we store on each line the following information for now:
8614 //
8615 // pkgName - package name
8616 // userId - application-specific user id
8617 // debugFlag - 0 or 1 if the package is debuggable.
8618 // dataPath - path to package's data path
8619 //
8620 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8621 //
8622 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8623 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8624 // system/core/run-as/run-as.c
8625 //
8626 sb.setLength(0);
8627 sb.append(ai.packageName);
8628 sb.append(" ");
8629 sb.append((int)ai.uid);
8630 sb.append(isDebug ? " 1 " : " 0 ");
8631 sb.append(dataPath);
8632 sb.append("\n");
8633 str.write(sb.toString().getBytes());
8634 }
8635 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008636 FileUtils.sync(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008637 str.close();
8638 journal.commit();
8639 }
8640 catch (Exception e) {
8641 journal.rollback();
8642 }
8643
8644 FileUtils.setPermissions(mPackageListFilename.toString(),
8645 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8646 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8647 |FileUtils.S_IROTH,
8648 -1, -1);
8649
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008650 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651
8652 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008653 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 -08008654 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008655 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 -08008656 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008657 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008658 if (mSettingsFilename.exists()) {
8659 if (!mSettingsFilename.delete()) {
8660 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8661 }
8662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 //Debug.stopMethodTracing();
8664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008665
8666 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008667 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 serializer.startTag(null, "updated-package");
8669 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008670 if (pkg.realName != null) {
8671 serializer.attribute(null, "realName", pkg.realName);
8672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008674 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8675 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8676 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008677 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8679 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8680 }
Kenny Root85387d72010-08-26 10:13:11 -07008681 if (pkg.nativeLibraryPathString != null) {
8682 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 if (pkg.sharedUser == null) {
8685 serializer.attribute(null, "userId",
8686 Integer.toString(pkg.userId));
8687 } else {
8688 serializer.attribute(null, "sharedUserId",
8689 Integer.toString(pkg.userId));
8690 }
8691 serializer.startTag(null, "perms");
8692 if (pkg.sharedUser == null) {
8693 // If this is a shared user, the permissions will
8694 // be written there. We still need to write an
8695 // empty permissions list so permissionsFixed will
8696 // be set.
8697 for (final String name : pkg.grantedPermissions) {
8698 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008699 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008700 // We only need to write signature or system permissions but this wont
8701 // match the semantics of grantedPermissions. So write all permissions.
8702 serializer.startTag(null, "item");
8703 serializer.attribute(null, "name", name);
8704 serializer.endTag(null, "item");
8705 }
8706 }
8707 }
8708 serializer.endTag(null, "perms");
8709 serializer.endTag(null, "updated-package");
8710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008711
8712 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008713 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 serializer.startTag(null, "package");
8715 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008716 if (pkg.realName != null) {
8717 serializer.attribute(null, "realName", pkg.realName);
8718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 serializer.attribute(null, "codePath", pkg.codePathString);
8720 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8721 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8722 }
Kenny Root85387d72010-08-26 10:13:11 -07008723 if (pkg.nativeLibraryPathString != null) {
8724 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8725 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008726 serializer.attribute(null, "flags",
8727 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008728 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8729 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8730 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008731 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008732 if (pkg.sharedUser == null) {
8733 serializer.attribute(null, "userId",
8734 Integer.toString(pkg.userId));
8735 } else {
8736 serializer.attribute(null, "sharedUserId",
8737 Integer.toString(pkg.userId));
8738 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008739 if (pkg.uidError) {
8740 serializer.attribute(null, "uidError", "true");
8741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008742 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8743 serializer.attribute(null, "enabled",
8744 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8745 ? "true" : "false");
8746 }
8747 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8748 serializer.attribute(null, "installStatus", "false");
8749 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008750 if (pkg.installerPackageName != null) {
8751 serializer.attribute(null, "installer", pkg.installerPackageName);
8752 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008753 if (pkg.obbPathString != null) {
8754 serializer.attribute(null, "obbPath", pkg.obbPathString);
8755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008756 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8757 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8758 serializer.startTag(null, "perms");
8759 if (pkg.sharedUser == null) {
8760 // If this is a shared user, the permissions will
8761 // be written there. We still need to write an
8762 // empty permissions list so permissionsFixed will
8763 // be set.
8764 for (final String name : pkg.grantedPermissions) {
8765 serializer.startTag(null, "item");
8766 serializer.attribute(null, "name", name);
8767 serializer.endTag(null, "item");
8768 }
8769 }
8770 serializer.endTag(null, "perms");
8771 }
8772 if (pkg.disabledComponents.size() > 0) {
8773 serializer.startTag(null, "disabled-components");
8774 for (final String name : pkg.disabledComponents) {
8775 serializer.startTag(null, "item");
8776 serializer.attribute(null, "name", name);
8777 serializer.endTag(null, "item");
8778 }
8779 serializer.endTag(null, "disabled-components");
8780 }
8781 if (pkg.enabledComponents.size() > 0) {
8782 serializer.startTag(null, "enabled-components");
8783 for (final String name : pkg.enabledComponents) {
8784 serializer.startTag(null, "item");
8785 serializer.attribute(null, "name", name);
8786 serializer.endTag(null, "item");
8787 }
8788 serializer.endTag(null, "enabled-components");
8789 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791 serializer.endTag(null, "package");
8792 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 void writePermission(XmlSerializer serializer, BasePermission bp)
8795 throws XmlPullParserException, java.io.IOException {
8796 if (bp.type != BasePermission.TYPE_BUILTIN
8797 && bp.sourcePackage != null) {
8798 serializer.startTag(null, "item");
8799 serializer.attribute(null, "name", bp.name);
8800 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008801 if (bp.protectionLevel !=
8802 PermissionInfo.PROTECTION_NORMAL) {
8803 serializer.attribute(null, "protection",
8804 Integer.toString(bp.protectionLevel));
8805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008806 if (DEBUG_SETTINGS) Log.v(TAG,
8807 "Writing perm: name=" + bp.name + " type=" + bp.type);
8808 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8809 PermissionInfo pi = bp.perm != null ? bp.perm.info
8810 : bp.pendingInfo;
8811 if (pi != null) {
8812 serializer.attribute(null, "type", "dynamic");
8813 if (pi.icon != 0) {
8814 serializer.attribute(null, "icon",
8815 Integer.toString(pi.icon));
8816 }
8817 if (pi.nonLocalizedLabel != null) {
8818 serializer.attribute(null, "label",
8819 pi.nonLocalizedLabel.toString());
8820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008821 }
8822 }
8823 serializer.endTag(null, "item");
8824 }
8825 }
8826
8827 String getReadMessagesLP() {
8828 return mReadMessages.toString();
8829 }
8830
Oscar Montemayora8529f62009-11-18 10:14:20 -08008831 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8833 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008834 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835 while(its.hasNext()) {
8836 String key = its.next();
8837 PackageSetting ps = mPackages.get(key);
8838 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008839 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008840 }
8841 }
8842 return ret;
8843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 boolean readLP() {
8846 FileInputStream str = null;
8847 if (mBackupSettingsFilename.exists()) {
8848 try {
8849 str = new FileInputStream(mBackupSettingsFilename);
8850 mReadMessages.append("Reading from backup settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008851 reportSettingsProblem(Log.INFO, "Need to read from backup settings file");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008852 if (mSettingsFilename.exists()) {
8853 // If both the backup and settings file exist, we
8854 // ignore the settings since it might have been
8855 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008856 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008857 mSettingsFilename.delete();
8858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008859 } catch (java.io.IOException e) {
8860 // We'll try for the normal settings file.
8861 }
8862 }
8863
8864 mPastSignatures.clear();
8865
8866 try {
8867 if (str == null) {
8868 if (!mSettingsFilename.exists()) {
8869 mReadMessages.append("No settings file found\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008870 reportSettingsProblem(Log.INFO, "No settings file; creating initial state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008871 return false;
8872 }
8873 str = new FileInputStream(mSettingsFilename);
8874 }
8875 XmlPullParser parser = Xml.newPullParser();
8876 parser.setInput(str, null);
8877
8878 int type;
8879 while ((type=parser.next()) != XmlPullParser.START_TAG
8880 && type != XmlPullParser.END_DOCUMENT) {
8881 ;
8882 }
8883
8884 if (type != XmlPullParser.START_TAG) {
8885 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008886 reportSettingsProblem(Log.WARN, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887 return false;
8888 }
8889
8890 int outerDepth = parser.getDepth();
8891 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8892 && (type != XmlPullParser.END_TAG
8893 || parser.getDepth() > outerDepth)) {
8894 if (type == XmlPullParser.END_TAG
8895 || type == XmlPullParser.TEXT) {
8896 continue;
8897 }
8898
8899 String tagName = parser.getName();
8900 if (tagName.equals("package")) {
8901 readPackageLP(parser);
8902 } else if (tagName.equals("permissions")) {
8903 readPermissionsLP(mPermissions, parser);
8904 } else if (tagName.equals("permission-trees")) {
8905 readPermissionsLP(mPermissionTrees, parser);
8906 } else if (tagName.equals("shared-user")) {
8907 readSharedUserLP(parser);
8908 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008909 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 } else if (tagName.equals("preferred-activities")) {
8911 readPreferredActivitiesLP(parser);
8912 } else if(tagName.equals("updated-package")) {
8913 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008914 } else if (tagName.equals("cleaning-package")) {
8915 String name = parser.getAttributeValue(null, "name");
8916 if (name != null) {
8917 mPackagesToBeCleaned.add(name);
8918 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008919 } else if (tagName.equals("renamed-package")) {
8920 String nname = parser.getAttributeValue(null, "new");
8921 String oname = parser.getAttributeValue(null, "old");
8922 if (nname != null && oname != null) {
8923 mRenamedPackages.put(nname, oname);
8924 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008925 } else if (tagName.equals("last-platform-version")) {
8926 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8927 try {
8928 String internal = parser.getAttributeValue(null, "internal");
8929 if (internal != null) {
8930 mInternalSdkPlatform = Integer.parseInt(internal);
8931 }
8932 String external = parser.getAttributeValue(null, "external");
8933 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008934 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008935 }
8936 } catch (NumberFormatException e) {
8937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008939 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940 + parser.getName());
8941 XmlUtils.skipCurrentTag(parser);
8942 }
8943 }
8944
8945 str.close();
8946
8947 } catch(XmlPullParserException e) {
8948 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07008949 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008950 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951
8952 } catch(java.io.IOException e) {
8953 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07008954 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008955 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956
8957 }
8958
8959 int N = mPendingPackages.size();
8960 for (int i=0; i<N; i++) {
8961 final PendingPackage pp = mPendingPackages.get(i);
8962 Object idObj = getUserIdLP(pp.sharedId);
8963 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008964 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008965 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8966 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008967 if (p == null) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07008968 reportSettingsProblem(Log.WARN, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008969 + pp.name);
8970 continue;
8971 }
8972 p.copyFrom(pp);
8973 } else if (idObj != null) {
8974 String msg = "Bad package setting: package " + pp.name
8975 + " has shared uid " + pp.sharedId
8976 + " that is not a shared uid\n";
8977 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07008978 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008979 } else {
8980 String msg = "Bad package setting: package " + pp.name
8981 + " has shared uid " + pp.sharedId
8982 + " that is not defined\n";
8983 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07008984 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 }
8986 }
8987 mPendingPackages.clear();
8988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 mReadMessages.append("Read completed successfully: "
8990 + mPackages.size() + " packages, "
8991 + mSharedUsers.size() + " shared uids\n");
8992
8993 return true;
8994 }
8995
8996 private int readInt(XmlPullParser parser, String ns, String name,
8997 int defValue) {
8998 String v = parser.getAttributeValue(ns, name);
8999 try {
9000 if (v == null) {
9001 return defValue;
9002 }
9003 return Integer.parseInt(v);
9004 } catch (NumberFormatException e) {
9005 reportSettingsProblem(Log.WARN,
9006 "Error in package manager settings: attribute " +
9007 name + " has bad integer value " + v + " at "
9008 + parser.getPositionDescription());
9009 }
9010 return defValue;
9011 }
9012
9013 private void readPermissionsLP(HashMap<String, BasePermission> out,
9014 XmlPullParser parser)
9015 throws IOException, XmlPullParserException {
9016 int outerDepth = parser.getDepth();
9017 int type;
9018 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9019 && (type != XmlPullParser.END_TAG
9020 || parser.getDepth() > outerDepth)) {
9021 if (type == XmlPullParser.END_TAG
9022 || type == XmlPullParser.TEXT) {
9023 continue;
9024 }
9025
9026 String tagName = parser.getName();
9027 if (tagName.equals("item")) {
9028 String name = parser.getAttributeValue(null, "name");
9029 String sourcePackage = parser.getAttributeValue(null, "package");
9030 String ptype = parser.getAttributeValue(null, "type");
9031 if (name != null && sourcePackage != null) {
9032 boolean dynamic = "dynamic".equals(ptype);
9033 BasePermission bp = new BasePermission(name, sourcePackage,
9034 dynamic
9035 ? BasePermission.TYPE_DYNAMIC
9036 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009037 bp.protectionLevel = readInt(parser, null, "protection",
9038 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009039 if (dynamic) {
9040 PermissionInfo pi = new PermissionInfo();
9041 pi.packageName = sourcePackage.intern();
9042 pi.name = name.intern();
9043 pi.icon = readInt(parser, null, "icon", 0);
9044 pi.nonLocalizedLabel = parser.getAttributeValue(
9045 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009046 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009047 bp.pendingInfo = pi;
9048 }
9049 out.put(bp.name, bp);
9050 } else {
9051 reportSettingsProblem(Log.WARN,
9052 "Error in package manager settings: permissions has"
9053 + " no name at " + parser.getPositionDescription());
9054 }
9055 } else {
9056 reportSettingsProblem(Log.WARN,
9057 "Unknown element reading permissions: "
9058 + parser.getName() + " at "
9059 + parser.getPositionDescription());
9060 }
9061 XmlUtils.skipCurrentTag(parser);
9062 }
9063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009066 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009067 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009068 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009069 String codePathStr = parser.getAttributeValue(null, "codePath");
9070 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009071 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009072 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009073 resourcePathStr = codePathStr;
9074 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009075 String version = parser.getAttributeValue(null, "version");
9076 int versionCode = 0;
9077 if (version != null) {
9078 try {
9079 versionCode = Integer.parseInt(version);
9080 } catch (NumberFormatException e) {
9081 }
9082 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 int pkgFlags = 0;
9085 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009086 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9087 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009088 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009089 if (timeStampStr != null) {
9090 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009091 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009092 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009093 } catch (NumberFormatException e) {
9094 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009095 } else {
9096 timeStampStr = parser.getAttributeValue(null, "ts");
9097 if (timeStampStr != null) {
9098 try {
9099 long timeStamp = Long.parseLong(timeStampStr);
9100 ps.setTimeStamp(timeStamp);
9101 } catch (NumberFormatException e) {
9102 }
9103 }
9104 }
9105 timeStampStr = parser.getAttributeValue(null, "it");
9106 if (timeStampStr != null) {
9107 try {
9108 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9109 } catch (NumberFormatException e) {
9110 }
9111 }
9112 timeStampStr = parser.getAttributeValue(null, "ut");
9113 if (timeStampStr != null) {
9114 try {
9115 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9116 } catch (NumberFormatException e) {
9117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009118 }
9119 String idStr = parser.getAttributeValue(null, "userId");
9120 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9121 if(ps.userId <= 0) {
9122 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9123 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9124 }
9125 int outerDepth = parser.getDepth();
9126 int type;
9127 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9128 && (type != XmlPullParser.END_TAG
9129 || parser.getDepth() > outerDepth)) {
9130 if (type == XmlPullParser.END_TAG
9131 || type == XmlPullParser.TEXT) {
9132 continue;
9133 }
9134
9135 String tagName = parser.getName();
9136 if (tagName.equals("perms")) {
9137 readGrantedPermissionsLP(parser,
9138 ps.grantedPermissions);
9139 } else {
9140 reportSettingsProblem(Log.WARN,
9141 "Unknown element under <updated-package>: "
9142 + parser.getName());
9143 XmlUtils.skipCurrentTag(parser);
9144 }
9145 }
9146 mDisabledSysPackages.put(name, ps);
9147 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 private void readPackageLP(XmlPullParser parser)
9150 throws XmlPullParserException, IOException {
9151 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009152 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009153 String idStr = null;
9154 String sharedIdStr = null;
9155 String codePathStr = null;
9156 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009157 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009158 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009159 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009160 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009161 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009162 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009163 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009164 long firstInstallTime = 0;
9165 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009166 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009167 String version = null;
9168 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 try {
9170 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009171 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009172 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009173 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009174 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9175 codePathStr = parser.getAttributeValue(null, "codePath");
9176 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009177 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009178 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009179 version = parser.getAttributeValue(null, "version");
9180 if (version != null) {
9181 try {
9182 versionCode = Integer.parseInt(version);
9183 } catch (NumberFormatException e) {
9184 }
9185 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009186 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009187
9188 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009189 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009190 try {
9191 pkgFlags = Integer.parseInt(systemStr);
9192 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 }
9194 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009195 // For backward compatibility
9196 systemStr = parser.getAttributeValue(null, "system");
9197 if (systemStr != null) {
9198 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9199 } else {
9200 // Old settings that don't specify system... just treat
9201 // them as system, good enough.
9202 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009204 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009205 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009206 if (timeStampStr != null) {
9207 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009208 timeStamp = Long.parseLong(timeStampStr, 16);
9209 } catch (NumberFormatException e) {
9210 }
9211 } else {
9212 timeStampStr = parser.getAttributeValue(null, "ts");
9213 if (timeStampStr != null) {
9214 try {
9215 timeStamp = Long.parseLong(timeStampStr);
9216 } catch (NumberFormatException e) {
9217 }
9218 }
9219 }
9220 timeStampStr = parser.getAttributeValue(null, "it");
9221 if (timeStampStr != null) {
9222 try {
9223 firstInstallTime = Long.parseLong(timeStampStr, 16);
9224 } catch (NumberFormatException e) {
9225 }
9226 }
9227 timeStampStr = parser.getAttributeValue(null, "ut");
9228 if (timeStampStr != null) {
9229 try {
9230 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009231 } catch (NumberFormatException e) {
9232 }
9233 }
9234 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9235 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9236 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9237 if (resourcePathStr == null) {
9238 resourcePathStr = codePathStr;
9239 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009240 if (realName != null) {
9241 realName = realName.intern();
9242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009243 if (name == null) {
9244 reportSettingsProblem(Log.WARN,
9245 "Error in package manager settings: <package> has no name at "
9246 + parser.getPositionDescription());
9247 } else if (codePathStr == null) {
9248 reportSettingsProblem(Log.WARN,
9249 "Error in package manager settings: <package> has no codePath at "
9250 + parser.getPositionDescription());
9251 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009252 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9253 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9254 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9256 + ": userId=" + userId + " pkg=" + packageSetting);
9257 if (packageSetting == null) {
9258 reportSettingsProblem(Log.ERROR,
9259 "Failure adding uid " + userId
9260 + " while parsing settings at "
9261 + parser.getPositionDescription());
9262 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009263 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009264 packageSetting.firstInstallTime = firstInstallTime;
9265 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 }
9267 } else if (sharedIdStr != null) {
9268 userId = sharedIdStr != null
9269 ? Integer.parseInt(sharedIdStr) : 0;
9270 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009271 packageSetting = new PendingPackage(name.intern(), realName,
9272 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009273 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009274 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009275 packageSetting.firstInstallTime = firstInstallTime;
9276 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277 mPendingPackages.add((PendingPackage) packageSetting);
9278 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9279 + ": sharedUserId=" + userId + " pkg="
9280 + packageSetting);
9281 } else {
9282 reportSettingsProblem(Log.WARN,
9283 "Error in package manager settings: package "
9284 + name + " has bad sharedId " + sharedIdStr
9285 + " at " + parser.getPositionDescription());
9286 }
9287 } else {
9288 reportSettingsProblem(Log.WARN,
9289 "Error in package manager settings: package "
9290 + name + " has bad userId " + idStr + " at "
9291 + parser.getPositionDescription());
9292 }
9293 } catch (NumberFormatException e) {
9294 reportSettingsProblem(Log.WARN,
9295 "Error in package manager settings: package "
9296 + name + " has bad userId " + idStr + " at "
9297 + parser.getPositionDescription());
9298 }
9299 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009300 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009301 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009302 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009303 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009304 final String enabledStr = parser.getAttributeValue(null, "enabled");
9305 if (enabledStr != null) {
9306 if (enabledStr.equalsIgnoreCase("true")) {
9307 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9308 } else if (enabledStr.equalsIgnoreCase("false")) {
9309 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9310 } else if (enabledStr.equalsIgnoreCase("default")) {
9311 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9312 } else {
9313 reportSettingsProblem(Log.WARN,
9314 "Error in package manager settings: package "
9315 + name + " has bad enabled value: " + idStr
9316 + " at " + parser.getPositionDescription());
9317 }
9318 } else {
9319 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9320 }
9321 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9322 if (installStatusStr != null) {
9323 if (installStatusStr.equalsIgnoreCase("false")) {
9324 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9325 } else {
9326 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9327 }
9328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330 int outerDepth = parser.getDepth();
9331 int type;
9332 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9333 && (type != XmlPullParser.END_TAG
9334 || parser.getDepth() > outerDepth)) {
9335 if (type == XmlPullParser.END_TAG
9336 || type == XmlPullParser.TEXT) {
9337 continue;
9338 }
9339
9340 String tagName = parser.getName();
9341 if (tagName.equals("disabled-components")) {
9342 readDisabledComponentsLP(packageSetting, parser);
9343 } else if (tagName.equals("enabled-components")) {
9344 readEnabledComponentsLP(packageSetting, parser);
9345 } else if (tagName.equals("sigs")) {
9346 packageSetting.signatures.readXml(parser, mPastSignatures);
9347 } else if (tagName.equals("perms")) {
9348 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009349 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009350 packageSetting.permissionsFixed = true;
9351 } else {
9352 reportSettingsProblem(Log.WARN,
9353 "Unknown element under <package>: "
9354 + parser.getName());
9355 XmlUtils.skipCurrentTag(parser);
9356 }
9357 }
9358 } else {
9359 XmlUtils.skipCurrentTag(parser);
9360 }
9361 }
9362
9363 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9364 XmlPullParser parser)
9365 throws IOException, XmlPullParserException {
9366 int outerDepth = parser.getDepth();
9367 int type;
9368 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9369 && (type != XmlPullParser.END_TAG
9370 || parser.getDepth() > outerDepth)) {
9371 if (type == XmlPullParser.END_TAG
9372 || type == XmlPullParser.TEXT) {
9373 continue;
9374 }
9375
9376 String tagName = parser.getName();
9377 if (tagName.equals("item")) {
9378 String name = parser.getAttributeValue(null, "name");
9379 if (name != null) {
9380 packageSetting.disabledComponents.add(name.intern());
9381 } else {
9382 reportSettingsProblem(Log.WARN,
9383 "Error in package manager settings: <disabled-components> has"
9384 + " no name at " + parser.getPositionDescription());
9385 }
9386 } else {
9387 reportSettingsProblem(Log.WARN,
9388 "Unknown element under <disabled-components>: "
9389 + parser.getName());
9390 }
9391 XmlUtils.skipCurrentTag(parser);
9392 }
9393 }
9394
9395 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9396 XmlPullParser parser)
9397 throws IOException, XmlPullParserException {
9398 int outerDepth = parser.getDepth();
9399 int type;
9400 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9401 && (type != XmlPullParser.END_TAG
9402 || parser.getDepth() > outerDepth)) {
9403 if (type == XmlPullParser.END_TAG
9404 || type == XmlPullParser.TEXT) {
9405 continue;
9406 }
9407
9408 String tagName = parser.getName();
9409 if (tagName.equals("item")) {
9410 String name = parser.getAttributeValue(null, "name");
9411 if (name != null) {
9412 packageSetting.enabledComponents.add(name.intern());
9413 } else {
9414 reportSettingsProblem(Log.WARN,
9415 "Error in package manager settings: <enabled-components> has"
9416 + " no name at " + parser.getPositionDescription());
9417 }
9418 } else {
9419 reportSettingsProblem(Log.WARN,
9420 "Unknown element under <enabled-components>: "
9421 + parser.getName());
9422 }
9423 XmlUtils.skipCurrentTag(parser);
9424 }
9425 }
9426
9427 private void readSharedUserLP(XmlPullParser parser)
9428 throws XmlPullParserException, IOException {
9429 String name = null;
9430 String idStr = null;
9431 int pkgFlags = 0;
9432 SharedUserSetting su = null;
9433 try {
9434 name = parser.getAttributeValue(null, "name");
9435 idStr = parser.getAttributeValue(null, "userId");
9436 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9437 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9438 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9439 }
9440 if (name == null) {
9441 reportSettingsProblem(Log.WARN,
9442 "Error in package manager settings: <shared-user> has no name at "
9443 + parser.getPositionDescription());
9444 } else if (userId == 0) {
9445 reportSettingsProblem(Log.WARN,
9446 "Error in package manager settings: shared-user "
9447 + name + " has bad userId " + idStr + " at "
9448 + parser.getPositionDescription());
9449 } else {
9450 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9451 reportSettingsProblem(Log.ERROR,
9452 "Occurred while parsing settings at "
9453 + parser.getPositionDescription());
9454 }
9455 }
9456 } catch (NumberFormatException e) {
9457 reportSettingsProblem(Log.WARN,
9458 "Error in package manager settings: package "
9459 + name + " has bad userId " + idStr + " at "
9460 + parser.getPositionDescription());
9461 };
9462
9463 if (su != null) {
9464 int outerDepth = parser.getDepth();
9465 int type;
9466 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9467 && (type != XmlPullParser.END_TAG
9468 || parser.getDepth() > outerDepth)) {
9469 if (type == XmlPullParser.END_TAG
9470 || type == XmlPullParser.TEXT) {
9471 continue;
9472 }
9473
9474 String tagName = parser.getName();
9475 if (tagName.equals("sigs")) {
9476 su.signatures.readXml(parser, mPastSignatures);
9477 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009478 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009479 } else {
9480 reportSettingsProblem(Log.WARN,
9481 "Unknown element under <shared-user>: "
9482 + parser.getName());
9483 XmlUtils.skipCurrentTag(parser);
9484 }
9485 }
9486
9487 } else {
9488 XmlUtils.skipCurrentTag(parser);
9489 }
9490 }
9491
9492 private void readGrantedPermissionsLP(XmlPullParser parser,
9493 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9494 int outerDepth = parser.getDepth();
9495 int type;
9496 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9497 && (type != XmlPullParser.END_TAG
9498 || parser.getDepth() > outerDepth)) {
9499 if (type == XmlPullParser.END_TAG
9500 || type == XmlPullParser.TEXT) {
9501 continue;
9502 }
9503
9504 String tagName = parser.getName();
9505 if (tagName.equals("item")) {
9506 String name = parser.getAttributeValue(null, "name");
9507 if (name != null) {
9508 outPerms.add(name.intern());
9509 } else {
9510 reportSettingsProblem(Log.WARN,
9511 "Error in package manager settings: <perms> has"
9512 + " no name at " + parser.getPositionDescription());
9513 }
9514 } else {
9515 reportSettingsProblem(Log.WARN,
9516 "Unknown element under <perms>: "
9517 + parser.getName());
9518 }
9519 XmlUtils.skipCurrentTag(parser);
9520 }
9521 }
9522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009523 private void readPreferredActivitiesLP(XmlPullParser parser)
9524 throws XmlPullParserException, IOException {
9525 int outerDepth = parser.getDepth();
9526 int type;
9527 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9528 && (type != XmlPullParser.END_TAG
9529 || parser.getDepth() > outerDepth)) {
9530 if (type == XmlPullParser.END_TAG
9531 || type == XmlPullParser.TEXT) {
9532 continue;
9533 }
9534
9535 String tagName = parser.getName();
9536 if (tagName.equals("item")) {
9537 PreferredActivity pa = new PreferredActivity(parser);
9538 if (pa.mParseError == null) {
9539 mPreferredActivities.addFilter(pa);
9540 } else {
9541 reportSettingsProblem(Log.WARN,
9542 "Error in package manager settings: <preferred-activity> "
9543 + pa.mParseError + " at "
9544 + parser.getPositionDescription());
9545 }
9546 } else {
9547 reportSettingsProblem(Log.WARN,
9548 "Unknown element under <preferred-activities>: "
9549 + parser.getName());
9550 XmlUtils.skipCurrentTag(parser);
9551 }
9552 }
9553 }
9554
9555 // Returns -1 if we could not find an available UserId to assign
9556 private int newUserIdLP(Object obj) {
9557 // Let's be stupidly inefficient for now...
9558 final int N = mUserIds.size();
9559 for (int i=0; i<N; i++) {
9560 if (mUserIds.get(i) == null) {
9561 mUserIds.set(i, obj);
9562 return FIRST_APPLICATION_UID + i;
9563 }
9564 }
9565
9566 // None left?
9567 if (N >= MAX_APPLICATION_UIDS) {
9568 return -1;
9569 }
9570
9571 mUserIds.add(obj);
9572 return FIRST_APPLICATION_UID + N;
9573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575 public PackageSetting getDisabledSystemPkg(String name) {
9576 synchronized(mPackages) {
9577 PackageSetting ps = mDisabledSysPackages.get(name);
9578 return ps;
9579 }
9580 }
9581
9582 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009583 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9584 return true;
9585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009586 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9587 if (Config.LOGV) {
9588 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9589 + " componentName = " + componentInfo.name);
9590 Log.v(TAG, "enabledComponents: "
9591 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9592 Log.v(TAG, "disabledComponents: "
9593 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9594 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009595 if (packageSettings == null) {
9596 if (false) {
9597 Log.w(TAG, "WAITING FOR DEBUGGER");
9598 Debug.waitForDebugger();
9599 Log.i(TAG, "We will crash!");
9600 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009601 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009602 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009603 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9604 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9605 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9606 return false;
9607 }
9608 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9609 return true;
9610 }
9611 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9612 return false;
9613 }
9614 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009615 }
9616 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009617
9618 // ------- apps on sdcard specific code -------
9619 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009620 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9621 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9622 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009623 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009624
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009625 private String getEncryptKey() {
9626 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009627 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9628 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009629 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009630 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9631 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009632 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009633 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009634 return null;
9635 }
9636 }
9637 return sdEncKey;
9638 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009639 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009640 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009641 } catch (IOException ioe) {
9642 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9643 + ioe);
9644 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009645 }
Rich Cannings8d578832010-09-09 15:12:40 -07009646
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009647 }
9648
Kenny Rootc78a8072010-07-27 15:18:38 -07009649 /* package */ static String getTempContainerId() {
9650 int tmpIdx = 1;
9651 String list[] = PackageHelper.getSecureContainerList();
9652 if (list != null) {
9653 for (final String name : list) {
9654 // Ignore null and non-temporary container entries
9655 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9656 continue;
9657 }
9658
9659 String subStr = name.substring(mTempContainerPrefix.length());
9660 try {
9661 int cid = Integer.parseInt(subStr);
9662 if (cid >= tmpIdx) {
9663 tmpIdx = cid + 1;
9664 }
9665 } catch (NumberFormatException e) {
9666 }
9667 }
9668 }
9669 return mTempContainerPrefix + tmpIdx;
9670 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009671
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009672 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009673 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009674 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009675 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
Marco Nelissen584f1372010-05-24 16:34:30 -07009676 int callingUid = Binder.getCallingUid();
9677 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009678 throw new SecurityException("Media status can only be updated by the system");
9679 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009680 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009681 Log.i(TAG, "Updating external media status from " +
9682 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9683 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009684 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9685 mediaStatus+", mMediaMounted=" + mMediaMounted);
9686 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009687 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9688 reportStatus ? 1 : 0, -1);
9689 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009690 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009691 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009692 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009693 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009694 // Queue up an async operation since the package installation may take a little while.
9695 mHandler.post(new Runnable() {
9696 public void run() {
9697 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009698 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009699 }
9700 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009701 }
9702
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009703 /*
9704 * Collect information of applications on external media, map them
9705 * against existing containers and update information based on current
9706 * mount status. Please note that we always have to report status
9707 * if reportStatus has been set to true especially when unloading packages.
9708 */
9709 private void updateExternalMediaStatusInner(boolean mediaStatus,
9710 boolean reportStatus) {
9711 // Collection of uids
9712 int uidArr[] = null;
9713 // Collection of stale containers
9714 HashSet<String> removeCids = new HashSet<String>();
9715 // Collection of packages on external media with valid containers.
9716 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9717 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009718 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009719 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009720 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009721 } else {
9722 // Process list of secure containers and categorize them
9723 // as active or stale based on their package internal state.
9724 int uidList[] = new int[list.length];
9725 int num = 0;
9726 synchronized (mPackages) {
9727 for (String cid : list) {
9728 SdInstallArgs args = new SdInstallArgs(cid);
9729 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009730 String pkgName = args.getPackageName();
9731 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009732 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9733 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009734 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009735 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009736 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9737 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009738 // The package status is changed only if the code path
9739 // matches between settings and the container id.
9740 if (ps != null && ps.codePathString != null &&
9741 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009742 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9743 " corresponds to pkg : " + pkgName +
9744 " at code path: " + ps.codePathString);
9745 // We do have a valid package installed on sdcard
9746 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009747 int uid = ps.userId;
9748 if (uid != -1) {
9749 uidList[num++] = uid;
9750 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009751 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009752 // Stale container on sdcard. Just delete
9753 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9754 removeCids.add(cid);
9755 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009756 }
9757 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009758
9759 if (num > 0) {
9760 // Sort uid list
9761 Arrays.sort(uidList, 0, num);
9762 // Throw away duplicates
9763 uidArr = new int[num];
9764 uidArr[0] = uidList[0];
9765 int di = 0;
9766 for (int i = 1; i < num; i++) {
9767 if (uidList[i-1] != uidList[i]) {
9768 uidArr[di++] = uidList[i];
9769 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009770 }
9771 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009772 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009773 // Process packages with valid entries.
9774 if (mediaStatus) {
9775 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009776 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009777 startCleaningPackages();
9778 } else {
9779 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009780 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009781 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009782 }
9783
9784 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009785 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009786 int size = pkgList.size();
9787 if (size > 0) {
9788 // Send broadcasts here
9789 Bundle extras = new Bundle();
9790 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9791 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009792 if (uidArr != null) {
9793 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9794 }
9795 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9796 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009797 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009798 }
9799 }
9800
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009801 /*
9802 * Look at potentially valid container ids from processCids
9803 * If package information doesn't match the one on record
9804 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009805 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009806 */
9807 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009808 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009809 ArrayList<String> pkgList = new ArrayList<String>();
9810 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009811 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009812 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009813 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009814 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9815 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009816 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009817 try {
9818 // Make sure there are no container errors first.
9819 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9820 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009821 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009822 " when installing from sdcard");
9823 continue;
9824 }
9825 // Check code path here.
9826 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009827 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009828 " does not match one in settings " + codePath);
9829 continue;
9830 }
9831 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009832 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009833 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009834 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009835 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009836 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009837 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009838 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009839 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009840 retCode = PackageManager.INSTALL_SUCCEEDED;
9841 pkgList.add(pkg.packageName);
9842 // Post process args
9843 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9844 }
9845 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009846 Slog.i(TAG, "Failed to install pkg from " +
9847 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009848 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009849 }
9850
9851 } finally {
9852 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9853 // Don't destroy container here. Wait till gc clears things up.
9854 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009855 }
9856 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009857 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009858 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009859 // If the platform SDK has changed since the last time we booted,
9860 // we need to re-grant app permission to catch any new ones that
9861 // appear. This is really a hack, and means that apps can in some
9862 // cases get permissions that the user didn't initially explicitly
9863 // allow... it would be nice to have some better way to handle
9864 // this situation.
9865 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9866 != mSdkVersion;
9867 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9868 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9869 + "; regranting permissions for external storage");
9870 mSettings.mExternalSdkPlatform = mSdkVersion;
9871
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009872 // Make sure group IDs have been assigned, and any permission
9873 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009874 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009875 // Persist settings
9876 mSettings.writeLP();
9877 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009878 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009879 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009880 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009881 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009882 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009883 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009884 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009885 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009886 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009887 if (removeCids != null) {
9888 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009889 if (cid.startsWith(mTempContainerPrefix)) {
9890 Log.i(TAG, "Destroying stale temporary container " + cid);
9891 PackageHelper.destroySdDir(cid);
9892 } else {
9893 Log.w(TAG, "Container " + cid + " is stale");
9894 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009895 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009896 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009897 }
9898
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009899 /*
9900 * Utility method to unload a list of specified containers
9901 */
9902 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9903 // Just unmount all valid containers.
9904 for (SdInstallArgs arg : cidArgs) {
9905 synchronized (mInstallLock) {
9906 arg.doPostDeleteLI(false);
9907 }
9908 }
9909 }
9910
9911 /*
9912 * Unload packages mounted on external media. This involves deleting
9913 * package data from internal structures, sending broadcasts about
9914 * diabled packages, gc'ing to free up references, unmounting all
9915 * secure containers corresponding to packages on external media, and
9916 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9917 * Please note that we always have to post this message if status has
9918 * been requested no matter what.
9919 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009920 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009921 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009922 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009923 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009924 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009925 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009926 for (SdInstallArgs args : keys) {
9927 String cid = args.cid;
9928 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009929 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009930 // Delete package internally
9931 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9932 synchronized (mInstallLock) {
9933 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009934 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009935 if (res) {
9936 pkgList.add(pkgName);
9937 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009938 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009939 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009940 }
9941 }
9942 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009943
9944 synchronized (mPackages) {
9945 // We didn't update the settings after removing each package;
9946 // write them now for all packages.
9947 mSettings.writeLP();
9948 }
9949
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009950 // We have to absolutely send UPDATED_MEDIA_STATUS only
9951 // after confirming that all the receivers processed the ordered
9952 // broadcast when packages get disabled, force a gc to clean things up.
9953 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009954 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009955 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9956 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9957 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009958 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9959 reportStatus ? 1 : 0, 1, keys);
9960 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009961 }
9962 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009963 } else {
9964 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9965 reportStatus ? 1 : 0, -1, keys);
9966 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009967 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009968 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009969
9970 public void movePackage(final String packageName,
9971 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009972 mContext.enforceCallingOrSelfPermission(
9973 android.Manifest.permission.MOVE_PACKAGE, null);
9974 int returnCode = PackageManager.MOVE_SUCCEEDED;
9975 int currFlags = 0;
9976 int newFlags = 0;
9977 synchronized (mPackages) {
9978 PackageParser.Package pkg = mPackages.get(packageName);
9979 if (pkg == null) {
9980 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009981 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009982 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009983 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009984 Slog.w(TAG, "Cannot move system application");
9985 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009986 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009987 Slog.w(TAG, "Cannot move forward locked app.");
9988 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009989 } else if (pkg.mOperationPending) {
9990 Slog.w(TAG, "Attempt to move package which has pending operations");
9991 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009992 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009993 // Find install location first
9994 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9995 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9996 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009997 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009998 } else {
9999 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
10000 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -070010001 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
10002 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010003 if (newFlags == currFlags) {
10004 Slog.w(TAG, "No move required. Trying to move to same location");
10005 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
10006 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010007 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010008 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10009 pkg.mOperationPending = true;
10010 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010011 }
10012 }
10013 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -070010014 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010015 } else {
10016 Message msg = mHandler.obtainMessage(INIT_COPY);
10017 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -070010018 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
10019 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
10020 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010021 msg.obj = mp;
10022 mHandler.sendMessage(msg);
10023 }
10024 }
10025 }
10026
10027 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10028 // Queue up an async operation since the package deletion may take a little while.
10029 mHandler.post(new Runnable() {
10030 public void run() {
10031 mHandler.removeCallbacks(this);
10032 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010033 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10034 int uidArr[] = null;
10035 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010036 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010037 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010038 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010039 Slog.w(TAG, " Package " + mp.packageName +
10040 " doesn't exist. Aborting move");
10041 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10042 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10043 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10044 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10045 " Aborting move and returning error");
10046 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10047 } else {
10048 uidArr = new int[] { pkg.applicationInfo.uid };
10049 pkgList = new ArrayList<String>();
10050 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010051 }
10052 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010053 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10054 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010055 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010056 // Update package code and resource paths
10057 synchronized (mInstallLock) {
10058 synchronized (mPackages) {
10059 PackageParser.Package pkg = mPackages.get(mp.packageName);
10060 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010061 if (pkg == null) {
10062 Slog.w(TAG, " Package " + mp.packageName
10063 + " doesn't exist. Aborting move");
10064 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010065 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10066 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10067 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10068 " Aborting move and returning error");
10069 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10070 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010071 final String oldCodePath = pkg.mPath;
10072 final String newCodePath = mp.targetArgs.getCodePath();
10073 final String newResPath = mp.targetArgs.getResourcePath();
10074 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010075
10076 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10077 if (mInstaller
10078 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10079 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10080 } else {
10081 NativeLibraryHelper.copyNativeBinariesLI(
10082 new File(newCodePath), new File(newNativePath));
10083 }
10084 } else {
10085 if (mInstaller.linkNativeLibraryDirectory(
10086 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10087 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10088 }
10089 }
10090
10091 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10092 pkg.mPath = newCodePath;
10093 // Move dex files around
10094 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10095 // Moving of dex files failed. Set
10096 // error code and abort move.
10097 pkg.mPath = pkg.mScanPath;
10098 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10099 }
10100 }
10101
10102 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010103 pkg.mScanPath = newCodePath;
10104 pkg.applicationInfo.sourceDir = newCodePath;
10105 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010106 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010107 PackageSetting ps = (PackageSetting) pkg.mExtras;
10108 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10109 ps.codePathString = ps.codePath.getPath();
10110 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10111 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010112 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010113 // Set the application info flag correctly.
10114 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10115 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10116 } else {
10117 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10118 }
10119 ps.setFlags(pkg.applicationInfo.flags);
10120 mAppDirs.remove(oldCodePath);
10121 mAppDirs.put(newCodePath, pkg);
10122 // Persist settings
10123 mSettings.writeLP();
10124 }
10125 }
10126 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010127 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010128 // Send resources available broadcast
10129 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010130 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010131 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010132 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010133 // Clean up failed installation
10134 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010135 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010136 }
10137 } else {
10138 // Force a gc to clear things up.
10139 Runtime.getRuntime().gc();
10140 // Delete older code
10141 synchronized (mInstallLock) {
10142 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010143 }
10144 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010145
10146 // Allow more operations on this file if we didn't fail because
10147 // an operation was already pending for this package.
10148 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10149 synchronized (mPackages) {
10150 PackageParser.Package pkg = mPackages.get(mp.packageName);
10151 if (pkg != null) {
10152 pkg.mOperationPending = false;
10153 }
10154 }
10155 }
10156
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010157 IPackageMoveObserver observer = mp.observer;
10158 if (observer != null) {
10159 try {
10160 observer.packageMoved(mp.packageName, returnCode);
10161 } catch (RemoteException e) {
10162 Log.i(TAG, "Observer no longer exists.");
10163 }
10164 }
10165 }
10166 });
10167 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010168
10169 public boolean setInstallLocation(int loc) {
10170 mContext.enforceCallingOrSelfPermission(
10171 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10172 if (getInstallLocation() == loc) {
10173 return true;
10174 }
10175 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10176 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10177 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10178 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10179 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10180 return true;
10181 }
10182 return false;
10183 }
10184
10185 public int getInstallLocation() {
10186 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10187 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010189}