blob: 8c74566c231b443ac7cad69d7fe433ee94ac541a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
57import android.content.pm.PackageStats;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
Kenny Root9f306d72010-09-26 11:19:47 -070094import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.FileReader;
101import java.io.FilenameFilter;
102import java.io.IOException;
103import java.io.InputStream;
104import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800105import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
108import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700109import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Collections;
111import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800112import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.Enumeration;
114import java.util.HashMap;
115import java.util.HashSet;
116import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700117import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.List;
119import java.util.Map;
120import java.util.Set;
121import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800122import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import java.util.zip.ZipFile;
124import java.util.zip.ZipOutputStream;
125
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700126/**
127 * Keep track of all those .apks everywhere.
128 *
129 * This is very central to the platform's security; please run the unit
130 * tests whenever making modifications here:
131 *
132mmm frameworks/base/tests/AndroidTests
133adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
134adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
135 *
136 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137class PackageManagerService extends IPackageManager.Stub {
138 private static final String TAG = "PackageManager";
139 private static final boolean DEBUG_SETTINGS = false;
140 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800141 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800142 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
145 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400146 private static final int LOG_UID = Process.LOG_UID;
Nick Pellybc21fde2010-10-13 17:25:24 -0700147 private static final int NFC_UID = Process.NFC_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private static final int FIRST_APPLICATION_UID =
149 Process.FIRST_APPLICATION_UID;
150 private static final int MAX_APPLICATION_UIDS = 1000;
151
152 private static final boolean SHOW_INFO = false;
153
154 private static final boolean GET_CERTIFICATES = true;
155
Oscar Montemayora8529f62009-11-18 10:14:20 -0800156 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private static final int REMOVE_EVENTS =
159 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
160 private static final int ADD_EVENTS =
161 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
162
163 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800164 // Suffix used during package installation when copying/moving
165 // package apks to install directory.
166 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800168 /**
169 * Indicates the state of installation. Used by PackageManager to
170 * figure out incomplete installations. Say a package is being installed
171 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
172 * the package installation is successful or unsuccesful lin which case
173 * the PackageManager will no longer maintain state information associated
174 * with the package. If some exception(like device freeze or battery being
175 * pulled out) occurs during installation of a package, the PackageManager
176 * needs this information to clean up the previously failed installation.
177 */
178 private static final int PKG_INSTALL_INCOMPLETE = 0;
179 private static final int PKG_INSTALL_COMPLETE = 1;
180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final int SCAN_MONITOR = 1<<0;
182 static final int SCAN_NO_DEX = 1<<1;
183 static final int SCAN_FORCE_DEX = 1<<2;
184 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800185 static final int SCAN_NEW_INSTALL = 1<<4;
186 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700187 static final int SCAN_UPDATE_TIME = 1<<6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700189 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700190
191 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
192
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800193 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700194 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800195 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700196
Kenny Root85387d72010-08-26 10:13:11 -0700197 private static final String LIB_DIR_NAME = "lib";
198
Kenny Rootc78a8072010-07-27 15:18:38 -0700199 static final String mTempContainerPrefix = "smdl2tmp";
200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
202 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700203 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Dianne Hackborn851a5412009-05-08 12:06:44 -0700205 final int mSdkVersion = Build.VERSION.SDK_INT;
206 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
207 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 final Context mContext;
210 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700211 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 final DisplayMetrics mMetrics;
213 final int mDefParseFlags;
214 final String[] mSeparateProcesses;
215
216 // This is where all application persistent data goes.
217 final File mAppDataDir;
218
Oscar Montemayora8529f62009-11-18 10:14:20 -0800219 // If Encrypted File System feature is enabled, all application persistent data
220 // should go here instead.
221 final File mSecureAppDataDir;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // This is the object monitoring the framework dir.
224 final FileObserver mFrameworkInstallObserver;
225
226 // This is the object monitoring the system app dir.
227 final FileObserver mSystemInstallObserver;
228
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700229 // This is the object monitoring the system app dir.
230 final FileObserver mVendorInstallObserver;
231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // This is the object monitoring mAppInstallDir.
233 final FileObserver mAppInstallObserver;
234
235 // This is the object monitoring mDrmAppPrivateInstallDir.
236 final FileObserver mDrmAppInstallObserver;
237
238 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
239 // LOCK HELD. Can be called with mInstallLock held.
240 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 final File mFrameworkDir;
243 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700244 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700246 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
249 // apps.
250 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // Lock for state used when installing and doing other long running
255 // operations. Methods that must be called with this lock held have
256 // the prefix "LI".
257 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 // These are the directories in the 3rd party applications installed dir
260 // that we have currently loaded packages from. Keys are the application's
261 // installed zip file (absolute codePath), and values are Package.
262 final HashMap<String, PackageParser.Package> mAppDirs =
263 new HashMap<String, PackageParser.Package>();
264
265 // Information for the parser to write more useful error messages.
266 File mScanningPath;
267 int mLastScanError;
268
269 final int[] mOutPermissions = new int[3];
270
271 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 // Keys are String (package name), values are Package. This also serves
274 // as the lock for the global state. Methods that must be called with
275 // this lock held have the prefix "LP".
276 final HashMap<String, PackageParser.Package> mPackages =
277 new HashMap<String, PackageParser.Package>();
278
279 final Settings mSettings;
280 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281
282 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
283 int[] mGlobalGids;
284
285 // These are the built-in uid -> permission mappings that were read from the
286 // etc/permissions.xml file.
287 final SparseArray<HashSet<String>> mSystemPermissions =
288 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 // These are the built-in shared libraries that were read from the
291 // etc/permissions.xml file.
292 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
Dianne Hackborn49237342009-08-27 20:08:01 -0700294 // Temporary for building the final shared libraries for an .apk.
295 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800296
Dianne Hackborn49237342009-08-27 20:08:01 -0700297 // These are the features this devices supports that were read from the
298 // etc/permissions.xml file.
299 final HashMap<String, FeatureInfo> mAvailableFeatures =
300 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 // All available activities, for your resolving pleasure.
303 final ActivityIntentResolver mActivities =
304 new ActivityIntentResolver();
305
306 // All available receivers, for your resolving pleasure.
307 final ActivityIntentResolver mReceivers =
308 new ActivityIntentResolver();
309
310 // All available services, for your resolving pleasure.
311 final ServiceIntentResolver mServices = new ServiceIntentResolver();
312
313 // Keys are String (provider class name), values are Provider.
314 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
315 new HashMap<ComponentName, PackageParser.Provider>();
316
317 // Mapping from provider base names (first directory in content URI codePath)
318 // to the provider information.
319 final HashMap<String, PackageParser.Provider> mProviders =
320 new HashMap<String, PackageParser.Provider>();
321
322 // Mapping from instrumentation class names to info about them.
323 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
324 new HashMap<ComponentName, PackageParser.Instrumentation>();
325
326 // Mapping from permission names to info about them.
327 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
328 new HashMap<String, PackageParser.PermissionGroup>();
329
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800330 // Packages whose data we have transfered into another package, thus
331 // should no longer exist.
332 final HashSet<String> mTransferedPackages = new HashSet<String>();
333
Dianne Hackborn854060af2009-07-09 18:14:31 -0700334 // Broadcast actions that are only available to the system.
335 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 boolean mSystemReady;
338 boolean mSafeMode;
339 boolean mHasSystemUidErrors;
340
341 ApplicationInfo mAndroidApplication;
342 final ActivityInfo mResolveActivity = new ActivityInfo();
343 final ResolveInfo mResolveInfo = new ResolveInfo();
344 ComponentName mResolveComponentName;
345 PackageParser.Package mPlatformPackage;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800348 final HashMap<String, ArrayList<String>> mPendingBroadcasts
349 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800350 // Service Connection to remote media container service to copy
351 // package uri's from external media onto secure containers
352 // or internal storage.
353 private IMediaContainerService mContainerService = null;
354
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700355 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800356 static final int MCS_BOUND = 3;
357 static final int END_COPY = 4;
358 static final int INIT_COPY = 5;
359 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800360 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800361 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800362 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800363 static final int MCS_RECONNECT = 10;
364 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700365 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700366 static final int WRITE_SETTINGS = 13;
367
368 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700370 // Delay time in millisecs
371 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372 final private DefaultContainerConnection mDefContainerConn =
373 new DefaultContainerConnection();
374 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800375 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800376 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800377 IMediaContainerService imcs =
378 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800379 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800380 }
381
382 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800383 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800384 }
385 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700386
Christopher Tate1bb69062010-02-19 17:02:12 -0800387 // Recordkeeping of restore-after-install operations that are currently in flight
388 // between the Package Manager and the Backup Manager
389 class PostInstallData {
390 public InstallArgs args;
391 public PackageInstalledInfo res;
392
393 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
394 args = _a;
395 res = _r;
396 }
397 };
398 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
399 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
400
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700401 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800403 final ArrayList<HandlerParams> mPendingInstalls =
404 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800405
406 private boolean connectToService() {
407 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
408 " DefaultContainerService");
409 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700410 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800411 if (mContext.bindService(service, mDefContainerConn,
412 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800414 mBound = true;
415 return true;
416 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700417 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800418 return false;
419 }
420
421 private void disconnectService() {
422 mContainerService = null;
423 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700424 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800425 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800427 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800428
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700429 PackageHandler(Looper looper) {
430 super(looper);
431 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700432
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700433 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700434 try {
435 doHandleMessage(msg);
436 } finally {
437 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
438 }
439 }
440
441 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700442 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800443 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800444 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800445 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800446 int idx = mPendingInstalls.size();
447 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
448 // If a bind was already initiated we dont really
449 // need to do anything. The pending install
450 // will be processed later on.
451 if (!mBound) {
452 // If this is the only one pending we might
453 // have to bind to the service again.
454 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800455 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800456 params.serviceError();
457 return;
458 } else {
459 // Once we bind to the service, the first
460 // pending request will be processed.
461 mPendingInstalls.add(idx, params);
462 }
463 } else {
464 mPendingInstalls.add(idx, params);
465 // Already bound to the service. Just make
466 // sure we trigger off processing the first request.
467 if (idx == 0) {
468 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800469 }
470 }
471 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800472 }
473 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800474 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800475 if (msg.obj != null) {
476 mContainerService = (IMediaContainerService) msg.obj;
477 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 if (mContainerService == null) {
479 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800480 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 for (HandlerParams params : mPendingInstalls) {
482 mPendingInstalls.remove(0);
483 // Indicate service bind error
484 params.serviceError();
485 }
486 mPendingInstalls.clear();
487 } else if (mPendingInstalls.size() > 0) {
488 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800489 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800490 params.startCopy();
491 }
492 } else {
493 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800494 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800495 }
496 break;
497 }
498 case MCS_RECONNECT : {
499 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
500 if (mPendingInstalls.size() > 0) {
501 if (mBound) {
502 disconnectService();
503 }
504 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800505 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800506 for (HandlerParams params : mPendingInstalls) {
507 mPendingInstalls.remove(0);
508 // Indicate service bind error
509 params.serviceError();
510 }
511 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800512 }
513 }
514 break;
515 }
516 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800517 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
518 // Delete pending install
519 if (mPendingInstalls.size() > 0) {
520 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800521 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800522 if (mPendingInstalls.size() == 0) {
523 if (mBound) {
524 disconnectService();
525 }
526 } else {
527 // There are more pending requests in queue.
528 // Just post MCS_BOUND message to trigger processing
529 // of next pending install.
530 mHandler.sendEmptyMessage(MCS_BOUND);
531 }
532 break;
533 }
534 case MCS_GIVE_UP: {
535 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
536 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800537 break;
538 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800540 String packages[];
541 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700543 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700544 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700545 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800546 if (mPendingBroadcasts == null) {
547 return;
548 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700549 size = mPendingBroadcasts.size();
550 if (size <= 0) {
551 // Nothing to be done. Just return
552 return;
553 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 packages = new String[size];
555 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700556 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800557 Iterator<HashMap.Entry<String, ArrayList<String>>>
558 it = mPendingBroadcasts.entrySet().iterator();
559 int i = 0;
560 while (it.hasNext() && i < size) {
561 HashMap.Entry<String, ArrayList<String>> ent = it.next();
562 packages[i] = ent.getKey();
563 components[i] = ent.getValue();
564 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700565 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800566 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700567 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800568 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700569 mPendingBroadcasts.clear();
570 }
571 // Send broadcasts
572 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800573 sendPackageChangedBroadcast(packages[i], true,
574 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700575 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700577 break;
578 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800579 case START_CLEANING_PACKAGE: {
580 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700581 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800582 synchronized (mPackages) {
583 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
584 mSettings.mPackagesToBeCleaned.add(packageName);
585 }
586 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700587 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800588 startCleaningPackages();
589 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800590 case POST_INSTALL: {
591 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
592 PostInstallData data = mRunningInstalls.get(msg.arg1);
593 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700594 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800595
596 if (data != null) {
597 InstallArgs args = data.args;
598 PackageInstalledInfo res = data.res;
599
600 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700601 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800602 Bundle extras = new Bundle(1);
603 extras.putInt(Intent.EXTRA_UID, res.uid);
604 final boolean update = res.removedInfo.removedPackage != null;
605 if (update) {
606 extras.putBoolean(Intent.EXTRA_REPLACING, true);
607 }
608 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
609 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700610 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800611 if (update) {
612 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
613 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700614 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800615 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700616 if (res.removedInfo.args != null) {
617 // Remove the replaced package's older resources safely now
618 deleteOld = true;
619 }
620 }
621 // Force a gc to clear up things
622 Runtime.getRuntime().gc();
623 // We delete after a gc for applications on sdcard.
624 if (deleteOld) {
625 synchronized (mInstallLock) {
626 res.removedInfo.args.doPostDeleteLI(true);
627 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800628 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800629 if (args.observer != null) {
630 try {
631 args.observer.packageInstalled(res.name, res.returnCode);
632 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800633 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800634 }
635 }
636 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800637 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800638 }
639 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700640 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700641 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
642 boolean reportStatus = msg.arg1 == 1;
643 boolean doGc = msg.arg2 == 1;
644 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
645 if (doGc) {
646 // Force a gc to clear up stale containers.
647 Runtime.getRuntime().gc();
648 }
649 if (msg.obj != null) {
650 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
651 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
652 // Unload containers
653 unloadAllContainers(args);
654 }
655 if (reportStatus) {
656 try {
657 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
658 PackageHelper.getMountService().finishMediaUpdate();
659 } catch (RemoteException e) {
660 Log.e(TAG, "MountService not running?");
661 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700662 }
663 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700664 case WRITE_SETTINGS: {
665 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
666 synchronized (mPackages) {
667 removeMessages(WRITE_SETTINGS);
668 mSettings.writeLP();
669 }
670 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
671 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700672 }
673 }
674 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800675
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700676 void scheduleWriteSettingsLocked() {
677 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
678 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
679 }
680 }
681
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800682 static boolean installOnSd(int flags) {
683 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700684 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800685 return false;
686 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700687 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
688 return true;
689 }
690 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800691 }
692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 public static final IPackageManager main(Context context, boolean factoryTest) {
694 PackageManagerService m = new PackageManagerService(context, factoryTest);
695 ServiceManager.addService("package", m);
696 return m;
697 }
698
699 static String[] splitString(String str, char sep) {
700 int count = 1;
701 int i = 0;
702 while ((i=str.indexOf(sep, i)) >= 0) {
703 count++;
704 i++;
705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 String[] res = new String[count];
708 i=0;
709 count = 0;
710 int lastI=0;
711 while ((i=str.indexOf(sep, i)) >= 0) {
712 res[count] = str.substring(lastI, i);
713 count++;
714 i++;
715 lastI = i;
716 }
717 res[count] = str.substring(lastI, str.length());
718 return res;
719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800722 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800726 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 mContext = context;
730 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700731 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 mMetrics = new DisplayMetrics();
733 mSettings = new Settings();
734 mSettings.addSharedUserLP("android.uid.system",
735 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
736 mSettings.addSharedUserLP("android.uid.phone",
737 MULTIPLE_APPLICATION_UIDS
738 ? RADIO_UID : FIRST_APPLICATION_UID,
739 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400740 mSettings.addSharedUserLP("android.uid.log",
741 MULTIPLE_APPLICATION_UIDS
742 ? LOG_UID : FIRST_APPLICATION_UID,
743 ApplicationInfo.FLAG_SYSTEM);
Nick Pellybc21fde2010-10-13 17:25:24 -0700744 mSettings.addSharedUserLP("android.uid.nfc",
745 MULTIPLE_APPLICATION_UIDS
746 ? NFC_UID : FIRST_APPLICATION_UID,
747 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748
749 String separateProcesses = SystemProperties.get("debug.separate_processes");
750 if (separateProcesses != null && separateProcesses.length() > 0) {
751 if ("*".equals(separateProcesses)) {
752 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
753 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800754 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 } else {
756 mDefParseFlags = 0;
757 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800758 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 + separateProcesses);
760 }
761 } else {
762 mDefParseFlags = 0;
763 mSeparateProcesses = null;
764 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 Installer installer = new Installer();
767 // Little hacky thing to check if installd is here, to determine
768 // whether we are running on the simulator and thus need to take
769 // care of building the /data file structure ourself.
770 // (apparently the sim now has a working installer)
771 if (installer.ping() && Process.supportsProcesses()) {
772 mInstaller = installer;
773 } else {
774 mInstaller = null;
775 }
776
777 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
778 Display d = wm.getDefaultDisplay();
779 d.getMetrics(mMetrics);
780
781 synchronized (mInstallLock) {
782 synchronized (mPackages) {
783 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700784 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 File dataDir = Environment.getDataDirectory();
787 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800788 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
790
791 if (mInstaller == null) {
792 // Make sure these dirs exist, when we are running in
793 // the simulator.
794 // Make a wide-open directory for random misc stuff.
795 File miscDir = new File(dataDir, "misc");
796 miscDir.mkdirs();
797 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800798 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 mDrmAppPrivateInstallDir.mkdirs();
800 }
801
802 readPermissions();
803
804 mRestoredSettings = mSettings.readLP();
805 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806
807 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800809
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800810 // Set flag to monitor and not change apk file paths when
811 // scanning install directories.
812 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700813 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800814 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700821 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700824 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 /**
827 * Out of paranoia, ensure that everything in the boot class
828 * path has been dexed.
829 */
830 String bootClassPath = System.getProperty("java.boot.class.path");
831 if (bootClassPath != null) {
832 String[] paths = splitString(bootClassPath, ':');
833 for (int i=0; i<paths.length; i++) {
834 try {
835 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
836 libFiles.add(paths[i]);
837 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700838 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
840 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800841 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800843 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845 }
846 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800847 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 /**
851 * Also ensure all external libraries have had dexopt run on them.
852 */
853 if (mSharedLibraries.size() > 0) {
854 Iterator<String> libs = mSharedLibraries.values().iterator();
855 while (libs.hasNext()) {
856 String lib = libs.next();
857 try {
858 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
859 libFiles.add(lib);
860 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700861 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
863 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800864 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800866 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
868 }
869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 // Gross hack for now: we know this file doesn't contain any
872 // code, so don't dexopt it to avoid the resulting log spew.
873 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 /**
876 * And there are a number of commands implemented in Java, which
877 * we currently need to do the dexopt on so that they can be
878 * run from a non-root shell.
879 */
880 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700881 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 for (int i=0; i<frameworkFiles.length; i++) {
883 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
884 String path = libPath.getPath();
885 // Skip the file if we alrady did it.
886 if (libFiles.contains(path)) {
887 continue;
888 }
889 // Skip the file if it is not a type we want to dexopt.
890 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
891 continue;
892 }
893 try {
894 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
895 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700896 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 }
898 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800899 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800901 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
903 }
904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800905
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700906 if (didDexOpt) {
907 // If we had to do a dexopt of one of the previous
908 // things, then something on the system has changed.
909 // Consider this significant, and wipe away all other
910 // existing dexopt files to ensure we don't leave any
911 // dangling around.
912 String[] files = mDalvikCacheDir.list();
913 if (files != null) {
914 for (int i=0; i<files.length; i++) {
915 String fn = files[i];
916 if (fn.startsWith("data@app@")
917 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800918 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700919 (new File(mDalvikCacheDir, fn)).delete();
920 }
921 }
922 }
923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800925
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800926 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 mFrameworkInstallObserver = new AppDirObserver(
928 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
929 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700930 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
931 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700932 scanMode | SCAN_NO_DEX, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800933
934 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
936 mSystemInstallObserver = new AppDirObserver(
937 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
938 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700939 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700940 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800941
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700942 // Collect all vendor packages.
943 mVendorAppDir = new File("/vendor/app");
944 mVendorInstallObserver = new AppDirObserver(
945 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
946 mVendorInstallObserver.startWatching();
947 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700948 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700949
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800950 if (mInstaller != null) {
951 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
952 mInstaller.moveFiles();
953 }
954
955 // Prune any system packages that no longer exist.
956 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
957 while (psit.hasNext()) {
958 PackageSetting ps = psit.next();
959 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800960 && !mPackages.containsKey(ps.name)
961 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800962 psit.remove();
963 String msg = "System package " + ps.name
964 + " no longer exists; wiping its data";
965 reportSettingsProblem(Log.WARN, msg);
966 if (mInstaller != null) {
967 // XXX how to set useEncryptedFSDir for packages that
968 // are not encrypted?
969 mInstaller.remove(ps.name, true);
970 }
971 }
972 }
973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 mAppInstallDir = new File(dataDir, "app");
975 if (mInstaller == null) {
976 // Make sure these dirs exist, when we are running in
977 // the simulator.
978 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
979 }
980 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800981 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 //clean up list
983 for(int i = 0; i < deletePkgsList.size(); i++) {
984 //clean up here
985 cleanupInstallFailedPackage(deletePkgsList.get(i));
986 }
987 //delete tmp files
988 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800989
990 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 SystemClock.uptimeMillis());
992 mAppInstallObserver = new AppDirObserver(
993 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
994 mAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700995 scanDirLI(mAppInstallDir, 0, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996
997 mDrmAppInstallObserver = new AppDirObserver(
998 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
999 mDrmAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001000 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1001 scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001003 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001005 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1007 + " seconds");
1008
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001009 // If the platform SDK has changed since the last time we booted,
1010 // we need to re-grant app permission to catch any new ones that
1011 // appear. This is really a hack, and means that apps can in some
1012 // cases get permissions that the user didn't initially explicitly
1013 // allow... it would be nice to have some better way to handle
1014 // this situation.
1015 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1016 != mSdkVersion;
1017 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1018 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1019 + "; regranting permissions for internal storage");
1020 mSettings.mInternalSdkPlatform = mSdkVersion;
1021
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001022 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023
1024 mSettings.writeLP();
1025
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001026 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 // Now after opening every single application zip, make sure they
1030 // are all flushed. Not really needed, but keeps things nice and
1031 // tidy.
1032 Runtime.getRuntime().gc();
1033 } // synchronized (mPackages)
1034 } // synchronized (mInstallLock)
1035 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 @Override
1038 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1039 throws RemoteException {
1040 try {
1041 return super.onTransact(code, data, reply, flags);
1042 } catch (RuntimeException e) {
1043 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001044 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046 throw e;
1047 }
1048 }
1049
Dianne Hackborne6620b22010-01-22 14:46:21 -08001050 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001053 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1054 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001056 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001057 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
1059 } else {
1060 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001061 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 File dataDir = new File(pkg.applicationInfo.dataDir);
1063 dataDir.delete();
1064 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001065 if (ps.codePath != null) {
1066 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001067 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001068 }
1069 }
1070 if (ps.resourcePath != null) {
1071 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001072 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001073 }
1074 }
1075 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
1077
1078 void readPermissions() {
1079 // Read permissions from .../etc/permission directory.
1080 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1081 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001082 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 return;
1084 }
1085 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001086 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 return;
1088 }
1089
1090 // Iterate over the files in the directory and scan .xml files
1091 for (File f : libraryDir.listFiles()) {
1092 // We'll read platform.xml last
1093 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1094 continue;
1095 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001098 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 continue;
1100 }
1101 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001102 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 continue;
1104 }
1105
1106 readPermissionsFromXml(f);
1107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1110 final File permFile = new File(Environment.getRootDirectory(),
1111 "etc/permissions/platform.xml");
1112 readPermissionsFromXml(permFile);
1113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
1115 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 FileReader permReader = null;
1117 try {
1118 permReader = new FileReader(permFile);
1119 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001120 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 return;
1122 }
1123
1124 try {
1125 XmlPullParser parser = Xml.newPullParser();
1126 parser.setInput(permReader);
1127
1128 XmlUtils.beginDocument(parser, "permissions");
1129
1130 while (true) {
1131 XmlUtils.nextElement(parser);
1132 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1133 break;
1134 }
1135
1136 String name = parser.getName();
1137 if ("group".equals(name)) {
1138 String gidStr = parser.getAttributeValue(null, "gid");
1139 if (gidStr != null) {
1140 int gid = Integer.parseInt(gidStr);
1141 mGlobalGids = appendInt(mGlobalGids, gid);
1142 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + parser.getPositionDescription());
1145 }
1146
1147 XmlUtils.skipCurrentTag(parser);
1148 continue;
1149 } else if ("permission".equals(name)) {
1150 String perm = parser.getAttributeValue(null, "name");
1151 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 + parser.getPositionDescription());
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157 perm = perm.intern();
1158 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 } else if ("assign-permission".equals(name)) {
1161 String perm = parser.getAttributeValue(null, "name");
1162 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001163 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 + parser.getPositionDescription());
1165 XmlUtils.skipCurrentTag(parser);
1166 continue;
1167 }
1168 String uidStr = parser.getAttributeValue(null, "uid");
1169 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001170 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 + parser.getPositionDescription());
1172 XmlUtils.skipCurrentTag(parser);
1173 continue;
1174 }
1175 int uid = Process.getUidForName(uidStr);
1176 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 + uidStr + "\" at "
1179 + parser.getPositionDescription());
1180 XmlUtils.skipCurrentTag(parser);
1181 continue;
1182 }
1183 perm = perm.intern();
1184 HashSet<String> perms = mSystemPermissions.get(uid);
1185 if (perms == null) {
1186 perms = new HashSet<String>();
1187 mSystemPermissions.put(uid, perms);
1188 }
1189 perms.add(perm);
1190 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 } else if ("library".equals(name)) {
1193 String lname = parser.getAttributeValue(null, "name");
1194 String lfile = parser.getAttributeValue(null, "file");
1195 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001196 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 + parser.getPositionDescription());
1198 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 + parser.getPositionDescription());
1201 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001202 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 mSharedLibraries.put(lname, lfile);
1204 }
1205 XmlUtils.skipCurrentTag(parser);
1206 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001207
Dianne Hackborn49237342009-08-27 20:08:01 -07001208 } else if ("feature".equals(name)) {
1209 String fname = parser.getAttributeValue(null, "name");
1210 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001211 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001212 + parser.getPositionDescription());
1213 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001214 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 FeatureInfo fi = new FeatureInfo();
1216 fi.name = fname;
1217 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219 XmlUtils.skipCurrentTag(parser);
1220 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } else {
1223 XmlUtils.skipCurrentTag(parser);
1224 continue;
1225 }
1226
1227 }
1228 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001229 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001231 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
1234
1235 void readPermission(XmlPullParser parser, String name)
1236 throws IOException, XmlPullParserException {
1237
1238 name = name.intern();
1239
1240 BasePermission bp = mSettings.mPermissions.get(name);
1241 if (bp == null) {
1242 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1243 mSettings.mPermissions.put(name, bp);
1244 }
1245 int outerDepth = parser.getDepth();
1246 int type;
1247 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1248 && (type != XmlPullParser.END_TAG
1249 || parser.getDepth() > outerDepth)) {
1250 if (type == XmlPullParser.END_TAG
1251 || type == XmlPullParser.TEXT) {
1252 continue;
1253 }
1254
1255 String tagName = parser.getName();
1256 if ("group".equals(tagName)) {
1257 String gidStr = parser.getAttributeValue(null, "gid");
1258 if (gidStr != null) {
1259 int gid = Process.getGidForName(gidStr);
1260 bp.gids = appendInt(bp.gids, gid);
1261 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001262 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 + parser.getPositionDescription());
1264 }
1265 }
1266 XmlUtils.skipCurrentTag(parser);
1267 }
1268 }
1269
1270 static int[] appendInt(int[] cur, int val) {
1271 if (cur == null) {
1272 return new int[] { val };
1273 }
1274 final int N = cur.length;
1275 for (int i=0; i<N; i++) {
1276 if (cur[i] == val) {
1277 return cur;
1278 }
1279 }
1280 int[] ret = new int[N+1];
1281 System.arraycopy(cur, 0, ret, 0, N);
1282 ret[N] = val;
1283 return ret;
1284 }
1285
1286 static int[] appendInts(int[] cur, int[] add) {
1287 if (add == null) return cur;
1288 if (cur == null) return add;
1289 final int N = add.length;
1290 for (int i=0; i<N; i++) {
1291 cur = appendInt(cur, add[i]);
1292 }
1293 return cur;
1294 }
1295
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001296 static int[] removeInt(int[] cur, int val) {
1297 if (cur == null) {
1298 return null;
1299 }
1300 final int N = cur.length;
1301 for (int i=0; i<N; i++) {
1302 if (cur[i] == val) {
1303 int[] ret = new int[N-1];
1304 if (i > 0) {
1305 System.arraycopy(cur, 0, ret, 0, i);
1306 }
1307 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001308 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001309 }
1310 return ret;
1311 }
1312 }
1313 return cur;
1314 }
1315
1316 static int[] removeInts(int[] cur, int[] rem) {
1317 if (rem == null) return cur;
1318 if (cur == null) return cur;
1319 final int N = rem.length;
1320 for (int i=0; i<N; i++) {
1321 cur = removeInt(cur, rem[i]);
1322 }
1323 return cur;
1324 }
1325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001327 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1328 // The package has been uninstalled but has retained data and resources.
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001329 return PackageParser.generatePackageInfo(p, null, flags, 0, 0);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 final PackageSetting ps = (PackageSetting)p.mExtras;
1332 if (ps == null) {
1333 return null;
1334 }
1335 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001336 return PackageParser.generatePackageInfo(p, gp.gids, flags,
1337 ps.firstInstallTime, ps.lastUpdateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 }
1339
1340 public PackageInfo getPackageInfo(String packageName, int flags) {
1341 synchronized (mPackages) {
1342 PackageParser.Package p = mPackages.get(packageName);
1343 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001344 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 + ": " + p);
1346 if (p != null) {
1347 return generatePackageInfo(p, flags);
1348 }
1349 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1350 return generatePackageInfoFromSettingsLP(packageName, flags);
1351 }
1352 }
1353 return null;
1354 }
1355
Dianne Hackborn47096932010-02-11 15:57:09 -08001356 public String[] currentToCanonicalPackageNames(String[] names) {
1357 String[] out = new String[names.length];
1358 synchronized (mPackages) {
1359 for (int i=names.length-1; i>=0; i--) {
1360 PackageSetting ps = mSettings.mPackages.get(names[i]);
1361 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1362 }
1363 }
1364 return out;
1365 }
1366
1367 public String[] canonicalToCurrentPackageNames(String[] names) {
1368 String[] out = new String[names.length];
1369 synchronized (mPackages) {
1370 for (int i=names.length-1; i>=0; i--) {
1371 String cur = mSettings.mRenamedPackages.get(names[i]);
1372 out[i] = cur != null ? cur : names[i];
1373 }
1374 }
1375 return out;
1376 }
1377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 public int getPackageUid(String packageName) {
1379 synchronized (mPackages) {
1380 PackageParser.Package p = mPackages.get(packageName);
1381 if(p != null) {
1382 return p.applicationInfo.uid;
1383 }
1384 PackageSetting ps = mSettings.mPackages.get(packageName);
1385 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1386 return -1;
1387 }
1388 p = ps.pkg;
1389 return p != null ? p.applicationInfo.uid : -1;
1390 }
1391 }
1392
1393 public int[] getPackageGids(String packageName) {
1394 synchronized (mPackages) {
1395 PackageParser.Package p = mPackages.get(packageName);
1396 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001397 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 + ": " + p);
1399 if (p != null) {
1400 final PackageSetting ps = (PackageSetting)p.mExtras;
1401 final SharedUserSetting suid = ps.sharedUser;
1402 return suid != null ? suid.gids : ps.gids;
1403 }
1404 }
1405 // stupid thing to indicate an error.
1406 return new int[0];
1407 }
1408
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001409 static final PermissionInfo generatePermissionInfo(
1410 BasePermission bp, int flags) {
1411 if (bp.perm != null) {
1412 return PackageParser.generatePermissionInfo(bp.perm, flags);
1413 }
1414 PermissionInfo pi = new PermissionInfo();
1415 pi.name = bp.name;
1416 pi.packageName = bp.sourcePackage;
1417 pi.nonLocalizedLabel = bp.name;
1418 pi.protectionLevel = bp.protectionLevel;
1419 return pi;
1420 }
1421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 public PermissionInfo getPermissionInfo(String name, int flags) {
1423 synchronized (mPackages) {
1424 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001425 if (p != null) {
1426 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428 return null;
1429 }
1430 }
1431
1432 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1433 synchronized (mPackages) {
1434 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1435 for (BasePermission p : mSettings.mPermissions.values()) {
1436 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001437 if (p.perm == null || p.perm.info.group == null) {
1438 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001441 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1443 }
1444 }
1445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 if (out.size() > 0) {
1448 return out;
1449 }
1450 return mPermissionGroups.containsKey(group) ? out : null;
1451 }
1452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1455 synchronized (mPackages) {
1456 return PackageParser.generatePermissionGroupInfo(
1457 mPermissionGroups.get(name), flags);
1458 }
1459 }
1460
1461 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1462 synchronized (mPackages) {
1463 final int N = mPermissionGroups.size();
1464 ArrayList<PermissionGroupInfo> out
1465 = new ArrayList<PermissionGroupInfo>(N);
1466 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1467 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1468 }
1469 return out;
1470 }
1471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1474 PackageSetting ps = mSettings.mPackages.get(packageName);
1475 if(ps != null) {
1476 if(ps.pkg == null) {
1477 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1478 if(pInfo != null) {
1479 return pInfo.applicationInfo;
1480 }
1481 return null;
1482 }
1483 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1484 }
1485 return null;
1486 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1489 PackageSetting ps = mSettings.mPackages.get(packageName);
1490 if(ps != null) {
1491 if(ps.pkg == null) {
1492 ps.pkg = new PackageParser.Package(packageName);
1493 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001494 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1495 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1496 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1497 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001498 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001499 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 }
1501 return generatePackageInfo(ps.pkg, flags);
1502 }
1503 return null;
1504 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1507 synchronized (mPackages) {
1508 PackageParser.Package p = mPackages.get(packageName);
1509 if (Config.LOGV) Log.v(
1510 TAG, "getApplicationInfo " + packageName
1511 + ": " + p);
1512 if (p != null) {
1513 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001514 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516 if ("android".equals(packageName)||"system".equals(packageName)) {
1517 return mAndroidApplication;
1518 }
1519 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1520 return generateApplicationInfoFromSettingsLP(packageName, flags);
1521 }
1522 }
1523 return null;
1524 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001525
1526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1528 mContext.enforceCallingOrSelfPermission(
1529 android.Manifest.permission.CLEAR_APP_CACHE, null);
1530 // Queue up an async operation since clearing cache may take a little while.
1531 mHandler.post(new Runnable() {
1532 public void run() {
1533 mHandler.removeCallbacks(this);
1534 int retCode = -1;
1535 if (mInstaller != null) {
1536 retCode = mInstaller.freeCache(freeStorageSize);
1537 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001538 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 } //end if mInstaller
1541 if (observer != null) {
1542 try {
1543 observer.onRemoveCompleted(null, (retCode >= 0));
1544 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001545 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547 }
1548 }
1549 });
1550 }
1551
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001552 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001553 mContext.enforceCallingOrSelfPermission(
1554 android.Manifest.permission.CLEAR_APP_CACHE, null);
1555 // Queue up an async operation since clearing cache may take a little while.
1556 mHandler.post(new Runnable() {
1557 public void run() {
1558 mHandler.removeCallbacks(this);
1559 int retCode = -1;
1560 if (mInstaller != null) {
1561 retCode = mInstaller.freeCache(freeStorageSize);
1562 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001563 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001564 }
1565 }
1566 if(pi != null) {
1567 try {
1568 // Callback via pending intent
1569 int code = (retCode >= 0) ? 1 : 0;
1570 pi.sendIntent(null, code, null,
1571 null, null);
1572 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001573 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001574 }
1575 }
1576 }
1577 });
1578 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1581 synchronized (mPackages) {
1582 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001583
1584 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001586 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
1588 if (mResolveComponentName.equals(component)) {
1589 return mResolveActivity;
1590 }
1591 }
1592 return null;
1593 }
1594
1595 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1596 synchronized (mPackages) {
1597 PackageParser.Activity a = mReceivers.mActivities.get(component);
1598 if (Config.LOGV) Log.v(
1599 TAG, "getReceiverInfo " + component + ": " + a);
1600 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1601 return PackageParser.generateActivityInfo(a, flags);
1602 }
1603 }
1604 return null;
1605 }
1606
1607 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1608 synchronized (mPackages) {
1609 PackageParser.Service s = mServices.mServices.get(component);
1610 if (Config.LOGV) Log.v(
1611 TAG, "getServiceInfo " + component + ": " + s);
1612 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1613 return PackageParser.generateServiceInfo(s, flags);
1614 }
1615 }
1616 return null;
1617 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001618
Dianne Hackborn361199b2010-08-30 17:42:07 -07001619 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1620 synchronized (mPackages) {
1621 PackageParser.Provider p = mProvidersByComponent.get(component);
1622 if (Config.LOGV) Log.v(
1623 TAG, "getProviderInfo " + component + ": " + p);
1624 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1625 return PackageParser.generateProviderInfo(p, flags);
1626 }
1627 }
1628 return null;
1629 }
1630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 public String[] getSystemSharedLibraryNames() {
1632 Set<String> libSet;
1633 synchronized (mPackages) {
1634 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001635 int size = libSet.size();
1636 if (size > 0) {
1637 String[] libs = new String[size];
1638 libSet.toArray(libs);
1639 return libs;
1640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001642 return null;
1643 }
1644
1645 public FeatureInfo[] getSystemAvailableFeatures() {
1646 Collection<FeatureInfo> featSet;
1647 synchronized (mPackages) {
1648 featSet = mAvailableFeatures.values();
1649 int size = featSet.size();
1650 if (size > 0) {
1651 FeatureInfo[] features = new FeatureInfo[size+1];
1652 featSet.toArray(features);
1653 FeatureInfo fi = new FeatureInfo();
1654 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1655 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1656 features[size] = fi;
1657 return features;
1658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 }
1660 return null;
1661 }
1662
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001663 public boolean hasSystemFeature(String name) {
1664 synchronized (mPackages) {
1665 return mAvailableFeatures.containsKey(name);
1666 }
1667 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 public int checkPermission(String permName, String pkgName) {
1670 synchronized (mPackages) {
1671 PackageParser.Package p = mPackages.get(pkgName);
1672 if (p != null && p.mExtras != null) {
1673 PackageSetting ps = (PackageSetting)p.mExtras;
1674 if (ps.sharedUser != null) {
1675 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1676 return PackageManager.PERMISSION_GRANTED;
1677 }
1678 } else if (ps.grantedPermissions.contains(permName)) {
1679 return PackageManager.PERMISSION_GRANTED;
1680 }
1681 }
1682 }
1683 return PackageManager.PERMISSION_DENIED;
1684 }
1685
1686 public int checkUidPermission(String permName, int uid) {
1687 synchronized (mPackages) {
1688 Object obj = mSettings.getUserIdLP(uid);
1689 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001690 GrantedPermissions gp = (GrantedPermissions)obj;
1691 if (gp.grantedPermissions.contains(permName)) {
1692 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694 } else {
1695 HashSet<String> perms = mSystemPermissions.get(uid);
1696 if (perms != null && perms.contains(permName)) {
1697 return PackageManager.PERMISSION_GRANTED;
1698 }
1699 }
1700 }
1701 return PackageManager.PERMISSION_DENIED;
1702 }
1703
1704 private BasePermission findPermissionTreeLP(String permName) {
1705 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1706 if (permName.startsWith(bp.name) &&
1707 permName.length() > bp.name.length() &&
1708 permName.charAt(bp.name.length()) == '.') {
1709 return bp;
1710 }
1711 }
1712 return null;
1713 }
1714
1715 private BasePermission checkPermissionTreeLP(String permName) {
1716 if (permName != null) {
1717 BasePermission bp = findPermissionTreeLP(permName);
1718 if (bp != null) {
1719 if (bp.uid == Binder.getCallingUid()) {
1720 return bp;
1721 }
1722 throw new SecurityException("Calling uid "
1723 + Binder.getCallingUid()
1724 + " is not allowed to add to permission tree "
1725 + bp.name + " owned by uid " + bp.uid);
1726 }
1727 }
1728 throw new SecurityException("No permission tree found for " + permName);
1729 }
1730
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001731 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1732 if (s1 == null) {
1733 return s2 == null;
1734 }
1735 if (s2 == null) {
1736 return false;
1737 }
1738 if (s1.getClass() != s2.getClass()) {
1739 return false;
1740 }
1741 return s1.equals(s2);
1742 }
1743
1744 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1745 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001746 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001747 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1748 if (!compareStrings(pi1.name, pi2.name)) return false;
1749 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1750 // We'll take care of setting this one.
1751 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1752 // These are not currently stored in settings.
1753 //if (!compareStrings(pi1.group, pi2.group)) return false;
1754 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1755 //if (pi1.labelRes != pi2.labelRes) return false;
1756 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1757 return true;
1758 }
1759
1760 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1761 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1762 throw new SecurityException("Label must be specified in permission");
1763 }
1764 BasePermission tree = checkPermissionTreeLP(info.name);
1765 BasePermission bp = mSettings.mPermissions.get(info.name);
1766 boolean added = bp == null;
1767 boolean changed = true;
1768 if (added) {
1769 bp = new BasePermission(info.name, tree.sourcePackage,
1770 BasePermission.TYPE_DYNAMIC);
1771 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1772 throw new SecurityException(
1773 "Not allowed to modify non-dynamic permission "
1774 + info.name);
1775 } else {
1776 if (bp.protectionLevel == info.protectionLevel
1777 && bp.perm.owner.equals(tree.perm.owner)
1778 && bp.uid == tree.uid
1779 && comparePermissionInfos(bp.perm.info, info)) {
1780 changed = false;
1781 }
1782 }
1783 bp.protectionLevel = info.protectionLevel;
1784 bp.perm = new PackageParser.Permission(tree.perm.owner,
1785 new PermissionInfo(info));
1786 bp.perm.info.packageName = tree.perm.info.packageName;
1787 bp.uid = tree.uid;
1788 if (added) {
1789 mSettings.mPermissions.put(info.name, bp);
1790 }
1791 if (changed) {
1792 if (!async) {
1793 mSettings.writeLP();
1794 } else {
1795 scheduleWriteSettingsLocked();
1796 }
1797 }
1798 return added;
1799 }
1800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 public boolean addPermission(PermissionInfo info) {
1802 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001803 return addPermissionLocked(info, false);
1804 }
1805 }
1806
1807 public boolean addPermissionAsync(PermissionInfo info) {
1808 synchronized (mPackages) {
1809 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 }
1811 }
1812
1813 public void removePermission(String name) {
1814 synchronized (mPackages) {
1815 checkPermissionTreeLP(name);
1816 BasePermission bp = mSettings.mPermissions.get(name);
1817 if (bp != null) {
1818 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1819 throw new SecurityException(
1820 "Not allowed to modify non-dynamic permission "
1821 + name);
1822 }
1823 mSettings.mPermissions.remove(name);
1824 mSettings.writeLP();
1825 }
1826 }
1827 }
1828
Dianne Hackborn854060af2009-07-09 18:14:31 -07001829 public boolean isProtectedBroadcast(String actionName) {
1830 synchronized (mPackages) {
1831 return mProtectedBroadcasts.contains(actionName);
1832 }
1833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 public int checkSignatures(String pkg1, String pkg2) {
1836 synchronized (mPackages) {
1837 PackageParser.Package p1 = mPackages.get(pkg1);
1838 PackageParser.Package p2 = mPackages.get(pkg2);
1839 if (p1 == null || p1.mExtras == null
1840 || p2 == null || p2.mExtras == null) {
1841 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1842 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001843 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
1845 }
1846
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001847 public int checkUidSignatures(int uid1, int uid2) {
1848 synchronized (mPackages) {
1849 Signature[] s1;
1850 Signature[] s2;
1851 Object obj = mSettings.getUserIdLP(uid1);
1852 if (obj != null) {
1853 if (obj instanceof SharedUserSetting) {
1854 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1855 } else if (obj instanceof PackageSetting) {
1856 s1 = ((PackageSetting)obj).signatures.mSignatures;
1857 } else {
1858 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1859 }
1860 } else {
1861 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1862 }
1863 obj = mSettings.getUserIdLP(uid2);
1864 if (obj != null) {
1865 if (obj instanceof SharedUserSetting) {
1866 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1867 } else if (obj instanceof PackageSetting) {
1868 s2 = ((PackageSetting)obj).signatures.mSignatures;
1869 } else {
1870 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1871 }
1872 } else {
1873 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1874 }
1875 return checkSignaturesLP(s1, s2);
1876 }
1877 }
1878
1879 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1880 if (s1 == null) {
1881 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1883 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1884 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001885 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1887 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001888 HashSet<Signature> set1 = new HashSet<Signature>();
1889 for (Signature sig : s1) {
1890 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001892 HashSet<Signature> set2 = new HashSet<Signature>();
1893 for (Signature sig : s2) {
1894 set2.add(sig);
1895 }
1896 // Make sure s2 contains all signatures in s1.
1897 if (set1.equals(set2)) {
1898 return PackageManager.SIGNATURE_MATCH;
1899 }
1900 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
1902
1903 public String[] getPackagesForUid(int uid) {
1904 synchronized (mPackages) {
1905 Object obj = mSettings.getUserIdLP(uid);
1906 if (obj instanceof SharedUserSetting) {
1907 SharedUserSetting sus = (SharedUserSetting)obj;
1908 final int N = sus.packages.size();
1909 String[] res = new String[N];
1910 Iterator<PackageSetting> it = sus.packages.iterator();
1911 int i=0;
1912 while (it.hasNext()) {
1913 res[i++] = it.next().name;
1914 }
1915 return res;
1916 } else if (obj instanceof PackageSetting) {
1917 PackageSetting ps = (PackageSetting)obj;
1918 return new String[] { ps.name };
1919 }
1920 }
1921 return null;
1922 }
1923
1924 public String getNameForUid(int uid) {
1925 synchronized (mPackages) {
1926 Object obj = mSettings.getUserIdLP(uid);
1927 if (obj instanceof SharedUserSetting) {
1928 SharedUserSetting sus = (SharedUserSetting)obj;
1929 return sus.name + ":" + sus.userId;
1930 } else if (obj instanceof PackageSetting) {
1931 PackageSetting ps = (PackageSetting)obj;
1932 return ps.name;
1933 }
1934 }
1935 return null;
1936 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 public int getUidForSharedUser(String sharedUserName) {
1939 if(sharedUserName == null) {
1940 return -1;
1941 }
1942 synchronized (mPackages) {
1943 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1944 if(suid == null) {
1945 return -1;
1946 }
1947 return suid.userId;
1948 }
1949 }
1950
1951 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1952 int flags) {
1953 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001954 return chooseBestActivity(intent, resolvedType, flags, query);
1955 }
1956
Mihai Predaeae850c2009-05-13 10:13:48 +02001957 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1958 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 if (query != null) {
1960 final int N = query.size();
1961 if (N == 1) {
1962 return query.get(0);
1963 } else if (N > 1) {
1964 // If there is more than one activity with the same priority,
1965 // then let the user decide between them.
1966 ResolveInfo r0 = query.get(0);
1967 ResolveInfo r1 = query.get(1);
1968 if (false) {
1969 System.out.println(r0.activityInfo.name +
1970 "=" + r0.priority + " vs " +
1971 r1.activityInfo.name +
1972 "=" + r1.priority);
1973 }
1974 // If the first activity has a higher priority, or a different
1975 // default, then it is always desireable to pick it.
1976 if (r0.priority != r1.priority
1977 || r0.preferredOrder != r1.preferredOrder
1978 || r0.isDefault != r1.isDefault) {
1979 return query.get(0);
1980 }
1981 // If we have saved a preference for a preferred activity for
1982 // this Intent, use that.
1983 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1984 flags, query, r0.priority);
1985 if (ri != null) {
1986 return ri;
1987 }
1988 return mResolveInfo;
1989 }
1990 }
1991 return null;
1992 }
1993
1994 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1995 int flags, List<ResolveInfo> query, int priority) {
1996 synchronized (mPackages) {
1997 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1998 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001999 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2001 if (prefs != null && prefs.size() > 0) {
2002 // First figure out how good the original match set is.
2003 // We will only allow preferred activities that came
2004 // from the same match quality.
2005 int match = 0;
2006 final int N = query.size();
2007 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2008 for (int j=0; j<N; j++) {
2009 ResolveInfo ri = query.get(j);
2010 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2011 + ": 0x" + Integer.toHexString(match));
2012 if (ri.match > match) match = ri.match;
2013 }
2014 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2015 + Integer.toHexString(match));
2016 match &= IntentFilter.MATCH_CATEGORY_MASK;
2017 final int M = prefs.size();
2018 for (int i=0; i<M; i++) {
2019 PreferredActivity pa = prefs.get(i);
2020 if (pa.mMatch != match) {
2021 continue;
2022 }
2023 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2024 if (DEBUG_PREFERRED) {
2025 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002026 if (ai != null) {
2027 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2028 } else {
2029 Log.v(TAG, " null");
2030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
2032 if (ai != null) {
2033 for (int j=0; j<N; j++) {
2034 ResolveInfo ri = query.get(j);
2035 if (!ri.activityInfo.applicationInfo.packageName
2036 .equals(ai.applicationInfo.packageName)) {
2037 continue;
2038 }
2039 if (!ri.activityInfo.name.equals(ai.name)) {
2040 continue;
2041 }
2042
2043 // Okay we found a previously set preferred app.
2044 // If the result set is different from when this
2045 // was created, we need to clear it and re-ask the
2046 // user their preference.
2047 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002048 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 + intent + " type " + resolvedType);
2050 mSettings.mPreferredActivities.removeFilter(pa);
2051 return null;
2052 }
2053
2054 // Yay!
2055 return ri;
2056 }
2057 }
2058 }
2059 }
2060 }
2061 return null;
2062 }
2063
2064 public List<ResolveInfo> queryIntentActivities(Intent intent,
2065 String resolvedType, int flags) {
2066 ComponentName comp = intent.getComponent();
2067 if (comp != null) {
2068 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2069 ActivityInfo ai = getActivityInfo(comp, flags);
2070 if (ai != null) {
2071 ResolveInfo ri = new ResolveInfo();
2072 ri.activityInfo = ai;
2073 list.add(ri);
2074 }
2075 return list;
2076 }
2077
2078 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002079 String pkgName = intent.getPackage();
2080 if (pkgName == null) {
2081 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2082 resolvedType, flags);
2083 }
2084 PackageParser.Package pkg = mPackages.get(pkgName);
2085 if (pkg != null) {
2086 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2087 resolvedType, flags, pkg.activities);
2088 }
2089 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
2091 }
2092
2093 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2094 Intent[] specifics, String[] specificTypes, Intent intent,
2095 String resolvedType, int flags) {
2096 final String resultsAction = intent.getAction();
2097
2098 List<ResolveInfo> results = queryIntentActivities(
2099 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2100 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2101
2102 int specificsPos = 0;
2103 int N;
2104
2105 // todo: note that the algorithm used here is O(N^2). This
2106 // isn't a problem in our current environment, but if we start running
2107 // into situations where we have more than 5 or 10 matches then this
2108 // should probably be changed to something smarter...
2109
2110 // First we go through and resolve each of the specific items
2111 // that were supplied, taking care of removing any corresponding
2112 // duplicate items in the generic resolve list.
2113 if (specifics != null) {
2114 for (int i=0; i<specifics.length; i++) {
2115 final Intent sintent = specifics[i];
2116 if (sintent == null) {
2117 continue;
2118 }
2119
2120 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2121 String action = sintent.getAction();
2122 if (resultsAction != null && resultsAction.equals(action)) {
2123 // If this action was explicitly requested, then don't
2124 // remove things that have it.
2125 action = null;
2126 }
2127 ComponentName comp = sintent.getComponent();
2128 ResolveInfo ri = null;
2129 ActivityInfo ai = null;
2130 if (comp == null) {
2131 ri = resolveIntent(
2132 sintent,
2133 specificTypes != null ? specificTypes[i] : null,
2134 flags);
2135 if (ri == null) {
2136 continue;
2137 }
2138 if (ri == mResolveInfo) {
2139 // ACK! Must do something better with this.
2140 }
2141 ai = ri.activityInfo;
2142 comp = new ComponentName(ai.applicationInfo.packageName,
2143 ai.name);
2144 } else {
2145 ai = getActivityInfo(comp, flags);
2146 if (ai == null) {
2147 continue;
2148 }
2149 }
2150
2151 // Look for any generic query activities that are duplicates
2152 // of this specific one, and remove them from the results.
2153 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2154 N = results.size();
2155 int j;
2156 for (j=specificsPos; j<N; j++) {
2157 ResolveInfo sri = results.get(j);
2158 if ((sri.activityInfo.name.equals(comp.getClassName())
2159 && sri.activityInfo.applicationInfo.packageName.equals(
2160 comp.getPackageName()))
2161 || (action != null && sri.filter.matchAction(action))) {
2162 results.remove(j);
2163 if (Config.LOGV) Log.v(
2164 TAG, "Removing duplicate item from " + j
2165 + " due to specific " + specificsPos);
2166 if (ri == null) {
2167 ri = sri;
2168 }
2169 j--;
2170 N--;
2171 }
2172 }
2173
2174 // Add this specific item to its proper place.
2175 if (ri == null) {
2176 ri = new ResolveInfo();
2177 ri.activityInfo = ai;
2178 }
2179 results.add(specificsPos, ri);
2180 ri.specificIndex = i;
2181 specificsPos++;
2182 }
2183 }
2184
2185 // Now we go through the remaining generic results and remove any
2186 // duplicate actions that are found here.
2187 N = results.size();
2188 for (int i=specificsPos; i<N-1; i++) {
2189 final ResolveInfo rii = results.get(i);
2190 if (rii.filter == null) {
2191 continue;
2192 }
2193
2194 // Iterate over all of the actions of this result's intent
2195 // filter... typically this should be just one.
2196 final Iterator<String> it = rii.filter.actionsIterator();
2197 if (it == null) {
2198 continue;
2199 }
2200 while (it.hasNext()) {
2201 final String action = it.next();
2202 if (resultsAction != null && resultsAction.equals(action)) {
2203 // If this action was explicitly requested, then don't
2204 // remove things that have it.
2205 continue;
2206 }
2207 for (int j=i+1; j<N; j++) {
2208 final ResolveInfo rij = results.get(j);
2209 if (rij.filter != null && rij.filter.hasAction(action)) {
2210 results.remove(j);
2211 if (Config.LOGV) Log.v(
2212 TAG, "Removing duplicate item from " + j
2213 + " due to action " + action + " at " + i);
2214 j--;
2215 N--;
2216 }
2217 }
2218 }
2219
2220 // If the caller didn't request filter information, drop it now
2221 // so we don't have to marshall/unmarshall it.
2222 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2223 rii.filter = null;
2224 }
2225 }
2226
2227 // Filter out the caller activity if so requested.
2228 if (caller != null) {
2229 N = results.size();
2230 for (int i=0; i<N; i++) {
2231 ActivityInfo ainfo = results.get(i).activityInfo;
2232 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2233 && caller.getClassName().equals(ainfo.name)) {
2234 results.remove(i);
2235 break;
2236 }
2237 }
2238 }
2239
2240 // If the caller didn't request filter information,
2241 // drop them now so we don't have to
2242 // marshall/unmarshall it.
2243 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2244 N = results.size();
2245 for (int i=0; i<N; i++) {
2246 results.get(i).filter = null;
2247 }
2248 }
2249
2250 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2251 return results;
2252 }
2253
2254 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2255 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002256 ComponentName comp = intent.getComponent();
2257 if (comp != null) {
2258 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2259 ActivityInfo ai = getReceiverInfo(comp, flags);
2260 if (ai != null) {
2261 ResolveInfo ri = new ResolveInfo();
2262 ri.activityInfo = ai;
2263 list.add(ri);
2264 }
2265 return list;
2266 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002269 String pkgName = intent.getPackage();
2270 if (pkgName == null) {
2271 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2272 resolvedType, flags);
2273 }
2274 PackageParser.Package pkg = mPackages.get(pkgName);
2275 if (pkg != null) {
2276 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2277 resolvedType, flags, pkg.receivers);
2278 }
2279 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 }
2281 }
2282
2283 public ResolveInfo resolveService(Intent intent, String resolvedType,
2284 int flags) {
2285 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2286 flags);
2287 if (query != null) {
2288 if (query.size() >= 1) {
2289 // If there is more than one service with the same priority,
2290 // just arbitrarily pick the first one.
2291 return query.get(0);
2292 }
2293 }
2294 return null;
2295 }
2296
2297 public List<ResolveInfo> queryIntentServices(Intent intent,
2298 String resolvedType, int flags) {
2299 ComponentName comp = intent.getComponent();
2300 if (comp != null) {
2301 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2302 ServiceInfo si = getServiceInfo(comp, flags);
2303 if (si != null) {
2304 ResolveInfo ri = new ResolveInfo();
2305 ri.serviceInfo = si;
2306 list.add(ri);
2307 }
2308 return list;
2309 }
2310
2311 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002312 String pkgName = intent.getPackage();
2313 if (pkgName == null) {
2314 return (List<ResolveInfo>)mServices.queryIntent(intent,
2315 resolvedType, flags);
2316 }
2317 PackageParser.Package pkg = mPackages.get(pkgName);
2318 if (pkg != null) {
2319 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2320 resolvedType, flags, pkg.services);
2321 }
2322 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
2324 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 public List<PackageInfo> getInstalledPackages(int flags) {
2327 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2328
2329 synchronized (mPackages) {
2330 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2331 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2332 while (i.hasNext()) {
2333 final PackageSetting ps = i.next();
2334 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2335 if(psPkg != null) {
2336 finalList.add(psPkg);
2337 }
2338 }
2339 }
2340 else {
2341 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2342 while (i.hasNext()) {
2343 final PackageParser.Package p = i.next();
2344 if (p.applicationInfo != null) {
2345 PackageInfo pi = generatePackageInfo(p, flags);
2346 if(pi != null) {
2347 finalList.add(pi);
2348 }
2349 }
2350 }
2351 }
2352 }
2353 return finalList;
2354 }
2355
2356 public List<ApplicationInfo> getInstalledApplications(int flags) {
2357 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2358 synchronized(mPackages) {
2359 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2360 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2361 while (i.hasNext()) {
2362 final PackageSetting ps = i.next();
2363 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2364 if(ai != null) {
2365 finalList.add(ai);
2366 }
2367 }
2368 }
2369 else {
2370 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2371 while (i.hasNext()) {
2372 final PackageParser.Package p = i.next();
2373 if (p.applicationInfo != null) {
2374 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2375 if(ai != null) {
2376 finalList.add(ai);
2377 }
2378 }
2379 }
2380 }
2381 }
2382 return finalList;
2383 }
2384
2385 public List<ApplicationInfo> getPersistentApplications(int flags) {
2386 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2387
2388 synchronized (mPackages) {
2389 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2390 while (i.hasNext()) {
2391 PackageParser.Package p = i.next();
2392 if (p.applicationInfo != null
2393 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002394 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002395 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 }
2397 }
2398 }
2399
2400 return finalList;
2401 }
2402
2403 public ProviderInfo resolveContentProvider(String name, int flags) {
2404 synchronized (mPackages) {
2405 final PackageParser.Provider provider = mProviders.get(name);
2406 return provider != null
2407 && mSettings.isEnabledLP(provider.info, flags)
2408 && (!mSafeMode || (provider.info.applicationInfo.flags
2409 &ApplicationInfo.FLAG_SYSTEM) != 0)
2410 ? PackageParser.generateProviderInfo(provider, flags)
2411 : null;
2412 }
2413 }
2414
Fred Quintana718d8a22009-04-29 17:53:20 -07002415 /**
2416 * @deprecated
2417 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 public void querySyncProviders(List outNames, List outInfo) {
2419 synchronized (mPackages) {
2420 Iterator<Map.Entry<String, PackageParser.Provider>> i
2421 = mProviders.entrySet().iterator();
2422
2423 while (i.hasNext()) {
2424 Map.Entry<String, PackageParser.Provider> entry = i.next();
2425 PackageParser.Provider p = entry.getValue();
2426
2427 if (p.syncable
2428 && (!mSafeMode || (p.info.applicationInfo.flags
2429 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2430 outNames.add(entry.getKey());
2431 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2432 }
2433 }
2434 }
2435 }
2436
2437 public List<ProviderInfo> queryContentProviders(String processName,
2438 int uid, int flags) {
2439 ArrayList<ProviderInfo> finalList = null;
2440
2441 synchronized (mPackages) {
2442 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2443 while (i.hasNext()) {
2444 PackageParser.Provider p = i.next();
2445 if (p.info.authority != null
2446 && (processName == null ||
2447 (p.info.processName.equals(processName)
2448 && p.info.applicationInfo.uid == uid))
2449 && mSettings.isEnabledLP(p.info, flags)
2450 && (!mSafeMode || (p.info.applicationInfo.flags
2451 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2452 if (finalList == null) {
2453 finalList = new ArrayList<ProviderInfo>(3);
2454 }
2455 finalList.add(PackageParser.generateProviderInfo(p,
2456 flags));
2457 }
2458 }
2459 }
2460
2461 if (finalList != null) {
2462 Collections.sort(finalList, mProviderInitOrderSorter);
2463 }
2464
2465 return finalList;
2466 }
2467
2468 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2469 int flags) {
2470 synchronized (mPackages) {
2471 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2472 return PackageParser.generateInstrumentationInfo(i, flags);
2473 }
2474 }
2475
2476 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2477 int flags) {
2478 ArrayList<InstrumentationInfo> finalList =
2479 new ArrayList<InstrumentationInfo>();
2480
2481 synchronized (mPackages) {
2482 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2483 while (i.hasNext()) {
2484 PackageParser.Instrumentation p = i.next();
2485 if (targetPackage == null
2486 || targetPackage.equals(p.info.targetPackage)) {
2487 finalList.add(PackageParser.generateInstrumentationInfo(p,
2488 flags));
2489 }
2490 }
2491 }
2492
2493 return finalList;
2494 }
2495
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002496 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002498 if (files == null) {
2499 Log.d(TAG, "No files in app dir " + dir);
2500 return;
2501 }
2502
Joe Onorato431bb222010-10-18 19:13:23 -04002503 if (false) {
2504 Log.d(TAG, "Scanning app dir " + dir);
2505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506
2507 int i;
2508 for (i=0; i<files.length; i++) {
2509 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002510 if (!isPackageFilename(files[i])) {
2511 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002512 continue;
2513 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002514 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002515 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002516 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002517 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2518 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002519 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002520 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002521 file.delete();
2522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
2524 }
2525
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002526 private static File getSettingsProblemFile() {
2527 File dataDir = Environment.getDataDirectory();
2528 File systemDir = new File(dataDir, "system");
2529 File fname = new File(systemDir, "uiderrors.txt");
2530 return fname;
2531 }
2532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 private static void reportSettingsProblem(int priority, String msg) {
2534 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002535 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 FileOutputStream out = new FileOutputStream(fname, true);
2537 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002538 SimpleDateFormat formatter = new SimpleDateFormat();
2539 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2540 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 pw.close();
2542 FileUtils.setPermissions(
2543 fname.toString(),
2544 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2545 -1, -1);
2546 } catch (java.io.IOException e) {
2547 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002548 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 }
2550
2551 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2552 PackageParser.Package pkg, File srcFile, int parseFlags) {
2553 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002554 if (ps != null
2555 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002556 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002557 if (ps.signatures.mSignatures != null
2558 && ps.signatures.mSignatures.length != 0) {
2559 // Optimization: reuse the existing cached certificates
2560 // if the package appears to be unchanged.
2561 pkg.mSignatures = ps.signatures.mSignatures;
2562 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 }
Jeff Browne7600722010-04-07 18:28:23 -07002564
2565 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002566 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002567 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2568 }
2569
2570 if (!pp.collectCertificates(pkg, parseFlags)) {
2571 mLastScanError = pp.getParseError();
2572 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
2574 }
2575 return true;
2576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 /*
2579 * Scan a package and return the newly parsed package.
2580 * Returns null in case of errors and the error code is stored in mLastScanError
2581 */
2582 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002583 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002585 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002587 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002590 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 if (pkg == null) {
2592 mLastScanError = pp.getParseError();
2593 return null;
2594 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002595 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 PackageSetting updatedPkg;
2597 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002598 // Look to see if we already know about this package.
2599 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002600 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002601 // This package has been renamed to its original name. Let's
2602 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002603 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002604 }
2605 // If there was no original package, see one for the real package name.
2606 if (ps == null) {
2607 ps = mSettings.peekPackageLP(pkg.packageName);
2608 }
2609 // Check to see if this package could be hiding/updating a system
2610 // package. Must look for it either under the original or real
2611 // package name depending on our state.
2612 updatedPkg = mSettings.mDisabledSysPackages.get(
2613 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002615 // First check if this is a system package that may involve an update
2616 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002617 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002618 // The path has changed from what was last scanned... check the
2619 // version of the new path against what we have stored to determine
2620 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002621 if (pkg.mVersionCode < ps.versionCode) {
2622 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002623 // Ignore entry. Skip it.
2624 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002625 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002626 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002627 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2628 return null;
2629 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002630 // The current app on the system partion is better than
2631 // what we have updated to on the data partition; switch
2632 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002633 // At this point, its safely assumed that package installation for
2634 // apps in system partition will go through. If not there won't be a working
2635 // version of the app
2636 synchronized (mPackages) {
2637 // Just remove the loaded entries from package lists.
2638 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002639 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002640 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002641 + "reverting from " + ps.codePathString
2642 + ": new version " + pkg.mVersionCode
2643 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002644 InstallArgs args = new FileInstallArgs(ps.codePathString,
2645 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002646 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002647 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 }
2650 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002651 if (updatedPkg != null) {
2652 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2653 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2654 }
2655 // Verify certificates against what was last scanned
2656 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002657 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002658 return null;
2659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 // The apk is forward locked (not public) if its code and resources
2661 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002662 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002664 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002665 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002666
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002667 String codePath = null;
2668 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002669 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2670 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002671 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002672 } else {
2673 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002674 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002675 }
2676 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002677 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002678 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002679 codePath = pkg.mScanPath;
2680 // Set application objects path explicitly.
2681 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002683 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 }
2685
Kenny Root85387d72010-08-26 10:13:11 -07002686 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2687 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002688 pkg.mPath = pkg.mScanPath = destCodePath;
2689 pkg.applicationInfo.sourceDir = destCodePath;
2690 pkg.applicationInfo.publicSourceDir = destResPath;
2691 }
2692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 private static String fixProcessName(String defProcessName,
2694 String processName, int uid) {
2695 if (processName == null) {
2696 return defProcessName;
2697 }
2698 return processName;
2699 }
2700
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002701 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002702 PackageParser.Package pkg) {
2703 if (pkgSetting.signatures.mSignatures != null) {
2704 // Already existing package. Make sure signatures match
2705 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2706 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002707 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002708 + " signatures do not match the previously installed version; ignoring!");
2709 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 return false;
2711 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002712 }
2713 // Check for shared user signatures
2714 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2715 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2716 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2717 Slog.e(TAG, "Package " + pkg.packageName
2718 + " has no signatures that match those in shared user "
2719 + pkgSetting.sharedUser.name + "; ignoring!");
2720 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2721 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
2724 return true;
2725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002726
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002727 public boolean performDexOpt(String packageName) {
2728 if (!mNoDexOpt) {
2729 return false;
2730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002731
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002732 PackageParser.Package p;
2733 synchronized (mPackages) {
2734 p = mPackages.get(packageName);
2735 if (p == null || p.mDidDexOpt) {
2736 return false;
2737 }
2738 }
2739 synchronized (mInstallLock) {
2740 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2741 }
2742 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002743
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002744 static final int DEX_OPT_SKIPPED = 0;
2745 static final int DEX_OPT_PERFORMED = 1;
2746 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002747
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002748 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2749 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002750 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002751 String path = pkg.mScanPath;
2752 int ret = 0;
2753 try {
2754 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002755 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002756 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002757 pkg.mDidDexOpt = true;
2758 performed = true;
2759 }
2760 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002761 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002762 ret = -1;
2763 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002764 Slog.w(TAG, "IOException reading apk: " + path, e);
2765 ret = -1;
2766 } catch (dalvik.system.StaleDexCacheError e) {
2767 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2768 ret = -1;
2769 } catch (Exception e) {
2770 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002771 ret = -1;
2772 }
2773 if (ret < 0) {
2774 //error from installer
2775 return DEX_OPT_FAILED;
2776 }
2777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002778
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002779 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2780 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002781
2782 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2783 return Environment.isEncryptedFilesystemEnabled() &&
2784 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2785 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002786
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002787 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2788 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002789 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002790 + " to " + newPkg.packageName
2791 + ": old package not in system partition");
2792 return false;
2793 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002794 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002795 + " to " + newPkg.packageName
2796 + ": old package still exists");
2797 return false;
2798 }
2799 return true;
2800 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002801
2802 private File getDataPathForPackage(PackageParser.Package pkg) {
2803 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2804 File dataPath;
2805 if (useEncryptedFSDir) {
2806 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2807 } else {
2808 dataPath = new File(mAppDataDir, pkg.packageName);
2809 }
2810 return dataPath;
2811 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002812
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002813 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002814 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002815 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002816 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2817 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002818 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002819 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002820 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2821 return null;
2822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 mScanningPath = scanFile;
2824 if (pkg == null) {
2825 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2826 return null;
2827 }
2828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2830 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2831 }
2832
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002833 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 synchronized (mPackages) {
2835 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002836 Slog.w(TAG, "*************************************************");
2837 Slog.w(TAG, "Core android package being redefined. Skipping.");
2838 Slog.w(TAG, " file=" + mScanningPath);
2839 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2841 return null;
2842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 // Set up information for our fall-back user intent resolution
2845 // activity.
2846 mPlatformPackage = pkg;
2847 pkg.mVersionCode = mSdkVersion;
2848 mAndroidApplication = pkg.applicationInfo;
2849 mResolveActivity.applicationInfo = mAndroidApplication;
2850 mResolveActivity.name = ResolverActivity.class.getName();
2851 mResolveActivity.packageName = mAndroidApplication.packageName;
2852 mResolveActivity.processName = mAndroidApplication.processName;
2853 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2854 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2855 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2856 mResolveActivity.exported = true;
2857 mResolveActivity.enabled = true;
2858 mResolveInfo.activityInfo = mResolveActivity;
2859 mResolveInfo.priority = 0;
2860 mResolveInfo.preferredOrder = 0;
2861 mResolveInfo.match = 0;
2862 mResolveComponentName = new ComponentName(
2863 mAndroidApplication.packageName, mResolveActivity.name);
2864 }
2865 }
2866
2867 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002868 TAG, "Scanning package " + pkg.packageName);
2869 if (mPackages.containsKey(pkg.packageName)
2870 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002871 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2874 return null;
2875 }
2876
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002877 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002878 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2879 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 SharedUserSetting suid = null;
2882 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002883
Kenny Root1c6e7642011-01-10 13:48:15 -08002884 if (!isSystemApp(pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002885 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002886 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002887 pkg.mRealPackage = null;
2888 pkg.mAdoptPermissions = null;
2889 }
Kenny Root1c6e7642011-01-10 13:48:15 -08002890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 synchronized (mPackages) {
2892 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002893 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2894 if (mTmpSharedLibraries == null ||
2895 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2896 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2897 }
2898 int num = 0;
2899 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2900 for (int i=0; i<N; i++) {
2901 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002903 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002905 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2907 return null;
2908 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002909 mTmpSharedLibraries[num] = file;
2910 num++;
2911 }
2912 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2913 for (int i=0; i<N; i++) {
2914 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2915 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002916 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002917 + " desires unavailable shared library "
2918 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2919 } else {
2920 mTmpSharedLibraries[num] = file;
2921 num++;
2922 }
2923 }
2924 if (num > 0) {
2925 pkg.usesLibraryFiles = new String[num];
2926 System.arraycopy(mTmpSharedLibraries, 0,
2927 pkg.usesLibraryFiles, 0, num);
2928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 if (pkg.mSharedUserId != null) {
2932 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2933 pkg.applicationInfo.flags, true);
2934 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002935 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 + " for shared user failed");
2937 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2938 return null;
2939 }
2940 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2941 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2942 + suid.userId + "): packages=" + suid.packages);
2943 }
2944 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002945
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002946 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002947 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002948 Log.w(TAG, "WAITING FOR DEBUGGER");
2949 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002950 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2951 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002952 }
2953 }
2954
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002955 // Check if we are renaming from an original package name.
2956 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002957 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002958 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002959 // This package may need to be renamed to a previously
2960 // installed name. Let's check on that...
2961 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002962 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002963 // This package had originally been installed as the
2964 // original name, and we have already taken care of
2965 // transitioning to the new one. Just update the new
2966 // one to continue using the old name.
2967 realName = pkg.mRealPackage;
2968 if (!pkg.packageName.equals(renamed)) {
2969 // Callers into this function may have already taken
2970 // care of renaming the package; only do it here if
2971 // it is not already done.
2972 pkg.setPackageName(renamed);
2973 }
2974
Dianne Hackbornc1552392010-03-03 16:19:01 -08002975 } else {
2976 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2977 if ((origPackage=mSettings.peekPackageLP(
2978 pkg.mOriginalPackages.get(i))) != null) {
2979 // We do have the package already installed under its
2980 // original name... should we use it?
2981 if (!verifyPackageUpdate(origPackage, pkg)) {
2982 // New package is not compatible with original.
2983 origPackage = null;
2984 continue;
2985 } else if (origPackage.sharedUser != null) {
2986 // Make sure uid is compatible between packages.
2987 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002988 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002989 + " to " + pkg.packageName + ": old uid "
2990 + origPackage.sharedUser.name
2991 + " differs from " + pkg.mSharedUserId);
2992 origPackage = null;
2993 continue;
2994 }
2995 } else {
2996 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2997 + pkg.packageName + " to old name " + origPackage.name);
2998 }
2999 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003000 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003001 }
3002 }
3003 }
3004
3005 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003006 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003007 + " was transferred to another, but its .apk remains");
3008 }
3009
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003010 // Just create the setting, don't add it yet. For already existing packages
3011 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003012 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003013 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3014 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003016 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3018 return null;
3019 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003020
3021 if (pkgSetting.origPackage != null) {
3022 // If we are first transitioning from an original package,
3023 // fix up the new package's name now. We need to do this after
3024 // looking up the package under its new name, so getPackageLP
3025 // can take care of fiddling things correctly.
3026 pkg.setPackageName(origPackage.name);
3027
3028 // File a report about this.
3029 String msg = "New package " + pkgSetting.realName
3030 + " renamed to replace old package " + pkgSetting.name;
3031 reportSettingsProblem(Log.WARN, msg);
3032
3033 // Make a note of it.
3034 mTransferedPackages.add(origPackage.name);
3035
3036 // No longer need to retain this.
3037 pkgSetting.origPackage = null;
3038 }
3039
3040 if (realName != null) {
3041 // Make a note of it.
3042 mTransferedPackages.add(pkg.packageName);
3043 }
3044
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003045 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3047 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 pkg.applicationInfo.uid = pkgSetting.userId;
3050 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003051
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003052 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003053 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 return null;
3055 }
3056 // The signature has changed, but this package is in the system
3057 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003058 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 // However... if this package is part of a shared user, but it
3060 // doesn't match the signature of the shared user, let's fail.
3061 // What this means is that you can't change the signatures
3062 // associated with an overall shared user, which doesn't seem all
3063 // that unreasonable.
3064 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003065 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3066 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3067 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3069 return null;
3070 }
3071 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003072 // File a report about this.
3073 String msg = "System package " + pkg.packageName
3074 + " signature changed; retaining data.";
3075 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003077
The Android Open Source Project10592532009-03-18 17:39:46 -07003078 // Verify that this new package doesn't have any content providers
3079 // that conflict with existing packages. Only do this if the
3080 // package isn't already installed, since we don't want to break
3081 // things that are installed.
3082 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3083 int N = pkg.providers.size();
3084 int i;
3085 for (i=0; i<N; i++) {
3086 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003087 if (p.info.authority != null) {
3088 String names[] = p.info.authority.split(";");
3089 for (int j = 0; j < names.length; j++) {
3090 if (mProviders.containsKey(names[j])) {
3091 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003092 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003093 " (in package " + pkg.applicationInfo.packageName +
3094 ") is already used by "
3095 + ((other != null && other.getComponentName() != null)
3096 ? other.getComponentName().getPackageName() : "?"));
3097 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3098 return null;
3099 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003100 }
3101 }
3102 }
3103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 }
3105
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003106 final String pkgName = pkg.packageName;
3107
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003108 if (pkg.mAdoptPermissions != null) {
3109 // This package wants to adopt ownership of permissions from
3110 // another package.
3111 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3112 String origName = pkg.mAdoptPermissions.get(i);
3113 PackageSetting orig = mSettings.peekPackageLP(origName);
3114 if (orig != null) {
3115 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003116 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003117 + origName + " to " + pkg.packageName);
3118 mSettings.transferPermissions(origName, pkg.packageName);
3119 }
3120 }
3121 }
3122 }
3123
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003124 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003126 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 pkg.applicationInfo.processName = fixProcessName(
3128 pkg.applicationInfo.packageName,
3129 pkg.applicationInfo.processName,
3130 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131
3132 File dataPath;
3133 if (mPlatformPackage == pkg) {
3134 // The system package is special.
3135 dataPath = new File (Environment.getDataDirectory(), "system");
3136 pkg.applicationInfo.dataDir = dataPath.getPath();
3137 } else {
3138 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003139 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003140 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003141
3142 boolean uidError = false;
3143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 if (dataPath.exists()) {
3145 mOutPermissions[1] = 0;
3146 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003147
3148 // If we have mismatched owners for the data path, we have a
3149 // problem (unless we're running in the simulator.)
3150 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 boolean recovered = false;
3152 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3153 // If this is a system app, we can at least delete its
3154 // current data so the application will still work.
3155 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003156 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003157 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 // Old data gone!
3159 String msg = "System package " + pkg.packageName
3160 + " has changed from uid: "
3161 + mOutPermissions[1] + " to "
3162 + pkg.applicationInfo.uid + "; old data erased";
3163 reportSettingsProblem(Log.WARN, msg);
3164 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003167 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 pkg.applicationInfo.uid);
3169 if (ret == -1) {
3170 // Ack should not happen!
3171 msg = "System package " + pkg.packageName
3172 + " could not have data directory re-created after delete.";
3173 reportSettingsProblem(Log.WARN, msg);
3174 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3175 return null;
3176 }
3177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 if (!recovered) {
3180 mHasSystemUidErrors = true;
3181 }
3182 }
3183 if (!recovered) {
3184 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3185 + pkg.applicationInfo.uid + "/fs_"
3186 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003187 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 String msg = "Package " + pkg.packageName
3189 + " has mismatched uid: "
3190 + mOutPermissions[1] + " on disk, "
3191 + pkg.applicationInfo.uid + " in settings";
3192 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003193 mSettings.mReadMessages.append(msg);
3194 mSettings.mReadMessages.append('\n');
3195 uidError = true;
3196 if (!pkgSetting.uidError) {
3197 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 }
3200 }
3201 }
3202 pkg.applicationInfo.dataDir = dataPath.getPath();
3203 } else {
3204 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3205 Log.v(TAG, "Want this data dir: " + dataPath);
3206 //invoke installer to do the actual installation
3207 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003208 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 pkg.applicationInfo.uid);
3210 if(ret < 0) {
3211 // Error from installer
3212 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3213 return null;
3214 }
3215 } else {
3216 dataPath.mkdirs();
3217 if (dataPath.exists()) {
3218 FileUtils.setPermissions(
3219 dataPath.toString(),
3220 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3221 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3222 }
3223 }
3224 if (dataPath.exists()) {
3225 pkg.applicationInfo.dataDir = dataPath.getPath();
3226 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003227 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 pkg.applicationInfo.dataDir = null;
3229 }
3230 }
Kenny Root85387d72010-08-26 10:13:11 -07003231
3232 /*
3233 * Set the data dir to the default "/data/data/<package name>/lib"
3234 * if we got here without anyone telling us different (e.g., apps
3235 * stored on SD card have their native libraries stored in the ASEC
3236 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003237 *
3238 * This happens during an upgrade from a package settings file that
3239 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003240 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003241 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3242 if (pkgSetting.nativeLibraryPathString == null) {
3243 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3244 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3245 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3246 } else {
3247 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3248 }
Kenny Root85387d72010-08-26 10:13:11 -07003249 }
3250
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003251 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 }
3253
Kenny Root85387d72010-08-26 10:13:11 -07003254 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 if (mInstaller != null) {
3256 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003257 /* Note: We don't want to unpack the native binaries for
3258 * system applications, unless they have been updated
3259 * (the binaries are already under /system/lib).
3260 * Also, don't unpack libs for apps on the external card
3261 * since they should have their libraries in the ASEC
3262 * container already.
3263 *
3264 * In other words, we're going to unpack the binaries
3265 * only for non-system apps and system app upgrades.
3266 */
Kenny Root831baa22010-10-05 12:29:25 -07003267 if (pkg.applicationInfo.nativeLibraryDir != null) {
Kenny Roote68d58a2010-10-18 16:08:54 -07003268 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3269 final String dataPathString = dataPath.getPath();
3270
Kenny Root831baa22010-10-05 12:29:25 -07003271 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3272 /*
3273 * Upgrading from a previous version of the OS sometimes
3274 * leaves native libraries in the /data/data/<app>/lib
3275 * directory for system apps even when they shouldn't be.
3276 * Recent changes in the JNI library search path
3277 * necessitates we remove those to match previous behavior.
3278 */
Kenny Roote68d58a2010-10-18 16:08:54 -07003279 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Kenny Root831baa22010-10-05 12:29:25 -07003280 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3281 }
Kenny Roote68d58a2010-10-18 16:08:54 -07003282 } else if (nativeLibraryDir.getParent().equals(dataPathString)) {
3283 /*
3284 * If this is an internal application or our
3285 * nativeLibraryPath points to our data directory, unpack
3286 * the libraries. The native library path pointing to the
3287 * data directory for an application in an ASEC container
3288 * can happen for older apps that existed before an OTA to
3289 * Gingerbread.
3290 */
3291 Slog.i(TAG, "Unpacking native libraries for " + path);
3292 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
3293 NativeLibraryHelper.copyNativeBinariesLI(scanFile, nativeLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003294 } else {
Kenny Roote68d58a2010-10-18 16:08:54 -07003295 Slog.i(TAG, "Linking native library dir for " + path);
3296 mInstaller.linkNativeLibraryDirectory(dataPathString,
Kenny Root6a6b0072010-10-07 16:46:10 -07003297 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003300 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003301
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003302 if ((scanMode&SCAN_NO_DEX) == 0) {
3303 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3305 return null;
3306 }
3307 }
3308 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 if (mFactoryTest && pkg.requestedPermissions.contains(
3311 android.Manifest.permission.FACTORY_TEST)) {
3312 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3313 }
3314
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003315 // Request the ActivityManager to kill the process(only for existing packages)
3316 // so that we do not end up in a confused state while the user is still using the older
3317 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003318 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003319 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003320 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003321 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003324 // We don't expect installation to fail beyond this point,
3325 if ((scanMode&SCAN_MONITOR) != 0) {
3326 mAppDirs.put(pkg.mPath, pkg);
3327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003329 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003331 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003332 // Make sure we don't accidentally delete its data.
3333 mSettings.mPackagesToBeCleaned.remove(pkgName);
3334
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003335 // Take care of first install / last update times.
3336 if (currentTime != 0) {
3337 if (pkgSetting.firstInstallTime == 0) {
3338 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3339 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3340 pkgSetting.lastUpdateTime = currentTime;
3341 }
3342 } else if (pkgSetting.firstInstallTime == 0) {
3343 // We need *something*. Take time time stamp of the file.
3344 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3345 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3346 if (scanFileTime != pkgSetting.timeStamp) {
3347 // A package on the system image has changed; consider this
3348 // to be an update.
3349 pkgSetting.lastUpdateTime = scanFileTime;
3350 }
3351 }
3352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 int N = pkg.providers.size();
3354 StringBuilder r = null;
3355 int i;
3356 for (i=0; i<N; i++) {
3357 PackageParser.Provider p = pkg.providers.get(i);
3358 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3359 p.info.processName, pkg.applicationInfo.uid);
3360 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3361 p.info.name), p);
3362 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003363 if (p.info.authority != null) {
3364 String names[] = p.info.authority.split(";");
3365 p.info.authority = null;
3366 for (int j = 0; j < names.length; j++) {
3367 if (j == 1 && p.syncable) {
3368 // We only want the first authority for a provider to possibly be
3369 // syncable, so if we already added this provider using a different
3370 // authority clear the syncable flag. We copy the provider before
3371 // changing it because the mProviders object contains a reference
3372 // to a provider that we don't want to change.
3373 // Only do this for the second authority since the resulting provider
3374 // object can be the same for all future authorities for this provider.
3375 p = new PackageParser.Provider(p);
3376 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003378 if (!mProviders.containsKey(names[j])) {
3379 mProviders.put(names[j], p);
3380 if (p.info.authority == null) {
3381 p.info.authority = names[j];
3382 } else {
3383 p.info.authority = p.info.authority + ";" + names[j];
3384 }
3385 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3386 Log.d(TAG, "Registered content provider: " + names[j] +
3387 ", className = " + p.info.name +
3388 ", isSyncable = " + p.info.isSyncable);
3389 } else {
3390 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003391 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003392 " (in package " + pkg.applicationInfo.packageName +
3393 "): name already used by "
3394 + ((other != null && other.getComponentName() != null)
3395 ? other.getComponentName().getPackageName() : "?"));
3396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 }
3398 }
3399 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3400 if (r == null) {
3401 r = new StringBuilder(256);
3402 } else {
3403 r.append(' ');
3404 }
3405 r.append(p.info.name);
3406 }
3407 }
3408 if (r != null) {
3409 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3410 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 N = pkg.services.size();
3413 r = null;
3414 for (i=0; i<N; i++) {
3415 PackageParser.Service s = pkg.services.get(i);
3416 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3417 s.info.processName, pkg.applicationInfo.uid);
3418 mServices.addService(s);
3419 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3420 if (r == null) {
3421 r = new StringBuilder(256);
3422 } else {
3423 r.append(' ');
3424 }
3425 r.append(s.info.name);
3426 }
3427 }
3428 if (r != null) {
3429 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3430 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 N = pkg.receivers.size();
3433 r = null;
3434 for (i=0; i<N; i++) {
3435 PackageParser.Activity a = pkg.receivers.get(i);
3436 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3437 a.info.processName, pkg.applicationInfo.uid);
3438 mReceivers.addActivity(a, "receiver");
3439 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3440 if (r == null) {
3441 r = new StringBuilder(256);
3442 } else {
3443 r.append(' ');
3444 }
3445 r.append(a.info.name);
3446 }
3447 }
3448 if (r != null) {
3449 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 N = pkg.activities.size();
3453 r = null;
3454 for (i=0; i<N; i++) {
3455 PackageParser.Activity a = pkg.activities.get(i);
3456 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3457 a.info.processName, pkg.applicationInfo.uid);
3458 mActivities.addActivity(a, "activity");
3459 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3460 if (r == null) {
3461 r = new StringBuilder(256);
3462 } else {
3463 r.append(' ');
3464 }
3465 r.append(a.info.name);
3466 }
3467 }
3468 if (r != null) {
3469 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 N = pkg.permissionGroups.size();
3473 r = null;
3474 for (i=0; i<N; i++) {
3475 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3476 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3477 if (cur == null) {
3478 mPermissionGroups.put(pg.info.name, pg);
3479 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3480 if (r == null) {
3481 r = new StringBuilder(256);
3482 } else {
3483 r.append(' ');
3484 }
3485 r.append(pg.info.name);
3486 }
3487 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003488 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 + pg.info.packageName + " ignored: original from "
3490 + cur.info.packageName);
3491 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3492 if (r == null) {
3493 r = new StringBuilder(256);
3494 } else {
3495 r.append(' ');
3496 }
3497 r.append("DUP:");
3498 r.append(pg.info.name);
3499 }
3500 }
3501 }
3502 if (r != null) {
3503 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3504 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 N = pkg.permissions.size();
3507 r = null;
3508 for (i=0; i<N; i++) {
3509 PackageParser.Permission p = pkg.permissions.get(i);
3510 HashMap<String, BasePermission> permissionMap =
3511 p.tree ? mSettings.mPermissionTrees
3512 : mSettings.mPermissions;
3513 p.group = mPermissionGroups.get(p.info.group);
3514 if (p.info.group == null || p.group != null) {
3515 BasePermission bp = permissionMap.get(p.info.name);
3516 if (bp == null) {
3517 bp = new BasePermission(p.info.name, p.info.packageName,
3518 BasePermission.TYPE_NORMAL);
3519 permissionMap.put(p.info.name, bp);
3520 }
3521 if (bp.perm == null) {
3522 if (bp.sourcePackage == null
3523 || bp.sourcePackage.equals(p.info.packageName)) {
3524 BasePermission tree = findPermissionTreeLP(p.info.name);
3525 if (tree == null
3526 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003527 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 bp.perm = p;
3529 bp.uid = pkg.applicationInfo.uid;
3530 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3531 if (r == null) {
3532 r = new StringBuilder(256);
3533 } else {
3534 r.append(' ');
3535 }
3536 r.append(p.info.name);
3537 }
3538 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003539 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 + p.info.packageName + " ignored: base tree "
3541 + tree.name + " is from package "
3542 + tree.sourcePackage);
3543 }
3544 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003545 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 + p.info.packageName + " ignored: original from "
3547 + bp.sourcePackage);
3548 }
3549 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3550 if (r == null) {
3551 r = new StringBuilder(256);
3552 } else {
3553 r.append(' ');
3554 }
3555 r.append("DUP:");
3556 r.append(p.info.name);
3557 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003558 if (bp.perm == p) {
3559 bp.protectionLevel = p.info.protectionLevel;
3560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003562 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 + p.info.packageName + " ignored: no group "
3564 + p.group);
3565 }
3566 }
3567 if (r != null) {
3568 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 N = pkg.instrumentation.size();
3572 r = null;
3573 for (i=0; i<N; i++) {
3574 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3575 a.info.packageName = pkg.applicationInfo.packageName;
3576 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3577 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3578 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003579 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003580 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3582 if (r == null) {
3583 r = new StringBuilder(256);
3584 } else {
3585 r.append(' ');
3586 }
3587 r.append(a.info.name);
3588 }
3589 }
3590 if (r != null) {
3591 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3592 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003593
Dianne Hackborn854060af2009-07-09 18:14:31 -07003594 if (pkg.protectedBroadcasts != null) {
3595 N = pkg.protectedBroadcasts.size();
3596 for (i=0; i<N; i++) {
3597 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3598 }
3599 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 pkgSetting.setTimeStamp(scanFileTime);
3602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 return pkg;
3605 }
3606
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003607 private void killApplication(String pkgName, int uid) {
3608 // Request the ActivityManager to kill the process(only for existing packages)
3609 // so that we do not end up in a confused state while the user is still using the older
3610 // version of the application while the new one gets installed.
3611 IActivityManager am = ActivityManagerNative.getDefault();
3612 if (am != null) {
3613 try {
3614 am.killApplicationWithUid(pkgName, uid);
3615 } catch (RemoteException e) {
3616 }
3617 }
3618 }
3619
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003620 // Return the path of the directory that will contain the native binaries
3621 // of a given installed package. This is relative to the data path.
3622 //
Kenny Root85387d72010-08-26 10:13:11 -07003623 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3624 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3625 if (nativeLibraryDir != null) {
3626 return new File(nativeLibraryDir);
3627 } else {
3628 // Fall back for old packages
3629 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3630 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003631 }
3632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3634 if (chatty && Config.LOGD) Log.d(
3635 TAG, "Removing package " + pkg.applicationInfo.packageName );
3636
3637 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 mPackages.remove(pkg.applicationInfo.packageName);
3641 if (pkg.mPath != null) {
3642 mAppDirs.remove(pkg.mPath);
3643 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 int N = pkg.providers.size();
3646 StringBuilder r = null;
3647 int i;
3648 for (i=0; i<N; i++) {
3649 PackageParser.Provider p = pkg.providers.get(i);
3650 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3651 p.info.name));
3652 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 /* The is another ContentProvider with this authority when
3655 * this app was installed so this authority is null,
3656 * Ignore it as we don't have to unregister the provider.
3657 */
3658 continue;
3659 }
3660 String names[] = p.info.authority.split(";");
3661 for (int j = 0; j < names.length; j++) {
3662 if (mProviders.get(names[j]) == p) {
3663 mProviders.remove(names[j]);
3664 if (chatty && Config.LOGD) Log.d(
3665 TAG, "Unregistered content provider: " + names[j] +
3666 ", className = " + p.info.name +
3667 ", isSyncable = " + p.info.isSyncable);
3668 }
3669 }
3670 if (chatty) {
3671 if (r == null) {
3672 r = new StringBuilder(256);
3673 } else {
3674 r.append(' ');
3675 }
3676 r.append(p.info.name);
3677 }
3678 }
3679 if (r != null) {
3680 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3681 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 N = pkg.services.size();
3684 r = null;
3685 for (i=0; i<N; i++) {
3686 PackageParser.Service s = pkg.services.get(i);
3687 mServices.removeService(s);
3688 if (chatty) {
3689 if (r == null) {
3690 r = new StringBuilder(256);
3691 } else {
3692 r.append(' ');
3693 }
3694 r.append(s.info.name);
3695 }
3696 }
3697 if (r != null) {
3698 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3699 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 N = pkg.receivers.size();
3702 r = null;
3703 for (i=0; i<N; i++) {
3704 PackageParser.Activity a = pkg.receivers.get(i);
3705 mReceivers.removeActivity(a, "receiver");
3706 if (chatty) {
3707 if (r == null) {
3708 r = new StringBuilder(256);
3709 } else {
3710 r.append(' ');
3711 }
3712 r.append(a.info.name);
3713 }
3714 }
3715 if (r != null) {
3716 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 N = pkg.activities.size();
3720 r = null;
3721 for (i=0; i<N; i++) {
3722 PackageParser.Activity a = pkg.activities.get(i);
3723 mActivities.removeActivity(a, "activity");
3724 if (chatty) {
3725 if (r == null) {
3726 r = new StringBuilder(256);
3727 } else {
3728 r.append(' ');
3729 }
3730 r.append(a.info.name);
3731 }
3732 }
3733 if (r != null) {
3734 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 N = pkg.permissions.size();
3738 r = null;
3739 for (i=0; i<N; i++) {
3740 PackageParser.Permission p = pkg.permissions.get(i);
3741 boolean tree = false;
3742 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3743 if (bp == null) {
3744 tree = true;
3745 bp = mSettings.mPermissionTrees.get(p.info.name);
3746 }
3747 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003748 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 if (chatty) {
3750 if (r == null) {
3751 r = new StringBuilder(256);
3752 } else {
3753 r.append(' ');
3754 }
3755 r.append(p.info.name);
3756 }
3757 }
3758 }
3759 if (r != null) {
3760 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3761 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 N = pkg.instrumentation.size();
3764 r = null;
3765 for (i=0; i<N; i++) {
3766 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003767 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003768 if (chatty) {
3769 if (r == null) {
3770 r = new StringBuilder(256);
3771 } else {
3772 r.append(' ');
3773 }
3774 r.append(a.info.name);
3775 }
3776 }
3777 if (r != null) {
3778 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3779 }
3780 }
3781 }
3782
3783 private static final boolean isPackageFilename(String name) {
3784 return name != null && name.endsWith(".apk");
3785 }
3786
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003787 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3788 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3789 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3790 return true;
3791 }
3792 }
3793 return false;
3794 }
3795
3796 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003797 PackageParser.Package pkgInfo, boolean grantPermissions,
3798 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 // Make sure there are no dangling permission trees.
3800 Iterator<BasePermission> it = mSettings.mPermissionTrees
3801 .values().iterator();
3802 while (it.hasNext()) {
3803 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003804 if (bp.packageSetting == null) {
3805 // We may not yet have parsed the package, so just see if
3806 // we still know about its settings.
3807 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3808 }
3809 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003810 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 + " from package " + bp.sourcePackage);
3812 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003813 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3814 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3815 Slog.i(TAG, "Removing old permission tree: " + bp.name
3816 + " from package " + bp.sourcePackage);
3817 grantPermissions = true;
3818 it.remove();
3819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 }
3821 }
3822
3823 // Make sure all dynamic permissions have been assigned to a package,
3824 // and make sure there are no dangling permissions.
3825 it = mSettings.mPermissions.values().iterator();
3826 while (it.hasNext()) {
3827 BasePermission bp = it.next();
3828 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3829 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3830 + bp.name + " pkg=" + bp.sourcePackage
3831 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003832 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 BasePermission tree = findPermissionTreeLP(bp.name);
3834 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003835 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 bp.perm = new PackageParser.Permission(tree.perm.owner,
3837 new PermissionInfo(bp.pendingInfo));
3838 bp.perm.info.packageName = tree.perm.info.packageName;
3839 bp.perm.info.name = bp.name;
3840 bp.uid = tree.uid;
3841 }
3842 }
3843 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003844 if (bp.packageSetting == null) {
3845 // We may not yet have parsed the package, so just see if
3846 // we still know about its settings.
3847 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3848 }
3849 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003850 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 + " from package " + bp.sourcePackage);
3852 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003853 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3854 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3855 Slog.i(TAG, "Removing old permission: " + bp.name
3856 + " from package " + bp.sourcePackage);
3857 grantPermissions = true;
3858 it.remove();
3859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 }
3861 }
3862
3863 // Now update the permissions for all packages, in particular
3864 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003865 if (grantPermissions) {
3866 for (PackageParser.Package pkg : mPackages.values()) {
3867 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003868 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003869 }
3870 }
3871 }
3872
3873 if (pkgInfo != null) {
3874 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 }
3876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3879 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3880 if (ps == null) {
3881 return;
3882 }
3883 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003884 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 if (replace) {
3887 ps.permissionsFixed = false;
3888 if (gp == ps) {
3889 gp.grantedPermissions.clear();
3890 gp.gids = mGlobalGids;
3891 }
3892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 if (gp.gids == null) {
3895 gp.gids = mGlobalGids;
3896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 final int N = pkg.requestedPermissions.size();
3899 for (int i=0; i<N; i++) {
3900 String name = pkg.requestedPermissions.get(i);
3901 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 if (false) {
3903 if (gp != ps) {
3904 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003905 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 }
3907 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003908 if (bp != null && bp.packageSetting != null) {
3909 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003911 boolean allowedSig = false;
3912 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3913 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003915 } else if (bp.packageSetting == null) {
3916 // This permission is invalid; skip it.
3917 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003918 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3919 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003920 allowed = (checkSignaturesLP(
3921 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003923 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003925 if (!allowed && bp.protectionLevel
3926 == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003927 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 // For updated system applications, the signatureOrSystem permission
3929 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003930 if (isUpdatedSystemApp(pkg)) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003931 PackageSetting sysPs = mSettings.getDisabledSystemPkg(
3932 pkg.packageName);
3933 final GrantedPermissions origGp = sysPs.sharedUser != null
3934 ? sysPs.sharedUser : sysPs;
3935 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 allowed = true;
3937 } else {
3938 allowed = false;
3939 }
3940 } else {
3941 allowed = true;
3942 }
3943 }
3944 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003945 if (allowed) {
3946 allowedSig = true;
3947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 } else {
3949 allowed = false;
3950 }
3951 if (false) {
3952 if (gp != ps) {
3953 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3954 }
3955 }
3956 if (allowed) {
3957 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3958 && ps.permissionsFixed) {
3959 // If this is an existing, non-system package, then
3960 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003961 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003963 // Except... if this is a permission that was added
3964 // to the platform (note: need to only do this when
3965 // updating the platform).
3966 final int NP = PackageParser.NEW_PERMISSIONS.length;
3967 for (int ip=0; ip<NP; ip++) {
3968 final PackageParser.NewPermissionInfo npi
3969 = PackageParser.NEW_PERMISSIONS[ip];
3970 if (npi.name.equals(perm)
3971 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3972 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003973 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003974 + pkg.packageName);
3975 break;
3976 }
3977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 }
3979 }
3980 if (allowed) {
3981 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003982 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 gp.grantedPermissions.add(perm);
3984 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003985 } else if (!ps.haveGids) {
3986 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 }
3988 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003989 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 + " to package " + pkg.packageName
3991 + " because it was previously installed without");
3992 }
3993 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003994 if (gp.grantedPermissions.remove(perm)) {
3995 changedPermission = true;
3996 gp.gids = removeInts(gp.gids, bp.gids);
3997 Slog.i(TAG, "Un-granting permission " + perm
3998 + " from package " + pkg.packageName
3999 + " (protectionLevel=" + bp.protectionLevel
4000 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4001 + ")");
4002 } else {
4003 Slog.w(TAG, "Not granting permission " + perm
4004 + " to package " + pkg.packageName
4005 + " (protectionLevel=" + bp.protectionLevel
4006 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4007 + ")");
4008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 }
4010 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004011 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 + " in package " + pkg.packageName);
4013 }
4014 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004015
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004016 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004017 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4018 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 // This is the first that we have heard about this package, so the
4020 // permissions we have now selected are fixed until explicitly
4021 // changed.
4022 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004024 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 private final class ActivityIntentResolver
4028 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004029 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004031 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 }
4033
Mihai Preda074edef2009-05-18 17:13:31 +02004034 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004036 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4038 }
4039
Mihai Predaeae850c2009-05-13 10:13:48 +02004040 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4041 ArrayList<PackageParser.Activity> packageActivities) {
4042 if (packageActivities == null) {
4043 return null;
4044 }
4045 mFlags = flags;
4046 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4047 int N = packageActivities.size();
4048 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4049 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004050
4051 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004052 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004053 intentFilters = packageActivities.get(i).intents;
4054 if (intentFilters != null && intentFilters.size() > 0) {
4055 listCut.add(intentFilters);
4056 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004057 }
4058 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4059 }
4060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 public final void addActivity(PackageParser.Activity a, String type) {
Kenny Root1c6e7642011-01-10 13:48:15 -08004062 final boolean systemApp = isSystemApp(a.info.applicationInfo);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004063 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 if (SHOW_INFO || Config.LOGV) Log.v(
4065 TAG, " " + type + " " +
4066 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4067 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4068 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004069 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root1c6e7642011-01-10 13:48:15 -08004071 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4072 intent.setPriority(0);
4073 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
4074 + a.className + " with priority > 0, forcing to 0");
4075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004076 if (SHOW_INFO || Config.LOGV) {
4077 Log.v(TAG, " IntentFilter:");
4078 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4079 }
4080 if (!intent.debugCheck()) {
4081 Log.w(TAG, "==> For Activity " + a.info.name);
4082 }
4083 addFilter(intent);
4084 }
4085 }
4086
4087 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004088 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 if (SHOW_INFO || Config.LOGV) Log.v(
4090 TAG, " " + type + " " +
4091 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4092 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4093 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004094 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4096 if (SHOW_INFO || Config.LOGV) {
4097 Log.v(TAG, " IntentFilter:");
4098 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4099 }
4100 removeFilter(intent);
4101 }
4102 }
4103
4104 @Override
4105 protected boolean allowFilterResult(
4106 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4107 ActivityInfo filterAi = filter.activity.info;
4108 for (int i=dest.size()-1; i>=0; i--) {
4109 ActivityInfo destAi = dest.get(i).activityInfo;
4110 if (destAi.name == filterAi.name
4111 && destAi.packageName == filterAi.packageName) {
4112 return false;
4113 }
4114 }
4115 return true;
4116 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004119 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4120 return info.activity.owner.packageName;
4121 }
4122
4123 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4125 int match) {
4126 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4127 return null;
4128 }
4129 final PackageParser.Activity activity = info.activity;
4130 if (mSafeMode && (activity.info.applicationInfo.flags
4131 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4132 return null;
4133 }
4134 final ResolveInfo res = new ResolveInfo();
4135 res.activityInfo = PackageParser.generateActivityInfo(activity,
4136 mFlags);
4137 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4138 res.filter = info;
4139 }
4140 res.priority = info.getPriority();
4141 res.preferredOrder = activity.owner.mPreferredOrder;
4142 //System.out.println("Result: " + res.activityInfo.className +
4143 // " = " + res.priority);
4144 res.match = match;
4145 res.isDefault = info.hasDefault;
4146 res.labelRes = info.labelRes;
4147 res.nonLocalizedLabel = info.nonLocalizedLabel;
4148 res.icon = info.icon;
4149 return res;
4150 }
4151
4152 @Override
4153 protected void sortResults(List<ResolveInfo> results) {
4154 Collections.sort(results, mResolvePrioritySorter);
4155 }
4156
4157 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004158 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004160 out.print(prefix); out.print(
4161 Integer.toHexString(System.identityHashCode(filter.activity)));
4162 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004163 out.print(filter.activity.getComponentShortName());
4164 out.print(" filter ");
4165 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 }
4167
4168// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4169// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4170// final List<ResolveInfo> retList = Lists.newArrayList();
4171// while (i.hasNext()) {
4172// final ResolveInfo resolveInfo = i.next();
4173// if (isEnabledLP(resolveInfo.activityInfo)) {
4174// retList.add(resolveInfo);
4175// }
4176// }
4177// return retList;
4178// }
4179
4180 // Keys are String (activity class name), values are Activity.
4181 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4182 = new HashMap<ComponentName, PackageParser.Activity>();
4183 private int mFlags;
4184 }
4185
4186 private final class ServiceIntentResolver
4187 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004188 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004189 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004190 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 }
4192
Mihai Preda074edef2009-05-18 17:13:31 +02004193 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004195 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4197 }
4198
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004199 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4200 ArrayList<PackageParser.Service> packageServices) {
4201 if (packageServices == null) {
4202 return null;
4203 }
4204 mFlags = flags;
4205 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4206 int N = packageServices.size();
4207 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4208 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4209
4210 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4211 for (int i = 0; i < N; ++i) {
4212 intentFilters = packageServices.get(i).intents;
4213 if (intentFilters != null && intentFilters.size() > 0) {
4214 listCut.add(intentFilters);
4215 }
4216 }
4217 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4218 }
4219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004221 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 if (SHOW_INFO || Config.LOGV) Log.v(
4223 TAG, " " + (s.info.nonLocalizedLabel != null
4224 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4225 if (SHOW_INFO || Config.LOGV) Log.v(
4226 TAG, " Class=" + s.info.name);
4227 int NI = s.intents.size();
4228 int j;
4229 for (j=0; j<NI; j++) {
4230 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4231 if (SHOW_INFO || Config.LOGV) {
4232 Log.v(TAG, " IntentFilter:");
4233 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4234 }
4235 if (!intent.debugCheck()) {
4236 Log.w(TAG, "==> For Service " + s.info.name);
4237 }
4238 addFilter(intent);
4239 }
4240 }
4241
4242 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004243 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 if (SHOW_INFO || Config.LOGV) Log.v(
4245 TAG, " " + (s.info.nonLocalizedLabel != null
4246 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4247 if (SHOW_INFO || Config.LOGV) Log.v(
4248 TAG, " Class=" + s.info.name);
4249 int NI = s.intents.size();
4250 int j;
4251 for (j=0; j<NI; j++) {
4252 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4253 if (SHOW_INFO || Config.LOGV) {
4254 Log.v(TAG, " IntentFilter:");
4255 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4256 }
4257 removeFilter(intent);
4258 }
4259 }
4260
4261 @Override
4262 protected boolean allowFilterResult(
4263 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4264 ServiceInfo filterSi = filter.service.info;
4265 for (int i=dest.size()-1; i>=0; i--) {
4266 ServiceInfo destAi = dest.get(i).serviceInfo;
4267 if (destAi.name == filterSi.name
4268 && destAi.packageName == filterSi.packageName) {
4269 return false;
4270 }
4271 }
4272 return true;
4273 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004275 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004276 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4277 return info.service.owner.packageName;
4278 }
4279
4280 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4282 int match) {
4283 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4284 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4285 return null;
4286 }
4287 final PackageParser.Service service = info.service;
4288 if (mSafeMode && (service.info.applicationInfo.flags
4289 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4290 return null;
4291 }
4292 final ResolveInfo res = new ResolveInfo();
4293 res.serviceInfo = PackageParser.generateServiceInfo(service,
4294 mFlags);
4295 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4296 res.filter = filter;
4297 }
4298 res.priority = info.getPriority();
4299 res.preferredOrder = service.owner.mPreferredOrder;
4300 //System.out.println("Result: " + res.activityInfo.className +
4301 // " = " + res.priority);
4302 res.match = match;
4303 res.isDefault = info.hasDefault;
4304 res.labelRes = info.labelRes;
4305 res.nonLocalizedLabel = info.nonLocalizedLabel;
4306 res.icon = info.icon;
4307 return res;
4308 }
4309
4310 @Override
4311 protected void sortResults(List<ResolveInfo> results) {
4312 Collections.sort(results, mResolvePrioritySorter);
4313 }
4314
4315 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004316 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004318 out.print(prefix); out.print(
4319 Integer.toHexString(System.identityHashCode(filter.service)));
4320 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004321 out.print(filter.service.getComponentShortName());
4322 out.print(" filter ");
4323 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004324 }
4325
4326// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4327// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4328// final List<ResolveInfo> retList = Lists.newArrayList();
4329// while (i.hasNext()) {
4330// final ResolveInfo resolveInfo = (ResolveInfo) i;
4331// if (isEnabledLP(resolveInfo.serviceInfo)) {
4332// retList.add(resolveInfo);
4333// }
4334// }
4335// return retList;
4336// }
4337
4338 // Keys are String (activity class name), values are Activity.
4339 private final HashMap<ComponentName, PackageParser.Service> mServices
4340 = new HashMap<ComponentName, PackageParser.Service>();
4341 private int mFlags;
4342 };
4343
4344 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4345 new Comparator<ResolveInfo>() {
4346 public int compare(ResolveInfo r1, ResolveInfo r2) {
4347 int v1 = r1.priority;
4348 int v2 = r2.priority;
4349 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4350 if (v1 != v2) {
4351 return (v1 > v2) ? -1 : 1;
4352 }
4353 v1 = r1.preferredOrder;
4354 v2 = r2.preferredOrder;
4355 if (v1 != v2) {
4356 return (v1 > v2) ? -1 : 1;
4357 }
4358 if (r1.isDefault != r2.isDefault) {
4359 return r1.isDefault ? -1 : 1;
4360 }
4361 v1 = r1.match;
4362 v2 = r2.match;
4363 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4364 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4365 }
4366 };
4367
4368 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4369 new Comparator<ProviderInfo>() {
4370 public int compare(ProviderInfo p1, ProviderInfo p2) {
4371 final int v1 = p1.initOrder;
4372 final int v2 = p2.initOrder;
4373 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4374 }
4375 };
4376
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004377 private static final void sendPackageBroadcast(String action, String pkg,
4378 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 IActivityManager am = ActivityManagerNative.getDefault();
4380 if (am != null) {
4381 try {
4382 final Intent intent = new Intent(action,
4383 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4384 if (extras != null) {
4385 intent.putExtras(extras);
4386 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004387 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004388 am.broadcastIntent(null, intent, null, finishedReceiver,
4389 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 } catch (RemoteException ex) {
4391 }
4392 }
4393 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004394
4395 public String nextPackageToClean(String lastPackage) {
4396 synchronized (mPackages) {
4397 if (!mMediaMounted) {
4398 // If the external storage is no longer mounted at this point,
4399 // the caller may not have been able to delete all of this
4400 // packages files and can not delete any more. Bail.
4401 return null;
4402 }
4403 if (lastPackage != null) {
4404 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4405 }
4406 return mSettings.mPackagesToBeCleaned.size() > 0
4407 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4408 }
4409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004411 void schedulePackageCleaning(String packageName) {
4412 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4413 }
4414
4415 void startCleaningPackages() {
4416 synchronized (mPackages) {
4417 if (!mMediaMounted) {
4418 return;
4419 }
4420 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4421 return;
4422 }
4423 }
4424 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4425 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4426 IActivityManager am = ActivityManagerNative.getDefault();
4427 if (am != null) {
4428 try {
4429 am.startService(null, intent, null);
4430 } catch (RemoteException e) {
4431 }
4432 }
4433 }
4434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004435 private final class AppDirObserver extends FileObserver {
4436 public AppDirObserver(String path, int mask, boolean isrom) {
4437 super(path, mask);
4438 mRootDir = path;
4439 mIsRom = isrom;
4440 }
4441
4442 public void onEvent(int event, String path) {
4443 String removedPackage = null;
4444 int removedUid = -1;
4445 String addedPackage = null;
4446 int addedUid = -1;
4447
4448 synchronized (mInstallLock) {
4449 String fullPathStr = null;
4450 File fullPath = null;
4451 if (path != null) {
4452 fullPath = new File(mRootDir, path);
4453 fullPathStr = fullPath.getPath();
4454 }
4455
4456 if (Config.LOGV) Log.v(
4457 TAG, "File " + fullPathStr + " changed: "
4458 + Integer.toHexString(event));
4459
4460 if (!isPackageFilename(path)) {
4461 if (Config.LOGV) Log.v(
4462 TAG, "Ignoring change of non-package file: " + fullPathStr);
4463 return;
4464 }
4465
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004466 // Ignore packages that are being installed or
4467 // have just been installed.
4468 if (ignoreCodePath(fullPathStr)) {
4469 return;
4470 }
4471 PackageParser.Package p = null;
4472 synchronized (mPackages) {
4473 p = mAppDirs.get(fullPathStr);
4474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004476 if (p != null) {
4477 removePackageLI(p, true);
4478 removedPackage = p.applicationInfo.packageName;
4479 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 }
4481 }
4482
4483 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004485 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004486 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4487 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 PackageParser.PARSE_CHATTY |
4489 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004490 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4491 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 if (p != null) {
4493 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004494 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004495 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 }
4497 addedPackage = p.applicationInfo.packageName;
4498 addedUid = p.applicationInfo.uid;
4499 }
4500 }
4501 }
4502
4503 synchronized (mPackages) {
4504 mSettings.writeLP();
4505 }
4506 }
4507
4508 if (removedPackage != null) {
4509 Bundle extras = new Bundle(1);
4510 extras.putInt(Intent.EXTRA_UID, removedUid);
4511 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004512 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4513 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 }
4515 if (addedPackage != null) {
4516 Bundle extras = new Bundle(1);
4517 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004518 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4519 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 }
4521 }
4522
4523 private final String mRootDir;
4524 private final boolean mIsRom;
4525 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 /* Called when a downloaded package installation has been confirmed by the user */
4528 public void installPackage(
4529 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004530 installPackage(packageURI, observer, flags, null);
4531 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004532
Jacek Surazski65e13172009-04-28 15:26:38 +02004533 /* Called when a downloaded package installation has been confirmed by the user */
4534 public void installPackage(
4535 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4536 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 mContext.enforceCallingOrSelfPermission(
4538 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004539
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004540 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004541 msg.obj = new InstallParams(packageURI, observer, flags,
4542 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004543 mHandler.sendMessage(msg);
4544 }
4545
Christopher Tate1bb69062010-02-19 17:02:12 -08004546 public void finishPackageInstall(int token) {
4547 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4548 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4549 mHandler.sendMessage(msg);
4550 }
4551
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004552 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 // Queue up an async operation since the package installation may take a little while.
4554 mHandler.post(new Runnable() {
4555 public void run() {
4556 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004557 // Result object to be returned
4558 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004559 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004560 res.uid = -1;
4561 res.pkg = null;
4562 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004563 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004564 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004565 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004566 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004567 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004568 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004569 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004570
4571 // A restore should be performed at this point if (a) the install
4572 // succeeded, (b) the operation is not an update, and (c) the new
4573 // package has a backupAgent defined.
4574 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004575 boolean doRestore = (!update
4576 && res.pkg != null
4577 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004578
4579 // Set up the post-install work request bookkeeping. This will be used
4580 // and cleaned up by the post-install event handling regardless of whether
4581 // there's a restore pass performed. Token values are >= 1.
4582 int token;
4583 if (mNextInstallToken < 0) mNextInstallToken = 1;
4584 token = mNextInstallToken++;
4585
4586 PostInstallData data = new PostInstallData(args, res);
4587 mRunningInstalls.put(token, data);
4588 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4589
4590 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4591 // Pass responsibility to the Backup Manager. It will perform a
4592 // restore if appropriate, then pass responsibility back to the
4593 // Package Manager to run the post-install observer callbacks
4594 // and broadcasts.
4595 IBackupManager bm = IBackupManager.Stub.asInterface(
4596 ServiceManager.getService(Context.BACKUP_SERVICE));
4597 if (bm != null) {
4598 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4599 + " to BM for possible restore");
4600 try {
4601 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4602 } catch (RemoteException e) {
4603 // can't happen; the backup manager is local
4604 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004605 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004606 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004607 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004608 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004609 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004610 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004613
4614 if (!doRestore) {
4615 // No restore possible, or the Backup Manager was mysteriously not
4616 // available -- just fire the post-install work request directly.
4617 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4618 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4619 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 }
4622 });
4623 }
4624
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004625 abstract class HandlerParams {
4626 final static int MAX_RETRIES = 4;
4627 int retry = 0;
4628 final void startCopy() {
4629 try {
4630 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4631 retry++;
4632 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004633 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004634 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4635 handleServiceError();
4636 return;
4637 } else {
4638 handleStartCopy();
4639 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4640 mHandler.sendEmptyMessage(MCS_UNBIND);
4641 }
4642 } catch (RemoteException e) {
4643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4644 mHandler.sendEmptyMessage(MCS_RECONNECT);
4645 }
4646 handleReturnCode();
4647 }
4648
4649 final void serviceError() {
4650 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4651 handleServiceError();
4652 handleReturnCode();
4653 }
4654 abstract void handleStartCopy() throws RemoteException;
4655 abstract void handleServiceError();
4656 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004657 }
4658
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004659 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004660 final IPackageInstallObserver observer;
4661 int flags;
4662 final Uri packageURI;
4663 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004664 private InstallArgs mArgs;
4665 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004666 InstallParams(Uri packageURI,
4667 IPackageInstallObserver observer, int flags,
4668 String installerPackageName) {
4669 this.packageURI = packageURI;
4670 this.flags = flags;
4671 this.observer = observer;
4672 this.installerPackageName = installerPackageName;
4673 }
4674
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004675 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4676 String packageName = pkgLite.packageName;
4677 int installLocation = pkgLite.installLocation;
4678 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4679 synchronized (mPackages) {
4680 PackageParser.Package pkg = mPackages.get(packageName);
4681 if (pkg != null) {
4682 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4683 // Check for updated system application.
4684 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4685 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004686 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004687 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4688 }
4689 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4690 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004691 if (onSd) {
4692 // Install flag overrides everything.
4693 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4694 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004695 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004696 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4697 // Application explicitly specified internal.
4698 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4699 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4700 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004701 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004702 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004703 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004704 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4705 }
4706 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004707 }
4708 }
4709 } else {
4710 // Invalid install. Return error code
4711 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4712 }
4713 }
4714 }
4715 // All the special cases have been taken care of.
4716 // Return result based on recommended install location.
4717 if (onSd) {
4718 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4719 }
4720 return pkgLite.recommendedInstallLocation;
4721 }
4722
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004723 /*
4724 * Invoke remote method to get package information and install
4725 * location values. Override install location based on default
4726 * policy if needed and then create install arguments based
4727 * on the install location.
4728 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004729 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004730 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004731 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4732 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004733 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4734 if (onInt && onSd) {
4735 // Check if both bits are set.
4736 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4737 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4738 } else if (fwdLocked && onSd) {
4739 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004740 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004741 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004742 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004743 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07004744 final PackageInfoLite pkgLite;
4745 try {
4746 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4747 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4748 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
4749 } finally {
4750 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4751 }
4752
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004753 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004754 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4755 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4756 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4757 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4758 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004759 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4760 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4761 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004762 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4763 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004764 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004765 // Override with defaults if needed.
4766 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004767 if (!onSd && !onInt) {
4768 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004769 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4770 // Set the flag to install on external media.
4771 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004772 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004773 } else {
4774 // Make sure the flag for installing on external
4775 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004776 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004777 flags &= ~PackageManager.INSTALL_EXTERNAL;
4778 }
4779 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004780 }
4781 }
4782 // Create the file args now.
4783 mArgs = createInstallArgs(this);
4784 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4785 // Create copy only if we are not in an erroneous state.
4786 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004787 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004788 }
4789 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004790 }
4791
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004792 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004793 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004794 // If mArgs is null, then MCS couldn't be reached. When it
4795 // reconnects, it will try again to install. At that point, this
4796 // will succeed.
4797 if (mArgs != null) {
4798 processPendingInstall(mArgs, mRet);
4799 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004800 }
4801
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004802 @Override
4803 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004804 mArgs = createInstallArgs(this);
4805 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004806 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004807 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004808
4809 /*
4810 * Utility class used in movePackage api.
4811 * srcArgs and targetArgs are not set for invalid flags and make
4812 * sure to do null checks when invoking methods on them.
4813 * We probably want to return ErrorPrams for both failed installs
4814 * and moves.
4815 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004816 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004817 final IPackageMoveObserver observer;
4818 final int flags;
4819 final String packageName;
4820 final InstallArgs srcArgs;
4821 final InstallArgs targetArgs;
4822 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004823
4824 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4825 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004826 this.srcArgs = srcArgs;
4827 this.observer = observer;
4828 this.flags = flags;
4829 this.packageName = packageName;
4830 if (srcArgs != null) {
4831 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004832 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004833 } else {
4834 targetArgs = null;
4835 }
4836 }
4837
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004838 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004839 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4840 // Check for storage space on target medium
4841 if (!targetArgs.checkFreeStorage(mContainerService)) {
4842 Log.w(TAG, "Insufficient storage to install");
4843 return;
4844 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004845 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004846 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004847 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004848 if (DEBUG_SD_INSTALL) {
4849 StringBuilder builder = new StringBuilder();
4850 if (srcArgs != null) {
4851 builder.append("src: ");
4852 builder.append(srcArgs.getCodePath());
4853 }
4854 if (targetArgs != null) {
4855 builder.append(" target : ");
4856 builder.append(targetArgs.getCodePath());
4857 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004858 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004859 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004860 }
4861
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004862 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004863 void handleReturnCode() {
4864 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004865 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4866 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4867 currentStatus = PackageManager.MOVE_SUCCEEDED;
4868 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4869 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4870 }
4871 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004872 }
4873
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004874 @Override
4875 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004876 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004877 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004878 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004879
4880 private InstallArgs createInstallArgs(InstallParams params) {
4881 if (installOnSd(params.flags)) {
4882 return new SdInstallArgs(params);
4883 } else {
4884 return new FileInstallArgs(params);
4885 }
4886 }
4887
Kenny Root85387d72010-08-26 10:13:11 -07004888 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4889 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004890 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004891 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004892 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004893 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004894 }
4895 }
4896
Kenny Root85387d72010-08-26 10:13:11 -07004897 // Used by package mover
4898 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004899 if (installOnSd(flags)) {
4900 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4901 return new SdInstallArgs(packageURI, cid);
4902 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004903 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004904 }
4905 }
4906
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004907 static abstract class InstallArgs {
4908 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004909 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004910 final int flags;
4911 final Uri packageURI;
4912 final String installerPackageName;
4913
4914 InstallArgs(Uri packageURI,
4915 IPackageInstallObserver observer, int flags,
4916 String installerPackageName) {
4917 this.packageURI = packageURI;
4918 this.flags = flags;
4919 this.observer = observer;
4920 this.installerPackageName = installerPackageName;
4921 }
4922
4923 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004924 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004925 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004926 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004927 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004928 abstract String getCodePath();
4929 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004930 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004931 // Need installer lock especially for dex file removal.
4932 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004933 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004934 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004935 }
4936
4937 class FileInstallArgs extends InstallArgs {
4938 File installDir;
4939 String codeFileName;
4940 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004941 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004942 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004943
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004944 FileInstallArgs(InstallParams params) {
4945 super(params.packageURI, params.observer,
4946 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004947 }
4948
Kenny Root85387d72010-08-26 10:13:11 -07004949 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004950 super(null, null, 0, null);
4951 File codeFile = new File(fullCodePath);
4952 installDir = codeFile.getParentFile();
4953 codeFileName = fullCodePath;
4954 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004955 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004956 }
4957
Kenny Root85387d72010-08-26 10:13:11 -07004958 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004959 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004960 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 String apkName = getNextCodePath(null, pkgName, ".apk");
4962 codeFileName = new File(installDir, apkName + ".apk").getPath();
4963 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004964 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004965 }
4966
Kenny Root11128572010-10-11 10:51:32 -07004967 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4968 try {
4969 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4970 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4971 return imcs.checkFreeStorage(false, packageURI);
4972 } finally {
4973 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4974 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004975 }
4976
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004977 String getCodePath() {
4978 return codeFileName;
4979 }
4980
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004981 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004982 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004983 codeFileName = createTempPackageFile(installDir).getPath();
4984 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004985 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004986 }
4987
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004988 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004989 if (temp) {
4990 // Generate temp file name
4991 createCopyFile();
4992 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004993 // Get a ParcelFileDescriptor to write to the output file
4994 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004995 if (!created) {
4996 try {
4997 codeFile.createNewFile();
4998 // Set permissions
4999 if (!setPermissions()) {
5000 // Failed setting permissions.
5001 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5002 }
5003 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005004 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005005 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5006 }
5007 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005008 ParcelFileDescriptor out = null;
5009 try {
Kenny Root85387d72010-08-26 10:13:11 -07005010 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005011 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005012 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005013 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5014 }
5015 // Copy the resource now
5016 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5017 try {
Kenny Root11128572010-10-11 10:51:32 -07005018 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5019 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005020 if (imcs.copyResource(packageURI, out)) {
5021 ret = PackageManager.INSTALL_SUCCEEDED;
5022 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005023 } finally {
5024 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005025 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005026 }
Kenny Root85387d72010-08-26 10:13:11 -07005027
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005028 return ret;
5029 }
5030
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005031 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005032 if (status != PackageManager.INSTALL_SUCCEEDED) {
5033 cleanUp();
5034 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005035 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005036 }
5037
5038 boolean doRename(int status, final String pkgName, String oldCodePath) {
5039 if (status != PackageManager.INSTALL_SUCCEEDED) {
5040 cleanUp();
5041 return false;
5042 } else {
5043 // Rename based on packageName
5044 File codeFile = new File(getCodePath());
5045 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5046 File desFile = new File(installDir, apkName + ".apk");
5047 if (!codeFile.renameTo(desFile)) {
5048 return false;
5049 }
5050 // Reset paths since the file has been renamed.
5051 codeFileName = desFile.getPath();
5052 resourceFileName = getResourcePathFromCodePath();
5053 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005054 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005055 // Failed setting permissions.
5056 return false;
5057 }
5058 return true;
5059 }
5060 }
5061
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005062 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 if (status != PackageManager.INSTALL_SUCCEEDED) {
5064 cleanUp();
5065 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005066 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005067 }
5068
5069 String getResourcePath() {
5070 return resourceFileName;
5071 }
5072
5073 String getResourcePathFromCodePath() {
5074 String codePath = getCodePath();
5075 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5076 String apkNameOnly = getApkName(codePath);
5077 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5078 } else {
5079 return codePath;
5080 }
5081 }
5082
Kenny Root85387d72010-08-26 10:13:11 -07005083 @Override
5084 String getNativeLibraryPath() {
5085 return libraryPath;
5086 }
5087
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005088 private boolean cleanUp() {
5089 boolean ret = true;
5090 String sourceDir = getCodePath();
5091 String publicSourceDir = getResourcePath();
5092 if (sourceDir != null) {
5093 File sourceFile = new File(sourceDir);
5094 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005095 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005096 ret = false;
5097 }
5098 // Delete application's code and resources
5099 sourceFile.delete();
5100 }
5101 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5102 final File publicSourceFile = new File(publicSourceDir);
5103 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005104 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005105 }
5106 if (publicSourceFile.exists()) {
5107 publicSourceFile.delete();
5108 }
5109 }
5110 return ret;
5111 }
5112
5113 void cleanUpResourcesLI() {
5114 String sourceDir = getCodePath();
5115 if (cleanUp() && mInstaller != null) {
5116 int retCode = mInstaller.rmdex(sourceDir);
5117 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005118 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005119 + " at location "
5120 + sourceDir + ", retcode=" + retCode);
5121 // we don't consider this to be a failure of the core package deletion
5122 }
5123 }
5124 }
5125
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005126 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005127 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005128 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005129 final int filePermissions =
5130 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5131 |FileUtils.S_IROTH;
5132 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5133 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005134 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005135 getCodePath()
5136 + ". The return code was: " + retCode);
5137 // TODO Define new internal error
5138 return false;
5139 }
5140 return true;
5141 }
5142 return true;
5143 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005144
5145 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005146 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005147 cleanUpResourcesLI();
5148 return true;
5149 }
Kenny Root85387d72010-08-26 10:13:11 -07005150
5151 private boolean isFwdLocked() {
5152 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5153 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005154 }
5155
5156 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005157 static final String RES_FILE_NAME = "pkg.apk";
5158
Kenny Root85387d72010-08-26 10:13:11 -07005159 String cid;
5160 String packagePath;
5161 String libraryPath;
5162
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005163 SdInstallArgs(InstallParams params) {
5164 super(params.packageURI, params.observer,
5165 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005166 }
5167
Kenny Root85387d72010-08-26 10:13:11 -07005168 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005169 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005170 // Extract cid from fullCodePath
5171 int eidx = fullCodePath.lastIndexOf("/");
5172 String subStr1 = fullCodePath.substring(0, eidx);
5173 int sidx = subStr1.lastIndexOf("/");
5174 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005175 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005176 }
5177
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005178 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005179 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5180 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005181 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005182 }
5183
5184 SdInstallArgs(Uri packageURI, String cid) {
5185 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005186 this.cid = cid;
5187 }
5188
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005189 void createCopyFile() {
5190 cid = getTempContainerId();
5191 }
5192
Kenny Root11128572010-10-11 10:51:32 -07005193 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5194 try {
5195 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5196 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5197 return imcs.checkFreeStorage(true, packageURI);
5198 } finally {
5199 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5200 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005201 }
5202
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005203 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005204 if (temp) {
5205 createCopyFile();
5206 }
Kenny Root11128572010-10-11 10:51:32 -07005207
5208 final String newCachePath;
5209 try {
5210 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5211 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5212 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5213 getEncryptKey(), RES_FILE_NAME);
5214 } finally {
5215 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5216 }
5217
Kenny Root85387d72010-08-26 10:13:11 -07005218 if (newCachePath != null) {
5219 setCachePath(newCachePath);
5220 return PackageManager.INSTALL_SUCCEEDED;
5221 } else {
5222 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5223 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005224 }
5225
5226 @Override
5227 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005228 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005229 }
5230
5231 @Override
5232 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005233 return packagePath;
5234 }
5235
5236 @Override
5237 String getNativeLibraryPath() {
5238 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005239 }
5240
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005241 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005242 if (status != PackageManager.INSTALL_SUCCEEDED) {
5243 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005244 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005245 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005246 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005247 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005248 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5249 Process.SYSTEM_UID);
5250 if (newCachePath != null) {
5251 setCachePath(newCachePath);
5252 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005253 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5254 }
5255 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005256 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005257 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005258 }
5259
5260 boolean doRename(int status, final String pkgName,
5261 String oldCodePath) {
5262 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005263 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005264 if (PackageHelper.isContainerMounted(cid)) {
5265 // Unmount the container
5266 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005267 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005268 return false;
5269 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005270 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005271 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005272 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5273 " which might be stale. Will try to clean up.");
5274 // Clean up the stale container and proceed to recreate.
5275 if (!PackageHelper.destroySdDir(newCacheId)) {
5276 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5277 return false;
5278 }
5279 // Successfully cleaned up stale container. Try to rename again.
5280 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5281 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5282 + " inspite of cleaning it up.");
5283 return false;
5284 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005285 }
5286 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005287 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005288 newCachePath = PackageHelper.mountSdDir(newCacheId,
5289 getEncryptKey(), Process.SYSTEM_UID);
5290 } else {
5291 newCachePath = PackageHelper.getSdDir(newCacheId);
5292 }
5293 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005294 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005295 return false;
5296 }
5297 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005298 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005299 " at new path: " + newCachePath);
5300 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005301 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005302 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005303 }
5304
Kenny Root85387d72010-08-26 10:13:11 -07005305 private void setCachePath(String newCachePath) {
5306 File cachePath = new File(newCachePath);
5307 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5308 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5309 }
5310
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005311 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005312 if (status != PackageManager.INSTALL_SUCCEEDED) {
5313 cleanUp();
5314 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005315 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005316 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005317 PackageHelper.mountSdDir(cid,
5318 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005319 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005320 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005321 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005322 }
5323
5324 private void cleanUp() {
5325 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005326 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005327 }
5328
5329 void cleanUpResourcesLI() {
5330 String sourceFile = getCodePath();
5331 // Remove dex file
5332 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005333 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005334 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005335 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005336 + " at location "
5337 + sourceFile.toString() + ", retcode=" + retCode);
5338 // we don't consider this to be a failure of the core package deletion
5339 }
5340 }
5341 cleanUp();
5342 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005343
5344 boolean matchContainer(String app) {
5345 if (cid.startsWith(app)) {
5346 return true;
5347 }
5348 return false;
5349 }
5350
5351 String getPackageName() {
5352 int idx = cid.lastIndexOf("-");
5353 if (idx == -1) {
5354 return cid;
5355 }
5356 return cid.substring(0, idx);
5357 }
5358
5359 boolean doPostDeleteLI(boolean delete) {
5360 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005361 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005362 if (mounted) {
5363 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005364 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005365 }
5366 if (ret && delete) {
5367 cleanUpResourcesLI();
5368 }
5369 return ret;
5370 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 };
5372
5373 // Utility method used to create code paths based on package name and available index.
5374 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5375 String idxStr = "";
5376 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005377 // Fall back to default value of idx=1 if prefix is not
5378 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005379 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005380 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005381 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005382 if (subStr.endsWith(suffix)) {
5383 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005384 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005385 // If oldCodePath already contains prefix find out the
5386 // ending index to either increment or decrement.
5387 int sidx = subStr.lastIndexOf(prefix);
5388 if (sidx != -1) {
5389 subStr = subStr.substring(sidx + prefix.length());
5390 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005391 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5392 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005393 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005394 try {
5395 idx = Integer.parseInt(subStr);
5396 if (idx <= 1) {
5397 idx++;
5398 } else {
5399 idx--;
5400 }
5401 } catch(NumberFormatException e) {
5402 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005403 }
5404 }
5405 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005406 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005407 return prefix + idxStr;
5408 }
5409
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005410 // Utility method used to ignore ADD/REMOVE events
5411 // by directory observer.
5412 private static boolean ignoreCodePath(String fullPathStr) {
5413 String apkName = getApkName(fullPathStr);
5414 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5415 if (idx != -1 && ((idx+1) < apkName.length())) {
5416 // Make sure the package ends with a numeral
5417 String version = apkName.substring(idx+1);
5418 try {
5419 Integer.parseInt(version);
5420 return true;
5421 } catch (NumberFormatException e) {}
5422 }
5423 return false;
5424 }
5425
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005426 // Utility method that returns the relative package path with respect
5427 // to the installation directory. Like say for /data/data/com.test-1.apk
5428 // string com.test-1 is returned.
5429 static String getApkName(String codePath) {
5430 if (codePath == null) {
5431 return null;
5432 }
5433 int sidx = codePath.lastIndexOf("/");
5434 int eidx = codePath.lastIndexOf(".");
5435 if (eidx == -1) {
5436 eidx = codePath.length();
5437 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005438 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005439 return null;
5440 }
5441 return codePath.substring(sidx+1, eidx);
5442 }
5443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 class PackageInstalledInfo {
5445 String name;
5446 int uid;
5447 PackageParser.Package pkg;
5448 int returnCode;
5449 PackageRemovedInfo removedInfo;
5450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 /*
5453 * Install a non-existing package.
5454 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005455 private void installNewPackageLI(PackageParser.Package pkg,
5456 int parseFlags,
5457 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005458 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005460 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005461
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005462 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 res.name = pkgName;
5464 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005465 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5466 // A package with the same name is already installed, though
5467 // it has been renamed to an older name. The package we
5468 // are trying to install should be installed as an update to
5469 // the existing one, but that has not been requested, so bail.
5470 Slog.w(TAG, "Attempt to re-install " + pkgName
5471 + " without first uninstalling package running as "
5472 + mSettings.mRenamedPackages.get(pkgName));
5473 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5474 return;
5475 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005476 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005478 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 + " without first uninstalling.");
5480 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5481 return;
5482 }
5483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005485 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5486 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005487 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005488 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5490 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5491 }
5492 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005493 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005494 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 res);
5496 // delete the partially installed application. the data directory will have to be
5497 // restored if it was already existing
5498 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5499 // remove package from internal structures. Note that we want deletePackageX to
5500 // delete the package data and cache directories that it created in
5501 // scanPackageLocked, unless those directories existed before we even tried to
5502 // install.
5503 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005504 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005506 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 }
5508 }
5509 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005510
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005511 private void replacePackageLI(PackageParser.Package pkg,
5512 int parseFlags,
5513 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005514 String installerPackageName, PackageInstalledInfo res) {
5515
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005516 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005517 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 // First find the old package info and check signatures
5519 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005520 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005521 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005522 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5524 return;
5525 }
5526 }
Kenny Root85387d72010-08-26 10:13:11 -07005527 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005528 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005529 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005531 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 }
5533 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005536 PackageParser.Package pkg,
5537 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005538 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 PackageParser.Package newPackage = null;
5540 String pkgName = deletedPackage.packageName;
5541 boolean deletedPkg = true;
5542 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005543
Jacek Surazski65e13172009-04-28 15:26:38 +02005544 String oldInstallerPackageName = null;
5545 synchronized (mPackages) {
5546 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005548
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005549 long origUpdateTime;
5550 if (pkg.mExtras != null) {
5551 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5552 } else {
5553 origUpdateTime = 0;
5554 }
5555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005557 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005558 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005559 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5561 deletedPkg = false;
5562 } else {
5563 // Successfully deleted the old package. Now proceed with re-installation
5564 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005565 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5566 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005568 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5570 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005571 }
5572 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005573 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005574 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 res);
5576 updatedSettings = true;
5577 }
5578 }
5579
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005580 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 // remove package from internal structures. Note that we want deletePackageX to
5582 // delete the package data and cache directories that it created in
5583 // scanPackageLocked, unless those directories existed before we even tried to
5584 // install.
5585 if(updatedSettings) {
5586 deletePackageLI(
5587 pkgName, true,
5588 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005589 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 }
5591 // Since we failed to install the new package we need to restore the old
5592 // package that we deleted.
5593 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005594 File restoreFile = new File(deletedPackage.mPath);
5595 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005596 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005597 return;
5598 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005599 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005600 boolean oldOnSd = isExternal(deletedPackage);
5601 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5602 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5603 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005604 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5605 | SCAN_UPDATE_TIME;
5606 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5607 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005608 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5609 return;
5610 }
5611 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005612 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005613 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005614 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005615 mSettings.writeLP();
5616 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005617 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 }
5619 }
5620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005623 PackageParser.Package pkg,
5624 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005625 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 PackageParser.Package newPackage = null;
5627 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005628 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005629 PackageParser.PARSE_IS_SYSTEM;
5630 String packageName = deletedPackage.packageName;
5631 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5632 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005633 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 return;
5635 }
5636 PackageParser.Package oldPkg;
5637 PackageSetting oldPkgSetting;
5638 synchronized (mPackages) {
5639 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005640 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5642 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005643 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 return;
5645 }
5646 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005647
5648 killApplication(packageName, oldPkg.applicationInfo.uid);
5649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5651 res.removedInfo.removedPackage = packageName;
5652 // Remove existing system package
5653 removePackageLI(oldPkg, true);
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005654 synchronized (mPackages) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005655 if (!mSettings.disableSystemPackageLP(packageName) && deletedPackage != null) {
5656 // We didn't need to disable the .apk as a current system package,
5657 // which means we are replacing another update that is already
5658 // installed. We need to make sure to delete the older one's .apk.
5659 res.removedInfo.args = createInstallArgs(isExternal(pkg)
5660 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL,
5661 deletedPackage.applicationInfo.sourceDir,
5662 deletedPackage.applicationInfo.publicSourceDir,
5663 deletedPackage.applicationInfo.nativeLibraryDir);
5664 } else {
5665 res.removedInfo.args = null;
5666 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005667 }
5668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 // Successfully disabled the old package. Now proceed with re-installation
5670 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5671 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005672 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005674 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5676 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5677 }
5678 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005679 if (newPackage.mExtras != null) {
5680 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5681 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5682 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5683 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005684 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 updatedSettings = true;
5686 }
5687
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005688 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 // Re installation failed. Restore old information
5690 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005691 if (newPackage != null) {
5692 removePackageLI(newPackage, true);
5693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005695 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 // Restore the old system information in Settings
5697 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005698 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005700 mSettings.setInstallerPackageName(packageName,
5701 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 }
5703 mSettings.writeLP();
5704 }
5705 }
5706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005707
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005708 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005709 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005710 int retCode;
5711 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5712 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5713 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005714 if (mNoDexOpt) {
5715 /*
5716 * If we're in an engineering build, programs are lazily run
5717 * through dexopt. If the .dex file doesn't exist yet, it
5718 * will be created when the program is run next.
5719 */
5720 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5721 } else {
5722 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5723 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5724 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005725 }
5726 }
5727 return PackageManager.INSTALL_SUCCEEDED;
5728 }
5729
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005730 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005731 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005732 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 synchronized (mPackages) {
5734 //write settings. the installStatus will be incomplete at this stage.
5735 //note that the new package setting would have already been
5736 //added to mPackages. It hasn't been persisted yet.
5737 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5738 mSettings.writeLP();
5739 }
5740
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005741 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005742 != PackageManager.INSTALL_SUCCEEDED) {
5743 // Discontinue if moving dex files failed.
5744 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005746 if((res.returnCode = setPermissionsLI(newPackage))
5747 != PackageManager.INSTALL_SUCCEEDED) {
5748 if (mInstaller != null) {
5749 mInstaller.rmdex(newPackage.mScanPath);
5750 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005751 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005753 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005756 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005757 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 res.name = pkgName;
5759 res.uid = newPackage.applicationInfo.uid;
5760 res.pkg = newPackage;
5761 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005762 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5764 //to update install status
5765 mSettings.writeLP();
5766 }
5767 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005768
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005769 private void installPackageLI(InstallArgs args,
5770 boolean newInstall, PackageInstalledInfo res) {
5771 int pFlags = args.flags;
5772 String installerPackageName = args.installerPackageName;
5773 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005774 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005775 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005776 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005777 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005778 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005779 // Result object to be returned
5780 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5781
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005782 // Retrieve PackageSettings and parse package
5783 int parseFlags = PackageParser.PARSE_CHATTY |
5784 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5785 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5786 parseFlags |= mDefParseFlags;
5787 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5788 pp.setSeparateProcesses(mSeparateProcesses);
5789 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5790 null, mMetrics, parseFlags);
5791 if (pkg == null) {
5792 res.returnCode = pp.getParseError();
5793 return;
5794 }
5795 String pkgName = res.name = pkg.packageName;
5796 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5797 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5798 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5799 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005801 }
5802 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5803 res.returnCode = pp.getParseError();
5804 return;
5805 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005806 // Get rid of all references to package scan path via parser.
5807 pp = null;
5808 String oldCodePath = null;
5809 boolean systemApp = false;
5810 synchronized (mPackages) {
5811 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005812 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5813 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005814 if (pkg.mOriginalPackages != null
5815 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005816 && mPackages.containsKey(oldName)) {
5817 // This package is derived from an original package,
5818 // and this device has been updating from that original
5819 // name. We must continue using the original name, so
5820 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005821 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005822 pkgName = pkg.packageName;
5823 replace = true;
5824 } else if (mPackages.containsKey(pkgName)) {
5825 // This package, under its official name, already exists
5826 // on the device; we should replace it.
5827 replace = true;
5828 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005829 }
5830 PackageSetting ps = mSettings.mPackages.get(pkgName);
5831 if (ps != null) {
5832 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5833 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5834 systemApp = (ps.pkg.applicationInfo.flags &
5835 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005836 }
5837 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005839
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005840 if (systemApp && onSd) {
5841 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005842 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005843 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5844 return;
5845 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005846
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005847 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5848 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5849 return;
5850 }
5851 // Set application objects path explicitly after the rename
5852 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005853 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005854 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005855 replacePackageLI(pkg, parseFlags, scanMode,
5856 installerPackageName, res);
5857 } else {
5858 installNewPackageLI(pkg, parseFlags, scanMode,
5859 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 }
5861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005862
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005863 private int setPermissionsLI(PackageParser.Package newPackage) {
5864 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005865 int retCode = 0;
5866 // TODO Gross hack but fix later. Ideally move this to be a post installation
5867 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005868 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005869 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005870 try {
5871 extractPublicFiles(newPackage, destResourceFile);
5872 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005873 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 -08005874 " forward-locked app.");
5875 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5876 } finally {
5877 //TODO clean up the extracted public files
5878 }
5879 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005880 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 newPackage.applicationInfo.uid);
5882 } else {
5883 final int filePermissions =
5884 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005885 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005886 newPackage.applicationInfo.uid);
5887 }
5888 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005889 // The permissions on the resource file was set when it was copied for
5890 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005891 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005894 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005895 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005896 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005897 // TODO Define new internal error
5898 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 }
5900 return PackageManager.INSTALL_SUCCEEDED;
5901 }
5902
Kenny Root85387d72010-08-26 10:13:11 -07005903 private static boolean isForwardLocked(PackageParser.Package pkg) {
5904 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 }
5906
Kenny Root85387d72010-08-26 10:13:11 -07005907 private static boolean isExternal(PackageParser.Package pkg) {
5908 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5909 }
5910
5911 private static boolean isSystemApp(PackageParser.Package pkg) {
5912 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5913 }
5914
Kenny Root1c6e7642011-01-10 13:48:15 -08005915 private static boolean isSystemApp(ApplicationInfo info) {
5916 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5917 }
5918
Kenny Root85387d72010-08-26 10:13:11 -07005919 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5920 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005921 }
5922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 private void extractPublicFiles(PackageParser.Package newPackage,
5924 File publicZipFile) throws IOException {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07005925 final FileOutputStream fstr = new FileOutputStream(publicZipFile);
5926 final ZipOutputStream publicZipOutStream = new ZipOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5928
5929 // Copy manifest, resources.arsc and res directory to public zip
5930
5931 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5932 while (privateZipEntries.hasMoreElements()) {
5933 final ZipEntry zipEntry = privateZipEntries.nextElement();
5934 final String zipEntryName = zipEntry.getName();
5935 if ("AndroidManifest.xml".equals(zipEntryName)
5936 || "resources.arsc".equals(zipEntryName)
5937 || zipEntryName.startsWith("res/")) {
5938 try {
5939 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5940 } catch (IOException e) {
5941 try {
5942 publicZipOutStream.close();
5943 throw e;
5944 } finally {
5945 publicZipFile.delete();
5946 }
5947 }
5948 }
5949 }
5950
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07005951 publicZipOutStream.finish();
5952 publicZipOutStream.flush();
5953 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 publicZipOutStream.close();
5955 FileUtils.setPermissions(
5956 publicZipFile.getAbsolutePath(),
5957 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5958 -1, -1);
5959 }
5960
5961 private static void copyZipEntry(ZipEntry zipEntry,
5962 ZipFile inZipFile,
5963 ZipOutputStream outZipStream) throws IOException {
5964 byte[] buffer = new byte[4096];
5965 int num;
5966
5967 ZipEntry newEntry;
5968 if (zipEntry.getMethod() == ZipEntry.STORED) {
5969 // Preserve the STORED method of the input entry.
5970 newEntry = new ZipEntry(zipEntry);
5971 } else {
5972 // Create a new entry so that the compressed len is recomputed.
5973 newEntry = new ZipEntry(zipEntry.getName());
5974 }
5975 outZipStream.putNextEntry(newEntry);
5976
5977 InputStream data = inZipFile.getInputStream(zipEntry);
5978 while ((num = data.read(buffer)) > 0) {
5979 outZipStream.write(buffer, 0, num);
5980 }
5981 outZipStream.flush();
5982 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 private void deleteTempPackageFiles() {
5985 FilenameFilter filter = new FilenameFilter() {
5986 public boolean accept(File dir, String name) {
5987 return name.startsWith("vmdl") && name.endsWith(".tmp");
5988 }
5989 };
5990 String tmpFilesList[] = mAppInstallDir.list(filter);
5991 if(tmpFilesList == null) {
5992 return;
5993 }
5994 for(int i = 0; i < tmpFilesList.length; i++) {
5995 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5996 tmpFile.delete();
5997 }
5998 }
5999
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006000 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 File tmpPackageFile;
6002 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006003 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006005 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 return null;
6007 }
6008 try {
6009 FileUtils.setPermissions(
6010 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6011 -1, -1);
6012 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006013 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 return null;
6015 }
6016 return tmpPackageFile;
6017 }
6018
6019 public void deletePackage(final String packageName,
6020 final IPackageDeleteObserver observer,
6021 final int flags) {
6022 mContext.enforceCallingOrSelfPermission(
6023 android.Manifest.permission.DELETE_PACKAGES, null);
6024 // Queue up an async operation since the package deletion may take a little while.
6025 mHandler.post(new Runnable() {
6026 public void run() {
6027 mHandler.removeCallbacks(this);
6028 final boolean succeded = deletePackageX(packageName, true, true, flags);
6029 if (observer != null) {
6030 try {
6031 observer.packageDeleted(succeded);
6032 } catch (RemoteException e) {
6033 Log.i(TAG, "Observer no longer exists.");
6034 } //end catch
6035 } //end if
6036 } //end run
6037 });
6038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 /**
6041 * This method is an internal method that could be get invoked either
6042 * to delete an installed package or to clean up a failed installation.
6043 * After deleting an installed package, a broadcast is sent to notify any
6044 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006045 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 * installation wouldn't have sent the initial broadcast either
6047 * The key steps in deleting a package are
6048 * deleting the package information in internal structures like mPackages,
6049 * deleting the packages base directories through installd
6050 * updating mSettings to reflect current status
6051 * persisting settings for later use
6052 * sending a broadcast if necessary
6053 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6055 boolean deleteCodeAndResources, int flags) {
6056 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006057 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006059 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6060 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6061 try {
6062 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006063 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006064 return false;
6065 }
6066 } catch (RemoteException e) {
6067 }
6068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006070 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006071 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006075 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006076 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006077
6078 // If the removed package was a system update, the old system packaged
6079 // was re-enabled; we need to broadcast this information
6080 if (systemUpdate) {
6081 Bundle extras = new Bundle(1);
6082 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6083 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6084
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006085 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6086 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006089 // Force a gc here.
6090 Runtime.getRuntime().gc();
6091 // Delete the resources here after sending the broadcast to let
6092 // other processes clean up before deleting resources.
6093 if (info.args != null) {
6094 synchronized (mInstallLock) {
6095 info.args.doPostDeleteLI(deleteCodeAndResources);
6096 }
6097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 return res;
6099 }
6100
6101 static class PackageRemovedInfo {
6102 String removedPackage;
6103 int uid = -1;
6104 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006105 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006106 // Clean up resources deleted packages.
6107 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006108
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006109 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110 Bundle extras = new Bundle(1);
6111 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6112 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6113 if (replacing) {
6114 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6115 }
6116 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006117 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 }
6119 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006120 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 }
6122 }
6123 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 /*
6126 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6127 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006128 * 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 -08006129 * delete a partially installed application.
6130 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006131 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006132 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006134 if (outInfo != null) {
6135 outInfo.removedPackage = packageName;
6136 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006137 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 // Retrieve object to delete permissions for shared user later on
6139 PackageSetting deletedPs;
6140 synchronized (mPackages) {
6141 deletedPs = mSettings.mPackages.get(packageName);
6142 }
6143 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006144 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006146 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006148 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 + packageName + ", retcode=" + retCode);
6150 // we don't consider this to be a failure of the core package deletion
6151 }
6152 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006153 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 PackageParser.Package pkg = mPackages.get(packageName);
6155 File dataDir = new File(pkg.applicationInfo.dataDir);
6156 dataDir.delete();
6157 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006158 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006159 }
6160 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006161 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006162 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6163 if (outInfo != null) {
6164 outInfo.removedUid = mSettings.removePackageLP(packageName);
6165 }
6166 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006167 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006168 if (deletedPs.sharedUser != null) {
6169 // remove permissions associated with package
6170 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6171 }
6172 }
6173 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006174 // remove from preferred activities.
6175 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6176 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6177 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6178 removed.add(pa);
6179 }
6180 }
6181 for (PreferredActivity pa : removed) {
6182 mSettings.mPreferredActivities.removeFilter(pa);
6183 }
6184 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006185 if (writeSettings) {
6186 // Save settings now
6187 mSettings.writeLP();
6188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 }
6190 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 /*
6193 * Tries to delete system package.
6194 */
6195 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006196 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 ApplicationInfo applicationInfo = p.applicationInfo;
6198 //applicable for non-partially installed applications only
6199 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006200 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 return false;
6202 }
6203 PackageSetting ps = null;
6204 // Confirm if the system package has been updated
6205 // An updated system app can be deleted. This will also have to restore
6206 // the system pkg from system partition
6207 synchronized (mPackages) {
6208 ps = mSettings.getDisabledSystemPkg(p.packageName);
6209 }
6210 if (ps == null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006211 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 return false;
6213 } else {
6214 Log.i(TAG, "Deleting system pkg from data partition");
6215 }
6216 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006217 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006218 if (ps.versionCode < p.mVersionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006219 // Delete data for downgrades
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006220 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006221 } else {
6222 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006223 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006224 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006225 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006226 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 if (!ret) {
6228 return false;
6229 }
6230 synchronized (mPackages) {
6231 // Reinstate the old system package
6232 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006233 // Remove any native libraries from the upgraded package.
6234 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 }
6236 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006237 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006239 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006242 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 return false;
6244 }
6245 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006246 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006247 if (writeSettings) {
6248 mSettings.writeLP();
6249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 }
6251 return true;
6252 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006255 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6256 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 ApplicationInfo applicationInfo = p.applicationInfo;
6258 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006259 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 return false;
6261 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006262 if (outInfo != null) {
6263 outInfo.uid = applicationInfo.uid;
6264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265
6266 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006267 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268
6269 // Delete application code and resources
6270 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006271 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006272 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6273 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6274 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6275 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 }
6277 return true;
6278 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 /*
6281 * This method handles package deletion in general
6282 */
6283 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006284 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6285 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006287 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 return false;
6289 }
6290 PackageParser.Package p;
6291 boolean dataOnly = false;
6292 synchronized (mPackages) {
6293 p = mPackages.get(packageName);
6294 if (p == null) {
6295 //this retrieves partially installed apps
6296 dataOnly = true;
6297 PackageSetting ps = mSettings.mPackages.get(packageName);
6298 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006299 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 return false;
6301 }
6302 p = ps.pkg;
6303 }
6304 }
6305 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006306 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 return false;
6308 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 if (dataOnly) {
6311 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006312 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 return true;
6314 }
6315 // At this point the package should have ApplicationInfo associated with it
6316 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006317 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 return false;
6319 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006320 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006321 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 Log.i(TAG, "Removing system package:"+p.packageName);
6323 // When an updated system application is deleted we delete the existing resources as well and
6324 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006325 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006326 } else {
6327 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006328 // Kill application pre-emptively especially for apps on sd.
6329 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006330 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6331 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006333 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 public void clearApplicationUserData(final String packageName,
6337 final IPackageDataObserver observer) {
6338 mContext.enforceCallingOrSelfPermission(
6339 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6340 // Queue up an async operation since the package deletion may take a little while.
6341 mHandler.post(new Runnable() {
6342 public void run() {
6343 mHandler.removeCallbacks(this);
6344 final boolean succeeded;
6345 synchronized (mInstallLock) {
6346 succeeded = clearApplicationUserDataLI(packageName);
6347 }
6348 if (succeeded) {
6349 // invoke DeviceStorageMonitor's update method to clear any notifications
6350 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6351 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6352 if (dsm != null) {
6353 dsm.updateMemory();
6354 }
6355 }
6356 if(observer != null) {
6357 try {
6358 observer.onRemoveCompleted(packageName, succeeded);
6359 } catch (RemoteException e) {
6360 Log.i(TAG, "Observer no longer exists.");
6361 }
6362 } //end if observer
6363 } //end run
6364 });
6365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 private boolean clearApplicationUserDataLI(String packageName) {
6368 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006369 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 return false;
6371 }
6372 PackageParser.Package p;
6373 boolean dataOnly = false;
6374 synchronized (mPackages) {
6375 p = mPackages.get(packageName);
6376 if(p == null) {
6377 dataOnly = true;
6378 PackageSetting ps = mSettings.mPackages.get(packageName);
6379 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006380 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 return false;
6382 }
6383 p = ps.pkg;
6384 }
6385 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006386 boolean useEncryptedFSDir = false;
6387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 if(!dataOnly) {
6389 //need to check this only for fully installed applications
6390 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006391 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 return false;
6393 }
6394 final ApplicationInfo applicationInfo = p.applicationInfo;
6395 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006396 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 return false;
6398 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006399 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 }
6401 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006402 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006404 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 + packageName);
6406 return false;
6407 }
6408 }
6409 return true;
6410 }
6411
6412 public void deleteApplicationCacheFiles(final String packageName,
6413 final IPackageDataObserver observer) {
6414 mContext.enforceCallingOrSelfPermission(
6415 android.Manifest.permission.DELETE_CACHE_FILES, null);
6416 // Queue up an async operation since the package deletion may take a little while.
6417 mHandler.post(new Runnable() {
6418 public void run() {
6419 mHandler.removeCallbacks(this);
6420 final boolean succeded;
6421 synchronized (mInstallLock) {
6422 succeded = deleteApplicationCacheFilesLI(packageName);
6423 }
6424 if(observer != null) {
6425 try {
6426 observer.onRemoveCompleted(packageName, succeded);
6427 } catch (RemoteException e) {
6428 Log.i(TAG, "Observer no longer exists.");
6429 }
6430 } //end if observer
6431 } //end run
6432 });
6433 }
6434
6435 private boolean deleteApplicationCacheFilesLI(String packageName) {
6436 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006437 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 return false;
6439 }
6440 PackageParser.Package p;
6441 synchronized (mPackages) {
6442 p = mPackages.get(packageName);
6443 }
6444 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006445 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 return false;
6447 }
6448 final ApplicationInfo applicationInfo = p.applicationInfo;
6449 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006450 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 return false;
6452 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006453 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006455 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006457 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 + packageName);
6459 return false;
6460 }
6461 }
6462 return true;
6463 }
6464
6465 public void getPackageSizeInfo(final String packageName,
6466 final IPackageStatsObserver observer) {
6467 mContext.enforceCallingOrSelfPermission(
6468 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6469 // Queue up an async operation since the package deletion may take a little while.
6470 mHandler.post(new Runnable() {
6471 public void run() {
6472 mHandler.removeCallbacks(this);
6473 PackageStats lStats = new PackageStats(packageName);
6474 final boolean succeded;
6475 synchronized (mInstallLock) {
6476 succeded = getPackageSizeInfoLI(packageName, lStats);
6477 }
6478 if(observer != null) {
6479 try {
6480 observer.onGetStatsCompleted(lStats, succeded);
6481 } catch (RemoteException e) {
6482 Log.i(TAG, "Observer no longer exists.");
6483 }
6484 } //end if observer
6485 } //end run
6486 });
6487 }
6488
6489 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6490 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006491 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 return false;
6493 }
6494 PackageParser.Package p;
6495 boolean dataOnly = false;
6496 synchronized (mPackages) {
6497 p = mPackages.get(packageName);
6498 if(p == null) {
6499 dataOnly = true;
6500 PackageSetting ps = mSettings.mPackages.get(packageName);
6501 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006502 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006503 return false;
6504 }
6505 p = ps.pkg;
6506 }
6507 }
6508 String publicSrcDir = null;
6509 if(!dataOnly) {
6510 final ApplicationInfo applicationInfo = p.applicationInfo;
6511 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006512 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 return false;
6514 }
6515 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6516 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006517 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 if (mInstaller != null) {
6519 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006520 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 if (res < 0) {
6522 return false;
6523 } else {
6524 return true;
6525 }
6526 }
6527 return true;
6528 }
6529
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006532 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 }
6534
6535 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006536 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 }
6538
6539 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006540 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 }
6542
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006543 int getUidTargetSdkVersionLockedLP(int uid) {
6544 Object obj = mSettings.getUserIdLP(uid);
6545 if (obj instanceof SharedUserSetting) {
6546 SharedUserSetting sus = (SharedUserSetting)obj;
6547 final int N = sus.packages.size();
6548 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6549 Iterator<PackageSetting> it = sus.packages.iterator();
6550 int i=0;
6551 while (it.hasNext()) {
6552 PackageSetting ps = it.next();
6553 if (ps.pkg != null) {
6554 int v = ps.pkg.applicationInfo.targetSdkVersion;
6555 if (v < vers) vers = v;
6556 }
6557 }
6558 return vers;
6559 } else if (obj instanceof PackageSetting) {
6560 PackageSetting ps = (PackageSetting)obj;
6561 if (ps.pkg != null) {
6562 return ps.pkg.applicationInfo.targetSdkVersion;
6563 }
6564 }
6565 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6566 }
6567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 public void addPreferredActivity(IntentFilter filter, int match,
6569 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006571 if (mContext.checkCallingOrSelfPermission(
6572 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6573 != PackageManager.PERMISSION_GRANTED) {
6574 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6575 < Build.VERSION_CODES.FROYO) {
6576 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6577 + Binder.getCallingUid());
6578 return;
6579 }
6580 mContext.enforceCallingOrSelfPermission(
6581 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6582 }
6583
6584 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6586 mSettings.mPreferredActivities.addFilter(
6587 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006588 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 }
6590 }
6591
Satish Sampath8dbe6122009-06-02 23:35:54 +01006592 public void replacePreferredActivity(IntentFilter filter, int match,
6593 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006594 if (filter.countActions() != 1) {
6595 throw new IllegalArgumentException(
6596 "replacePreferredActivity expects filter to have only 1 action.");
6597 }
6598 if (filter.countCategories() != 1) {
6599 throw new IllegalArgumentException(
6600 "replacePreferredActivity expects filter to have only 1 category.");
6601 }
6602 if (filter.countDataAuthorities() != 0
6603 || filter.countDataPaths() != 0
6604 || filter.countDataSchemes() != 0
6605 || filter.countDataTypes() != 0) {
6606 throw new IllegalArgumentException(
6607 "replacePreferredActivity expects filter to have no data authorities, " +
6608 "paths, schemes or types.");
6609 }
6610 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006611 if (mContext.checkCallingOrSelfPermission(
6612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6613 != PackageManager.PERMISSION_GRANTED) {
6614 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6615 < Build.VERSION_CODES.FROYO) {
6616 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6617 + Binder.getCallingUid());
6618 return;
6619 }
6620 mContext.enforceCallingOrSelfPermission(
6621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6622 }
6623
Satish Sampath8dbe6122009-06-02 23:35:54 +01006624 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6625 String action = filter.getAction(0);
6626 String category = filter.getCategory(0);
6627 while (it.hasNext()) {
6628 PreferredActivity pa = it.next();
6629 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6630 it.remove();
6631 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6632 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6633 }
6634 }
6635 addPreferredActivity(filter, match, set, activity);
6636 }
6637 }
6638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006641 int uid = Binder.getCallingUid();
6642 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006643 if (pkg == null || pkg.applicationInfo.uid != uid) {
6644 if (mContext.checkCallingOrSelfPermission(
6645 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6646 != PackageManager.PERMISSION_GRANTED) {
6647 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6648 < Build.VERSION_CODES.FROYO) {
6649 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6650 + Binder.getCallingUid());
6651 return;
6652 }
6653 mContext.enforceCallingOrSelfPermission(
6654 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6655 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006656 }
6657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006659 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 }
6661 }
6662 }
6663
6664 boolean clearPackagePreferredActivitiesLP(String packageName) {
6665 boolean changed = false;
6666 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6667 while (it.hasNext()) {
6668 PreferredActivity pa = it.next();
6669 if (pa.mActivity.getPackageName().equals(packageName)) {
6670 it.remove();
6671 changed = true;
6672 }
6673 }
6674 return changed;
6675 }
6676
6677 public int getPreferredActivities(List<IntentFilter> outFilters,
6678 List<ComponentName> outActivities, String packageName) {
6679
6680 int num = 0;
6681 synchronized (mPackages) {
6682 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6683 while (it.hasNext()) {
6684 PreferredActivity pa = it.next();
6685 if (packageName == null
6686 || pa.mActivity.getPackageName().equals(packageName)) {
6687 if (outFilters != null) {
6688 outFilters.add(new IntentFilter(pa));
6689 }
6690 if (outActivities != null) {
6691 outActivities.add(pa.mActivity);
6692 }
6693 }
6694 }
6695 }
6696
6697 return num;
6698 }
6699
6700 public void setApplicationEnabledSetting(String appPackageName,
6701 int newState, int flags) {
6702 setEnabledSetting(appPackageName, null, newState, flags);
6703 }
6704
6705 public void setComponentEnabledSetting(ComponentName componentName,
6706 int newState, int flags) {
6707 setEnabledSetting(componentName.getPackageName(),
6708 componentName.getClassName(), newState, flags);
6709 }
6710
6711 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006712 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6714 || newState == COMPONENT_ENABLED_STATE_ENABLED
6715 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6716 throw new IllegalArgumentException("Invalid new component state: "
6717 + newState);
6718 }
6719 PackageSetting pkgSetting;
6720 final int uid = Binder.getCallingUid();
6721 final int permission = mContext.checkCallingPermission(
6722 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6723 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006724 boolean sendNow = false;
6725 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006726 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006728 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006730 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006732 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006734 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 }
6736 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006737 "Unknown component: " + packageName
6738 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 }
6740 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6741 throw new SecurityException(
6742 "Permission Denial: attempt to change component state from pid="
6743 + Binder.getCallingPid()
6744 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6745 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006746 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006748 if (pkgSetting.enabled == newState) {
6749 // Nothing to do
6750 return;
6751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006753 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 } else {
6755 // We're dealing with a component level state change
6756 switch (newState) {
6757 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006758 if (!pkgSetting.enableComponentLP(className)) {
6759 return;
6760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 break;
6762 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006763 if (!pkgSetting.disableComponentLP(className)) {
6764 return;
6765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 break;
6767 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006768 if (!pkgSetting.restoreComponentLP(className)) {
6769 return;
6770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 break;
6772 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006773 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006774 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 }
6776 }
6777 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006778 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006779 components = mPendingBroadcasts.get(packageName);
6780 boolean newPackage = components == null;
6781 if (newPackage) {
6782 components = new ArrayList<String>();
6783 }
6784 if (!components.contains(componentName)) {
6785 components.add(componentName);
6786 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006787 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6788 sendNow = true;
6789 // Purge entry from pending broadcast list if another one exists already
6790 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006791 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006792 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006793 if (newPackage) {
6794 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006795 }
6796 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6797 // Schedule a message
6798 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6799 }
6800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 long callingId = Binder.clearCallingIdentity();
6804 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006805 if (sendNow) {
6806 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006807 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 } finally {
6810 Binder.restoreCallingIdentity(callingId);
6811 }
6812 }
6813
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006814 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006815 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6816 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6817 + " components=" + componentNames);
6818 Bundle extras = new Bundle(4);
6819 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6820 String nameList[] = new String[componentNames.size()];
6821 componentNames.toArray(nameList);
6822 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006823 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6824 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006825 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006826 }
6827
Jacek Surazski65e13172009-04-28 15:26:38 +02006828 public String getInstallerPackageName(String packageName) {
6829 synchronized (mPackages) {
6830 PackageSetting pkg = mSettings.mPackages.get(packageName);
6831 if (pkg == null) {
6832 throw new IllegalArgumentException("Unknown package: " + packageName);
6833 }
6834 return pkg.installerPackageName;
6835 }
6836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 public int getApplicationEnabledSetting(String appPackageName) {
6839 synchronized (mPackages) {
6840 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6841 if (pkg == null) {
6842 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6843 }
6844 return pkg.enabled;
6845 }
6846 }
6847
6848 public int getComponentEnabledSetting(ComponentName componentName) {
6849 synchronized (mPackages) {
6850 final String packageNameStr = componentName.getPackageName();
6851 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6852 if (pkg == null) {
6853 throw new IllegalArgumentException("Unknown component: " + componentName);
6854 }
6855 final String classNameStr = componentName.getClassName();
6856 return pkg.currentEnabledStateLP(classNameStr);
6857 }
6858 }
6859
6860 public void enterSafeMode() {
6861 if (!mSystemReady) {
6862 mSafeMode = true;
6863 }
6864 }
6865
6866 public void systemReady() {
6867 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006868
6869 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006870 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006871 mContext.getContentResolver(),
6872 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006873 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006874 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006875 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006877 }
6878
6879 public boolean isSafeMode() {
6880 return mSafeMode;
6881 }
6882
6883 public boolean hasSystemUidErrors() {
6884 return mHasSystemUidErrors;
6885 }
6886
6887 static String arrayToString(int[] array) {
6888 StringBuffer buf = new StringBuffer(128);
6889 buf.append('[');
6890 if (array != null) {
6891 for (int i=0; i<array.length; i++) {
6892 if (i > 0) buf.append(", ");
6893 buf.append(array[i]);
6894 }
6895 }
6896 buf.append(']');
6897 return buf.toString();
6898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 @Override
6901 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6902 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6903 != PackageManager.PERMISSION_GRANTED) {
6904 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6905 + Binder.getCallingPid()
6906 + ", uid=" + Binder.getCallingUid()
6907 + " without permission "
6908 + android.Manifest.permission.DUMP);
6909 return;
6910 }
6911
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006912 boolean dumpStar = true;
6913 boolean dumpLibs = false;
6914 boolean dumpFeatures = false;
6915 boolean dumpResolvers = false;
6916 boolean dumpPermissions = false;
6917 boolean dumpPackages = false;
6918 boolean dumpSharedUsers = false;
6919 boolean dumpMessages = false;
6920 boolean dumpProviders = false;
6921
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006922 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006923 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006924
6925 int opti = 0;
6926 while (opti < args.length) {
6927 String opt = args[opti];
6928 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6929 break;
6930 }
6931 opti++;
6932 if ("-a".equals(opt)) {
6933 // Right now we only know how to print all.
6934 } else if ("-h".equals(opt)) {
6935 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006936 pw.println(" [-h] [-f] [cmd] ...");
6937 pw.println(" -f: print details of intent filters");
6938 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006939 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006940 pw.println(" l[ibraries]: list known shared libraries");
6941 pw.println(" f[ibraries]: list device features");
6942 pw.println(" r[esolvers]: dump intent resolvers");
6943 pw.println(" perm[issions]: dump permissions");
6944 pw.println(" prov[iders]: dump content providers");
6945 pw.println(" p[ackages]: dump installed packages");
6946 pw.println(" s[hared-users]: dump shared user IDs");
6947 pw.println(" m[essages]: print collected runtime messages");
6948 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006949 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006950 } else if ("-f".equals(opt)) {
6951 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006952 } else {
6953 pw.println("Unknown argument: " + opt + "; use -h for help");
6954 }
6955 }
6956
6957 // Is the caller requesting to dump a particular piece of data?
6958 if (opti < args.length) {
6959 String cmd = args[opti];
6960 opti++;
6961 // Is this a package name?
6962 if ("android".equals(cmd) || cmd.contains(".")) {
6963 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006964 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
6965 dumpStar = false;
6966 dumpLibs = true;
6967 } else if ("f".equals(cmd) || "features".equals(cmd)) {
6968 dumpStar = false;
6969 dumpFeatures = true;
6970 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
6971 dumpStar = false;
6972 dumpResolvers = true;
6973 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
6974 dumpStar = false;
6975 dumpPermissions = true;
6976 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
6977 dumpStar = false;
6978 dumpPackages = true;
6979 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
6980 dumpStar = false;
6981 dumpSharedUsers = true;
6982 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
6983 dumpStar = false;
6984 dumpProviders = true;
6985 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
6986 dumpStar = false;
6987 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006988 }
6989 }
6990
6991 boolean printedTitle = false;
6992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006993 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006994 if ((dumpStar || dumpLibs) && packageName == null) {
6995 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006996 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006997 pw.println("Libraries:");
6998 Iterator<String> it = mSharedLibraries.keySet().iterator();
6999 while (it.hasNext()) {
7000 String name = it.next();
7001 pw.print(" ");
7002 pw.print(name);
7003 pw.print(" -> ");
7004 pw.println(mSharedLibraries.get(name));
7005 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007006 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007007
7008 if ((dumpStar || dumpFeatures) && packageName == null) {
7009 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007010 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007011 pw.println("Features:");
7012 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7013 while (it.hasNext()) {
7014 String name = it.next();
7015 pw.print(" ");
7016 pw.println(name);
7017 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007018 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007019
7020 if (dumpStar || dumpResolvers) {
7021 if (mActivities.dump(pw, printedTitle
7022 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7023 " ", packageName, showFilters)) {
7024 printedTitle = true;
7025 }
7026 if (mReceivers.dump(pw, printedTitle
7027 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7028 " ", packageName, showFilters)) {
7029 printedTitle = true;
7030 }
7031 if (mServices.dump(pw, printedTitle
7032 ? "\nService Resolver Table:" : "Service Resolver Table:",
7033 " ", packageName, showFilters)) {
7034 printedTitle = true;
7035 }
7036 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7037 ? "\nPreferred Activities:" : "Preferred Activities:",
7038 " ", packageName, showFilters)) {
7039 printedTitle = true;
7040 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007041 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007042
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007043 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007044 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007045 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007046 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7047 continue;
7048 }
7049 if (!printedSomething) {
7050 if (printedTitle) pw.println(" ");
7051 pw.println("Permissions:");
7052 printedSomething = true;
7053 printedTitle = true;
7054 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007055 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7056 pw.print(Integer.toHexString(System.identityHashCode(p)));
7057 pw.println("):");
7058 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7059 pw.print(" uid="); pw.print(p.uid);
7060 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007061 pw.print(" type="); pw.print(p.type);
7062 pw.print(" prot="); pw.println(p.protectionLevel);
7063 if (p.packageSetting != null) {
7064 pw.print(" packageSetting="); pw.println(p.packageSetting);
7065 }
7066 if (p.perm != null) {
7067 pw.print(" perm="); pw.println(p.perm);
7068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 }
7070 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007071
7072 if (dumpStar || dumpProviders) {
7073 printedSomething = false;
7074 for (PackageParser.Provider p : mProviders.values()) {
7075 if (packageName != null && !packageName.equals(p.info.packageName)) {
7076 continue;
7077 }
7078 if (!printedSomething) {
7079 if (printedTitle) pw.println(" ");
7080 pw.println("Registered ContentProviders:");
7081 printedSomething = true;
7082 printedTitle = true;
7083 }
7084 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7085 pw.println(p.toString());
7086 }
7087 }
7088
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007089 printedSomething = false;
7090 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007091 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007092 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7093 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007095 if (packageName != null && !packageName.equals(ps.realName)
7096 && !packageName.equals(ps.name)) {
7097 continue;
7098 }
7099 if (!printedSomething) {
7100 if (printedTitle) pw.println(" ");
7101 pw.println("Packages:");
7102 printedSomething = true;
7103 printedTitle = true;
7104 }
7105 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007106 pw.print(" Package [");
7107 pw.print(ps.realName != null ? ps.realName : ps.name);
7108 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007109 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7110 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007111 if (ps.realName != null) {
7112 pw.print(" compat name="); pw.println(ps.name);
7113 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007114 pw.print(" userId="); pw.print(ps.userId);
7115 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7116 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7117 pw.print(" pkg="); pw.println(ps.pkg);
7118 pw.print(" codePath="); pw.println(ps.codePathString);
7119 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007120 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root70fc04c2010-10-22 10:07:11 -07007121 pw.print(" versionCode="); pw.println(ps.versionCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122 if (ps.pkg != null) {
Kenny Root70fc04c2010-10-22 10:07:11 -07007123 pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007124 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007125 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007126 if (ps.pkg.mOperationPending) {
7127 pw.println(" mOperationPending=true");
7128 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007129 pw.print(" supportsScreens=[");
7130 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007131 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007132 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7133 if (!first) pw.print(", ");
7134 first = false;
7135 pw.print("small");
7136 }
7137 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007138 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007139 if (!first) pw.print(", ");
7140 first = false;
7141 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007142 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007143 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007144 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007145 if (!first) pw.print(", ");
7146 first = false;
7147 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007148 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007149 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007150 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007151 if (!first) pw.print(", ");
7152 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007153 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007154 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007155 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007156 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007157 if (!first) pw.print(", ");
7158 first = false;
7159 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007160 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007161 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007162 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7163 if (!first) pw.print(", ");
7164 first = false;
7165 pw.print("anyDensity");
7166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007167 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007168 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007169 pw.print(" timeStamp=");
7170 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7171 pw.print(" firstInstallTime=");
7172 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7173 pw.print(" lastUpdateTime=");
7174 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007175 pw.print(" signatures="); pw.println(ps.signatures);
7176 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007177 pw.print(" haveGids="); pw.println(ps.haveGids);
7178 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007179 pw.print(" installStatus="); pw.print(ps.installStatus);
7180 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 if (ps.disabledComponents.size() > 0) {
7182 pw.println(" disabledComponents:");
7183 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007184 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007185 }
7186 }
7187 if (ps.enabledComponents.size() > 0) {
7188 pw.println(" enabledComponents:");
7189 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007190 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007191 }
7192 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007193 if (ps.grantedPermissions.size() > 0) {
7194 pw.println(" grantedPermissions:");
7195 for (String s : ps.grantedPermissions) {
7196 pw.print(" "); pw.println(s);
7197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 }
7200 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007201 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007202 if (dumpStar || dumpPackages) {
7203 if (mSettings.mRenamedPackages.size() > 0) {
7204 for (HashMap.Entry<String, String> e
7205 : mSettings.mRenamedPackages.entrySet()) {
7206 if (packageName != null && !packageName.equals(e.getKey())
7207 && !packageName.equals(e.getValue())) {
7208 continue;
7209 }
7210 if (!printedSomething) {
7211 if (printedTitle) pw.println(" ");
7212 pw.println("Renamed packages:");
7213 printedSomething = true;
7214 printedTitle = true;
7215 }
7216 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7217 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007218 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007219 }
7220 printedSomething = false;
7221 if (mSettings.mDisabledSysPackages.size() > 0) {
7222 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7223 if (packageName != null && !packageName.equals(ps.realName)
7224 && !packageName.equals(ps.name)) {
7225 continue;
7226 }
7227 if (!printedSomething) {
7228 if (printedTitle) pw.println(" ");
7229 pw.println("Hidden system packages:");
7230 printedSomething = true;
7231 printedTitle = true;
7232 }
7233 pw.print(" Package [");
7234 pw.print(ps.realName != null ? ps.realName : ps.name);
7235 pw.print("] (");
7236 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7237 pw.println("):");
7238 if (ps.realName != null) {
7239 pw.print(" compat name="); pw.println(ps.name);
7240 }
7241 pw.print(" userId="); pw.println(ps.userId);
7242 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7243 pw.print(" codePath="); pw.println(ps.codePathString);
7244 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007245 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007246 }
7247 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007248 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007249 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007251 if (packageName != null && su != packageSharedUser) {
7252 continue;
7253 }
7254 if (!printedSomething) {
7255 if (printedTitle) pw.println(" ");
7256 pw.println("Shared users:");
7257 printedSomething = true;
7258 printedTitle = true;
7259 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007260 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7261 pw.print(Integer.toHexString(System.identityHashCode(su)));
7262 pw.println("):");
7263 pw.print(" userId="); pw.print(su.userId);
7264 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 pw.println(" grantedPermissions:");
7266 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007267 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007269 }
7270 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007271
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007272 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007273 if (printedTitle) pw.println(" ");
7274 printedTitle = true;
7275 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007276 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007277
7278 pw.println(" ");
7279 pw.println("Package warning messages:");
7280 File fname = getSettingsProblemFile();
7281 FileInputStream in;
7282 try {
7283 in = new FileInputStream(fname);
7284 int avail = in.available();
7285 byte[] data = new byte[avail];
7286 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007287 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007288 } catch (FileNotFoundException e) {
7289 } catch (IOException e) {
7290 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 }
7293 }
7294
7295 static final class BasePermission {
7296 final static int TYPE_NORMAL = 0;
7297 final static int TYPE_BUILTIN = 1;
7298 final static int TYPE_DYNAMIC = 2;
7299
7300 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007301 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007302 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007303 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007304 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007305 PackageParser.Permission perm;
7306 PermissionInfo pendingInfo;
7307 int uid;
7308 int[] gids;
7309
7310 BasePermission(String _name, String _sourcePackage, int _type) {
7311 name = _name;
7312 sourcePackage = _sourcePackage;
7313 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007314 // Default to most conservative protection level.
7315 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7316 }
7317
7318 public String toString() {
7319 return "BasePermission{"
7320 + Integer.toHexString(System.identityHashCode(this))
7321 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007322 }
7323 }
7324
7325 static class PackageSignatures {
7326 private Signature[] mSignatures;
7327
Kenny Rootea6bf362011-01-13 14:53:17 -08007328 PackageSignatures(PackageSignatures orig) {
7329 if (orig != null && orig.mSignatures != null) {
7330 mSignatures = orig.mSignatures.clone();
7331 }
7332 }
7333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 PackageSignatures(Signature[] sigs) {
7335 assignSignatures(sigs);
7336 }
7337
7338 PackageSignatures() {
7339 }
7340
7341 void writeXml(XmlSerializer serializer, String tagName,
7342 ArrayList<Signature> pastSignatures) throws IOException {
7343 if (mSignatures == null) {
7344 return;
7345 }
7346 serializer.startTag(null, tagName);
7347 serializer.attribute(null, "count",
7348 Integer.toString(mSignatures.length));
7349 for (int i=0; i<mSignatures.length; i++) {
7350 serializer.startTag(null, "cert");
7351 final Signature sig = mSignatures[i];
7352 final int sigHash = sig.hashCode();
7353 final int numPast = pastSignatures.size();
7354 int j;
7355 for (j=0; j<numPast; j++) {
7356 Signature pastSig = pastSignatures.get(j);
7357 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7358 serializer.attribute(null, "index", Integer.toString(j));
7359 break;
7360 }
7361 }
7362 if (j >= numPast) {
7363 pastSignatures.add(sig);
7364 serializer.attribute(null, "index", Integer.toString(numPast));
7365 serializer.attribute(null, "key", sig.toCharsString());
7366 }
7367 serializer.endTag(null, "cert");
7368 }
7369 serializer.endTag(null, tagName);
7370 }
7371
7372 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7373 throws IOException, XmlPullParserException {
7374 String countStr = parser.getAttributeValue(null, "count");
7375 if (countStr == null) {
7376 reportSettingsProblem(Log.WARN,
7377 "Error in package manager settings: <signatures> has"
7378 + " no count at " + parser.getPositionDescription());
7379 XmlUtils.skipCurrentTag(parser);
7380 }
7381 final int count = Integer.parseInt(countStr);
7382 mSignatures = new Signature[count];
7383 int pos = 0;
7384
7385 int outerDepth = parser.getDepth();
7386 int type;
7387 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7388 && (type != XmlPullParser.END_TAG
7389 || parser.getDepth() > outerDepth)) {
7390 if (type == XmlPullParser.END_TAG
7391 || type == XmlPullParser.TEXT) {
7392 continue;
7393 }
7394
7395 String tagName = parser.getName();
7396 if (tagName.equals("cert")) {
7397 if (pos < count) {
7398 String index = parser.getAttributeValue(null, "index");
7399 if (index != null) {
7400 try {
7401 int idx = Integer.parseInt(index);
7402 String key = parser.getAttributeValue(null, "key");
7403 if (key == null) {
7404 if (idx >= 0 && idx < pastSignatures.size()) {
7405 Signature sig = pastSignatures.get(idx);
7406 if (sig != null) {
7407 mSignatures[pos] = pastSignatures.get(idx);
7408 pos++;
7409 } else {
7410 reportSettingsProblem(Log.WARN,
7411 "Error in package manager settings: <cert> "
7412 + "index " + index + " is not defined at "
7413 + parser.getPositionDescription());
7414 }
7415 } else {
7416 reportSettingsProblem(Log.WARN,
7417 "Error in package manager settings: <cert> "
7418 + "index " + index + " is out of bounds at "
7419 + parser.getPositionDescription());
7420 }
7421 } else {
7422 while (pastSignatures.size() <= idx) {
7423 pastSignatures.add(null);
7424 }
7425 Signature sig = new Signature(key);
7426 pastSignatures.set(idx, sig);
7427 mSignatures[pos] = sig;
7428 pos++;
7429 }
7430 } catch (NumberFormatException e) {
7431 reportSettingsProblem(Log.WARN,
7432 "Error in package manager settings: <cert> "
7433 + "index " + index + " is not a number at "
7434 + parser.getPositionDescription());
7435 }
7436 } else {
7437 reportSettingsProblem(Log.WARN,
7438 "Error in package manager settings: <cert> has"
7439 + " no index at " + parser.getPositionDescription());
7440 }
7441 } else {
7442 reportSettingsProblem(Log.WARN,
7443 "Error in package manager settings: too "
7444 + "many <cert> tags, expected " + count
7445 + " at " + parser.getPositionDescription());
7446 }
7447 } else {
7448 reportSettingsProblem(Log.WARN,
7449 "Unknown element under <cert>: "
7450 + parser.getName());
7451 }
7452 XmlUtils.skipCurrentTag(parser);
7453 }
7454
7455 if (pos < count) {
7456 // Should never happen -- there is an error in the written
7457 // settings -- but if it does we don't want to generate
7458 // a bad array.
7459 Signature[] newSigs = new Signature[pos];
7460 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7461 mSignatures = newSigs;
7462 }
7463 }
7464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007465 private void assignSignatures(Signature[] sigs) {
7466 if (sigs == null) {
7467 mSignatures = null;
7468 return;
7469 }
7470 mSignatures = new Signature[sigs.length];
7471 for (int i=0; i<sigs.length; i++) {
7472 mSignatures[i] = sigs[i];
7473 }
7474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 @Override
7477 public String toString() {
7478 StringBuffer buf = new StringBuffer(128);
7479 buf.append("PackageSignatures{");
7480 buf.append(Integer.toHexString(System.identityHashCode(this)));
7481 buf.append(" [");
7482 if (mSignatures != null) {
7483 for (int i=0; i<mSignatures.length; i++) {
7484 if (i > 0) buf.append(", ");
7485 buf.append(Integer.toHexString(
7486 System.identityHashCode(mSignatures[i])));
7487 }
7488 }
7489 buf.append("]}");
7490 return buf.toString();
7491 }
7492 }
7493
7494 static class PreferredActivity extends IntentFilter {
7495 final int mMatch;
7496 final String[] mSetPackages;
7497 final String[] mSetClasses;
7498 final String[] mSetComponents;
7499 final ComponentName mActivity;
7500 final String mShortActivity;
7501 String mParseError;
7502
7503 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7504 ComponentName activity) {
7505 super(filter);
7506 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7507 mActivity = activity;
7508 mShortActivity = activity.flattenToShortString();
7509 mParseError = null;
7510 if (set != null) {
7511 final int N = set.length;
7512 String[] myPackages = new String[N];
7513 String[] myClasses = new String[N];
7514 String[] myComponents = new String[N];
7515 for (int i=0; i<N; i++) {
7516 ComponentName cn = set[i];
7517 if (cn == null) {
7518 mSetPackages = null;
7519 mSetClasses = null;
7520 mSetComponents = null;
7521 return;
7522 }
7523 myPackages[i] = cn.getPackageName().intern();
7524 myClasses[i] = cn.getClassName().intern();
7525 myComponents[i] = cn.flattenToShortString().intern();
7526 }
7527 mSetPackages = myPackages;
7528 mSetClasses = myClasses;
7529 mSetComponents = myComponents;
7530 } else {
7531 mSetPackages = null;
7532 mSetClasses = null;
7533 mSetComponents = null;
7534 }
7535 }
7536
7537 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7538 IOException {
7539 mShortActivity = parser.getAttributeValue(null, "name");
7540 mActivity = ComponentName.unflattenFromString(mShortActivity);
7541 if (mActivity == null) {
7542 mParseError = "Bad activity name " + mShortActivity;
7543 }
7544 String matchStr = parser.getAttributeValue(null, "match");
7545 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7546 String setCountStr = parser.getAttributeValue(null, "set");
7547 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7548
7549 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7550 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7551 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7552
7553 int setPos = 0;
7554
7555 int outerDepth = parser.getDepth();
7556 int type;
7557 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7558 && (type != XmlPullParser.END_TAG
7559 || parser.getDepth() > outerDepth)) {
7560 if (type == XmlPullParser.END_TAG
7561 || type == XmlPullParser.TEXT) {
7562 continue;
7563 }
7564
7565 String tagName = parser.getName();
7566 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7567 // + parser.getDepth() + " tag=" + tagName);
7568 if (tagName.equals("set")) {
7569 String name = parser.getAttributeValue(null, "name");
7570 if (name == null) {
7571 if (mParseError == null) {
7572 mParseError = "No name in set tag in preferred activity "
7573 + mShortActivity;
7574 }
7575 } else if (setPos >= setCount) {
7576 if (mParseError == null) {
7577 mParseError = "Too many set tags in preferred activity "
7578 + mShortActivity;
7579 }
7580 } else {
7581 ComponentName cn = ComponentName.unflattenFromString(name);
7582 if (cn == null) {
7583 if (mParseError == null) {
7584 mParseError = "Bad set name " + name + " in preferred activity "
7585 + mShortActivity;
7586 }
7587 } else {
7588 myPackages[setPos] = cn.getPackageName();
7589 myClasses[setPos] = cn.getClassName();
7590 myComponents[setPos] = name;
7591 setPos++;
7592 }
7593 }
7594 XmlUtils.skipCurrentTag(parser);
7595 } else if (tagName.equals("filter")) {
7596 //Log.i(TAG, "Starting to parse filter...");
7597 readFromXml(parser);
7598 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7599 // + parser.getDepth() + " tag=" + parser.getName());
7600 } else {
7601 reportSettingsProblem(Log.WARN,
7602 "Unknown element under <preferred-activities>: "
7603 + parser.getName());
7604 XmlUtils.skipCurrentTag(parser);
7605 }
7606 }
7607
7608 if (setPos != setCount) {
7609 if (mParseError == null) {
7610 mParseError = "Not enough set tags (expected " + setCount
7611 + " but found " + setPos + ") in " + mShortActivity;
7612 }
7613 }
7614
7615 mSetPackages = myPackages;
7616 mSetClasses = myClasses;
7617 mSetComponents = myComponents;
7618 }
7619
7620 public void writeToXml(XmlSerializer serializer) throws IOException {
7621 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7622 serializer.attribute(null, "name", mShortActivity);
7623 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7624 serializer.attribute(null, "set", Integer.toString(NS));
7625 for (int s=0; s<NS; s++) {
7626 serializer.startTag(null, "set");
7627 serializer.attribute(null, "name", mSetComponents[s]);
7628 serializer.endTag(null, "set");
7629 }
7630 serializer.startTag(null, "filter");
7631 super.writeToXml(serializer);
7632 serializer.endTag(null, "filter");
7633 }
7634
7635 boolean sameSet(List<ResolveInfo> query, int priority) {
7636 if (mSetPackages == null) return false;
7637 final int NQ = query.size();
7638 final int NS = mSetPackages.length;
7639 int numMatch = 0;
7640 for (int i=0; i<NQ; i++) {
7641 ResolveInfo ri = query.get(i);
7642 if (ri.priority != priority) continue;
7643 ActivityInfo ai = ri.activityInfo;
7644 boolean good = false;
7645 for (int j=0; j<NS; j++) {
7646 if (mSetPackages[j].equals(ai.packageName)
7647 && mSetClasses[j].equals(ai.name)) {
7648 numMatch++;
7649 good = true;
7650 break;
7651 }
7652 }
7653 if (!good) return false;
7654 }
7655 return numMatch == NS;
7656 }
7657 }
7658
7659 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007660 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 HashSet<String> grantedPermissions = new HashSet<String>();
7663 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007665 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007666 setFlags(pkgFlags);
7667 }
7668
Kenny Rootea6bf362011-01-13 14:53:17 -08007669 GrantedPermissions(GrantedPermissions base) {
7670 pkgFlags = base.pkgFlags;
7671 grantedPermissions = (HashSet<String>) base.grantedPermissions.clone();
7672
7673 if (base.gids != null) {
7674 gids = base.gids.clone();
7675 }
7676 }
7677
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007678 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007679 this.pkgFlags = pkgFlags & (
7680 ApplicationInfo.FLAG_SYSTEM |
7681 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007682 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007683 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007684 }
7685 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 /**
7688 * Settings base class for pending and resolved classes.
7689 */
7690 static class PackageSettingBase extends GrantedPermissions {
7691 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007692 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007693 File codePath;
7694 String codePathString;
7695 File resourcePath;
7696 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007697 String nativeLibraryPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007698 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007699 long firstInstallTime;
7700 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007701 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007703 boolean uidError;
Kenny Rootea6bf362011-01-13 14:53:17 -08007704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705 PackageSignatures signatures = new PackageSignatures();
7706
7707 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007708 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 /* Explicitly disabled components */
7711 HashSet<String> disabledComponents = new HashSet<String>(0);
7712 /* Explicitly enabled components */
7713 HashSet<String> enabledComponents = new HashSet<String>(0);
7714 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7715 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007716
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007717 PackageSettingBase origPackage;
7718
Jacek Surazski65e13172009-04-28 15:26:38 +02007719 /* package name of the app that installed this package */
7720 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007722 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007723 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 super(pkgFlags);
7725 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007726 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007727 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007728 }
7729
Kenny Rootea6bf362011-01-13 14:53:17 -08007730 /**
7731 * New instance of PackageSetting with one-level-deep cloning.
7732 */
7733 PackageSettingBase(PackageSettingBase base) {
7734 super(base);
7735
7736 name = base.name;
7737 realName = base.realName;
7738 codePath = base.codePath;
7739 codePathString = base.codePathString;
7740 resourcePath = base.resourcePath;
7741 resourcePathString = base.resourcePathString;
7742 nativeLibraryPathString = base.nativeLibraryPathString;
Kenny Rootea6bf362011-01-13 14:53:17 -08007743 timeStamp = base.timeStamp;
7744 firstInstallTime = base.firstInstallTime;
7745 lastUpdateTime = base.lastUpdateTime;
7746 versionCode = base.versionCode;
7747
7748 uidError = base.uidError;
7749
7750 signatures = new PackageSignatures(base.signatures);
7751
7752 permissionsFixed = base.permissionsFixed;
7753 haveGids = base.haveGids;
7754
7755 disabledComponents = (HashSet<String>) base.disabledComponents.clone();
7756
7757 enabledComponents = (HashSet<String>) base.enabledComponents.clone();
7758
7759 enabled = base.enabled;
7760 installStatus = base.installStatus;
7761
7762 origPackage = base.origPackage;
7763
7764 installerPackageName = base.installerPackageName;
7765 }
7766
Kenny Root806cc132010-09-12 08:34:19 -07007767 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7768 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 this.codePath = codePath;
7770 this.codePathString = codePath.toString();
7771 this.resourcePath = resourcePath;
7772 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007773 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007774 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007775 }
Kenny Root85387d72010-08-26 10:13:11 -07007776
Jacek Surazski65e13172009-04-28 15:26:38 +02007777 public void setInstallerPackageName(String packageName) {
7778 installerPackageName = packageName;
7779 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007780
Jacek Surazski65e13172009-04-28 15:26:38 +02007781 String getInstallerPackageName() {
7782 return installerPackageName;
7783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 public void setInstallStatus(int newStatus) {
7786 installStatus = newStatus;
7787 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007789 public int getInstallStatus() {
7790 return installStatus;
7791 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007794 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 }
7796
Kenny Rootea6bf362011-01-13 14:53:17 -08007797 /**
7798 * Make a shallow copy of this package settings.
7799 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 public void copyFrom(PackageSettingBase base) {
7801 grantedPermissions = base.grantedPermissions;
7802 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007805 firstInstallTime = base.firstInstallTime;
7806 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 signatures = base.signatures;
7808 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007809 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007810 disabledComponents = base.disabledComponents;
7811 enabledComponents = base.enabledComponents;
7812 enabled = base.enabled;
7813 installStatus = base.installStatus;
7814 }
7815
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007816 boolean enableComponentLP(String componentClassName) {
7817 boolean changed = disabledComponents.remove(componentClassName);
7818 changed |= enabledComponents.add(componentClassName);
7819 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 }
7821
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007822 boolean disableComponentLP(String componentClassName) {
7823 boolean changed = enabledComponents.remove(componentClassName);
7824 changed |= disabledComponents.add(componentClassName);
7825 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 }
7827
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007828 boolean restoreComponentLP(String componentClassName) {
7829 boolean changed = enabledComponents.remove(componentClassName);
7830 changed |= disabledComponents.remove(componentClassName);
7831 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832 }
7833
7834 int currentEnabledStateLP(String componentName) {
7835 if (enabledComponents.contains(componentName)) {
7836 return COMPONENT_ENABLED_STATE_ENABLED;
7837 } else if (disabledComponents.contains(componentName)) {
7838 return COMPONENT_ENABLED_STATE_DISABLED;
7839 } else {
7840 return COMPONENT_ENABLED_STATE_DEFAULT;
7841 }
7842 }
7843 }
7844
7845 /**
7846 * Settings data for a particular package we know about.
7847 */
7848 static final class PackageSetting extends PackageSettingBase {
7849 int userId;
7850 PackageParser.Package pkg;
7851 SharedUserSetting sharedUser;
7852
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007853 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007854 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7855 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7856 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007858
Kenny Rootea6bf362011-01-13 14:53:17 -08007859 /**
7860 * New instance of PackageSetting replicating the original settings.
7861 * Note that it keeps the same PackageParser.Package instance.
7862 */
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007863 PackageSetting(PackageSetting orig) {
Kenny Rootea6bf362011-01-13 14:53:17 -08007864 super(orig);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007865
Kenny Rootea6bf362011-01-13 14:53:17 -08007866 userId = orig.userId;
7867 pkg = orig.pkg;
7868 sharedUser = orig.sharedUser;
Kenny Root91c459e2011-01-11 10:08:01 -08007869 }
7870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 @Override
7872 public String toString() {
7873 return "PackageSetting{"
7874 + Integer.toHexString(System.identityHashCode(this))
7875 + " " + name + "/" + userId + "}";
7876 }
7877 }
7878
7879 /**
7880 * Settings data for a particular shared user ID we know about.
7881 */
7882 static final class SharedUserSetting extends GrantedPermissions {
7883 final String name;
7884 int userId;
7885 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7886 final PackageSignatures signatures = new PackageSignatures();
7887
7888 SharedUserSetting(String _name, int _pkgFlags) {
7889 super(_pkgFlags);
7890 name = _name;
7891 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 @Override
7894 public String toString() {
7895 return "SharedUserSetting{"
7896 + Integer.toHexString(System.identityHashCode(this))
7897 + " " + name + "/" + userId + "}";
7898 }
7899 }
7900
7901 /**
7902 * Holds information about dynamic settings.
7903 */
7904 private static final class Settings {
7905 private final File mSettingsFilename;
7906 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007907 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 private final HashMap<String, PackageSetting> mPackages =
7909 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007910 // List of replaced system applications
7911 final HashMap<String, PackageSetting> mDisabledSysPackages =
7912 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007913
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007914 // These are the last platform API version we were using for
7915 // the apps installed on internal and external storage. It is
7916 // used to grant newer permissions one time during a system upgrade.
7917 int mInternalSdkPlatform;
7918 int mExternalSdkPlatform;
7919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007920 // The user's preferred activities associated with particular intent
7921 // filters.
7922 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7923 new IntentResolver<PreferredActivity, PreferredActivity>() {
7924 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007925 protected String packageForFilter(PreferredActivity filter) {
7926 return filter.mActivity.getPackageName();
7927 }
7928 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007929 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007931 out.print(prefix); out.print(
7932 Integer.toHexString(System.identityHashCode(filter)));
7933 out.print(' ');
7934 out.print(filter.mActivity.flattenToShortString());
7935 out.print(" match=0x");
7936 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007938 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007939 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007940 out.print(prefix); out.print(" ");
7941 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007942 }
7943 }
7944 }
7945 };
7946 private final HashMap<String, SharedUserSetting> mSharedUsers =
7947 new HashMap<String, SharedUserSetting>();
7948 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7949 private final SparseArray<Object> mOtherUserIds =
7950 new SparseArray<Object>();
7951
7952 // For reading/writing settings file.
7953 private final ArrayList<Signature> mPastSignatures =
7954 new ArrayList<Signature>();
7955
7956 // Mapping from permission names to info about them.
7957 final HashMap<String, BasePermission> mPermissions =
7958 new HashMap<String, BasePermission>();
7959
7960 // Mapping from permission tree names to info about them.
7961 final HashMap<String, BasePermission> mPermissionTrees =
7962 new HashMap<String, BasePermission>();
7963
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007964 // Packages that have been uninstalled and still need their external
7965 // storage data deleted.
7966 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7967
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007968 // Packages that have been renamed since they were first installed.
7969 // Keys are the new names of the packages, values are the original
7970 // names. The packages appear everwhere else under their original
7971 // names.
7972 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 private final StringBuilder mReadMessages = new StringBuilder();
7975
7976 private static final class PendingPackage extends PackageSettingBase {
7977 final int sharedId;
7978
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007979 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007980 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7981 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7982 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 this.sharedId = sharedId;
7984 }
7985 }
7986 private final ArrayList<PendingPackage> mPendingPackages
7987 = new ArrayList<PendingPackage>();
7988
7989 Settings() {
7990 File dataDir = Environment.getDataDirectory();
7991 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007992 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7993 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007995 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 FileUtils.setPermissions(systemDir.toString(),
7997 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7998 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7999 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08008000 FileUtils.setPermissions(systemSecureDir.toString(),
8001 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8002 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8003 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008004 mSettingsFilename = new File(systemDir, "packages.xml");
8005 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008006 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008007 }
8008
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008009 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008010 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008011 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008013 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07008014 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 return p;
8016 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008017
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008018 PackageSetting peekPackageLP(String name) {
8019 return mPackages.get(name);
8020 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021 PackageSetting p = mPackages.get(name);
8022 if (p != null && p.codePath.getPath().equals(codePath)) {
8023 return p;
8024 }
8025 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008026 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008029 void setInstallStatus(String pkgName, int status) {
8030 PackageSetting p = mPackages.get(pkgName);
8031 if(p != null) {
8032 if(p.getInstallStatus() != status) {
8033 p.setInstallStatus(status);
8034 }
8035 }
8036 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008037
Jacek Surazski65e13172009-04-28 15:26:38 +02008038 void setInstallerPackageName(String pkgName,
8039 String installerPkgName) {
8040 PackageSetting p = mPackages.get(pkgName);
8041 if(p != null) {
8042 p.setInstallerPackageName(installerPkgName);
8043 }
8044 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008045
Jacek Surazski65e13172009-04-28 15:26:38 +02008046 String getInstallerPackageName(String pkgName) {
8047 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008048 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008049 }
8050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 int getInstallStatus(String pkgName) {
8052 PackageSetting p = mPackages.get(pkgName);
8053 if(p != null) {
8054 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008056 return -1;
8057 }
8058
8059 SharedUserSetting getSharedUserLP(String name,
8060 int pkgFlags, boolean create) {
8061 SharedUserSetting s = mSharedUsers.get(name);
8062 if (s == null) {
8063 if (!create) {
8064 return null;
8065 }
8066 s = new SharedUserSetting(name, pkgFlags);
8067 if (MULTIPLE_APPLICATION_UIDS) {
8068 s.userId = newUserIdLP(s);
8069 } else {
8070 s.userId = FIRST_APPLICATION_UID;
8071 }
8072 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8073 // < 0 means we couldn't assign a userid; fall out and return
8074 // s, which is currently null
8075 if (s.userId >= 0) {
8076 mSharedUsers.put(name, s);
8077 }
8078 }
8079
8080 return s;
8081 }
8082
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008083 boolean disableSystemPackageLP(String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 PackageSetting p = mPackages.get(name);
8085 if(p == null) {
8086 Log.w(TAG, "Package:"+name+" is not an installed package");
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008087 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 }
8089 PackageSetting dp = mDisabledSysPackages.get(name);
8090 // always make sure the system package code and resource paths dont change
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008091 if (dp == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8093 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8094 }
8095 mDisabledSysPackages.put(name, p);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008096
8097 // a little trick... when we install the new package, we don't
8098 // want to modify the existing PackageSetting for the built-in
8099 // version. so at this point we need a new PackageSetting that
Kenny Rootea6bf362011-01-13 14:53:17 -08008100 // is okay to muck with.
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008101 PackageSetting newp = new PackageSetting(p);
8102 replacePackageLP(name, newp);
8103 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008105 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 PackageSetting enableSystemPackageLP(String name) {
8109 PackageSetting p = mDisabledSysPackages.get(name);
8110 if(p == null) {
8111 Log.w(TAG, "Package:"+name+" is not disabled");
8112 return null;
8113 }
8114 // Reset flag in ApplicationInfo object
8115 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8116 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8117 }
Kenny Root806cc132010-09-12 08:34:19 -07008118 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8119 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008120 mDisabledSysPackages.remove(name);
8121 return ret;
8122 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008123
Kenny Root806cc132010-09-12 08:34:19 -07008124 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8125 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126 PackageSetting p = mPackages.get(name);
8127 if (p != null) {
8128 if (p.userId == uid) {
8129 return p;
8130 }
8131 reportSettingsProblem(Log.ERROR,
8132 "Adding duplicate package, keeping first: " + name);
8133 return null;
8134 }
Kenny Root806cc132010-09-12 08:34:19 -07008135 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8136 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 p.userId = uid;
8138 if (addUserIdLP(uid, p, name)) {
8139 mPackages.put(name, p);
8140 return p;
8141 }
8142 return null;
8143 }
8144
8145 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8146 SharedUserSetting s = mSharedUsers.get(name);
8147 if (s != null) {
8148 if (s.userId == uid) {
8149 return s;
8150 }
8151 reportSettingsProblem(Log.ERROR,
8152 "Adding duplicate shared user, keeping first: " + name);
8153 return null;
8154 }
8155 s = new SharedUserSetting(name, pkgFlags);
8156 s.userId = uid;
8157 if (addUserIdLP(uid, s, name)) {
8158 mSharedUsers.put(name, s);
8159 return s;
8160 }
8161 return null;
8162 }
8163
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008164 // Transfer ownership of permissions from one package to another.
8165 private void transferPermissions(String origPkg, String newPkg) {
8166 // Transfer ownership of permissions to the new package.
8167 for (int i=0; i<2; i++) {
8168 HashMap<String, BasePermission> permissions =
8169 i == 0 ? mPermissionTrees : mPermissions;
8170 for (BasePermission bp : permissions.values()) {
8171 if (origPkg.equals(bp.sourcePackage)) {
8172 if (DEBUG_UPGRADE) Log.v(TAG,
8173 "Moving permission " + bp.name
8174 + " from pkg " + bp.sourcePackage
8175 + " to " + newPkg);
8176 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008177 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008178 bp.perm = null;
8179 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008180 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008181 }
8182 bp.uid = 0;
8183 bp.gids = null;
8184 }
8185 }
8186 }
8187 }
8188
8189 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008190 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008191 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 PackageSetting p = mPackages.get(name);
8193 if (p != null) {
8194 if (!p.codePath.equals(codePath)) {
8195 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008196 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008197 // This is an updated system app with versions in both system
8198 // and data partition. Just let the most recent version
8199 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008200 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008201 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008202 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008203 // Just a change in the code path is not an issue, but
8204 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008205 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008206 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008207 /*
8208 * Since we've changed paths, we need to prefer the new
8209 * native library path over the one stored in the
8210 * package settings since we might have moved from
8211 * internal to external storage or vice versa.
8212 */
8213 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008214 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008215 }
8216 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008217 reportSettingsProblem(Log.WARN,
8218 "Package " + name + " shared user changed from "
8219 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8220 + " to "
8221 + (sharedUser != null ? sharedUser.name : "<nothing>")
8222 + "; replacing with new");
8223 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008224 } else {
8225 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8226 // If what we are scanning is a system package, then
8227 // make it so, regardless of whether it was previously
8228 // installed only in the data partition.
8229 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008231 }
8232 }
8233 if (p == null) {
8234 // Create a new PackageSettings entry. this can end up here because
8235 // of code path mismatch or user id mismatch of an updated system partition
8236 if (!create) {
8237 return null;
8238 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008239 if (origPackage != null) {
8240 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008241 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8242 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008243 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8244 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008245 // Note that we will retain the new package's signature so
8246 // that we can keep its data.
8247 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008248 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008249 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008250 p.sharedUser = origPackage.sharedUser;
8251 p.userId = origPackage.userId;
8252 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008253 mRenamedPackages.put(name, origPackage.name);
8254 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008255 // Update new package state.
8256 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008258 p = new PackageSetting(name, realName, codePath, resourcePath,
8259 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008260 p.setTimeStamp(codePath.lastModified());
8261 p.sharedUser = sharedUser;
8262 if (sharedUser != null) {
8263 p.userId = sharedUser.userId;
8264 } else if (MULTIPLE_APPLICATION_UIDS) {
8265 // Clone the setting here for disabled system packages
8266 PackageSetting dis = mDisabledSysPackages.get(name);
8267 if (dis != null) {
8268 // For disabled packages a new setting is created
8269 // from the existing user id. This still has to be
8270 // added to list of user id's
8271 // Copy signatures from previous setting
8272 if (dis.signatures.mSignatures != null) {
8273 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8274 }
8275 p.userId = dis.userId;
8276 // Clone permissions
8277 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008278 // Clone component info
8279 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8280 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8281 // Add new setting to list of user ids
8282 addUserIdLP(p.userId, p, name);
8283 } else {
8284 // Assign new user id
8285 p.userId = newUserIdLP(p);
8286 }
8287 } else {
8288 p.userId = FIRST_APPLICATION_UID;
8289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 }
8291 if (p.userId < 0) {
8292 reportSettingsProblem(Log.WARN,
8293 "Package " + name + " could not be assigned a valid uid");
8294 return null;
8295 }
8296 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008297 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008298 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008299 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008300 }
8301 }
8302 return p;
8303 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008304
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008305 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008306 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008307 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008308 final String codePath = pkg.applicationInfo.sourceDir;
8309 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008310 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008311 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008312 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008313 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008314 p.codePath = new File(codePath);
8315 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008316 }
8317 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008318 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008319 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008320 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008321 p.resourcePath = new File(resourcePath);
8322 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008323 }
Kenny Root85387d72010-08-26 10:13:11 -07008324 // Update the native library path if needed
8325 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8326 if (nativeLibraryPath != null
8327 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8328 p.nativeLibraryPathString = nativeLibraryPath;
8329 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008330 // Update version code if needed
8331 if (pkg.mVersionCode != p.versionCode) {
8332 p.versionCode = pkg.mVersionCode;
8333 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008334 // Update signatures if needed.
8335 if (p.signatures.mSignatures == null) {
8336 p.signatures.assignSignatures(pkg.mSignatures);
8337 }
8338 // If this app defines a shared user id initialize
8339 // the shared user signatures as well.
8340 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8341 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8342 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008343 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8344 }
8345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 // Utility method that adds a PackageSetting to mPackages and
8347 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008348 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008349 SharedUserSetting sharedUser) {
8350 mPackages.put(name, p);
8351 if (sharedUser != null) {
8352 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8353 reportSettingsProblem(Log.ERROR,
8354 "Package " + p.name + " was user "
8355 + p.sharedUser + " but is now " + sharedUser
8356 + "; I am not changing its files so it will probably fail!");
8357 p.sharedUser.packages.remove(p);
8358 } else if (p.userId != sharedUser.userId) {
8359 reportSettingsProblem(Log.ERROR,
8360 "Package " + p.name + " was user id " + p.userId
8361 + " but is now user " + sharedUser
8362 + " with id " + sharedUser.userId
8363 + "; I am not changing its files so it will probably fail!");
8364 }
8365
8366 sharedUser.packages.add(p);
8367 p.sharedUser = sharedUser;
8368 p.userId = sharedUser.userId;
8369 }
8370 }
8371
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008372 /*
8373 * Update the shared user setting when a package using
8374 * specifying the shared user id is removed. The gids
8375 * associated with each permission of the deleted package
8376 * are removed from the shared user's gid list only if its
8377 * not in use by other permissions of packages in the
8378 * shared user setting.
8379 */
8380 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008381 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008382 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 return;
8384 }
8385 // No sharedUserId
8386 if (deletedPs.sharedUser == null) {
8387 return;
8388 }
8389 SharedUserSetting sus = deletedPs.sharedUser;
8390 // Update permissions
8391 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8392 boolean used = false;
8393 if (!sus.grantedPermissions.contains (eachPerm)) {
8394 continue;
8395 }
8396 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008397 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008398 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008399 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008400 used = true;
8401 break;
8402 }
8403 }
8404 if (!used) {
8405 // can safely delete this permission from list
8406 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008407 }
8408 }
8409 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008410 int newGids[] = globalGids;
8411 for (String eachPerm : sus.grantedPermissions) {
8412 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008413 if (bp != null) {
8414 newGids = appendInts(newGids, bp.gids);
8415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 }
8417 sus.gids = newGids;
8418 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008420 private int removePackageLP(String name) {
8421 PackageSetting p = mPackages.get(name);
8422 if (p != null) {
8423 mPackages.remove(name);
8424 if (p.sharedUser != null) {
8425 p.sharedUser.packages.remove(p);
8426 if (p.sharedUser.packages.size() == 0) {
8427 mSharedUsers.remove(p.sharedUser.name);
8428 removeUserIdLP(p.sharedUser.userId);
8429 return p.sharedUser.userId;
8430 }
8431 } else {
8432 removeUserIdLP(p.userId);
8433 return p.userId;
8434 }
8435 }
8436 return -1;
8437 }
8438
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008439 private void replacePackageLP(String name, PackageSetting newp) {
8440 PackageSetting p = mPackages.get(name);
8441 if (p != null) {
8442 if (p.sharedUser != null) {
8443 p.sharedUser.packages.remove(p);
8444 p.sharedUser.packages.add(newp);
8445 } else {
8446 replaceUserIdLP(p.userId, newp);
8447 }
8448 }
8449 mPackages.put(name, newp);
8450 }
8451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008452 private boolean addUserIdLP(int uid, Object obj, Object name) {
8453 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8454 return false;
8455 }
8456
8457 if (uid >= FIRST_APPLICATION_UID) {
8458 int N = mUserIds.size();
8459 final int index = uid - FIRST_APPLICATION_UID;
8460 while (index >= N) {
8461 mUserIds.add(null);
8462 N++;
8463 }
8464 if (mUserIds.get(index) != null) {
8465 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008466 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008467 + " name=" + name);
8468 return false;
8469 }
8470 mUserIds.set(index, obj);
8471 } else {
8472 if (mOtherUserIds.get(uid) != null) {
8473 reportSettingsProblem(Log.ERROR,
8474 "Adding duplicate shared id: " + uid
8475 + " name=" + name);
8476 return false;
8477 }
8478 mOtherUserIds.put(uid, obj);
8479 }
8480 return true;
8481 }
8482
8483 public Object getUserIdLP(int uid) {
8484 if (uid >= FIRST_APPLICATION_UID) {
8485 int N = mUserIds.size();
8486 final int index = uid - FIRST_APPLICATION_UID;
8487 return index < N ? mUserIds.get(index) : null;
8488 } else {
8489 return mOtherUserIds.get(uid);
8490 }
8491 }
8492
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008493 private Set<String> findPackagesWithFlag(int flag) {
8494 Set<String> ret = new HashSet<String>();
8495 for (PackageSetting ps : mPackages.values()) {
8496 // Has to match atleast all the flag bits set on flag
8497 if ((ps.pkgFlags & flag) == flag) {
8498 ret.add(ps.name);
8499 }
8500 }
8501 return ret;
8502 }
8503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 private void removeUserIdLP(int uid) {
8505 if (uid >= FIRST_APPLICATION_UID) {
8506 int N = mUserIds.size();
8507 final int index = uid - FIRST_APPLICATION_UID;
8508 if (index < N) mUserIds.set(index, null);
8509 } else {
8510 mOtherUserIds.remove(uid);
8511 }
8512 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008513
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008514 private void replaceUserIdLP(int uid, Object obj) {
8515 if (uid >= FIRST_APPLICATION_UID) {
8516 int N = mUserIds.size();
8517 final int index = uid - FIRST_APPLICATION_UID;
8518 if (index < N) mUserIds.set(index, obj);
8519 } else {
8520 mOtherUserIds.put(uid, obj);
8521 }
8522 }
8523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 void writeLP() {
8525 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8526
8527 // Keep the old settings around until we know the new ones have
8528 // been successfully written.
8529 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008530 // Presence of backup settings file indicates that we failed
8531 // to persist settings earlier. So preserve the older
8532 // backup for future reference since the current settings
8533 // might have been corrupted.
8534 if (!mBackupSettingsFilename.exists()) {
8535 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008536 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008537 return;
8538 }
8539 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008540 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008541 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 }
8544
8545 mPastSignatures.clear();
8546
8547 try {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008548 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
8549 BufferedOutputStream str = new BufferedOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550
8551 //XmlSerializer serializer = XmlUtils.serializerInstance();
8552 XmlSerializer serializer = new FastXmlSerializer();
8553 serializer.setOutput(str, "utf-8");
8554 serializer.startDocument(null, true);
8555 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8556
8557 serializer.startTag(null, "packages");
8558
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008559 serializer.startTag(null, "last-platform-version");
8560 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8561 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8562 serializer.endTag(null, "last-platform-version");
8563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 serializer.startTag(null, "permission-trees");
8565 for (BasePermission bp : mPermissionTrees.values()) {
8566 writePermission(serializer, bp);
8567 }
8568 serializer.endTag(null, "permission-trees");
8569
8570 serializer.startTag(null, "permissions");
8571 for (BasePermission bp : mPermissions.values()) {
8572 writePermission(serializer, bp);
8573 }
8574 serializer.endTag(null, "permissions");
8575
8576 for (PackageSetting pkg : mPackages.values()) {
8577 writePackage(serializer, pkg);
8578 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8581 writeDisabledSysPackage(serializer, pkg);
8582 }
8583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008584 serializer.startTag(null, "preferred-activities");
8585 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8586 serializer.startTag(null, "item");
8587 pa.writeToXml(serializer);
8588 serializer.endTag(null, "item");
8589 }
8590 serializer.endTag(null, "preferred-activities");
8591
8592 for (SharedUserSetting usr : mSharedUsers.values()) {
8593 serializer.startTag(null, "shared-user");
8594 serializer.attribute(null, "name", usr.name);
8595 serializer.attribute(null, "userId",
8596 Integer.toString(usr.userId));
8597 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8598 serializer.startTag(null, "perms");
8599 for (String name : usr.grantedPermissions) {
8600 serializer.startTag(null, "item");
8601 serializer.attribute(null, "name", name);
8602 serializer.endTag(null, "item");
8603 }
8604 serializer.endTag(null, "perms");
8605 serializer.endTag(null, "shared-user");
8606 }
8607
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008608 if (mPackagesToBeCleaned.size() > 0) {
8609 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8610 serializer.startTag(null, "cleaning-package");
8611 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8612 serializer.endTag(null, "cleaning-package");
8613 }
8614 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008615
8616 if (mRenamedPackages.size() > 0) {
8617 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8618 serializer.startTag(null, "renamed-package");
8619 serializer.attribute(null, "new", e.getKey());
8620 serializer.attribute(null, "old", e.getValue());
8621 serializer.endTag(null, "renamed-package");
8622 }
8623 }
8624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 serializer.endTag(null, "packages");
8626
8627 serializer.endDocument();
8628
8629 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008630 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008631 str.close();
8632
8633 // New settings successfully written, old ones are no longer
8634 // needed.
8635 mBackupSettingsFilename.delete();
8636 FileUtils.setPermissions(mSettingsFilename.toString(),
8637 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8638 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8639 |FileUtils.S_IROTH,
8640 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008641
8642 // Write package list file now, use a JournaledFile.
8643 //
8644 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8645 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8646
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008647 fstr = new FileOutputStream(journal.chooseForWrite());
8648 str = new BufferedOutputStream(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008649 try {
8650 StringBuilder sb = new StringBuilder();
8651 for (PackageSetting pkg : mPackages.values()) {
8652 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008653 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008654 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8655
8656 // Avoid any application that has a space in its path
8657 // or that is handled by the system.
8658 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8659 continue;
8660
8661 // we store on each line the following information for now:
8662 //
8663 // pkgName - package name
8664 // userId - application-specific user id
8665 // debugFlag - 0 or 1 if the package is debuggable.
8666 // dataPath - path to package's data path
8667 //
8668 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8669 //
8670 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8671 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8672 // system/core/run-as/run-as.c
8673 //
8674 sb.setLength(0);
8675 sb.append(ai.packageName);
8676 sb.append(" ");
8677 sb.append((int)ai.uid);
8678 sb.append(isDebug ? " 1 " : " 0 ");
8679 sb.append(dataPath);
8680 sb.append("\n");
8681 str.write(sb.toString().getBytes());
8682 }
8683 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008684 FileUtils.sync(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008685 str.close();
8686 journal.commit();
8687 }
8688 catch (Exception e) {
8689 journal.rollback();
8690 }
8691
8692 FileUtils.setPermissions(mPackageListFilename.toString(),
8693 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8694 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8695 |FileUtils.S_IROTH,
8696 -1, -1);
8697
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008698 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699
8700 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008701 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 -08008702 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008703 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 -08008704 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008705 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008706 if (mSettingsFilename.exists()) {
8707 if (!mSettingsFilename.delete()) {
8708 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8709 }
8710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 //Debug.stopMethodTracing();
8712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008713
8714 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008715 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 serializer.startTag(null, "updated-package");
8717 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008718 if (pkg.realName != null) {
8719 serializer.attribute(null, "realName", pkg.realName);
8720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008721 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008722 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8723 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8724 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008725 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008726 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8727 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8728 }
Kenny Root85387d72010-08-26 10:13:11 -07008729 if (pkg.nativeLibraryPathString != null) {
8730 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8731 }
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 }
8739 serializer.startTag(null, "perms");
8740 if (pkg.sharedUser == null) {
8741 // If this is a shared user, the permissions will
8742 // be written there. We still need to write an
8743 // empty permissions list so permissionsFixed will
8744 // be set.
8745 for (final String name : pkg.grantedPermissions) {
8746 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008747 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008748 // We only need to write signature or system permissions but this wont
8749 // match the semantics of grantedPermissions. So write all permissions.
8750 serializer.startTag(null, "item");
8751 serializer.attribute(null, "name", name);
8752 serializer.endTag(null, "item");
8753 }
8754 }
8755 }
8756 serializer.endTag(null, "perms");
8757 serializer.endTag(null, "updated-package");
8758 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008759
8760 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008761 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008762 serializer.startTag(null, "package");
8763 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008764 if (pkg.realName != null) {
8765 serializer.attribute(null, "realName", pkg.realName);
8766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008767 serializer.attribute(null, "codePath", pkg.codePathString);
8768 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8769 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8770 }
Kenny Root85387d72010-08-26 10:13:11 -07008771 if (pkg.nativeLibraryPathString != null) {
8772 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8773 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008774 serializer.attribute(null, "flags",
8775 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008776 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8777 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8778 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008779 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008780 if (pkg.sharedUser == null) {
8781 serializer.attribute(null, "userId",
8782 Integer.toString(pkg.userId));
8783 } else {
8784 serializer.attribute(null, "sharedUserId",
8785 Integer.toString(pkg.userId));
8786 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008787 if (pkg.uidError) {
8788 serializer.attribute(null, "uidError", "true");
8789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8791 serializer.attribute(null, "enabled",
8792 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8793 ? "true" : "false");
8794 }
8795 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8796 serializer.attribute(null, "installStatus", "false");
8797 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008798 if (pkg.installerPackageName != null) {
8799 serializer.attribute(null, "installer", pkg.installerPackageName);
8800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8802 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8803 serializer.startTag(null, "perms");
8804 if (pkg.sharedUser == null) {
8805 // If this is a shared user, the permissions will
8806 // be written there. We still need to write an
8807 // empty permissions list so permissionsFixed will
8808 // be set.
8809 for (final String name : pkg.grantedPermissions) {
8810 serializer.startTag(null, "item");
8811 serializer.attribute(null, "name", name);
8812 serializer.endTag(null, "item");
8813 }
8814 }
8815 serializer.endTag(null, "perms");
8816 }
8817 if (pkg.disabledComponents.size() > 0) {
8818 serializer.startTag(null, "disabled-components");
8819 for (final String name : pkg.disabledComponents) {
8820 serializer.startTag(null, "item");
8821 serializer.attribute(null, "name", name);
8822 serializer.endTag(null, "item");
8823 }
8824 serializer.endTag(null, "disabled-components");
8825 }
8826 if (pkg.enabledComponents.size() > 0) {
8827 serializer.startTag(null, "enabled-components");
8828 for (final String name : pkg.enabledComponents) {
8829 serializer.startTag(null, "item");
8830 serializer.attribute(null, "name", name);
8831 serializer.endTag(null, "item");
8832 }
8833 serializer.endTag(null, "enabled-components");
8834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 serializer.endTag(null, "package");
8837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008839 void writePermission(XmlSerializer serializer, BasePermission bp)
8840 throws XmlPullParserException, java.io.IOException {
8841 if (bp.type != BasePermission.TYPE_BUILTIN
8842 && bp.sourcePackage != null) {
8843 serializer.startTag(null, "item");
8844 serializer.attribute(null, "name", bp.name);
8845 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008846 if (bp.protectionLevel !=
8847 PermissionInfo.PROTECTION_NORMAL) {
8848 serializer.attribute(null, "protection",
8849 Integer.toString(bp.protectionLevel));
8850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008851 if (DEBUG_SETTINGS) Log.v(TAG,
8852 "Writing perm: name=" + bp.name + " type=" + bp.type);
8853 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8854 PermissionInfo pi = bp.perm != null ? bp.perm.info
8855 : bp.pendingInfo;
8856 if (pi != null) {
8857 serializer.attribute(null, "type", "dynamic");
8858 if (pi.icon != 0) {
8859 serializer.attribute(null, "icon",
8860 Integer.toString(pi.icon));
8861 }
8862 if (pi.nonLocalizedLabel != null) {
8863 serializer.attribute(null, "label",
8864 pi.nonLocalizedLabel.toString());
8865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 }
8867 }
8868 serializer.endTag(null, "item");
8869 }
8870 }
8871
8872 String getReadMessagesLP() {
8873 return mReadMessages.toString();
8874 }
8875
Oscar Montemayora8529f62009-11-18 10:14:20 -08008876 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008877 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8878 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008879 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 while(its.hasNext()) {
8881 String key = its.next();
8882 PackageSetting ps = mPackages.get(key);
8883 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008884 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 }
8886 }
8887 return ret;
8888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 boolean readLP() {
8891 FileInputStream str = null;
8892 if (mBackupSettingsFilename.exists()) {
8893 try {
8894 str = new FileInputStream(mBackupSettingsFilename);
8895 mReadMessages.append("Reading from backup settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008896 reportSettingsProblem(Log.INFO, "Need to read from backup settings file");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008897 if (mSettingsFilename.exists()) {
8898 // If both the backup and settings file exist, we
8899 // ignore the settings since it might have been
8900 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008901 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008902 mSettingsFilename.delete();
8903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904 } catch (java.io.IOException e) {
8905 // We'll try for the normal settings file.
8906 }
8907 }
8908
8909 mPastSignatures.clear();
8910
8911 try {
8912 if (str == null) {
8913 if (!mSettingsFilename.exists()) {
8914 mReadMessages.append("No settings file found\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008915 reportSettingsProblem(Log.INFO, "No settings file; creating initial state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008916 return false;
8917 }
8918 str = new FileInputStream(mSettingsFilename);
8919 }
8920 XmlPullParser parser = Xml.newPullParser();
8921 parser.setInput(str, null);
8922
8923 int type;
8924 while ((type=parser.next()) != XmlPullParser.START_TAG
8925 && type != XmlPullParser.END_DOCUMENT) {
8926 ;
8927 }
8928
8929 if (type != XmlPullParser.START_TAG) {
8930 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008931 reportSettingsProblem(Log.WARN, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 return false;
8933 }
8934
8935 int outerDepth = parser.getDepth();
8936 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8937 && (type != XmlPullParser.END_TAG
8938 || parser.getDepth() > outerDepth)) {
8939 if (type == XmlPullParser.END_TAG
8940 || type == XmlPullParser.TEXT) {
8941 continue;
8942 }
8943
8944 String tagName = parser.getName();
8945 if (tagName.equals("package")) {
8946 readPackageLP(parser);
8947 } else if (tagName.equals("permissions")) {
8948 readPermissionsLP(mPermissions, parser);
8949 } else if (tagName.equals("permission-trees")) {
8950 readPermissionsLP(mPermissionTrees, parser);
8951 } else if (tagName.equals("shared-user")) {
8952 readSharedUserLP(parser);
8953 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008954 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 } else if (tagName.equals("preferred-activities")) {
8956 readPreferredActivitiesLP(parser);
8957 } else if(tagName.equals("updated-package")) {
8958 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008959 } else if (tagName.equals("cleaning-package")) {
8960 String name = parser.getAttributeValue(null, "name");
8961 if (name != null) {
8962 mPackagesToBeCleaned.add(name);
8963 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008964 } else if (tagName.equals("renamed-package")) {
8965 String nname = parser.getAttributeValue(null, "new");
8966 String oname = parser.getAttributeValue(null, "old");
8967 if (nname != null && oname != null) {
8968 mRenamedPackages.put(nname, oname);
8969 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008970 } else if (tagName.equals("last-platform-version")) {
8971 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8972 try {
8973 String internal = parser.getAttributeValue(null, "internal");
8974 if (internal != null) {
8975 mInternalSdkPlatform = Integer.parseInt(internal);
8976 }
8977 String external = parser.getAttributeValue(null, "external");
8978 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008979 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008980 }
8981 } catch (NumberFormatException e) {
8982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008983 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008984 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 + parser.getName());
8986 XmlUtils.skipCurrentTag(parser);
8987 }
8988 }
8989
8990 str.close();
8991
8992 } catch(XmlPullParserException e) {
8993 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07008994 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008995 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008996
8997 } catch(java.io.IOException e) {
8998 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07008999 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009000 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001
9002 }
9003
9004 int N = mPendingPackages.size();
9005 for (int i=0; i<N; i++) {
9006 final PendingPackage pp = mPendingPackages.get(i);
9007 Object idObj = getUserIdLP(pp.sharedId);
9008 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009009 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07009010 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
9011 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 if (p == null) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07009013 reportSettingsProblem(Log.WARN, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014 + pp.name);
9015 continue;
9016 }
9017 p.copyFrom(pp);
9018 } else if (idObj != null) {
9019 String msg = "Bad package setting: package " + pp.name
9020 + " has shared uid " + pp.sharedId
9021 + " that is not a shared uid\n";
9022 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009023 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 } else {
9025 String msg = "Bad package setting: package " + pp.name
9026 + " has shared uid " + pp.sharedId
9027 + " that is not defined\n";
9028 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009029 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009030 }
9031 }
9032 mPendingPackages.clear();
9033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 mReadMessages.append("Read completed successfully: "
9035 + mPackages.size() + " packages, "
9036 + mSharedUsers.size() + " shared uids\n");
9037
9038 return true;
9039 }
9040
9041 private int readInt(XmlPullParser parser, String ns, String name,
9042 int defValue) {
9043 String v = parser.getAttributeValue(ns, name);
9044 try {
9045 if (v == null) {
9046 return defValue;
9047 }
9048 return Integer.parseInt(v);
9049 } catch (NumberFormatException e) {
9050 reportSettingsProblem(Log.WARN,
9051 "Error in package manager settings: attribute " +
9052 name + " has bad integer value " + v + " at "
9053 + parser.getPositionDescription());
9054 }
9055 return defValue;
9056 }
9057
9058 private void readPermissionsLP(HashMap<String, BasePermission> out,
9059 XmlPullParser parser)
9060 throws IOException, XmlPullParserException {
9061 int outerDepth = parser.getDepth();
9062 int type;
9063 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9064 && (type != XmlPullParser.END_TAG
9065 || parser.getDepth() > outerDepth)) {
9066 if (type == XmlPullParser.END_TAG
9067 || type == XmlPullParser.TEXT) {
9068 continue;
9069 }
9070
9071 String tagName = parser.getName();
9072 if (tagName.equals("item")) {
9073 String name = parser.getAttributeValue(null, "name");
9074 String sourcePackage = parser.getAttributeValue(null, "package");
9075 String ptype = parser.getAttributeValue(null, "type");
9076 if (name != null && sourcePackage != null) {
9077 boolean dynamic = "dynamic".equals(ptype);
9078 BasePermission bp = new BasePermission(name, sourcePackage,
9079 dynamic
9080 ? BasePermission.TYPE_DYNAMIC
9081 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009082 bp.protectionLevel = readInt(parser, null, "protection",
9083 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 if (dynamic) {
9085 PermissionInfo pi = new PermissionInfo();
9086 pi.packageName = sourcePackage.intern();
9087 pi.name = name.intern();
9088 pi.icon = readInt(parser, null, "icon", 0);
9089 pi.nonLocalizedLabel = parser.getAttributeValue(
9090 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009091 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 bp.pendingInfo = pi;
9093 }
9094 out.put(bp.name, bp);
9095 } else {
9096 reportSettingsProblem(Log.WARN,
9097 "Error in package manager settings: permissions has"
9098 + " no name at " + parser.getPositionDescription());
9099 }
9100 } else {
9101 reportSettingsProblem(Log.WARN,
9102 "Unknown element reading permissions: "
9103 + parser.getName() + " at "
9104 + parser.getPositionDescription());
9105 }
9106 XmlUtils.skipCurrentTag(parser);
9107 }
9108 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009110 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009111 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009112 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009113 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009114 String codePathStr = parser.getAttributeValue(null, "codePath");
9115 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009116 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009117 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009118 resourcePathStr = codePathStr;
9119 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009120 String version = parser.getAttributeValue(null, "version");
9121 int versionCode = 0;
9122 if (version != null) {
9123 try {
9124 versionCode = Integer.parseInt(version);
9125 } catch (NumberFormatException e) {
9126 }
9127 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 int pkgFlags = 0;
9130 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009131 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9132 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009133 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009134 if (timeStampStr != null) {
9135 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009136 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009137 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009138 } catch (NumberFormatException e) {
9139 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009140 } else {
9141 timeStampStr = parser.getAttributeValue(null, "ts");
9142 if (timeStampStr != null) {
9143 try {
9144 long timeStamp = Long.parseLong(timeStampStr);
9145 ps.setTimeStamp(timeStamp);
9146 } catch (NumberFormatException e) {
9147 }
9148 }
9149 }
9150 timeStampStr = parser.getAttributeValue(null, "it");
9151 if (timeStampStr != null) {
9152 try {
9153 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9154 } catch (NumberFormatException e) {
9155 }
9156 }
9157 timeStampStr = parser.getAttributeValue(null, "ut");
9158 if (timeStampStr != null) {
9159 try {
9160 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9161 } catch (NumberFormatException e) {
9162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009163 }
9164 String idStr = parser.getAttributeValue(null, "userId");
9165 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9166 if(ps.userId <= 0) {
9167 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9168 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9169 }
9170 int outerDepth = parser.getDepth();
9171 int type;
9172 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9173 && (type != XmlPullParser.END_TAG
9174 || parser.getDepth() > outerDepth)) {
9175 if (type == XmlPullParser.END_TAG
9176 || type == XmlPullParser.TEXT) {
9177 continue;
9178 }
9179
9180 String tagName = parser.getName();
9181 if (tagName.equals("perms")) {
9182 readGrantedPermissionsLP(parser,
9183 ps.grantedPermissions);
9184 } else {
9185 reportSettingsProblem(Log.WARN,
9186 "Unknown element under <updated-package>: "
9187 + parser.getName());
9188 XmlUtils.skipCurrentTag(parser);
9189 }
9190 }
9191 mDisabledSysPackages.put(name, ps);
9192 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194 private void readPackageLP(XmlPullParser parser)
9195 throws XmlPullParserException, IOException {
9196 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009197 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198 String idStr = null;
9199 String sharedIdStr = null;
9200 String codePathStr = null;
9201 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009202 String nativeLibraryPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009203 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009204 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009205 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009206 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009207 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009208 long firstInstallTime = 0;
9209 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009210 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009211 String version = null;
9212 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213 try {
9214 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009215 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009216 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009217 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009218 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9219 codePathStr = parser.getAttributeValue(null, "codePath");
9220 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009221 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009222 version = parser.getAttributeValue(null, "version");
9223 if (version != null) {
9224 try {
9225 versionCode = Integer.parseInt(version);
9226 } catch (NumberFormatException e) {
9227 }
9228 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009229 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009230
9231 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009232 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009233 try {
9234 pkgFlags = Integer.parseInt(systemStr);
9235 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009236 }
9237 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009238 // For backward compatibility
9239 systemStr = parser.getAttributeValue(null, "system");
9240 if (systemStr != null) {
9241 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9242 } else {
9243 // Old settings that don't specify system... just treat
9244 // them as system, good enough.
9245 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009247 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009248 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009249 if (timeStampStr != null) {
9250 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009251 timeStamp = Long.parseLong(timeStampStr, 16);
9252 } catch (NumberFormatException e) {
9253 }
9254 } else {
9255 timeStampStr = parser.getAttributeValue(null, "ts");
9256 if (timeStampStr != null) {
9257 try {
9258 timeStamp = Long.parseLong(timeStampStr);
9259 } catch (NumberFormatException e) {
9260 }
9261 }
9262 }
9263 timeStampStr = parser.getAttributeValue(null, "it");
9264 if (timeStampStr != null) {
9265 try {
9266 firstInstallTime = Long.parseLong(timeStampStr, 16);
9267 } catch (NumberFormatException e) {
9268 }
9269 }
9270 timeStampStr = parser.getAttributeValue(null, "ut");
9271 if (timeStampStr != null) {
9272 try {
9273 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009274 } catch (NumberFormatException e) {
9275 }
9276 }
9277 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9278 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9279 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9280 if (resourcePathStr == null) {
9281 resourcePathStr = codePathStr;
9282 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009283 if (realName != null) {
9284 realName = realName.intern();
9285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 if (name == null) {
9287 reportSettingsProblem(Log.WARN,
9288 "Error in package manager settings: <package> has no name at "
9289 + parser.getPositionDescription());
9290 } else if (codePathStr == null) {
9291 reportSettingsProblem(Log.WARN,
9292 "Error in package manager settings: <package> has no codePath at "
9293 + parser.getPositionDescription());
9294 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009295 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9296 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9297 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009298 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9299 + ": userId=" + userId + " pkg=" + packageSetting);
9300 if (packageSetting == null) {
9301 reportSettingsProblem(Log.ERROR,
9302 "Failure adding uid " + userId
9303 + " while parsing settings at "
9304 + parser.getPositionDescription());
9305 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009306 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009307 packageSetting.firstInstallTime = firstInstallTime;
9308 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009309 }
9310 } else if (sharedIdStr != null) {
9311 userId = sharedIdStr != null
9312 ? Integer.parseInt(sharedIdStr) : 0;
9313 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009314 packageSetting = new PendingPackage(name.intern(), realName,
9315 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009316 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009317 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009318 packageSetting.firstInstallTime = firstInstallTime;
9319 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009320 mPendingPackages.add((PendingPackage) packageSetting);
9321 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9322 + ": sharedUserId=" + userId + " pkg="
9323 + packageSetting);
9324 } else {
9325 reportSettingsProblem(Log.WARN,
9326 "Error in package manager settings: package "
9327 + name + " has bad sharedId " + sharedIdStr
9328 + " at " + parser.getPositionDescription());
9329 }
9330 } else {
9331 reportSettingsProblem(Log.WARN,
9332 "Error in package manager settings: package "
9333 + name + " has bad userId " + idStr + " at "
9334 + parser.getPositionDescription());
9335 }
9336 } catch (NumberFormatException e) {
9337 reportSettingsProblem(Log.WARN,
9338 "Error in package manager settings: package "
9339 + name + " has bad userId " + idStr + " at "
9340 + parser.getPositionDescription());
9341 }
9342 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009343 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009344 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009345 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 final String enabledStr = parser.getAttributeValue(null, "enabled");
9347 if (enabledStr != null) {
9348 if (enabledStr.equalsIgnoreCase("true")) {
9349 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9350 } else if (enabledStr.equalsIgnoreCase("false")) {
9351 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9352 } else if (enabledStr.equalsIgnoreCase("default")) {
9353 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9354 } else {
9355 reportSettingsProblem(Log.WARN,
9356 "Error in package manager settings: package "
9357 + name + " has bad enabled value: " + idStr
9358 + " at " + parser.getPositionDescription());
9359 }
9360 } else {
9361 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9362 }
9363 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9364 if (installStatusStr != null) {
9365 if (installStatusStr.equalsIgnoreCase("false")) {
9366 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9367 } else {
9368 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9369 }
9370 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009372 int outerDepth = parser.getDepth();
9373 int type;
9374 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9375 && (type != XmlPullParser.END_TAG
9376 || parser.getDepth() > outerDepth)) {
9377 if (type == XmlPullParser.END_TAG
9378 || type == XmlPullParser.TEXT) {
9379 continue;
9380 }
9381
9382 String tagName = parser.getName();
9383 if (tagName.equals("disabled-components")) {
9384 readDisabledComponentsLP(packageSetting, parser);
9385 } else if (tagName.equals("enabled-components")) {
9386 readEnabledComponentsLP(packageSetting, parser);
9387 } else if (tagName.equals("sigs")) {
9388 packageSetting.signatures.readXml(parser, mPastSignatures);
9389 } else if (tagName.equals("perms")) {
9390 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009391 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009392 packageSetting.permissionsFixed = true;
9393 } else {
9394 reportSettingsProblem(Log.WARN,
9395 "Unknown element under <package>: "
9396 + parser.getName());
9397 XmlUtils.skipCurrentTag(parser);
9398 }
9399 }
9400 } else {
9401 XmlUtils.skipCurrentTag(parser);
9402 }
9403 }
9404
9405 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9406 XmlPullParser parser)
9407 throws IOException, XmlPullParserException {
9408 int outerDepth = parser.getDepth();
9409 int type;
9410 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9411 && (type != XmlPullParser.END_TAG
9412 || parser.getDepth() > outerDepth)) {
9413 if (type == XmlPullParser.END_TAG
9414 || type == XmlPullParser.TEXT) {
9415 continue;
9416 }
9417
9418 String tagName = parser.getName();
9419 if (tagName.equals("item")) {
9420 String name = parser.getAttributeValue(null, "name");
9421 if (name != null) {
9422 packageSetting.disabledComponents.add(name.intern());
9423 } else {
9424 reportSettingsProblem(Log.WARN,
9425 "Error in package manager settings: <disabled-components> has"
9426 + " no name at " + parser.getPositionDescription());
9427 }
9428 } else {
9429 reportSettingsProblem(Log.WARN,
9430 "Unknown element under <disabled-components>: "
9431 + parser.getName());
9432 }
9433 XmlUtils.skipCurrentTag(parser);
9434 }
9435 }
9436
9437 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9438 XmlPullParser parser)
9439 throws IOException, XmlPullParserException {
9440 int outerDepth = parser.getDepth();
9441 int type;
9442 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9443 && (type != XmlPullParser.END_TAG
9444 || parser.getDepth() > outerDepth)) {
9445 if (type == XmlPullParser.END_TAG
9446 || type == XmlPullParser.TEXT) {
9447 continue;
9448 }
9449
9450 String tagName = parser.getName();
9451 if (tagName.equals("item")) {
9452 String name = parser.getAttributeValue(null, "name");
9453 if (name != null) {
9454 packageSetting.enabledComponents.add(name.intern());
9455 } else {
9456 reportSettingsProblem(Log.WARN,
9457 "Error in package manager settings: <enabled-components> has"
9458 + " no name at " + parser.getPositionDescription());
9459 }
9460 } else {
9461 reportSettingsProblem(Log.WARN,
9462 "Unknown element under <enabled-components>: "
9463 + parser.getName());
9464 }
9465 XmlUtils.skipCurrentTag(parser);
9466 }
9467 }
9468
9469 private void readSharedUserLP(XmlPullParser parser)
9470 throws XmlPullParserException, IOException {
9471 String name = null;
9472 String idStr = null;
9473 int pkgFlags = 0;
9474 SharedUserSetting su = null;
9475 try {
9476 name = parser.getAttributeValue(null, "name");
9477 idStr = parser.getAttributeValue(null, "userId");
9478 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9479 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9480 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9481 }
9482 if (name == null) {
9483 reportSettingsProblem(Log.WARN,
9484 "Error in package manager settings: <shared-user> has no name at "
9485 + parser.getPositionDescription());
9486 } else if (userId == 0) {
9487 reportSettingsProblem(Log.WARN,
9488 "Error in package manager settings: shared-user "
9489 + name + " has bad userId " + idStr + " at "
9490 + parser.getPositionDescription());
9491 } else {
9492 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9493 reportSettingsProblem(Log.ERROR,
9494 "Occurred while parsing settings at "
9495 + parser.getPositionDescription());
9496 }
9497 }
9498 } catch (NumberFormatException e) {
9499 reportSettingsProblem(Log.WARN,
9500 "Error in package manager settings: package "
9501 + name + " has bad userId " + idStr + " at "
9502 + parser.getPositionDescription());
9503 };
9504
9505 if (su != null) {
9506 int outerDepth = parser.getDepth();
9507 int type;
9508 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9509 && (type != XmlPullParser.END_TAG
9510 || parser.getDepth() > outerDepth)) {
9511 if (type == XmlPullParser.END_TAG
9512 || type == XmlPullParser.TEXT) {
9513 continue;
9514 }
9515
9516 String tagName = parser.getName();
9517 if (tagName.equals("sigs")) {
9518 su.signatures.readXml(parser, mPastSignatures);
9519 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009520 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009521 } else {
9522 reportSettingsProblem(Log.WARN,
9523 "Unknown element under <shared-user>: "
9524 + parser.getName());
9525 XmlUtils.skipCurrentTag(parser);
9526 }
9527 }
9528
9529 } else {
9530 XmlUtils.skipCurrentTag(parser);
9531 }
9532 }
9533
9534 private void readGrantedPermissionsLP(XmlPullParser parser,
9535 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9536 int outerDepth = parser.getDepth();
9537 int type;
9538 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9539 && (type != XmlPullParser.END_TAG
9540 || parser.getDepth() > outerDepth)) {
9541 if (type == XmlPullParser.END_TAG
9542 || type == XmlPullParser.TEXT) {
9543 continue;
9544 }
9545
9546 String tagName = parser.getName();
9547 if (tagName.equals("item")) {
9548 String name = parser.getAttributeValue(null, "name");
9549 if (name != null) {
9550 outPerms.add(name.intern());
9551 } else {
9552 reportSettingsProblem(Log.WARN,
9553 "Error in package manager settings: <perms> has"
9554 + " no name at " + parser.getPositionDescription());
9555 }
9556 } else {
9557 reportSettingsProblem(Log.WARN,
9558 "Unknown element under <perms>: "
9559 + parser.getName());
9560 }
9561 XmlUtils.skipCurrentTag(parser);
9562 }
9563 }
9564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009565 private void readPreferredActivitiesLP(XmlPullParser parser)
9566 throws XmlPullParserException, IOException {
9567 int outerDepth = parser.getDepth();
9568 int type;
9569 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9570 && (type != XmlPullParser.END_TAG
9571 || parser.getDepth() > outerDepth)) {
9572 if (type == XmlPullParser.END_TAG
9573 || type == XmlPullParser.TEXT) {
9574 continue;
9575 }
9576
9577 String tagName = parser.getName();
9578 if (tagName.equals("item")) {
9579 PreferredActivity pa = new PreferredActivity(parser);
9580 if (pa.mParseError == null) {
9581 mPreferredActivities.addFilter(pa);
9582 } else {
9583 reportSettingsProblem(Log.WARN,
9584 "Error in package manager settings: <preferred-activity> "
9585 + pa.mParseError + " at "
9586 + parser.getPositionDescription());
9587 }
9588 } else {
9589 reportSettingsProblem(Log.WARN,
9590 "Unknown element under <preferred-activities>: "
9591 + parser.getName());
9592 XmlUtils.skipCurrentTag(parser);
9593 }
9594 }
9595 }
9596
9597 // Returns -1 if we could not find an available UserId to assign
9598 private int newUserIdLP(Object obj) {
9599 // Let's be stupidly inefficient for now...
9600 final int N = mUserIds.size();
9601 for (int i=0; i<N; i++) {
9602 if (mUserIds.get(i) == null) {
9603 mUserIds.set(i, obj);
9604 return FIRST_APPLICATION_UID + i;
9605 }
9606 }
9607
9608 // None left?
9609 if (N >= MAX_APPLICATION_UIDS) {
9610 return -1;
9611 }
9612
9613 mUserIds.add(obj);
9614 return FIRST_APPLICATION_UID + N;
9615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009617 public PackageSetting getDisabledSystemPkg(String name) {
9618 synchronized(mPackages) {
9619 PackageSetting ps = mDisabledSysPackages.get(name);
9620 return ps;
9621 }
9622 }
9623
9624 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009625 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9626 return true;
9627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009628 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9629 if (Config.LOGV) {
9630 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9631 + " componentName = " + componentInfo.name);
9632 Log.v(TAG, "enabledComponents: "
9633 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9634 Log.v(TAG, "disabledComponents: "
9635 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9636 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009637 if (packageSettings == null) {
9638 if (false) {
9639 Log.w(TAG, "WAITING FOR DEBUGGER");
9640 Debug.waitForDebugger();
9641 Log.i(TAG, "We will crash!");
9642 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009643 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009644 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009645 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9646 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9647 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9648 return false;
9649 }
9650 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9651 return true;
9652 }
9653 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9654 return false;
9655 }
9656 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009657 }
9658 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009659
9660 // ------- apps on sdcard specific code -------
9661 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009662 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9663 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9664 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009665 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009666
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009667 private String getEncryptKey() {
9668 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009669 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9670 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009671 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009672 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9673 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009674 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009675 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009676 return null;
9677 }
9678 }
9679 return sdEncKey;
9680 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009681 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009682 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009683 } catch (IOException ioe) {
9684 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9685 + ioe);
9686 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009687 }
Rich Cannings8d578832010-09-09 15:12:40 -07009688
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009689 }
9690
Kenny Rootc78a8072010-07-27 15:18:38 -07009691 /* package */ static String getTempContainerId() {
9692 int tmpIdx = 1;
9693 String list[] = PackageHelper.getSecureContainerList();
9694 if (list != null) {
9695 for (final String name : list) {
9696 // Ignore null and non-temporary container entries
9697 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9698 continue;
9699 }
9700
9701 String subStr = name.substring(mTempContainerPrefix.length());
9702 try {
9703 int cid = Integer.parseInt(subStr);
9704 if (cid >= tmpIdx) {
9705 tmpIdx = cid + 1;
9706 }
9707 } catch (NumberFormatException e) {
9708 }
9709 }
9710 }
9711 return mTempContainerPrefix + tmpIdx;
9712 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009713
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009714 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009715 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009716 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009717 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9718 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9719 throw new SecurityException("Media status can only be updated by the system");
9720 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009721 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009722 Log.i(TAG, "Updating external media status from " +
9723 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9724 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009725 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9726 mediaStatus+", mMediaMounted=" + mMediaMounted);
9727 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009728 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9729 reportStatus ? 1 : 0, -1);
9730 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009731 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009732 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009733 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009734 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009735 // Queue up an async operation since the package installation may take a little while.
9736 mHandler.post(new Runnable() {
9737 public void run() {
9738 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009739 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009740 }
9741 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009742 }
9743
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009744 /*
9745 * Collect information of applications on external media, map them
9746 * against existing containers and update information based on current
9747 * mount status. Please note that we always have to report status
9748 * if reportStatus has been set to true especially when unloading packages.
9749 */
9750 private void updateExternalMediaStatusInner(boolean mediaStatus,
9751 boolean reportStatus) {
9752 // Collection of uids
9753 int uidArr[] = null;
9754 // Collection of stale containers
9755 HashSet<String> removeCids = new HashSet<String>();
9756 // Collection of packages on external media with valid containers.
9757 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9758 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009759 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009760 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009761 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009762 } else {
9763 // Process list of secure containers and categorize them
9764 // as active or stale based on their package internal state.
9765 int uidList[] = new int[list.length];
9766 int num = 0;
9767 synchronized (mPackages) {
9768 for (String cid : list) {
9769 SdInstallArgs args = new SdInstallArgs(cid);
9770 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009771 String pkgName = args.getPackageName();
9772 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009773 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9774 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009775 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009776 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009777 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9778 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009779 // The package status is changed only if the code path
9780 // matches between settings and the container id.
9781 if (ps != null && ps.codePathString != null &&
9782 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009783 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9784 " corresponds to pkg : " + pkgName +
9785 " at code path: " + ps.codePathString);
9786 // We do have a valid package installed on sdcard
9787 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009788 int uid = ps.userId;
9789 if (uid != -1) {
9790 uidList[num++] = uid;
9791 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009792 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009793 // Stale container on sdcard. Just delete
9794 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9795 removeCids.add(cid);
9796 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009797 }
9798 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009799
9800 if (num > 0) {
9801 // Sort uid list
9802 Arrays.sort(uidList, 0, num);
9803 // Throw away duplicates
9804 uidArr = new int[num];
9805 uidArr[0] = uidList[0];
9806 int di = 0;
9807 for (int i = 1; i < num; i++) {
9808 if (uidList[i-1] != uidList[i]) {
9809 uidArr[di++] = uidList[i];
9810 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009811 }
9812 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009813 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009814 // Process packages with valid entries.
9815 if (mediaStatus) {
9816 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009817 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009818 startCleaningPackages();
9819 } else {
9820 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009821 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009822 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009823 }
9824
9825 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009826 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009827 int size = pkgList.size();
9828 if (size > 0) {
9829 // Send broadcasts here
9830 Bundle extras = new Bundle();
9831 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9832 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009833 if (uidArr != null) {
9834 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9835 }
9836 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9837 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009838 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009839 }
9840 }
9841
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009842 /*
9843 * Look at potentially valid container ids from processCids
9844 * If package information doesn't match the one on record
9845 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009846 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009847 */
9848 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009849 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009850 ArrayList<String> pkgList = new ArrayList<String>();
9851 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009852 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009853 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009854 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009855 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9856 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009857 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009858 try {
9859 // Make sure there are no container errors first.
9860 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9861 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009862 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009863 " when installing from sdcard");
9864 continue;
9865 }
9866 // Check code path here.
9867 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009868 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009869 " does not match one in settings " + codePath);
9870 continue;
9871 }
9872 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009873 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009874 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009875 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009876 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009877 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009878 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009879 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009880 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009881 retCode = PackageManager.INSTALL_SUCCEEDED;
9882 pkgList.add(pkg.packageName);
9883 // Post process args
9884 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9885 }
9886 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009887 Slog.i(TAG, "Failed to install pkg from " +
9888 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009889 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009890 }
9891
9892 } finally {
9893 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9894 // Don't destroy container here. Wait till gc clears things up.
9895 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009896 }
9897 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009898 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009899 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009900 // If the platform SDK has changed since the last time we booted,
9901 // we need to re-grant app permission to catch any new ones that
9902 // appear. This is really a hack, and means that apps can in some
9903 // cases get permissions that the user didn't initially explicitly
9904 // allow... it would be nice to have some better way to handle
9905 // this situation.
9906 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9907 != mSdkVersion;
9908 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9909 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9910 + "; regranting permissions for external storage");
9911 mSettings.mExternalSdkPlatform = mSdkVersion;
9912
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009913 // Make sure group IDs have been assigned, and any permission
9914 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009915 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009916 // Persist settings
9917 mSettings.writeLP();
9918 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009919 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009920 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009921 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009922 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009923 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009924 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009925 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009926 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009927 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009928 if (removeCids != null) {
9929 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009930 if (cid.startsWith(mTempContainerPrefix)) {
9931 Log.i(TAG, "Destroying stale temporary container " + cid);
9932 PackageHelper.destroySdDir(cid);
9933 } else {
9934 Log.w(TAG, "Container " + cid + " is stale");
9935 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009936 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009937 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009938 }
9939
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009940 /*
9941 * Utility method to unload a list of specified containers
9942 */
9943 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9944 // Just unmount all valid containers.
9945 for (SdInstallArgs arg : cidArgs) {
9946 synchronized (mInstallLock) {
9947 arg.doPostDeleteLI(false);
9948 }
9949 }
9950 }
9951
9952 /*
9953 * Unload packages mounted on external media. This involves deleting
9954 * package data from internal structures, sending broadcasts about
9955 * diabled packages, gc'ing to free up references, unmounting all
9956 * secure containers corresponding to packages on external media, and
9957 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9958 * Please note that we always have to post this message if status has
9959 * been requested no matter what.
9960 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009961 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009962 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009963 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009964 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009965 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009966 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009967 for (SdInstallArgs args : keys) {
9968 String cid = args.cid;
9969 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009970 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009971 // Delete package internally
9972 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9973 synchronized (mInstallLock) {
9974 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009975 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009976 if (res) {
9977 pkgList.add(pkgName);
9978 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009979 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009980 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009981 }
9982 }
9983 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009984
9985 synchronized (mPackages) {
9986 // We didn't update the settings after removing each package;
9987 // write them now for all packages.
9988 mSettings.writeLP();
9989 }
9990
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009991 // We have to absolutely send UPDATED_MEDIA_STATUS only
9992 // after confirming that all the receivers processed the ordered
9993 // broadcast when packages get disabled, force a gc to clean things up.
9994 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009995 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009996 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9997 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9998 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009999 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10000 reportStatus ? 1 : 0, 1, keys);
10001 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010002 }
10003 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010004 } else {
10005 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10006 reportStatus ? 1 : 0, -1, keys);
10007 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010008 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -080010009 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010010
10011 public void movePackage(final String packageName,
10012 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010013 mContext.enforceCallingOrSelfPermission(
10014 android.Manifest.permission.MOVE_PACKAGE, null);
10015 int returnCode = PackageManager.MOVE_SUCCEEDED;
10016 int currFlags = 0;
10017 int newFlags = 0;
10018 synchronized (mPackages) {
10019 PackageParser.Package pkg = mPackages.get(packageName);
10020 if (pkg == null) {
10021 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010022 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010023 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -070010024 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010025 Slog.w(TAG, "Cannot move system application");
10026 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -070010027 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010028 Slog.w(TAG, "Cannot move forward locked app.");
10029 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -070010030 } else if (pkg.mOperationPending) {
10031 Slog.w(TAG, "Attempt to move package which has pending operations");
10032 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010033 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010034 // Find install location first
10035 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
10036 (flags & PackageManager.MOVE_INTERNAL) != 0) {
10037 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010038 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010039 } else {
10040 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
10041 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -070010042 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
10043 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010044 if (newFlags == currFlags) {
10045 Slog.w(TAG, "No move required. Trying to move to same location");
10046 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
10047 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010048 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010049 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10050 pkg.mOperationPending = true;
10051 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010052 }
10053 }
10054 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -070010055 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010056 } else {
10057 Message msg = mHandler.obtainMessage(INIT_COPY);
10058 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -070010059 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
10060 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
10061 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010062 msg.obj = mp;
10063 mHandler.sendMessage(msg);
10064 }
10065 }
10066 }
10067
10068 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10069 // Queue up an async operation since the package deletion may take a little while.
10070 mHandler.post(new Runnable() {
10071 public void run() {
10072 mHandler.removeCallbacks(this);
10073 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010074 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10075 int uidArr[] = null;
10076 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010077 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010078 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010079 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010080 Slog.w(TAG, " Package " + mp.packageName +
10081 " doesn't exist. Aborting move");
10082 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10083 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10084 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10085 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10086 " Aborting move and returning error");
10087 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10088 } else {
10089 uidArr = new int[] { pkg.applicationInfo.uid };
10090 pkgList = new ArrayList<String>();
10091 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010092 }
10093 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010094 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10095 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010096 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010097 // Update package code and resource paths
10098 synchronized (mInstallLock) {
10099 synchronized (mPackages) {
10100 PackageParser.Package pkg = mPackages.get(mp.packageName);
10101 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010102 if (pkg == null) {
10103 Slog.w(TAG, " Package " + mp.packageName
10104 + " doesn't exist. Aborting move");
10105 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010106 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10107 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10108 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10109 " Aborting move and returning error");
10110 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10111 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010112 final String oldCodePath = pkg.mPath;
10113 final String newCodePath = mp.targetArgs.getCodePath();
10114 final String newResPath = mp.targetArgs.getResourcePath();
10115 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010116
10117 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10118 if (mInstaller
10119 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10120 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10121 } else {
10122 NativeLibraryHelper.copyNativeBinariesLI(
10123 new File(newCodePath), new File(newNativePath));
10124 }
10125 } else {
10126 if (mInstaller.linkNativeLibraryDirectory(
10127 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10128 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10129 }
10130 }
10131
10132 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10133 pkg.mPath = newCodePath;
10134 // Move dex files around
10135 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10136 // Moving of dex files failed. Set
10137 // error code and abort move.
10138 pkg.mPath = pkg.mScanPath;
10139 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10140 }
10141 }
10142
10143 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010144 pkg.mScanPath = newCodePath;
10145 pkg.applicationInfo.sourceDir = newCodePath;
10146 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010147 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010148 PackageSetting ps = (PackageSetting) pkg.mExtras;
10149 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10150 ps.codePathString = ps.codePath.getPath();
10151 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10152 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010153 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010154 // Set the application info flag correctly.
10155 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10156 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10157 } else {
10158 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10159 }
10160 ps.setFlags(pkg.applicationInfo.flags);
10161 mAppDirs.remove(oldCodePath);
10162 mAppDirs.put(newCodePath, pkg);
10163 // Persist settings
10164 mSettings.writeLP();
10165 }
10166 }
10167 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010168 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010169 // Send resources available broadcast
10170 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010171 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010172 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010173 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010174 // Clean up failed installation
10175 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010176 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010177 }
10178 } else {
10179 // Force a gc to clear things up.
10180 Runtime.getRuntime().gc();
10181 // Delete older code
10182 synchronized (mInstallLock) {
10183 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010184 }
10185 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010186
10187 // Allow more operations on this file if we didn't fail because
10188 // an operation was already pending for this package.
10189 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10190 synchronized (mPackages) {
10191 PackageParser.Package pkg = mPackages.get(mp.packageName);
10192 if (pkg != null) {
10193 pkg.mOperationPending = false;
10194 }
10195 }
10196 }
10197
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010198 IPackageMoveObserver observer = mp.observer;
10199 if (observer != null) {
10200 try {
10201 observer.packageMoved(mp.packageName, returnCode);
10202 } catch (RemoteException e) {
10203 Log.i(TAG, "Observer no longer exists.");
10204 }
10205 }
10206 }
10207 });
10208 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010209
10210 public boolean setInstallLocation(int loc) {
10211 mContext.enforceCallingOrSelfPermission(
10212 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10213 if (getInstallLocation() == loc) {
10214 return true;
10215 }
10216 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10217 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10218 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10219 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10220 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10221 return true;
10222 }
10223 return false;
10224 }
10225
10226 public int getInstallLocation() {
10227 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10228 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010230}