blob: e54e2152f1b6c17f0f88f9149f6568cdb0a22524 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
Jason parksa3cdaa52011-01-13 14:15:43 -060027import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
Jason parks1125d782011-01-12 09:47:26 -060035import android.content.Context;
Jason parksa3cdaa52011-01-13 14:15:43 -060036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Jason parks1125d782011-01-12 09:47:26 -060041import android.content.ServiceConnection;
Jason parksa3cdaa52011-01-13 14:15:43 -060042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
Jason parks1125d782011-01-12 09:47:26 -060057import android.content.pm.PackageStats;
Jason parksa3cdaa52011-01-13 14:15:43 -060058import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
61import android.content.pm.PackageParser;
Jason parks1125d782011-01-12 09:47:26 -060062import android.content.pm.PermissionInfo;
Jason parksa3cdaa52011-01-13 14:15:43 -060063import android.content.pm.PermissionGroupInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
Jason parksa3cdaa52011-01-13 14:15:43 -060078import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Jason parksa3cdaa52011-01-13 14:15:43 -060088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
Jason parksa3cdaa52011-01-13 14:15:43 -060090import android.util.*;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.view.Display;
92import android.view.WindowManager;
93
Kenny Root9f306d72010-09-26 11:19:47 -070094import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.FileReader;
101import java.io.FilenameFilter;
102import java.io.IOException;
103import java.io.InputStream;
104import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800105import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
108import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700109import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Collections;
111import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800112import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.Enumeration;
114import java.util.HashMap;
115import java.util.HashSet;
116import java.util.Iterator;
Jason parksa3cdaa52011-01-13 14:15:43 -0600117import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.List;
119import java.util.Map;
120import java.util.Set;
121import java.util.zip.ZipEntry;
Jason parksa3cdaa52011-01-13 14:15:43 -0600122import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import java.util.zip.ZipFile;
124import java.util.zip.ZipOutputStream;
125
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700126/**
127 * Keep track of all those .apks everywhere.
128 *
129 * This is very central to the platform's security; please run the unit
130 * tests whenever making modifications here:
131 *
132mmm frameworks/base/tests/AndroidTests
133adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
134adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
135 *
136 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137class PackageManagerService extends IPackageManager.Stub {
138 private static final String TAG = "PackageManager";
139 private static final boolean DEBUG_SETTINGS = false;
140 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800141 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800142 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
145 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400146 private static final int LOG_UID = Process.LOG_UID;
Nick Pellycd0e8392010-10-13 17:25:24 -0700147 private static final int NFC_UID = Process.NFC_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private static final int FIRST_APPLICATION_UID =
149 Process.FIRST_APPLICATION_UID;
150 private static final int MAX_APPLICATION_UIDS = 1000;
151
152 private static final boolean SHOW_INFO = false;
153
154 private static final boolean GET_CERTIFICATES = true;
155
Oscar Montemayora8529f62009-11-18 10:14:20 -0800156 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private static final int REMOVE_EVENTS =
159 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
160 private static final int ADD_EVENTS =
161 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
162
163 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800164 // Suffix used during package installation when copying/moving
165 // package apks to install directory.
166 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800168 /**
169 * Indicates the state of installation. Used by PackageManager to
170 * figure out incomplete installations. Say a package is being installed
171 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
172 * the package installation is successful or unsuccesful lin which case
173 * the PackageManager will no longer maintain state information associated
174 * with the package. If some exception(like device freeze or battery being
175 * pulled out) occurs during installation of a package, the PackageManager
176 * needs this information to clean up the previously failed installation.
177 */
178 private static final int PKG_INSTALL_INCOMPLETE = 0;
179 private static final int PKG_INSTALL_COMPLETE = 1;
180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final int SCAN_MONITOR = 1<<0;
182 static final int SCAN_NO_DEX = 1<<1;
183 static final int SCAN_FORCE_DEX = 1<<2;
184 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800185 static final int SCAN_NEW_INSTALL = 1<<4;
186 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700187 static final int SCAN_UPDATE_TIME = 1<<6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700189 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700190
191 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
192
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800193 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700194 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800195 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700196
Kenny Root85387d72010-08-26 10:13:11 -0700197 private static final String LIB_DIR_NAME = "lib";
198
Kenny Rootc78a8072010-07-27 15:18:38 -0700199 static final String mTempContainerPrefix = "smdl2tmp";
200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
202 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700203 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Dianne Hackborn851a5412009-05-08 12:06:44 -0700205 final int mSdkVersion = Build.VERSION.SDK_INT;
206 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
207 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 final Context mContext;
210 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700211 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 final DisplayMetrics mMetrics;
213 final int mDefParseFlags;
214 final String[] mSeparateProcesses;
215
216 // This is where all application persistent data goes.
217 final File mAppDataDir;
218
219 // This is the object monitoring the framework dir.
220 final FileObserver mFrameworkInstallObserver;
221
222 // This is the object monitoring the system app dir.
223 final FileObserver mSystemInstallObserver;
224
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700225 // This is the object monitoring the system app dir.
226 final FileObserver mVendorInstallObserver;
227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 // This is the object monitoring mAppInstallDir.
229 final FileObserver mAppInstallObserver;
230
231 // This is the object monitoring mDrmAppPrivateInstallDir.
232 final FileObserver mDrmAppInstallObserver;
233
234 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
235 // LOCK HELD. Can be called with mInstallLock held.
236 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 final File mFrameworkDir;
239 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700240 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700242 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
244 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
245 // apps.
246 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 // Lock for state used when installing and doing other long running
251 // operations. Methods that must be called with this lock held have
252 // the prefix "LI".
253 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // These are the directories in the 3rd party applications installed dir
256 // that we have currently loaded packages from. Keys are the application's
257 // installed zip file (absolute codePath), and values are Package.
258 final HashMap<String, PackageParser.Package> mAppDirs =
259 new HashMap<String, PackageParser.Package>();
260
261 // Information for the parser to write more useful error messages.
262 File mScanningPath;
263 int mLastScanError;
264
265 final int[] mOutPermissions = new int[3];
266
267 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 // Keys are String (package name), values are Package. This also serves
270 // as the lock for the global state. Methods that must be called with
271 // this lock held have the prefix "LP".
272 final HashMap<String, PackageParser.Package> mPackages =
273 new HashMap<String, PackageParser.Package>();
274
275 final Settings mSettings;
276 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277
278 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
279 int[] mGlobalGids;
280
281 // These are the built-in uid -> permission mappings that were read from the
282 // etc/permissions.xml file.
283 final SparseArray<HashSet<String>> mSystemPermissions =
284 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 // These are the built-in shared libraries that were read from the
287 // etc/permissions.xml file.
288 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800289
Dianne Hackborn49237342009-08-27 20:08:01 -0700290 // Temporary for building the final shared libraries for an .apk.
291 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800292
Dianne Hackborn49237342009-08-27 20:08:01 -0700293 // These are the features this devices supports that were read from the
294 // etc/permissions.xml file.
295 final HashMap<String, FeatureInfo> mAvailableFeatures =
296 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 // All available activities, for your resolving pleasure.
299 final ActivityIntentResolver mActivities =
300 new ActivityIntentResolver();
301
302 // All available receivers, for your resolving pleasure.
303 final ActivityIntentResolver mReceivers =
304 new ActivityIntentResolver();
305
306 // All available services, for your resolving pleasure.
307 final ServiceIntentResolver mServices = new ServiceIntentResolver();
308
309 // Keys are String (provider class name), values are Provider.
310 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
311 new HashMap<ComponentName, PackageParser.Provider>();
312
313 // Mapping from provider base names (first directory in content URI codePath)
314 // to the provider information.
315 final HashMap<String, PackageParser.Provider> mProviders =
316 new HashMap<String, PackageParser.Provider>();
317
318 // Mapping from instrumentation class names to info about them.
319 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
320 new HashMap<ComponentName, PackageParser.Instrumentation>();
321
322 // Mapping from permission names to info about them.
323 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
324 new HashMap<String, PackageParser.PermissionGroup>();
325
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800326 // Packages whose data we have transfered into another package, thus
327 // should no longer exist.
328 final HashSet<String> mTransferedPackages = new HashSet<String>();
329
Dianne Hackborn854060af2009-07-09 18:14:31 -0700330 // Broadcast actions that are only available to the system.
331 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 boolean mSystemReady;
334 boolean mSafeMode;
335 boolean mHasSystemUidErrors;
336
337 ApplicationInfo mAndroidApplication;
338 final ActivityInfo mResolveActivity = new ActivityInfo();
339 final ResolveInfo mResolveInfo = new ResolveInfo();
340 ComponentName mResolveComponentName;
341 PackageParser.Package mPlatformPackage;
342
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700343 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800344 final HashMap<String, ArrayList<String>> mPendingBroadcasts
345 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800346 // Service Connection to remote media container service to copy
347 // package uri's from external media onto secure containers
348 // or internal storage.
349 private IMediaContainerService mContainerService = null;
350
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700351 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800352 static final int MCS_BOUND = 3;
353 static final int END_COPY = 4;
354 static final int INIT_COPY = 5;
355 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800356 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800357 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800358 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800359 static final int MCS_RECONNECT = 10;
360 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700361 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700362 static final int WRITE_SETTINGS = 13;
363
364 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800365
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700366 // Delay time in millisecs
367 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800368 final private DefaultContainerConnection mDefContainerConn =
369 new DefaultContainerConnection();
370 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800371 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800373 IMediaContainerService imcs =
374 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 }
377
378 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800379 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800380 }
381 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700382
Christopher Tate1bb69062010-02-19 17:02:12 -0800383 // Recordkeeping of restore-after-install operations that are currently in flight
384 // between the Package Manager and the Backup Manager
385 class PostInstallData {
386 public InstallArgs args;
387 public PackageInstalledInfo res;
388
389 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
390 args = _a;
391 res = _r;
392 }
393 };
394 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
395 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
396
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700397 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800398 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800399 final ArrayList<HandlerParams> mPendingInstalls =
400 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800401
402 private boolean connectToService() {
403 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
404 " DefaultContainerService");
405 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700406 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800407 if (mContext.bindService(service, mDefContainerConn,
408 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 mBound = true;
411 return true;
412 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800414 return false;
415 }
416
417 private void disconnectService() {
418 mContainerService = null;
419 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700420 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800421 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700422 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800423 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800424
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700425 PackageHandler(Looper looper) {
426 super(looper);
427 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700428
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700429 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700430 try {
431 doHandleMessage(msg);
432 } finally {
433 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
434 }
435 }
436
437 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700438 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800439 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800440 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800441 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800442 int idx = mPendingInstalls.size();
443 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
444 // If a bind was already initiated we dont really
445 // need to do anything. The pending install
446 // will be processed later on.
447 if (!mBound) {
448 // If this is the only one pending we might
449 // have to bind to the service again.
450 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800451 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800452 params.serviceError();
453 return;
454 } else {
455 // Once we bind to the service, the first
456 // pending request will be processed.
457 mPendingInstalls.add(idx, params);
458 }
459 } else {
460 mPendingInstalls.add(idx, params);
461 // Already bound to the service. Just make
462 // sure we trigger off processing the first request.
463 if (idx == 0) {
464 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800465 }
466 }
467 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800468 }
469 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800471 if (msg.obj != null) {
472 mContainerService = (IMediaContainerService) msg.obj;
473 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800474 if (mContainerService == null) {
475 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800476 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800477 for (HandlerParams params : mPendingInstalls) {
478 mPendingInstalls.remove(0);
479 // Indicate service bind error
480 params.serviceError();
481 }
482 mPendingInstalls.clear();
483 } else if (mPendingInstalls.size() > 0) {
484 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800485 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800486 params.startCopy();
487 }
488 } else {
489 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800490 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800491 }
492 break;
493 }
494 case MCS_RECONNECT : {
495 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
496 if (mPendingInstalls.size() > 0) {
497 if (mBound) {
498 disconnectService();
499 }
500 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800501 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800502 for (HandlerParams params : mPendingInstalls) {
503 mPendingInstalls.remove(0);
504 // Indicate service bind error
505 params.serviceError();
506 }
507 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800508 }
509 }
510 break;
511 }
512 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800513 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
514 // Delete pending install
515 if (mPendingInstalls.size() > 0) {
516 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800517 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800518 if (mPendingInstalls.size() == 0) {
519 if (mBound) {
520 disconnectService();
521 }
522 } else {
523 // There are more pending requests in queue.
524 // Just post MCS_BOUND message to trigger processing
525 // of next pending install.
526 mHandler.sendEmptyMessage(MCS_BOUND);
527 }
528 break;
529 }
530 case MCS_GIVE_UP: {
531 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
532 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800533 break;
534 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800536 String packages[];
537 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700538 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700540 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800542 if (mPendingBroadcasts == null) {
543 return;
544 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700545 size = mPendingBroadcasts.size();
546 if (size <= 0) {
547 // Nothing to be done. Just return
548 return;
549 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800550 packages = new String[size];
551 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700552 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800553 Iterator<HashMap.Entry<String, ArrayList<String>>>
554 it = mPendingBroadcasts.entrySet().iterator();
555 int i = 0;
556 while (it.hasNext() && i < size) {
557 HashMap.Entry<String, ArrayList<String>> ent = it.next();
558 packages[i] = ent.getKey();
559 components[i] = ent.getValue();
560 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700561 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800562 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700563 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800564 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700565 mPendingBroadcasts.clear();
566 }
567 // Send broadcasts
568 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800569 sendPackageChangedBroadcast(packages[i], true,
Jason parksa3cdaa52011-01-13 14:15:43 -0600570 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700571 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700572 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700573 break;
574 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800575 case START_CLEANING_PACKAGE: {
576 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700577 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800578 synchronized (mPackages) {
579 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
580 mSettings.mPackagesToBeCleaned.add(packageName);
581 }
582 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700583 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800584 startCleaningPackages();
585 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800586 case POST_INSTALL: {
587 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
588 PostInstallData data = mRunningInstalls.get(msg.arg1);
589 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700590 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800591
592 if (data != null) {
593 InstallArgs args = data.args;
594 PackageInstalledInfo res = data.res;
595
596 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700597 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800598 Bundle extras = new Bundle(1);
599 extras.putInt(Intent.EXTRA_UID, res.uid);
600 final boolean update = res.removedInfo.removedPackage != null;
601 if (update) {
602 extras.putBoolean(Intent.EXTRA_REPLACING, true);
603 }
604 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
605 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700606 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800607 if (update) {
608 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
609 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700610 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800611 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700612 if (res.removedInfo.args != null) {
613 // Remove the replaced package's older resources safely now
614 deleteOld = true;
615 }
616 }
617 // Force a gc to clear up things
618 Runtime.getRuntime().gc();
619 // We delete after a gc for applications on sdcard.
620 if (deleteOld) {
621 synchronized (mInstallLock) {
622 res.removedInfo.args.doPostDeleteLI(true);
623 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800624 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800625 if (args.observer != null) {
626 try {
627 args.observer.packageInstalled(res.name, res.returnCode);
628 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800629 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800630 }
631 }
632 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800633 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800634 }
635 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700636 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700637 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
638 boolean reportStatus = msg.arg1 == 1;
639 boolean doGc = msg.arg2 == 1;
640 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
641 if (doGc) {
642 // Force a gc to clear up stale containers.
643 Runtime.getRuntime().gc();
644 }
645 if (msg.obj != null) {
646 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
647 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
648 // Unload containers
649 unloadAllContainers(args);
650 }
651 if (reportStatus) {
652 try {
653 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
654 PackageHelper.getMountService().finishMediaUpdate();
655 } catch (RemoteException e) {
656 Log.e(TAG, "MountService not running?");
657 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700658 }
659 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700660 case WRITE_SETTINGS: {
661 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
662 synchronized (mPackages) {
663 removeMessages(WRITE_SETTINGS);
664 mSettings.writeLP();
665 }
666 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
667 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700668 }
669 }
670 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800671
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700672 void scheduleWriteSettingsLocked() {
673 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
674 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
675 }
676 }
677
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800678 static boolean installOnSd(int flags) {
679 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700680 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800681 return false;
682 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700683 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
684 return true;
685 }
686 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800687 }
688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 public static final IPackageManager main(Context context, boolean factoryTest) {
690 PackageManagerService m = new PackageManagerService(context, factoryTest);
691 ServiceManager.addService("package", m);
692 return m;
693 }
694
695 static String[] splitString(String str, char sep) {
696 int count = 1;
697 int i = 0;
698 while ((i=str.indexOf(sep, i)) >= 0) {
699 count++;
700 i++;
701 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 String[] res = new String[count];
704 i=0;
705 count = 0;
706 int lastI=0;
707 while ((i=str.indexOf(sep, i)) >= 0) {
708 res[count] = str.substring(lastI, i);
709 count++;
710 i++;
711 lastI = i;
712 }
713 res[count] = str.substring(lastI, str.length());
714 return res;
715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800718 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800722 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 mContext = context;
726 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700727 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 mMetrics = new DisplayMetrics();
729 mSettings = new Settings();
730 mSettings.addSharedUserLP("android.uid.system",
731 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
732 mSettings.addSharedUserLP("android.uid.phone",
733 MULTIPLE_APPLICATION_UIDS
734 ? RADIO_UID : FIRST_APPLICATION_UID,
735 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400736 mSettings.addSharedUserLP("android.uid.log",
737 MULTIPLE_APPLICATION_UIDS
738 ? LOG_UID : FIRST_APPLICATION_UID,
739 ApplicationInfo.FLAG_SYSTEM);
Nick Pellycd0e8392010-10-13 17:25:24 -0700740 mSettings.addSharedUserLP("android.uid.nfc",
741 MULTIPLE_APPLICATION_UIDS
742 ? NFC_UID : FIRST_APPLICATION_UID,
743 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744
745 String separateProcesses = SystemProperties.get("debug.separate_processes");
746 if (separateProcesses != null && separateProcesses.length() > 0) {
747 if ("*".equals(separateProcesses)) {
748 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
749 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800750 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 } else {
752 mDefParseFlags = 0;
753 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800754 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 + separateProcesses);
756 }
757 } else {
758 mDefParseFlags = 0;
759 mSeparateProcesses = null;
760 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 Installer installer = new Installer();
763 // Little hacky thing to check if installd is here, to determine
764 // whether we are running on the simulator and thus need to take
765 // care of building the /data file structure ourself.
766 // (apparently the sim now has a working installer)
767 if (installer.ping() && Process.supportsProcesses()) {
768 mInstaller = installer;
769 } else {
770 mInstaller = null;
771 }
772
773 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
774 Display d = wm.getDefaultDisplay();
775 d.getMetrics(mMetrics);
776
777 synchronized (mInstallLock) {
778 synchronized (mPackages) {
779 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700780 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 File dataDir = Environment.getDataDirectory();
783 mAppDataDir = new File(dataDir, "data");
784 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
785
786 if (mInstaller == null) {
787 // Make sure these dirs exist, when we are running in
788 // the simulator.
789 // Make a wide-open directory for random misc stuff.
790 File miscDir = new File(dataDir, "misc");
791 miscDir.mkdirs();
792 mAppDataDir.mkdirs();
793 mDrmAppPrivateInstallDir.mkdirs();
794 }
795
796 readPermissions();
797
798 mRestoredSettings = mSettings.readLP();
799 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800800
801 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800803
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800804 // Set flag to monitor and not change apk file paths when
805 // scanning install directories.
806 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700807 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800808 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800809 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700810 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700815 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700818 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 /**
821 * Out of paranoia, ensure that everything in the boot class
822 * path has been dexed.
823 */
824 String bootClassPath = System.getProperty("java.boot.class.path");
825 if (bootClassPath != null) {
826 String[] paths = splitString(bootClassPath, ':');
827 for (int i=0; i<paths.length; i++) {
828 try {
829 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
830 libFiles.add(paths[i]);
831 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700832 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
834 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800835 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800837 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 }
839 }
840 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800841 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 /**
845 * Also ensure all external libraries have had dexopt run on them.
846 */
847 if (mSharedLibraries.size() > 0) {
848 Iterator<String> libs = mSharedLibraries.values().iterator();
849 while (libs.hasNext()) {
850 String lib = libs.next();
851 try {
852 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
853 libFiles.add(lib);
854 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700855 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800858 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800860 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 }
862 }
863 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 // Gross hack for now: we know this file doesn't contain any
866 // code, so don't dexopt it to avoid the resulting log spew.
867 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 /**
870 * And there are a number of commands implemented in Java, which
871 * we currently need to do the dexopt on so that they can be
872 * run from a non-root shell.
873 */
874 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700875 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 for (int i=0; i<frameworkFiles.length; i++) {
877 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
878 String path = libPath.getPath();
879 // Skip the file if we alrady did it.
880 if (libFiles.contains(path)) {
881 continue;
882 }
883 // Skip the file if it is not a type we want to dexopt.
884 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
885 continue;
886 }
887 try {
888 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
889 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700890 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 }
892 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800893 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800895 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 }
897 }
898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800899
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700900 if (didDexOpt) {
901 // If we had to do a dexopt of one of the previous
902 // things, then something on the system has changed.
903 // Consider this significant, and wipe away all other
904 // existing dexopt files to ensure we don't leave any
905 // dangling around.
906 String[] files = mDalvikCacheDir.list();
907 if (files != null) {
908 for (int i=0; i<files.length; i++) {
909 String fn = files[i];
910 if (fn.startsWith("data@app@")
911 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800912 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700913 (new File(mDalvikCacheDir, fn)).delete();
914 }
915 }
916 }
917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800919
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800920 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 mFrameworkInstallObserver = new AppDirObserver(
922 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
923 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700924 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
925 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700926 scanMode | SCAN_NO_DEX, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800927
928 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
930 mSystemInstallObserver = new AppDirObserver(
931 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
932 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700933 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700934 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800935
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700936 // Collect all vendor packages.
937 mVendorAppDir = new File("/vendor/app");
938 mVendorInstallObserver = new AppDirObserver(
939 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
940 mVendorInstallObserver.startWatching();
941 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700942 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700943
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800944 if (mInstaller != null) {
945 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
946 mInstaller.moveFiles();
947 }
948
949 // Prune any system packages that no longer exist.
950 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
951 while (psit.hasNext()) {
952 PackageSetting ps = psit.next();
953 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800954 && !mPackages.containsKey(ps.name)
955 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800956 psit.remove();
957 String msg = "System package " + ps.name
958 + " no longer exists; wiping its data";
959 reportSettingsProblem(Log.WARN, msg);
960 if (mInstaller != null) {
Kenny Root35ab3ad2011-02-02 16:42:14 -0800961 mInstaller.remove(ps.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800962 }
963 }
964 }
965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 mAppInstallDir = new File(dataDir, "app");
967 if (mInstaller == null) {
968 // Make sure these dirs exist, when we are running in
969 // the simulator.
970 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
971 }
972 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800973 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 //clean up list
975 for(int i = 0; i < deletePkgsList.size(); i++) {
976 //clean up here
977 cleanupInstallFailedPackage(deletePkgsList.get(i));
978 }
979 //delete tmp files
980 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800981
982 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 SystemClock.uptimeMillis());
984 mAppInstallObserver = new AppDirObserver(
985 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
986 mAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700987 scanDirLI(mAppInstallDir, 0, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988
989 mDrmAppInstallObserver = new AppDirObserver(
990 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
991 mDrmAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700992 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
993 scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800995 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800997 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 + ((SystemClock.uptimeMillis()-startTime)/1000f)
999 + " seconds");
1000
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001001 // If the platform SDK has changed since the last time we booted,
1002 // we need to re-grant app permission to catch any new ones that
1003 // appear. This is really a hack, and means that apps can in some
1004 // cases get permissions that the user didn't initially explicitly
1005 // allow... it would be nice to have some better way to handle
1006 // this situation.
1007 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1008 != mSdkVersion;
1009 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1010 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1011 + "; regranting permissions for internal storage");
1012 mSettings.mInternalSdkPlatform = mSdkVersion;
1013
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001014 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015
1016 mSettings.writeLP();
1017
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001018 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 // Now after opening every single application zip, make sure they
1022 // are all flushed. Not really needed, but keeps things nice and
1023 // tidy.
1024 Runtime.getRuntime().gc();
1025 } // synchronized (mPackages)
1026 } // synchronized (mInstallLock)
1027 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 @Override
1030 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1031 throws RemoteException {
1032 try {
1033 return super.onTransact(code, data, reply, flags);
1034 } catch (RuntimeException e) {
1035 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001036 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038 throw e;
1039 }
1040 }
1041
Dianne Hackborne6620b22010-01-22 14:46:21 -08001042 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001043 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 if (mInstaller != null) {
Kenny Root35ab3ad2011-02-02 16:42:14 -08001045 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001047 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001048 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050 } else {
1051 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001052 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 File dataDir = new File(pkg.applicationInfo.dataDir);
1054 dataDir.delete();
1055 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001056 if (ps.codePath != null) {
1057 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001058 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001059 }
1060 }
1061 if (ps.resourcePath != null) {
1062 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001063 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001064 }
1065 }
1066 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068
1069 void readPermissions() {
1070 // Read permissions from .../etc/permission directory.
1071 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1072 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001073 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 return;
1075 }
1076 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001077 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 return;
1079 }
1080
1081 // Iterate over the files in the directory and scan .xml files
1082 for (File f : libraryDir.listFiles()) {
1083 // We'll read platform.xml last
1084 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1085 continue;
1086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001089 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 continue;
1091 }
1092 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001093 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 continue;
1095 }
1096
1097 readPermissionsFromXml(f);
1098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1101 final File permFile = new File(Environment.getRootDirectory(),
1102 "etc/permissions/platform.xml");
1103 readPermissionsFromXml(permFile);
1104 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001105
1106 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 FileReader permReader = null;
1108 try {
1109 permReader = new FileReader(permFile);
1110 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001111 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 return;
1113 }
1114
1115 try {
1116 XmlPullParser parser = Xml.newPullParser();
1117 parser.setInput(permReader);
1118
1119 XmlUtils.beginDocument(parser, "permissions");
1120
1121 while (true) {
1122 XmlUtils.nextElement(parser);
1123 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1124 break;
1125 }
1126
1127 String name = parser.getName();
1128 if ("group".equals(name)) {
1129 String gidStr = parser.getAttributeValue(null, "gid");
1130 if (gidStr != null) {
1131 int gid = Integer.parseInt(gidStr);
1132 mGlobalGids = appendInt(mGlobalGids, gid);
1133 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001134 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 + parser.getPositionDescription());
1136 }
1137
1138 XmlUtils.skipCurrentTag(parser);
1139 continue;
1140 } else if ("permission".equals(name)) {
1141 String perm = parser.getAttributeValue(null, "name");
1142 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + parser.getPositionDescription());
1145 XmlUtils.skipCurrentTag(parser);
1146 continue;
1147 }
1148 perm = perm.intern();
1149 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 } else if ("assign-permission".equals(name)) {
1152 String perm = parser.getAttributeValue(null, "name");
1153 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001154 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 + parser.getPositionDescription());
1156 XmlUtils.skipCurrentTag(parser);
1157 continue;
1158 }
1159 String uidStr = parser.getAttributeValue(null, "uid");
1160 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001161 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 + parser.getPositionDescription());
1163 XmlUtils.skipCurrentTag(parser);
1164 continue;
1165 }
1166 int uid = Process.getUidForName(uidStr);
1167 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001168 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 + uidStr + "\" at "
1170 + parser.getPositionDescription());
1171 XmlUtils.skipCurrentTag(parser);
1172 continue;
1173 }
1174 perm = perm.intern();
1175 HashSet<String> perms = mSystemPermissions.get(uid);
1176 if (perms == null) {
1177 perms = new HashSet<String>();
1178 mSystemPermissions.put(uid, perms);
1179 }
1180 perms.add(perm);
1181 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 } else if ("library".equals(name)) {
1184 String lname = parser.getAttributeValue(null, "name");
1185 String lfile = parser.getAttributeValue(null, "file");
1186 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001187 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 + parser.getPositionDescription());
1189 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001190 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 + parser.getPositionDescription());
1192 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001193 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001194 mSharedLibraries.put(lname, lfile);
1195 }
1196 XmlUtils.skipCurrentTag(parser);
1197 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001198
Dianne Hackborn49237342009-08-27 20:08:01 -07001199 } else if ("feature".equals(name)) {
1200 String fname = parser.getAttributeValue(null, "name");
1201 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001202 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 + parser.getPositionDescription());
1204 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001205 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001206 FeatureInfo fi = new FeatureInfo();
1207 fi.name = fname;
1208 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
1210 XmlUtils.skipCurrentTag(parser);
1211 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 } else {
1214 XmlUtils.skipCurrentTag(parser);
1215 continue;
1216 }
1217
1218 }
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001219 permReader.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001221 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001223 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
1225 }
1226
1227 void readPermission(XmlPullParser parser, String name)
1228 throws IOException, XmlPullParserException {
1229
1230 name = name.intern();
1231
1232 BasePermission bp = mSettings.mPermissions.get(name);
1233 if (bp == null) {
1234 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1235 mSettings.mPermissions.put(name, bp);
1236 }
1237 int outerDepth = parser.getDepth();
1238 int type;
1239 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1240 && (type != XmlPullParser.END_TAG
1241 || parser.getDepth() > outerDepth)) {
1242 if (type == XmlPullParser.END_TAG
1243 || type == XmlPullParser.TEXT) {
1244 continue;
1245 }
1246
1247 String tagName = parser.getName();
1248 if ("group".equals(tagName)) {
1249 String gidStr = parser.getAttributeValue(null, "gid");
1250 if (gidStr != null) {
1251 int gid = Process.getGidForName(gidStr);
1252 bp.gids = appendInt(bp.gids, gid);
1253 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001254 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 + parser.getPositionDescription());
1256 }
1257 }
1258 XmlUtils.skipCurrentTag(parser);
1259 }
1260 }
1261
1262 static int[] appendInt(int[] cur, int val) {
1263 if (cur == null) {
1264 return new int[] { val };
1265 }
1266 final int N = cur.length;
1267 for (int i=0; i<N; i++) {
1268 if (cur[i] == val) {
1269 return cur;
1270 }
1271 }
1272 int[] ret = new int[N+1];
1273 System.arraycopy(cur, 0, ret, 0, N);
1274 ret[N] = val;
1275 return ret;
1276 }
1277
1278 static int[] appendInts(int[] cur, int[] add) {
1279 if (add == null) return cur;
1280 if (cur == null) return add;
1281 final int N = add.length;
1282 for (int i=0; i<N; i++) {
1283 cur = appendInt(cur, add[i]);
1284 }
1285 return cur;
1286 }
1287
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001288 static int[] removeInt(int[] cur, int val) {
1289 if (cur == null) {
1290 return null;
1291 }
1292 final int N = cur.length;
1293 for (int i=0; i<N; i++) {
1294 if (cur[i] == val) {
1295 int[] ret = new int[N-1];
1296 if (i > 0) {
1297 System.arraycopy(cur, 0, ret, 0, i);
1298 }
1299 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001300 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001301 }
1302 return ret;
1303 }
1304 }
1305 return cur;
1306 }
1307
1308 static int[] removeInts(int[] cur, int[] rem) {
1309 if (rem == null) return cur;
1310 if (cur == null) return cur;
1311 final int N = rem.length;
1312 for (int i=0; i<N; i++) {
1313 cur = removeInt(cur, rem[i]);
1314 }
1315 return cur;
1316 }
1317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001319 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1320 // The package has been uninstalled but has retained data and resources.
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001321 return PackageParser.generatePackageInfo(p, null, flags, 0, 0);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 final PackageSetting ps = (PackageSetting)p.mExtras;
1324 if (ps == null) {
1325 return null;
1326 }
1327 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001328 return PackageParser.generatePackageInfo(p, gp.gids, flags,
1329 ps.firstInstallTime, ps.lastUpdateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 }
1331
1332 public PackageInfo getPackageInfo(String packageName, int flags) {
1333 synchronized (mPackages) {
1334 PackageParser.Package p = mPackages.get(packageName);
1335 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001336 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 + ": " + p);
1338 if (p != null) {
1339 return generatePackageInfo(p, flags);
1340 }
1341 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1342 return generatePackageInfoFromSettingsLP(packageName, flags);
1343 }
1344 }
1345 return null;
1346 }
1347
Dianne Hackborn47096932010-02-11 15:57:09 -08001348 public String[] currentToCanonicalPackageNames(String[] names) {
1349 String[] out = new String[names.length];
1350 synchronized (mPackages) {
1351 for (int i=names.length-1; i>=0; i--) {
1352 PackageSetting ps = mSettings.mPackages.get(names[i]);
1353 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1354 }
1355 }
1356 return out;
1357 }
1358
1359 public String[] canonicalToCurrentPackageNames(String[] names) {
1360 String[] out = new String[names.length];
1361 synchronized (mPackages) {
1362 for (int i=names.length-1; i>=0; i--) {
1363 String cur = mSettings.mRenamedPackages.get(names[i]);
1364 out[i] = cur != null ? cur : names[i];
1365 }
1366 }
1367 return out;
1368 }
1369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 public int getPackageUid(String packageName) {
1371 synchronized (mPackages) {
1372 PackageParser.Package p = mPackages.get(packageName);
1373 if(p != null) {
1374 return p.applicationInfo.uid;
1375 }
1376 PackageSetting ps = mSettings.mPackages.get(packageName);
1377 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1378 return -1;
1379 }
1380 p = ps.pkg;
1381 return p != null ? p.applicationInfo.uid : -1;
1382 }
1383 }
1384
1385 public int[] getPackageGids(String packageName) {
1386 synchronized (mPackages) {
1387 PackageParser.Package p = mPackages.get(packageName);
1388 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001389 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 + ": " + p);
1391 if (p != null) {
1392 final PackageSetting ps = (PackageSetting)p.mExtras;
1393 final SharedUserSetting suid = ps.sharedUser;
1394 return suid != null ? suid.gids : ps.gids;
1395 }
1396 }
1397 // stupid thing to indicate an error.
1398 return new int[0];
1399 }
1400
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001401 static final PermissionInfo generatePermissionInfo(
1402 BasePermission bp, int flags) {
1403 if (bp.perm != null) {
1404 return PackageParser.generatePermissionInfo(bp.perm, flags);
1405 }
1406 PermissionInfo pi = new PermissionInfo();
1407 pi.name = bp.name;
1408 pi.packageName = bp.sourcePackage;
1409 pi.nonLocalizedLabel = bp.name;
1410 pi.protectionLevel = bp.protectionLevel;
1411 return pi;
1412 }
1413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 public PermissionInfo getPermissionInfo(String name, int flags) {
1415 synchronized (mPackages) {
1416 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001417 if (p != null) {
1418 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420 return null;
1421 }
1422 }
1423
1424 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1425 synchronized (mPackages) {
1426 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1427 for (BasePermission p : mSettings.mPermissions.values()) {
1428 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001429 if (p.perm == null || p.perm.info.group == null) {
1430 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 }
1432 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001433 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1435 }
1436 }
1437 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 if (out.size() > 0) {
1440 return out;
1441 }
1442 return mPermissionGroups.containsKey(group) ? out : null;
1443 }
1444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1447 synchronized (mPackages) {
1448 return PackageParser.generatePermissionGroupInfo(
1449 mPermissionGroups.get(name), flags);
1450 }
1451 }
1452
1453 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1454 synchronized (mPackages) {
1455 final int N = mPermissionGroups.size();
1456 ArrayList<PermissionGroupInfo> out
1457 = new ArrayList<PermissionGroupInfo>(N);
1458 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1459 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1460 }
1461 return out;
1462 }
1463 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1466 PackageSetting ps = mSettings.mPackages.get(packageName);
1467 if(ps != null) {
1468 if(ps.pkg == null) {
1469 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1470 if(pInfo != null) {
1471 return pInfo.applicationInfo;
1472 }
1473 return null;
1474 }
1475 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1476 }
1477 return null;
1478 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1481 PackageSetting ps = mSettings.mPackages.get(packageName);
1482 if(ps != null) {
1483 if(ps.pkg == null) {
1484 ps.pkg = new PackageParser.Package(packageName);
1485 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001486 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1487 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1488 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1489 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001490 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001491 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
1493 return generatePackageInfo(ps.pkg, flags);
1494 }
1495 return null;
1496 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1499 synchronized (mPackages) {
1500 PackageParser.Package p = mPackages.get(packageName);
1501 if (Config.LOGV) Log.v(
1502 TAG, "getApplicationInfo " + packageName
1503 + ": " + p);
1504 if (p != null) {
1505 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001506 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 }
1508 if ("android".equals(packageName)||"system".equals(packageName)) {
1509 return mAndroidApplication;
1510 }
1511 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1512 return generateApplicationInfoFromSettingsLP(packageName, flags);
1513 }
1514 }
1515 return null;
1516 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001517
1518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1520 mContext.enforceCallingOrSelfPermission(
1521 android.Manifest.permission.CLEAR_APP_CACHE, null);
1522 // Queue up an async operation since clearing cache may take a little while.
1523 mHandler.post(new Runnable() {
1524 public void run() {
1525 mHandler.removeCallbacks(this);
1526 int retCode = -1;
1527 if (mInstaller != null) {
1528 retCode = mInstaller.freeCache(freeStorageSize);
1529 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001530 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 }
1532 } //end if mInstaller
1533 if (observer != null) {
1534 try {
1535 observer.onRemoveCompleted(null, (retCode >= 0));
1536 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001537 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 }
1540 }
1541 });
1542 }
1543
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001544 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001545 mContext.enforceCallingOrSelfPermission(
1546 android.Manifest.permission.CLEAR_APP_CACHE, null);
1547 // Queue up an async operation since clearing cache may take a little while.
1548 mHandler.post(new Runnable() {
1549 public void run() {
1550 mHandler.removeCallbacks(this);
1551 int retCode = -1;
1552 if (mInstaller != null) {
1553 retCode = mInstaller.freeCache(freeStorageSize);
1554 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001555 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001556 }
1557 }
1558 if(pi != null) {
1559 try {
1560 // Callback via pending intent
1561 int code = (retCode >= 0) ? 1 : 0;
1562 pi.sendIntent(null, code, null,
1563 null, null);
1564 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001565 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001566 }
1567 }
1568 }
1569 });
1570 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1573 synchronized (mPackages) {
1574 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001575
1576 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001578 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580 if (mResolveComponentName.equals(component)) {
1581 return mResolveActivity;
1582 }
1583 }
1584 return null;
1585 }
1586
1587 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1588 synchronized (mPackages) {
1589 PackageParser.Activity a = mReceivers.mActivities.get(component);
1590 if (Config.LOGV) Log.v(
1591 TAG, "getReceiverInfo " + component + ": " + a);
1592 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1593 return PackageParser.generateActivityInfo(a, flags);
1594 }
1595 }
1596 return null;
1597 }
1598
1599 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1600 synchronized (mPackages) {
1601 PackageParser.Service s = mServices.mServices.get(component);
1602 if (Config.LOGV) Log.v(
1603 TAG, "getServiceInfo " + component + ": " + s);
1604 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1605 return PackageParser.generateServiceInfo(s, flags);
1606 }
1607 }
1608 return null;
1609 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001610
Dianne Hackborn361199b2010-08-30 17:42:07 -07001611 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1612 synchronized (mPackages) {
1613 PackageParser.Provider p = mProvidersByComponent.get(component);
1614 if (Config.LOGV) Log.v(
1615 TAG, "getProviderInfo " + component + ": " + p);
1616 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1617 return PackageParser.generateProviderInfo(p, flags);
1618 }
1619 }
1620 return null;
1621 }
1622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 public String[] getSystemSharedLibraryNames() {
1624 Set<String> libSet;
1625 synchronized (mPackages) {
1626 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001627 int size = libSet.size();
1628 if (size > 0) {
1629 String[] libs = new String[size];
1630 libSet.toArray(libs);
1631 return libs;
1632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001634 return null;
1635 }
1636
1637 public FeatureInfo[] getSystemAvailableFeatures() {
1638 Collection<FeatureInfo> featSet;
1639 synchronized (mPackages) {
1640 featSet = mAvailableFeatures.values();
1641 int size = featSet.size();
1642 if (size > 0) {
1643 FeatureInfo[] features = new FeatureInfo[size+1];
1644 featSet.toArray(features);
1645 FeatureInfo fi = new FeatureInfo();
1646 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1647 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1648 features[size] = fi;
1649 return features;
1650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
1652 return null;
1653 }
1654
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001655 public boolean hasSystemFeature(String name) {
1656 synchronized (mPackages) {
1657 return mAvailableFeatures.containsKey(name);
1658 }
1659 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 public int checkPermission(String permName, String pkgName) {
1662 synchronized (mPackages) {
1663 PackageParser.Package p = mPackages.get(pkgName);
1664 if (p != null && p.mExtras != null) {
1665 PackageSetting ps = (PackageSetting)p.mExtras;
1666 if (ps.sharedUser != null) {
1667 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1668 return PackageManager.PERMISSION_GRANTED;
1669 }
1670 } else if (ps.grantedPermissions.contains(permName)) {
1671 return PackageManager.PERMISSION_GRANTED;
1672 }
1673 }
1674 }
1675 return PackageManager.PERMISSION_DENIED;
1676 }
1677
1678 public int checkUidPermission(String permName, int uid) {
1679 synchronized (mPackages) {
1680 Object obj = mSettings.getUserIdLP(uid);
1681 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001682 GrantedPermissions gp = (GrantedPermissions)obj;
1683 if (gp.grantedPermissions.contains(permName)) {
1684 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686 } else {
1687 HashSet<String> perms = mSystemPermissions.get(uid);
1688 if (perms != null && perms.contains(permName)) {
1689 return PackageManager.PERMISSION_GRANTED;
1690 }
1691 }
1692 }
1693 return PackageManager.PERMISSION_DENIED;
1694 }
1695
1696 private BasePermission findPermissionTreeLP(String permName) {
1697 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1698 if (permName.startsWith(bp.name) &&
1699 permName.length() > bp.name.length() &&
1700 permName.charAt(bp.name.length()) == '.') {
1701 return bp;
1702 }
1703 }
1704 return null;
1705 }
1706
1707 private BasePermission checkPermissionTreeLP(String permName) {
1708 if (permName != null) {
1709 BasePermission bp = findPermissionTreeLP(permName);
1710 if (bp != null) {
1711 if (bp.uid == Binder.getCallingUid()) {
1712 return bp;
1713 }
1714 throw new SecurityException("Calling uid "
1715 + Binder.getCallingUid()
1716 + " is not allowed to add to permission tree "
1717 + bp.name + " owned by uid " + bp.uid);
1718 }
1719 }
1720 throw new SecurityException("No permission tree found for " + permName);
1721 }
1722
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001723 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1724 if (s1 == null) {
1725 return s2 == null;
1726 }
1727 if (s2 == null) {
1728 return false;
1729 }
1730 if (s1.getClass() != s2.getClass()) {
1731 return false;
1732 }
1733 return s1.equals(s2);
1734 }
1735
1736 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1737 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001738 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001739 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1740 if (!compareStrings(pi1.name, pi2.name)) return false;
1741 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1742 // We'll take care of setting this one.
1743 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1744 // These are not currently stored in settings.
1745 //if (!compareStrings(pi1.group, pi2.group)) return false;
1746 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1747 //if (pi1.labelRes != pi2.labelRes) return false;
1748 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1749 return true;
1750 }
1751
1752 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1753 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1754 throw new SecurityException("Label must be specified in permission");
1755 }
1756 BasePermission tree = checkPermissionTreeLP(info.name);
1757 BasePermission bp = mSettings.mPermissions.get(info.name);
1758 boolean added = bp == null;
1759 boolean changed = true;
1760 if (added) {
1761 bp = new BasePermission(info.name, tree.sourcePackage,
1762 BasePermission.TYPE_DYNAMIC);
1763 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1764 throw new SecurityException(
1765 "Not allowed to modify non-dynamic permission "
1766 + info.name);
1767 } else {
1768 if (bp.protectionLevel == info.protectionLevel
1769 && bp.perm.owner.equals(tree.perm.owner)
1770 && bp.uid == tree.uid
1771 && comparePermissionInfos(bp.perm.info, info)) {
1772 changed = false;
1773 }
1774 }
1775 bp.protectionLevel = info.protectionLevel;
1776 bp.perm = new PackageParser.Permission(tree.perm.owner,
1777 new PermissionInfo(info));
1778 bp.perm.info.packageName = tree.perm.info.packageName;
1779 bp.uid = tree.uid;
1780 if (added) {
1781 mSettings.mPermissions.put(info.name, bp);
1782 }
1783 if (changed) {
1784 if (!async) {
1785 mSettings.writeLP();
1786 } else {
1787 scheduleWriteSettingsLocked();
1788 }
1789 }
1790 return added;
1791 }
1792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 public boolean addPermission(PermissionInfo info) {
1794 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001795 return addPermissionLocked(info, false);
1796 }
1797 }
1798
1799 public boolean addPermissionAsync(PermissionInfo info) {
1800 synchronized (mPackages) {
1801 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 }
1803 }
1804
1805 public void removePermission(String name) {
1806 synchronized (mPackages) {
1807 checkPermissionTreeLP(name);
1808 BasePermission bp = mSettings.mPermissions.get(name);
1809 if (bp != null) {
1810 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1811 throw new SecurityException(
1812 "Not allowed to modify non-dynamic permission "
1813 + name);
1814 }
1815 mSettings.mPermissions.remove(name);
1816 mSettings.writeLP();
1817 }
1818 }
1819 }
1820
Dianne Hackborn854060af2009-07-09 18:14:31 -07001821 public boolean isProtectedBroadcast(String actionName) {
1822 synchronized (mPackages) {
1823 return mProtectedBroadcasts.contains(actionName);
1824 }
1825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 public int checkSignatures(String pkg1, String pkg2) {
1828 synchronized (mPackages) {
1829 PackageParser.Package p1 = mPackages.get(pkg1);
1830 PackageParser.Package p2 = mPackages.get(pkg2);
1831 if (p1 == null || p1.mExtras == null
1832 || p2 == null || p2.mExtras == null) {
1833 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1834 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001835 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 }
1837 }
1838
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001839 public int checkUidSignatures(int uid1, int uid2) {
1840 synchronized (mPackages) {
1841 Signature[] s1;
1842 Signature[] s2;
1843 Object obj = mSettings.getUserIdLP(uid1);
1844 if (obj != null) {
1845 if (obj instanceof SharedUserSetting) {
1846 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1847 } else if (obj instanceof PackageSetting) {
1848 s1 = ((PackageSetting)obj).signatures.mSignatures;
1849 } else {
1850 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1851 }
1852 } else {
1853 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1854 }
1855 obj = mSettings.getUserIdLP(uid2);
1856 if (obj != null) {
1857 if (obj instanceof SharedUserSetting) {
1858 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1859 } else if (obj instanceof PackageSetting) {
1860 s2 = ((PackageSetting)obj).signatures.mSignatures;
1861 } else {
1862 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1863 }
1864 } else {
1865 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1866 }
1867 return checkSignaturesLP(s1, s2);
1868 }
1869 }
1870
1871 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1872 if (s1 == null) {
1873 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1875 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1876 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001877 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1879 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001880 HashSet<Signature> set1 = new HashSet<Signature>();
1881 for (Signature sig : s1) {
1882 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001884 HashSet<Signature> set2 = new HashSet<Signature>();
1885 for (Signature sig : s2) {
1886 set2.add(sig);
1887 }
1888 // Make sure s2 contains all signatures in s1.
1889 if (set1.equals(set2)) {
1890 return PackageManager.SIGNATURE_MATCH;
1891 }
1892 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894
1895 public String[] getPackagesForUid(int uid) {
1896 synchronized (mPackages) {
1897 Object obj = mSettings.getUserIdLP(uid);
1898 if (obj instanceof SharedUserSetting) {
1899 SharedUserSetting sus = (SharedUserSetting)obj;
1900 final int N = sus.packages.size();
1901 String[] res = new String[N];
1902 Iterator<PackageSetting> it = sus.packages.iterator();
1903 int i=0;
1904 while (it.hasNext()) {
1905 res[i++] = it.next().name;
1906 }
1907 return res;
1908 } else if (obj instanceof PackageSetting) {
1909 PackageSetting ps = (PackageSetting)obj;
1910 return new String[] { ps.name };
1911 }
1912 }
1913 return null;
1914 }
1915
1916 public String getNameForUid(int uid) {
1917 synchronized (mPackages) {
1918 Object obj = mSettings.getUserIdLP(uid);
1919 if (obj instanceof SharedUserSetting) {
1920 SharedUserSetting sus = (SharedUserSetting)obj;
1921 return sus.name + ":" + sus.userId;
1922 } else if (obj instanceof PackageSetting) {
1923 PackageSetting ps = (PackageSetting)obj;
1924 return ps.name;
1925 }
1926 }
1927 return null;
1928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 public int getUidForSharedUser(String sharedUserName) {
1931 if(sharedUserName == null) {
1932 return -1;
1933 }
1934 synchronized (mPackages) {
1935 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1936 if(suid == null) {
1937 return -1;
1938 }
1939 return suid.userId;
1940 }
1941 }
1942
1943 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1944 int flags) {
1945 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001946 return chooseBestActivity(intent, resolvedType, flags, query);
1947 }
1948
Mihai Predaeae850c2009-05-13 10:13:48 +02001949 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1950 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 if (query != null) {
1952 final int N = query.size();
1953 if (N == 1) {
1954 return query.get(0);
1955 } else if (N > 1) {
1956 // If there is more than one activity with the same priority,
1957 // then let the user decide between them.
1958 ResolveInfo r0 = query.get(0);
1959 ResolveInfo r1 = query.get(1);
1960 if (false) {
1961 System.out.println(r0.activityInfo.name +
1962 "=" + r0.priority + " vs " +
1963 r1.activityInfo.name +
1964 "=" + r1.priority);
1965 }
1966 // If the first activity has a higher priority, or a different
1967 // default, then it is always desireable to pick it.
1968 if (r0.priority != r1.priority
1969 || r0.preferredOrder != r1.preferredOrder
1970 || r0.isDefault != r1.isDefault) {
1971 return query.get(0);
1972 }
1973 // If we have saved a preference for a preferred activity for
1974 // this Intent, use that.
1975 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1976 flags, query, r0.priority);
1977 if (ri != null) {
1978 return ri;
1979 }
1980 return mResolveInfo;
1981 }
1982 }
1983 return null;
1984 }
1985
1986 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1987 int flags, List<ResolveInfo> query, int priority) {
1988 synchronized (mPackages) {
1989 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1990 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001991 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1993 if (prefs != null && prefs.size() > 0) {
1994 // First figure out how good the original match set is.
1995 // We will only allow preferred activities that came
1996 // from the same match quality.
1997 int match = 0;
1998 final int N = query.size();
1999 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2000 for (int j=0; j<N; j++) {
2001 ResolveInfo ri = query.get(j);
2002 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2003 + ": 0x" + Integer.toHexString(match));
2004 if (ri.match > match) match = ri.match;
2005 }
2006 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2007 + Integer.toHexString(match));
2008 match &= IntentFilter.MATCH_CATEGORY_MASK;
2009 final int M = prefs.size();
2010 for (int i=0; i<M; i++) {
2011 PreferredActivity pa = prefs.get(i);
2012 if (pa.mMatch != match) {
2013 continue;
2014 }
2015 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2016 if (DEBUG_PREFERRED) {
2017 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002018 if (ai != null) {
2019 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2020 } else {
2021 Log.v(TAG, " null");
2022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 }
2024 if (ai != null) {
2025 for (int j=0; j<N; j++) {
2026 ResolveInfo ri = query.get(j);
2027 if (!ri.activityInfo.applicationInfo.packageName
2028 .equals(ai.applicationInfo.packageName)) {
2029 continue;
2030 }
2031 if (!ri.activityInfo.name.equals(ai.name)) {
2032 continue;
2033 }
2034
2035 // Okay we found a previously set preferred app.
2036 // If the result set is different from when this
2037 // was created, we need to clear it and re-ask the
2038 // user their preference.
2039 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002040 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 + intent + " type " + resolvedType);
2042 mSettings.mPreferredActivities.removeFilter(pa);
2043 return null;
2044 }
2045
2046 // Yay!
2047 return ri;
2048 }
2049 }
2050 }
2051 }
2052 }
2053 return null;
2054 }
2055
2056 public List<ResolveInfo> queryIntentActivities(Intent intent,
2057 String resolvedType, int flags) {
2058 ComponentName comp = intent.getComponent();
2059 if (comp != null) {
2060 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2061 ActivityInfo ai = getActivityInfo(comp, flags);
2062 if (ai != null) {
2063 ResolveInfo ri = new ResolveInfo();
2064 ri.activityInfo = ai;
2065 list.add(ri);
2066 }
2067 return list;
2068 }
2069
2070 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002071 String pkgName = intent.getPackage();
2072 if (pkgName == null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002073 return (List<ResolveInfo>)mActivities.queryIntent(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002074 resolvedType, flags);
2075 }
2076 PackageParser.Package pkg = mPackages.get(pkgName);
2077 if (pkg != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002078 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002079 resolvedType, flags, pkg.activities);
2080 }
Dianne Hackborn5d9d03a02011-01-24 13:15:09 -08002081 return new ArrayList<ResolveInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 }
2083 }
2084
2085 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2086 Intent[] specifics, String[] specificTypes, Intent intent,
2087 String resolvedType, int flags) {
2088 final String resultsAction = intent.getAction();
2089
2090 List<ResolveInfo> results = queryIntentActivities(
2091 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2092 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2093
2094 int specificsPos = 0;
2095 int N;
2096
2097 // todo: note that the algorithm used here is O(N^2). This
2098 // isn't a problem in our current environment, but if we start running
2099 // into situations where we have more than 5 or 10 matches then this
2100 // should probably be changed to something smarter...
2101
2102 // First we go through and resolve each of the specific items
2103 // that were supplied, taking care of removing any corresponding
2104 // duplicate items in the generic resolve list.
2105 if (specifics != null) {
2106 for (int i=0; i<specifics.length; i++) {
2107 final Intent sintent = specifics[i];
2108 if (sintent == null) {
2109 continue;
2110 }
2111
2112 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2113 String action = sintent.getAction();
2114 if (resultsAction != null && resultsAction.equals(action)) {
2115 // If this action was explicitly requested, then don't
2116 // remove things that have it.
2117 action = null;
2118 }
2119 ComponentName comp = sintent.getComponent();
2120 ResolveInfo ri = null;
2121 ActivityInfo ai = null;
2122 if (comp == null) {
2123 ri = resolveIntent(
2124 sintent,
2125 specificTypes != null ? specificTypes[i] : null,
2126 flags);
2127 if (ri == null) {
2128 continue;
2129 }
2130 if (ri == mResolveInfo) {
2131 // ACK! Must do something better with this.
2132 }
2133 ai = ri.activityInfo;
2134 comp = new ComponentName(ai.applicationInfo.packageName,
2135 ai.name);
2136 } else {
2137 ai = getActivityInfo(comp, flags);
2138 if (ai == null) {
2139 continue;
2140 }
2141 }
2142
2143 // Look for any generic query activities that are duplicates
2144 // of this specific one, and remove them from the results.
2145 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2146 N = results.size();
2147 int j;
2148 for (j=specificsPos; j<N; j++) {
2149 ResolveInfo sri = results.get(j);
2150 if ((sri.activityInfo.name.equals(comp.getClassName())
2151 && sri.activityInfo.applicationInfo.packageName.equals(
2152 comp.getPackageName()))
2153 || (action != null && sri.filter.matchAction(action))) {
2154 results.remove(j);
2155 if (Config.LOGV) Log.v(
2156 TAG, "Removing duplicate item from " + j
2157 + " due to specific " + specificsPos);
2158 if (ri == null) {
2159 ri = sri;
2160 }
2161 j--;
2162 N--;
2163 }
2164 }
2165
2166 // Add this specific item to its proper place.
2167 if (ri == null) {
2168 ri = new ResolveInfo();
2169 ri.activityInfo = ai;
2170 }
2171 results.add(specificsPos, ri);
2172 ri.specificIndex = i;
2173 specificsPos++;
2174 }
2175 }
2176
2177 // Now we go through the remaining generic results and remove any
2178 // duplicate actions that are found here.
2179 N = results.size();
2180 for (int i=specificsPos; i<N-1; i++) {
2181 final ResolveInfo rii = results.get(i);
2182 if (rii.filter == null) {
2183 continue;
2184 }
2185
2186 // Iterate over all of the actions of this result's intent
2187 // filter... typically this should be just one.
2188 final Iterator<String> it = rii.filter.actionsIterator();
2189 if (it == null) {
2190 continue;
2191 }
2192 while (it.hasNext()) {
2193 final String action = it.next();
2194 if (resultsAction != null && resultsAction.equals(action)) {
2195 // If this action was explicitly requested, then don't
2196 // remove things that have it.
2197 continue;
2198 }
2199 for (int j=i+1; j<N; j++) {
2200 final ResolveInfo rij = results.get(j);
2201 if (rij.filter != null && rij.filter.hasAction(action)) {
2202 results.remove(j);
2203 if (Config.LOGV) Log.v(
2204 TAG, "Removing duplicate item from " + j
2205 + " due to action " + action + " at " + i);
2206 j--;
2207 N--;
2208 }
2209 }
2210 }
2211
2212 // If the caller didn't request filter information, drop it now
2213 // so we don't have to marshall/unmarshall it.
2214 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2215 rii.filter = null;
2216 }
2217 }
2218
2219 // Filter out the caller activity if so requested.
2220 if (caller != null) {
2221 N = results.size();
2222 for (int i=0; i<N; i++) {
2223 ActivityInfo ainfo = results.get(i).activityInfo;
2224 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2225 && caller.getClassName().equals(ainfo.name)) {
2226 results.remove(i);
2227 break;
2228 }
2229 }
2230 }
2231
2232 // If the caller didn't request filter information,
2233 // drop them now so we don't have to
2234 // marshall/unmarshall it.
2235 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2236 N = results.size();
2237 for (int i=0; i<N; i++) {
2238 results.get(i).filter = null;
2239 }
2240 }
2241
2242 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2243 return results;
2244 }
2245
2246 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2247 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002248 ComponentName comp = intent.getComponent();
2249 if (comp != null) {
2250 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2251 ActivityInfo ai = getReceiverInfo(comp, flags);
2252 if (ai != null) {
2253 ResolveInfo ri = new ResolveInfo();
2254 ri.activityInfo = ai;
2255 list.add(ri);
2256 }
2257 return list;
2258 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002261 String pkgName = intent.getPackage();
2262 if (pkgName == null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002263 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002264 resolvedType, flags);
2265 }
2266 PackageParser.Package pkg = mPackages.get(pkgName);
2267 if (pkg != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002268 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002269 resolvedType, flags, pkg.receivers);
2270 }
2271 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 }
2273 }
2274
2275 public ResolveInfo resolveService(Intent intent, String resolvedType,
2276 int flags) {
2277 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2278 flags);
2279 if (query != null) {
2280 if (query.size() >= 1) {
2281 // If there is more than one service with the same priority,
2282 // just arbitrarily pick the first one.
2283 return query.get(0);
2284 }
2285 }
2286 return null;
2287 }
2288
2289 public List<ResolveInfo> queryIntentServices(Intent intent,
2290 String resolvedType, int flags) {
2291 ComponentName comp = intent.getComponent();
2292 if (comp != null) {
2293 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2294 ServiceInfo si = getServiceInfo(comp, flags);
2295 if (si != null) {
2296 ResolveInfo ri = new ResolveInfo();
2297 ri.serviceInfo = si;
2298 list.add(ri);
2299 }
2300 return list;
2301 }
2302
2303 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002304 String pkgName = intent.getPackage();
2305 if (pkgName == null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002306 return (List<ResolveInfo>)mServices.queryIntent(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002307 resolvedType, flags);
2308 }
2309 PackageParser.Package pkg = mPackages.get(pkgName);
2310 if (pkg != null) {
Jason parksa3cdaa52011-01-13 14:15:43 -06002311 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002312 resolvedType, flags, pkg.services);
2313 }
2314 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
2316 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 public List<PackageInfo> getInstalledPackages(int flags) {
2319 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2320
2321 synchronized (mPackages) {
2322 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2323 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2324 while (i.hasNext()) {
2325 final PackageSetting ps = i.next();
2326 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2327 if(psPkg != null) {
2328 finalList.add(psPkg);
2329 }
2330 }
2331 }
2332 else {
2333 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2334 while (i.hasNext()) {
2335 final PackageParser.Package p = i.next();
2336 if (p.applicationInfo != null) {
2337 PackageInfo pi = generatePackageInfo(p, flags);
2338 if(pi != null) {
2339 finalList.add(pi);
2340 }
2341 }
2342 }
2343 }
2344 }
2345 return finalList;
2346 }
2347
2348 public List<ApplicationInfo> getInstalledApplications(int flags) {
2349 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2350 synchronized(mPackages) {
2351 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2352 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2353 while (i.hasNext()) {
2354 final PackageSetting ps = i.next();
2355 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2356 if(ai != null) {
2357 finalList.add(ai);
2358 }
2359 }
2360 }
2361 else {
2362 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2363 while (i.hasNext()) {
2364 final PackageParser.Package p = i.next();
2365 if (p.applicationInfo != null) {
2366 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2367 if(ai != null) {
2368 finalList.add(ai);
2369 }
2370 }
2371 }
2372 }
2373 }
2374 return finalList;
2375 }
2376
2377 public List<ApplicationInfo> getPersistentApplications(int flags) {
2378 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2379
2380 synchronized (mPackages) {
2381 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2382 while (i.hasNext()) {
2383 PackageParser.Package p = i.next();
2384 if (p.applicationInfo != null
2385 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002386 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002387 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 }
2389 }
2390 }
2391
2392 return finalList;
2393 }
2394
2395 public ProviderInfo resolveContentProvider(String name, int flags) {
2396 synchronized (mPackages) {
2397 final PackageParser.Provider provider = mProviders.get(name);
2398 return provider != null
2399 && mSettings.isEnabledLP(provider.info, flags)
2400 && (!mSafeMode || (provider.info.applicationInfo.flags
2401 &ApplicationInfo.FLAG_SYSTEM) != 0)
2402 ? PackageParser.generateProviderInfo(provider, flags)
2403 : null;
2404 }
2405 }
2406
Fred Quintana718d8a22009-04-29 17:53:20 -07002407 /**
2408 * @deprecated
2409 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 public void querySyncProviders(List outNames, List outInfo) {
2411 synchronized (mPackages) {
2412 Iterator<Map.Entry<String, PackageParser.Provider>> i
2413 = mProviders.entrySet().iterator();
2414
2415 while (i.hasNext()) {
2416 Map.Entry<String, PackageParser.Provider> entry = i.next();
2417 PackageParser.Provider p = entry.getValue();
2418
2419 if (p.syncable
2420 && (!mSafeMode || (p.info.applicationInfo.flags
2421 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2422 outNames.add(entry.getKey());
2423 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2424 }
2425 }
2426 }
2427 }
2428
2429 public List<ProviderInfo> queryContentProviders(String processName,
2430 int uid, int flags) {
2431 ArrayList<ProviderInfo> finalList = null;
2432
2433 synchronized (mPackages) {
2434 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2435 while (i.hasNext()) {
2436 PackageParser.Provider p = i.next();
2437 if (p.info.authority != null
2438 && (processName == null ||
2439 (p.info.processName.equals(processName)
2440 && p.info.applicationInfo.uid == uid))
2441 && mSettings.isEnabledLP(p.info, flags)
2442 && (!mSafeMode || (p.info.applicationInfo.flags
2443 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2444 if (finalList == null) {
2445 finalList = new ArrayList<ProviderInfo>(3);
2446 }
2447 finalList.add(PackageParser.generateProviderInfo(p,
2448 flags));
2449 }
2450 }
2451 }
2452
2453 if (finalList != null) {
2454 Collections.sort(finalList, mProviderInitOrderSorter);
2455 }
2456
2457 return finalList;
2458 }
2459
2460 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2461 int flags) {
2462 synchronized (mPackages) {
2463 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2464 return PackageParser.generateInstrumentationInfo(i, flags);
2465 }
2466 }
2467
2468 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2469 int flags) {
2470 ArrayList<InstrumentationInfo> finalList =
2471 new ArrayList<InstrumentationInfo>();
2472
2473 synchronized (mPackages) {
2474 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2475 while (i.hasNext()) {
2476 PackageParser.Instrumentation p = i.next();
2477 if (targetPackage == null
2478 || targetPackage.equals(p.info.targetPackage)) {
2479 finalList.add(PackageParser.generateInstrumentationInfo(p,
2480 flags));
2481 }
2482 }
2483 }
2484
2485 return finalList;
2486 }
2487
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002488 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002490 if (files == null) {
2491 Log.d(TAG, "No files in app dir " + dir);
2492 return;
2493 }
2494
Joe Onorato431bb222010-10-18 19:13:23 -04002495 if (false) {
2496 Log.d(TAG, "Scanning app dir " + dir);
2497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498
2499 int i;
2500 for (i=0; i<files.length; i++) {
2501 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002502 if (!isPackageFilename(files[i])) {
2503 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002504 continue;
2505 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002506 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002507 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002508 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002509 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2510 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002511 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002512 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002513 file.delete();
2514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 }
2516 }
2517
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002518 private static File getSettingsProblemFile() {
2519 File dataDir = Environment.getDataDirectory();
2520 File systemDir = new File(dataDir, "system");
2521 File fname = new File(systemDir, "uiderrors.txt");
2522 return fname;
2523 }
2524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 private static void reportSettingsProblem(int priority, String msg) {
2526 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002527 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 FileOutputStream out = new FileOutputStream(fname, true);
2529 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002530 SimpleDateFormat formatter = new SimpleDateFormat();
2531 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2532 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 pw.close();
2534 FileUtils.setPermissions(
2535 fname.toString(),
2536 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2537 -1, -1);
2538 } catch (java.io.IOException e) {
2539 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002540 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 }
2542
2543 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2544 PackageParser.Package pkg, File srcFile, int parseFlags) {
2545 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002546 if (ps != null
2547 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002548 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002549 if (ps.signatures.mSignatures != null
2550 && ps.signatures.mSignatures.length != 0) {
2551 // Optimization: reuse the existing cached certificates
2552 // if the package appears to be unchanged.
2553 pkg.mSignatures = ps.signatures.mSignatures;
2554 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 }
Jeff Browne7600722010-04-07 18:28:23 -07002556
2557 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002558 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002559 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2560 }
2561
2562 if (!pp.collectCertificates(pkg, parseFlags)) {
2563 mLastScanError = pp.getParseError();
2564 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 }
2566 }
2567 return true;
2568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 /*
2571 * Scan a package and return the newly parsed package.
2572 * Returns null in case of errors and the error code is stored in mLastScanError
2573 */
2574 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002575 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002577 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002579 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002582 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 if (pkg == null) {
2584 mLastScanError = pp.getParseError();
2585 return null;
2586 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002587 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 PackageSetting updatedPkg;
2589 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002590 // Look to see if we already know about this package.
2591 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002592 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002593 // This package has been renamed to its original name. Let's
2594 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002595 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002596 }
2597 // If there was no original package, see one for the real package name.
2598 if (ps == null) {
2599 ps = mSettings.peekPackageLP(pkg.packageName);
2600 }
2601 // Check to see if this package could be hiding/updating a system
2602 // package. Must look for it either under the original or real
2603 // package name depending on our state.
2604 updatedPkg = mSettings.mDisabledSysPackages.get(
2605 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002607 // First check if this is a system package that may involve an update
2608 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002609 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002610 // The path has changed from what was last scanned... check the
2611 // version of the new path against what we have stored to determine
2612 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002613 if (pkg.mVersionCode < ps.versionCode) {
2614 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002615 // Ignore entry. Skip it.
2616 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002617 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002618 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002619 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2620 return null;
2621 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002622 // The current app on the system partion is better than
2623 // what we have updated to on the data partition; switch
2624 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002625 // At this point, its safely assumed that package installation for
2626 // apps in system partition will go through. If not there won't be a working
2627 // version of the app
2628 synchronized (mPackages) {
2629 // Just remove the loaded entries from package lists.
2630 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002631 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002632 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002633 + "reverting from " + ps.codePathString
2634 + ": new version " + pkg.mVersionCode
2635 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002636 InstallArgs args = new FileInstallArgs(ps.codePathString,
2637 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002638 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002639 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 }
2642 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002643 if (updatedPkg != null) {
2644 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2645 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2646 }
2647 // Verify certificates against what was last scanned
2648 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002649 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002650 return null;
2651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 // The apk is forward locked (not public) if its code and resources
2653 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002654 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002656 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002657 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002658
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002659 String codePath = null;
2660 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002661 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2662 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002663 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002664 } else {
2665 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002666 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002667 }
2668 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002669 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002670 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002671 codePath = pkg.mScanPath;
2672 // Set application objects path explicitly.
2673 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002675 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
2677
Kenny Root85387d72010-08-26 10:13:11 -07002678 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2679 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002680 pkg.mPath = pkg.mScanPath = destCodePath;
2681 pkg.applicationInfo.sourceDir = destCodePath;
2682 pkg.applicationInfo.publicSourceDir = destResPath;
2683 }
2684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 private static String fixProcessName(String defProcessName,
2686 String processName, int uid) {
2687 if (processName == null) {
2688 return defProcessName;
2689 }
2690 return processName;
2691 }
2692
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002693 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002694 PackageParser.Package pkg) {
2695 if (pkgSetting.signatures.mSignatures != null) {
2696 // Already existing package. Make sure signatures match
2697 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2698 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002699 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002700 + " signatures do not match the previously installed version; ignoring!");
2701 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 return false;
2703 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002704 }
2705 // Check for shared user signatures
2706 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2707 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2708 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2709 Slog.e(TAG, "Package " + pkg.packageName
2710 + " has no signatures that match those in shared user "
2711 + pkgSetting.sharedUser.name + "; ignoring!");
2712 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2713 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 }
2716 return true;
2717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002718
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002719 public boolean performDexOpt(String packageName) {
2720 if (!mNoDexOpt) {
2721 return false;
2722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002723
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002724 PackageParser.Package p;
2725 synchronized (mPackages) {
2726 p = mPackages.get(packageName);
2727 if (p == null || p.mDidDexOpt) {
2728 return false;
2729 }
2730 }
2731 synchronized (mInstallLock) {
2732 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2733 }
2734 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002735
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002736 static final int DEX_OPT_SKIPPED = 0;
2737 static final int DEX_OPT_PERFORMED = 1;
2738 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002739
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002740 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2741 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002742 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002743 String path = pkg.mScanPath;
2744 int ret = 0;
2745 try {
2746 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002747 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002748 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002749 pkg.mDidDexOpt = true;
2750 performed = true;
2751 }
2752 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002753 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002754 ret = -1;
2755 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002756 Slog.w(TAG, "IOException reading apk: " + path, e);
2757 ret = -1;
2758 } catch (dalvik.system.StaleDexCacheError e) {
2759 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2760 ret = -1;
2761 } catch (Exception e) {
2762 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002763 ret = -1;
2764 }
2765 if (ret < 0) {
2766 //error from installer
2767 return DEX_OPT_FAILED;
2768 }
2769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002770
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002771 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2772 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002773
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002774 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2775 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002776 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002777 + " to " + newPkg.packageName
2778 + ": old package not in system partition");
2779 return false;
2780 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002781 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002782 + " to " + newPkg.packageName
2783 + ": old package still exists");
2784 return false;
2785 }
2786 return true;
2787 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002788
2789 private File getDataPathForPackage(PackageParser.Package pkg) {
Kenny Root35ab3ad2011-02-02 16:42:14 -08002790 final File dataPath = new File(mAppDataDir, pkg.packageName);
Jason parksa3cdaa52011-01-13 14:15:43 -06002791 return dataPath;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002792 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002793
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002794 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002795 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002796 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002797 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2798 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002799 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002800 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002801 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2802 return null;
2803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 mScanningPath = scanFile;
2805 if (pkg == null) {
2806 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2807 return null;
2808 }
2809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2811 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2812 }
2813
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002814 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 synchronized (mPackages) {
2816 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002817 Slog.w(TAG, "*************************************************");
2818 Slog.w(TAG, "Core android package being redefined. Skipping.");
2819 Slog.w(TAG, " file=" + mScanningPath);
2820 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2822 return null;
2823 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 // Set up information for our fall-back user intent resolution
2826 // activity.
2827 mPlatformPackage = pkg;
2828 pkg.mVersionCode = mSdkVersion;
2829 mAndroidApplication = pkg.applicationInfo;
2830 mResolveActivity.applicationInfo = mAndroidApplication;
2831 mResolveActivity.name = ResolverActivity.class.getName();
2832 mResolveActivity.packageName = mAndroidApplication.packageName;
2833 mResolveActivity.processName = mAndroidApplication.processName;
2834 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2835 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
Joe Onorato646f46e2010-11-08 15:08:56 -08002836 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 mResolveActivity.exported = true;
2838 mResolveActivity.enabled = true;
2839 mResolveInfo.activityInfo = mResolveActivity;
2840 mResolveInfo.priority = 0;
2841 mResolveInfo.preferredOrder = 0;
2842 mResolveInfo.match = 0;
2843 mResolveComponentName = new ComponentName(
2844 mAndroidApplication.packageName, mResolveActivity.name);
2845 }
2846 }
2847
2848 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002849 TAG, "Scanning package " + pkg.packageName);
2850 if (mPackages.containsKey(pkg.packageName)
2851 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002852 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2855 return null;
2856 }
2857
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002858 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002859 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2860 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 SharedUserSetting suid = null;
2863 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002864
Kenny Root502e9a42011-01-10 13:48:15 -08002865 if (!isSystemApp(pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002866 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002867 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002868 pkg.mRealPackage = null;
2869 pkg.mAdoptPermissions = null;
2870 }
Kenny Root502e9a42011-01-10 13:48:15 -08002871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 synchronized (mPackages) {
2873 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002874 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2875 if (mTmpSharedLibraries == null ||
2876 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2877 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2878 }
2879 int num = 0;
2880 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2881 for (int i=0; i<N; i++) {
2882 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002884 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002886 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2888 return null;
2889 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002890 mTmpSharedLibraries[num] = file;
2891 num++;
2892 }
2893 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2894 for (int i=0; i<N; i++) {
2895 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2896 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002897 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002898 + " desires unavailable shared library "
2899 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2900 } else {
2901 mTmpSharedLibraries[num] = file;
2902 num++;
2903 }
2904 }
2905 if (num > 0) {
2906 pkg.usesLibraryFiles = new String[num];
2907 System.arraycopy(mTmpSharedLibraries, 0,
2908 pkg.usesLibraryFiles, 0, num);
2909 }
Kenny Root1683afa2011-01-07 14:27:50 -08002910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 if (pkg.mSharedUserId != null) {
2913 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2914 pkg.applicationInfo.flags, true);
2915 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002916 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 + " for shared user failed");
2918 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2919 return null;
2920 }
2921 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2922 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2923 + suid.userId + "): packages=" + suid.packages);
2924 }
2925 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002926
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002927 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002928 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002929 Log.w(TAG, "WAITING FOR DEBUGGER");
2930 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002931 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2932 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002933 }
2934 }
2935
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002936 // Check if we are renaming from an original package name.
2937 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002938 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002939 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002940 // This package may need to be renamed to a previously
2941 // installed name. Let's check on that...
2942 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002943 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002944 // This package had originally been installed as the
2945 // original name, and we have already taken care of
2946 // transitioning to the new one. Just update the new
2947 // one to continue using the old name.
2948 realName = pkg.mRealPackage;
2949 if (!pkg.packageName.equals(renamed)) {
2950 // Callers into this function may have already taken
2951 // care of renaming the package; only do it here if
2952 // it is not already done.
2953 pkg.setPackageName(renamed);
2954 }
2955
Dianne Hackbornc1552392010-03-03 16:19:01 -08002956 } else {
2957 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2958 if ((origPackage=mSettings.peekPackageLP(
2959 pkg.mOriginalPackages.get(i))) != null) {
2960 // We do have the package already installed under its
2961 // original name... should we use it?
2962 if (!verifyPackageUpdate(origPackage, pkg)) {
2963 // New package is not compatible with original.
2964 origPackage = null;
2965 continue;
2966 } else if (origPackage.sharedUser != null) {
2967 // Make sure uid is compatible between packages.
2968 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002969 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002970 + " to " + pkg.packageName + ": old uid "
2971 + origPackage.sharedUser.name
2972 + " differs from " + pkg.mSharedUserId);
2973 origPackage = null;
2974 continue;
2975 }
2976 } else {
2977 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2978 + pkg.packageName + " to old name " + origPackage.name);
2979 }
2980 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002981 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002982 }
2983 }
2984 }
2985
2986 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002987 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002988 + " was transferred to another, but its .apk remains");
2989 }
2990
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002991 // Just create the setting, don't add it yet. For already existing packages
2992 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002993 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07002994 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
2995 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002997 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2999 return null;
3000 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003001
3002 if (pkgSetting.origPackage != null) {
3003 // If we are first transitioning from an original package,
3004 // fix up the new package's name now. We need to do this after
3005 // looking up the package under its new name, so getPackageLP
3006 // can take care of fiddling things correctly.
3007 pkg.setPackageName(origPackage.name);
3008
3009 // File a report about this.
3010 String msg = "New package " + pkgSetting.realName
3011 + " renamed to replace old package " + pkgSetting.name;
3012 reportSettingsProblem(Log.WARN, msg);
3013
3014 // Make a note of it.
3015 mTransferedPackages.add(origPackage.name);
3016
3017 // No longer need to retain this.
3018 pkgSetting.origPackage = null;
3019 }
3020
3021 if (realName != null) {
3022 // Make a note of it.
3023 mTransferedPackages.add(pkg.packageName);
3024 }
3025
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003026 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 pkg.applicationInfo.uid = pkgSetting.userId;
3031 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003032
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003033 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003034 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 return null;
3036 }
3037 // The signature has changed, but this package is in the system
3038 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003039 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 // However... if this package is part of a shared user, but it
3041 // doesn't match the signature of the shared user, let's fail.
3042 // What this means is that you can't change the signatures
3043 // associated with an overall shared user, which doesn't seem all
3044 // that unreasonable.
3045 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003046 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3047 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3048 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3050 return null;
3051 }
3052 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003053 // File a report about this.
3054 String msg = "System package " + pkg.packageName
3055 + " signature changed; retaining data.";
3056 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003058
The Android Open Source Project10592532009-03-18 17:39:46 -07003059 // Verify that this new package doesn't have any content providers
3060 // that conflict with existing packages. Only do this if the
3061 // package isn't already installed, since we don't want to break
3062 // things that are installed.
3063 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3064 int N = pkg.providers.size();
3065 int i;
3066 for (i=0; i<N; i++) {
3067 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003068 if (p.info.authority != null) {
3069 String names[] = p.info.authority.split(";");
3070 for (int j = 0; j < names.length; j++) {
3071 if (mProviders.containsKey(names[j])) {
3072 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003073 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003074 " (in package " + pkg.applicationInfo.packageName +
3075 ") is already used by "
3076 + ((other != null && other.getComponentName() != null)
3077 ? other.getComponentName().getPackageName() : "?"));
3078 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3079 return null;
3080 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003081 }
3082 }
3083 }
3084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 }
3086
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003087 final String pkgName = pkg.packageName;
3088
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003089 if (pkg.mAdoptPermissions != null) {
3090 // This package wants to adopt ownership of permissions from
3091 // another package.
3092 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3093 String origName = pkg.mAdoptPermissions.get(i);
3094 PackageSetting orig = mSettings.peekPackageLP(origName);
3095 if (orig != null) {
3096 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003097 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003098 + origName + " to " + pkg.packageName);
3099 mSettings.transferPermissions(origName, pkg.packageName);
3100 }
3101 }
3102 }
3103 }
3104
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003105 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003107 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 pkg.applicationInfo.processName = fixProcessName(
3109 pkg.applicationInfo.packageName,
3110 pkg.applicationInfo.processName,
3111 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112
3113 File dataPath;
3114 if (mPlatformPackage == pkg) {
3115 // The system package is special.
3116 dataPath = new File (Environment.getDataDirectory(), "system");
3117 pkg.applicationInfo.dataDir = dataPath.getPath();
3118 } else {
3119 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003120 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003121
3122 boolean uidError = false;
3123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003124 if (dataPath.exists()) {
3125 mOutPermissions[1] = 0;
3126 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003127
3128 // If we have mismatched owners for the data path, we have a
3129 // problem (unless we're running in the simulator.)
3130 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 boolean recovered = false;
3132 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3133 // If this is a system app, we can at least delete its
3134 // current data so the application will still work.
3135 if (mInstaller != null) {
Kenny Root35ab3ad2011-02-02 16:42:14 -08003136 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003137 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 // Old data gone!
3139 String msg = "System package " + pkg.packageName
3140 + " has changed from uid: "
3141 + mOutPermissions[1] + " to "
3142 + pkg.applicationInfo.uid + "; old data erased";
3143 reportSettingsProblem(Log.WARN, msg);
3144 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 // And now re-install the app.
Kenny Root35ab3ad2011-02-02 16:42:14 -08003147 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 pkg.applicationInfo.uid);
3149 if (ret == -1) {
3150 // Ack should not happen!
3151 msg = "System package " + pkg.packageName
3152 + " could not have data directory re-created after delete.";
3153 reportSettingsProblem(Log.WARN, msg);
3154 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3155 return null;
3156 }
3157 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 if (!recovered) {
3160 mHasSystemUidErrors = true;
3161 }
3162 }
3163 if (!recovered) {
3164 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3165 + pkg.applicationInfo.uid + "/fs_"
3166 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003167 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 String msg = "Package " + pkg.packageName
3169 + " has mismatched uid: "
3170 + mOutPermissions[1] + " on disk, "
3171 + pkg.applicationInfo.uid + " in settings";
3172 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003173 mSettings.mReadMessages.append(msg);
3174 mSettings.mReadMessages.append('\n');
3175 uidError = true;
3176 if (!pkgSetting.uidError) {
3177 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 }
3180 }
3181 }
3182 pkg.applicationInfo.dataDir = dataPath.getPath();
3183 } else {
3184 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3185 Log.v(TAG, "Want this data dir: " + dataPath);
3186 //invoke installer to do the actual installation
3187 if (mInstaller != null) {
Kenny Root35ab3ad2011-02-02 16:42:14 -08003188 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 pkg.applicationInfo.uid);
3190 if(ret < 0) {
3191 // Error from installer
3192 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3193 return null;
3194 }
3195 } else {
3196 dataPath.mkdirs();
3197 if (dataPath.exists()) {
3198 FileUtils.setPermissions(
3199 dataPath.toString(),
3200 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3201 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3202 }
3203 }
3204 if (dataPath.exists()) {
3205 pkg.applicationInfo.dataDir = dataPath.getPath();
3206 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003207 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 pkg.applicationInfo.dataDir = null;
3209 }
3210 }
Kenny Root85387d72010-08-26 10:13:11 -07003211
3212 /*
3213 * Set the data dir to the default "/data/data/<package name>/lib"
3214 * if we got here without anyone telling us different (e.g., apps
3215 * stored on SD card have their native libraries stored in the ASEC
3216 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003217 *
3218 * This happens during an upgrade from a package settings file that
3219 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003220 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003221 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3222 if (pkgSetting.nativeLibraryPathString == null) {
3223 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3224 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3225 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3226 } else {
3227 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3228 }
Kenny Root85387d72010-08-26 10:13:11 -07003229 }
3230
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003231 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 }
3233
Kenny Root85387d72010-08-26 10:13:11 -07003234 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 if (mInstaller != null) {
3236 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003237 /* Note: We don't want to unpack the native binaries for
3238 * system applications, unless they have been updated
3239 * (the binaries are already under /system/lib).
3240 * Also, don't unpack libs for apps on the external card
3241 * since they should have their libraries in the ASEC
3242 * container already.
3243 *
3244 * In other words, we're going to unpack the binaries
3245 * only for non-system apps and system app upgrades.
3246 */
Kenny Root831baa22010-10-05 12:29:25 -07003247 if (pkg.applicationInfo.nativeLibraryDir != null) {
Kenny Roote68d58a2010-10-18 16:08:54 -07003248 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3249 final String dataPathString = dataPath.getPath();
3250
Kenny Root831baa22010-10-05 12:29:25 -07003251 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3252 /*
3253 * Upgrading from a previous version of the OS sometimes
3254 * leaves native libraries in the /data/data/<app>/lib
3255 * directory for system apps even when they shouldn't be.
3256 * Recent changes in the JNI library search path
3257 * necessitates we remove those to match previous behavior.
3258 */
Kenny Roote68d58a2010-10-18 16:08:54 -07003259 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Kenny Root831baa22010-10-05 12:29:25 -07003260 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3261 }
Kenny Roote68d58a2010-10-18 16:08:54 -07003262 } else if (nativeLibraryDir.getParent().equals(dataPathString)) {
3263 /*
3264 * If this is an internal application or our
3265 * nativeLibraryPath points to our data directory, unpack
3266 * the libraries. The native library path pointing to the
3267 * data directory for an application in an ASEC container
3268 * can happen for older apps that existed before an OTA to
3269 * Gingerbread.
3270 */
3271 Slog.i(TAG, "Unpacking native libraries for " + path);
3272 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
3273 NativeLibraryHelper.copyNativeBinariesLI(scanFile, nativeLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003274 } else {
Kenny Roote68d58a2010-10-18 16:08:54 -07003275 Slog.i(TAG, "Linking native library dir for " + path);
3276 mInstaller.linkNativeLibraryDirectory(dataPathString,
Kenny Root6a6b0072010-10-07 16:46:10 -07003277 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003280 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003281
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003282 if ((scanMode&SCAN_NO_DEX) == 0) {
3283 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3285 return null;
3286 }
3287 }
3288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 if (mFactoryTest && pkg.requestedPermissions.contains(
3291 android.Manifest.permission.FACTORY_TEST)) {
3292 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3293 }
3294
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003295 // Request the ActivityManager to kill the process(only for existing packages)
3296 // so that we do not end up in a confused state while the user is still using the older
3297 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003298 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003299 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003300 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003301 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003304 // We don't expect installation to fail beyond this point,
3305 if ((scanMode&SCAN_MONITOR) != 0) {
3306 mAppDirs.put(pkg.mPath, pkg);
3307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003309 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003311 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003312 // Make sure we don't accidentally delete its data.
3313 mSettings.mPackagesToBeCleaned.remove(pkgName);
3314
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003315 // Take care of first install / last update times.
3316 if (currentTime != 0) {
3317 if (pkgSetting.firstInstallTime == 0) {
3318 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3319 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3320 pkgSetting.lastUpdateTime = currentTime;
3321 }
3322 } else if (pkgSetting.firstInstallTime == 0) {
3323 // We need *something*. Take time time stamp of the file.
3324 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3325 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3326 if (scanFileTime != pkgSetting.timeStamp) {
3327 // A package on the system image has changed; consider this
3328 // to be an update.
3329 pkgSetting.lastUpdateTime = scanFileTime;
3330 }
3331 }
3332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 int N = pkg.providers.size();
3334 StringBuilder r = null;
3335 int i;
3336 for (i=0; i<N; i++) {
3337 PackageParser.Provider p = pkg.providers.get(i);
3338 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3339 p.info.processName, pkg.applicationInfo.uid);
3340 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3341 p.info.name), p);
3342 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003343 if (p.info.authority != null) {
3344 String names[] = p.info.authority.split(";");
3345 p.info.authority = null;
3346 for (int j = 0; j < names.length; j++) {
3347 if (j == 1 && p.syncable) {
3348 // We only want the first authority for a provider to possibly be
3349 // syncable, so if we already added this provider using a different
3350 // authority clear the syncable flag. We copy the provider before
3351 // changing it because the mProviders object contains a reference
3352 // to a provider that we don't want to change.
3353 // Only do this for the second authority since the resulting provider
3354 // object can be the same for all future authorities for this provider.
3355 p = new PackageParser.Provider(p);
3356 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003358 if (!mProviders.containsKey(names[j])) {
3359 mProviders.put(names[j], p);
3360 if (p.info.authority == null) {
3361 p.info.authority = names[j];
3362 } else {
3363 p.info.authority = p.info.authority + ";" + names[j];
3364 }
3365 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3366 Log.d(TAG, "Registered content provider: " + names[j] +
3367 ", className = " + p.info.name +
3368 ", isSyncable = " + p.info.isSyncable);
3369 } else {
3370 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003371 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003372 " (in package " + pkg.applicationInfo.packageName +
3373 "): name already used by "
3374 + ((other != null && other.getComponentName() != null)
3375 ? other.getComponentName().getPackageName() : "?"));
3376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 }
3378 }
3379 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3380 if (r == null) {
3381 r = new StringBuilder(256);
3382 } else {
3383 r.append(' ');
3384 }
3385 r.append(p.info.name);
3386 }
3387 }
3388 if (r != null) {
3389 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3390 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 N = pkg.services.size();
3393 r = null;
3394 for (i=0; i<N; i++) {
3395 PackageParser.Service s = pkg.services.get(i);
3396 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3397 s.info.processName, pkg.applicationInfo.uid);
3398 mServices.addService(s);
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(s.info.name);
3406 }
3407 }
3408 if (r != null) {
3409 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3410 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 N = pkg.receivers.size();
3413 r = null;
3414 for (i=0; i<N; i++) {
3415 PackageParser.Activity a = pkg.receivers.get(i);
3416 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3417 a.info.processName, pkg.applicationInfo.uid);
3418 mReceivers.addActivity(a, "receiver");
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(a.info.name);
3426 }
3427 }
3428 if (r != null) {
3429 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3430 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 N = pkg.activities.size();
3433 r = null;
3434 for (i=0; i<N; i++) {
3435 PackageParser.Activity a = pkg.activities.get(i);
3436 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3437 a.info.processName, pkg.applicationInfo.uid);
3438 mActivities.addActivity(a, "activity");
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, " Activities: " + r);
3450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 N = pkg.permissionGroups.size();
3453 r = null;
3454 for (i=0; i<N; i++) {
3455 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3456 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3457 if (cur == null) {
3458 mPermissionGroups.put(pg.info.name, pg);
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(pg.info.name);
3466 }
3467 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003468 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 + pg.info.packageName + " ignored: original from "
3470 + cur.info.packageName);
3471 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3472 if (r == null) {
3473 r = new StringBuilder(256);
3474 } else {
3475 r.append(' ');
3476 }
3477 r.append("DUP:");
3478 r.append(pg.info.name);
3479 }
3480 }
3481 }
3482 if (r != null) {
3483 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3484 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 N = pkg.permissions.size();
3487 r = null;
3488 for (i=0; i<N; i++) {
3489 PackageParser.Permission p = pkg.permissions.get(i);
3490 HashMap<String, BasePermission> permissionMap =
3491 p.tree ? mSettings.mPermissionTrees
3492 : mSettings.mPermissions;
3493 p.group = mPermissionGroups.get(p.info.group);
3494 if (p.info.group == null || p.group != null) {
3495 BasePermission bp = permissionMap.get(p.info.name);
3496 if (bp == null) {
3497 bp = new BasePermission(p.info.name, p.info.packageName,
3498 BasePermission.TYPE_NORMAL);
3499 permissionMap.put(p.info.name, bp);
3500 }
3501 if (bp.perm == null) {
3502 if (bp.sourcePackage == null
3503 || bp.sourcePackage.equals(p.info.packageName)) {
3504 BasePermission tree = findPermissionTreeLP(p.info.name);
3505 if (tree == null
3506 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003507 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 bp.perm = p;
3509 bp.uid = pkg.applicationInfo.uid;
3510 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3511 if (r == null) {
3512 r = new StringBuilder(256);
3513 } else {
3514 r.append(' ');
3515 }
3516 r.append(p.info.name);
3517 }
3518 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003519 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 + p.info.packageName + " ignored: base tree "
3521 + tree.name + " is from package "
3522 + tree.sourcePackage);
3523 }
3524 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003525 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 + p.info.packageName + " ignored: original from "
3527 + bp.sourcePackage);
3528 }
3529 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3530 if (r == null) {
3531 r = new StringBuilder(256);
3532 } else {
3533 r.append(' ');
3534 }
3535 r.append("DUP:");
3536 r.append(p.info.name);
3537 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003538 if (bp.perm == p) {
3539 bp.protectionLevel = p.info.protectionLevel;
3540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003542 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 + p.info.packageName + " ignored: no group "
3544 + p.group);
3545 }
3546 }
3547 if (r != null) {
3548 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 N = pkg.instrumentation.size();
3552 r = null;
3553 for (i=0; i<N; i++) {
3554 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3555 a.info.packageName = pkg.applicationInfo.packageName;
3556 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3557 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3558 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003559 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003560 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3562 if (r == null) {
3563 r = new StringBuilder(256);
3564 } else {
3565 r.append(' ');
3566 }
3567 r.append(a.info.name);
3568 }
3569 }
3570 if (r != null) {
3571 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003573
Dianne Hackborn854060af2009-07-09 18:14:31 -07003574 if (pkg.protectedBroadcasts != null) {
3575 N = pkg.protectedBroadcasts.size();
3576 for (i=0; i<N; i++) {
3577 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3578 }
3579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 pkgSetting.setTimeStamp(scanFileTime);
3582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 return pkg;
3585 }
3586
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003587 private void killApplication(String pkgName, int uid) {
3588 // Request the ActivityManager to kill the process(only for existing packages)
3589 // so that we do not end up in a confused state while the user is still using the older
3590 // version of the application while the new one gets installed.
3591 IActivityManager am = ActivityManagerNative.getDefault();
3592 if (am != null) {
3593 try {
3594 am.killApplicationWithUid(pkgName, uid);
3595 } catch (RemoteException e) {
3596 }
3597 }
3598 }
3599
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003600 // Return the path of the directory that will contain the native binaries
3601 // of a given installed package. This is relative to the data path.
3602 //
Kenny Root85387d72010-08-26 10:13:11 -07003603 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3604 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3605 if (nativeLibraryDir != null) {
3606 return new File(nativeLibraryDir);
3607 } else {
3608 // Fall back for old packages
3609 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3610 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003611 }
3612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3614 if (chatty && Config.LOGD) Log.d(
3615 TAG, "Removing package " + pkg.applicationInfo.packageName );
3616
3617 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 mPackages.remove(pkg.applicationInfo.packageName);
3621 if (pkg.mPath != null) {
3622 mAppDirs.remove(pkg.mPath);
3623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 int N = pkg.providers.size();
3626 StringBuilder r = null;
3627 int i;
3628 for (i=0; i<N; i++) {
3629 PackageParser.Provider p = pkg.providers.get(i);
3630 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3631 p.info.name));
3632 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 /* The is another ContentProvider with this authority when
3635 * this app was installed so this authority is null,
3636 * Ignore it as we don't have to unregister the provider.
3637 */
3638 continue;
3639 }
3640 String names[] = p.info.authority.split(";");
3641 for (int j = 0; j < names.length; j++) {
3642 if (mProviders.get(names[j]) == p) {
3643 mProviders.remove(names[j]);
3644 if (chatty && Config.LOGD) Log.d(
3645 TAG, "Unregistered content provider: " + names[j] +
3646 ", className = " + p.info.name +
3647 ", isSyncable = " + p.info.isSyncable);
3648 }
3649 }
3650 if (chatty) {
3651 if (r == null) {
3652 r = new StringBuilder(256);
3653 } else {
3654 r.append(' ');
3655 }
3656 r.append(p.info.name);
3657 }
3658 }
3659 if (r != null) {
3660 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 N = pkg.services.size();
3664 r = null;
3665 for (i=0; i<N; i++) {
3666 PackageParser.Service s = pkg.services.get(i);
3667 mServices.removeService(s);
3668 if (chatty) {
3669 if (r == null) {
3670 r = new StringBuilder(256);
3671 } else {
3672 r.append(' ');
3673 }
3674 r.append(s.info.name);
3675 }
3676 }
3677 if (r != null) {
3678 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3679 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 N = pkg.receivers.size();
3682 r = null;
3683 for (i=0; i<N; i++) {
3684 PackageParser.Activity a = pkg.receivers.get(i);
3685 mReceivers.removeActivity(a, "receiver");
3686 if (chatty) {
3687 if (r == null) {
3688 r = new StringBuilder(256);
3689 } else {
3690 r.append(' ');
3691 }
3692 r.append(a.info.name);
3693 }
3694 }
3695 if (r != null) {
3696 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 N = pkg.activities.size();
3700 r = null;
3701 for (i=0; i<N; i++) {
3702 PackageParser.Activity a = pkg.activities.get(i);
3703 mActivities.removeActivity(a, "activity");
3704 if (chatty) {
3705 if (r == null) {
3706 r = new StringBuilder(256);
3707 } else {
3708 r.append(' ');
3709 }
3710 r.append(a.info.name);
3711 }
3712 }
3713 if (r != null) {
3714 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 N = pkg.permissions.size();
3718 r = null;
3719 for (i=0; i<N; i++) {
3720 PackageParser.Permission p = pkg.permissions.get(i);
3721 boolean tree = false;
3722 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3723 if (bp == null) {
3724 tree = true;
3725 bp = mSettings.mPermissionTrees.get(p.info.name);
3726 }
3727 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003728 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 if (chatty) {
3730 if (r == null) {
3731 r = new StringBuilder(256);
3732 } else {
3733 r.append(' ');
3734 }
3735 r.append(p.info.name);
3736 }
3737 }
3738 }
3739 if (r != null) {
3740 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3741 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 N = pkg.instrumentation.size();
3744 r = null;
3745 for (i=0; i<N; i++) {
3746 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003747 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 if (chatty) {
3749 if (r == null) {
3750 r = new StringBuilder(256);
3751 } else {
3752 r.append(' ');
3753 }
3754 r.append(a.info.name);
3755 }
3756 }
3757 if (r != null) {
3758 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3759 }
3760 }
3761 }
3762
3763 private static final boolean isPackageFilename(String name) {
3764 return name != null && name.endsWith(".apk");
3765 }
3766
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003767 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3768 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3769 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3770 return true;
3771 }
3772 }
3773 return false;
3774 }
3775
3776 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003777 PackageParser.Package pkgInfo, boolean grantPermissions,
3778 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 // Make sure there are no dangling permission trees.
3780 Iterator<BasePermission> it = mSettings.mPermissionTrees
3781 .values().iterator();
3782 while (it.hasNext()) {
3783 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003784 if (bp.packageSetting == null) {
3785 // We may not yet have parsed the package, so just see if
3786 // we still know about its settings.
3787 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3788 }
3789 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003790 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 + " from package " + bp.sourcePackage);
3792 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003793 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3794 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3795 Slog.i(TAG, "Removing old permission tree: " + bp.name
3796 + " from package " + bp.sourcePackage);
3797 grantPermissions = true;
3798 it.remove();
3799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 }
3801 }
3802
3803 // Make sure all dynamic permissions have been assigned to a package,
3804 // and make sure there are no dangling permissions.
3805 it = mSettings.mPermissions.values().iterator();
3806 while (it.hasNext()) {
3807 BasePermission bp = it.next();
3808 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3809 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3810 + bp.name + " pkg=" + bp.sourcePackage
3811 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003812 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 BasePermission tree = findPermissionTreeLP(bp.name);
3814 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003815 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 bp.perm = new PackageParser.Permission(tree.perm.owner,
3817 new PermissionInfo(bp.pendingInfo));
3818 bp.perm.info.packageName = tree.perm.info.packageName;
3819 bp.perm.info.name = bp.name;
3820 bp.uid = tree.uid;
3821 }
3822 }
3823 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003824 if (bp.packageSetting == null) {
3825 // We may not yet have parsed the package, so just see if
3826 // we still know about its settings.
3827 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3828 }
3829 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003830 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 + " from package " + bp.sourcePackage);
3832 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003833 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3834 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3835 Slog.i(TAG, "Removing old permission: " + bp.name
3836 + " from package " + bp.sourcePackage);
3837 grantPermissions = true;
3838 it.remove();
3839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 }
3841 }
3842
3843 // Now update the permissions for all packages, in particular
3844 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003845 if (grantPermissions) {
3846 for (PackageParser.Package pkg : mPackages.values()) {
3847 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003848 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003849 }
3850 }
3851 }
3852
3853 if (pkgInfo != null) {
3854 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 }
3856 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3859 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3860 if (ps == null) {
3861 return;
3862 }
3863 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003864 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 if (replace) {
3867 ps.permissionsFixed = false;
3868 if (gp == ps) {
3869 gp.grantedPermissions.clear();
3870 gp.gids = mGlobalGids;
3871 }
3872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 if (gp.gids == null) {
3875 gp.gids = mGlobalGids;
3876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 final int N = pkg.requestedPermissions.size();
3879 for (int i=0; i<N; i++) {
3880 String name = pkg.requestedPermissions.get(i);
3881 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 if (false) {
3883 if (gp != ps) {
3884 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003885 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 }
3887 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003888 if (bp != null && bp.packageSetting != null) {
3889 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003891 boolean allowedSig = false;
3892 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3893 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003895 } else if (bp.packageSetting == null) {
3896 // This permission is invalid; skip it.
3897 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003898 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3899 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003900 allowed = (checkSignaturesLP(
3901 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003903 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003905 if (!allowed && bp.protectionLevel
3906 == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003907 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 // For updated system applications, the signatureOrSystem permission
3909 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003910 if (isUpdatedSystemApp(pkg)) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003911 PackageSetting sysPs = mSettings.getDisabledSystemPkg(
3912 pkg.packageName);
3913 final GrantedPermissions origGp = sysPs.sharedUser != null
3914 ? sysPs.sharedUser : sysPs;
3915 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 allowed = true;
3917 } else {
3918 allowed = false;
3919 }
3920 } else {
3921 allowed = true;
3922 }
3923 }
3924 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003925 if (allowed) {
3926 allowedSig = true;
3927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 } else {
3929 allowed = false;
3930 }
3931 if (false) {
3932 if (gp != ps) {
3933 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3934 }
3935 }
3936 if (allowed) {
3937 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3938 && ps.permissionsFixed) {
3939 // If this is an existing, non-system package, then
3940 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003941 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003943 // Except... if this is a permission that was added
3944 // to the platform (note: need to only do this when
3945 // updating the platform).
3946 final int NP = PackageParser.NEW_PERMISSIONS.length;
3947 for (int ip=0; ip<NP; ip++) {
3948 final PackageParser.NewPermissionInfo npi
3949 = PackageParser.NEW_PERMISSIONS[ip];
3950 if (npi.name.equals(perm)
3951 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3952 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003953 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003954 + pkg.packageName);
3955 break;
3956 }
3957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 }
3959 }
3960 if (allowed) {
3961 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003962 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 gp.grantedPermissions.add(perm);
3964 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003965 } else if (!ps.haveGids) {
3966 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 }
3968 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003969 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 + " to package " + pkg.packageName
3971 + " because it was previously installed without");
3972 }
3973 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003974 if (gp.grantedPermissions.remove(perm)) {
3975 changedPermission = true;
3976 gp.gids = removeInts(gp.gids, bp.gids);
3977 Slog.i(TAG, "Un-granting permission " + perm
3978 + " from package " + pkg.packageName
3979 + " (protectionLevel=" + bp.protectionLevel
3980 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3981 + ")");
3982 } else {
3983 Slog.w(TAG, "Not granting permission " + perm
3984 + " to package " + pkg.packageName
3985 + " (protectionLevel=" + bp.protectionLevel
3986 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3987 + ")");
3988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 }
3990 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003991 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 + " in package " + pkg.packageName);
3993 }
3994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003995
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003996 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003997 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3998 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 // This is the first that we have heard about this package, so the
4000 // permissions we have now selected are fixed until explicitly
4001 // changed.
4002 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004004 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 private final class ActivityIntentResolver
4008 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004009 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004011 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 }
4013
Mihai Preda074edef2009-05-18 17:13:31 +02004014 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004016 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4018 }
4019
Mihai Predaeae850c2009-05-13 10:13:48 +02004020 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4021 ArrayList<PackageParser.Activity> packageActivities) {
4022 if (packageActivities == null) {
4023 return null;
4024 }
4025 mFlags = flags;
4026 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4027 int N = packageActivities.size();
4028 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4029 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004030
4031 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004032 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004033 intentFilters = packageActivities.get(i).intents;
4034 if (intentFilters != null && intentFilters.size() > 0) {
4035 listCut.add(intentFilters);
4036 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004037 }
4038 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4039 }
4040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 public final void addActivity(PackageParser.Activity a, String type) {
Kenny Root502e9a42011-01-10 13:48:15 -08004042 final boolean systemApp = isSystemApp(a.info.applicationInfo);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004043 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 if (SHOW_INFO || Config.LOGV) Log.v(
4045 TAG, " " + type + " " +
4046 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4047 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4048 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004049 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004050 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
Kenny Root502e9a42011-01-10 13:48:15 -08004051 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
4052 intent.setPriority(0);
4053 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
4054 + a.className + " with priority > 0, forcing to 0");
4055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 if (SHOW_INFO || Config.LOGV) {
4057 Log.v(TAG, " IntentFilter:");
4058 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4059 }
4060 if (!intent.debugCheck()) {
4061 Log.w(TAG, "==> For Activity " + a.info.name);
4062 }
4063 addFilter(intent);
4064 }
4065 }
4066
4067 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004068 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 if (SHOW_INFO || Config.LOGV) Log.v(
4070 TAG, " " + type + " " +
4071 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4072 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4073 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004074 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4076 if (SHOW_INFO || Config.LOGV) {
4077 Log.v(TAG, " IntentFilter:");
4078 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4079 }
4080 removeFilter(intent);
4081 }
4082 }
4083
4084 @Override
4085 protected boolean allowFilterResult(
4086 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4087 ActivityInfo filterAi = filter.activity.info;
4088 for (int i=dest.size()-1; i>=0; i--) {
4089 ActivityInfo destAi = dest.get(i).activityInfo;
4090 if (destAi.name == filterAi.name
4091 && destAi.packageName == filterAi.packageName) {
4092 return false;
4093 }
4094 }
4095 return true;
4096 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004099 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4100 return info.activity.owner.packageName;
4101 }
4102
4103 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4105 int match) {
4106 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4107 return null;
4108 }
4109 final PackageParser.Activity activity = info.activity;
4110 if (mSafeMode && (activity.info.applicationInfo.flags
4111 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4112 return null;
4113 }
4114 final ResolveInfo res = new ResolveInfo();
4115 res.activityInfo = PackageParser.generateActivityInfo(activity,
4116 mFlags);
4117 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4118 res.filter = info;
4119 }
4120 res.priority = info.getPriority();
4121 res.preferredOrder = activity.owner.mPreferredOrder;
4122 //System.out.println("Result: " + res.activityInfo.className +
4123 // " = " + res.priority);
4124 res.match = match;
4125 res.isDefault = info.hasDefault;
4126 res.labelRes = info.labelRes;
4127 res.nonLocalizedLabel = info.nonLocalizedLabel;
4128 res.icon = info.icon;
4129 return res;
4130 }
4131
4132 @Override
4133 protected void sortResults(List<ResolveInfo> results) {
4134 Collections.sort(results, mResolvePrioritySorter);
4135 }
4136
4137 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004138 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004140 out.print(prefix); out.print(
4141 Integer.toHexString(System.identityHashCode(filter.activity)));
4142 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004143 out.print(filter.activity.getComponentShortName());
4144 out.print(" filter ");
4145 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 }
4147
4148// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4149// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4150// final List<ResolveInfo> retList = Lists.newArrayList();
4151// while (i.hasNext()) {
4152// final ResolveInfo resolveInfo = i.next();
4153// if (isEnabledLP(resolveInfo.activityInfo)) {
4154// retList.add(resolveInfo);
4155// }
4156// }
4157// return retList;
4158// }
4159
4160 // Keys are String (activity class name), values are Activity.
4161 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4162 = new HashMap<ComponentName, PackageParser.Activity>();
4163 private int mFlags;
4164 }
4165
4166 private final class ServiceIntentResolver
4167 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004168 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004170 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 }
4172
Mihai Preda074edef2009-05-18 17:13:31 +02004173 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004175 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4177 }
4178
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004179 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4180 ArrayList<PackageParser.Service> packageServices) {
4181 if (packageServices == null) {
4182 return null;
4183 }
4184 mFlags = flags;
4185 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4186 int N = packageServices.size();
4187 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4188 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4189
4190 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4191 for (int i = 0; i < N; ++i) {
4192 intentFilters = packageServices.get(i).intents;
4193 if (intentFilters != null && intentFilters.size() > 0) {
4194 listCut.add(intentFilters);
4195 }
4196 }
4197 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4198 }
4199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004201 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 if (SHOW_INFO || Config.LOGV) Log.v(
4203 TAG, " " + (s.info.nonLocalizedLabel != null
4204 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4205 if (SHOW_INFO || Config.LOGV) Log.v(
4206 TAG, " Class=" + s.info.name);
4207 int NI = s.intents.size();
4208 int j;
4209 for (j=0; j<NI; j++) {
4210 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4211 if (SHOW_INFO || Config.LOGV) {
4212 Log.v(TAG, " IntentFilter:");
4213 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4214 }
4215 if (!intent.debugCheck()) {
4216 Log.w(TAG, "==> For Service " + s.info.name);
4217 }
4218 addFilter(intent);
4219 }
4220 }
4221
4222 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004223 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 if (SHOW_INFO || Config.LOGV) Log.v(
4225 TAG, " " + (s.info.nonLocalizedLabel != null
4226 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4227 if (SHOW_INFO || Config.LOGV) Log.v(
4228 TAG, " Class=" + s.info.name);
4229 int NI = s.intents.size();
4230 int j;
4231 for (j=0; j<NI; j++) {
4232 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4233 if (SHOW_INFO || Config.LOGV) {
4234 Log.v(TAG, " IntentFilter:");
4235 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4236 }
4237 removeFilter(intent);
4238 }
4239 }
4240
4241 @Override
4242 protected boolean allowFilterResult(
4243 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4244 ServiceInfo filterSi = filter.service.info;
4245 for (int i=dest.size()-1; i>=0; i--) {
4246 ServiceInfo destAi = dest.get(i).serviceInfo;
4247 if (destAi.name == filterSi.name
4248 && destAi.packageName == filterSi.packageName) {
4249 return false;
4250 }
4251 }
4252 return true;
4253 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004256 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4257 return info.service.owner.packageName;
4258 }
4259
4260 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4262 int match) {
Jason parksa3cdaa52011-01-13 14:15:43 -06004263 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4265 return null;
4266 }
4267 final PackageParser.Service service = info.service;
4268 if (mSafeMode && (service.info.applicationInfo.flags
4269 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4270 return null;
4271 }
4272 final ResolveInfo res = new ResolveInfo();
4273 res.serviceInfo = PackageParser.generateServiceInfo(service,
4274 mFlags);
4275 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4276 res.filter = filter;
4277 }
4278 res.priority = info.getPriority();
4279 res.preferredOrder = service.owner.mPreferredOrder;
4280 //System.out.println("Result: " + res.activityInfo.className +
4281 // " = " + res.priority);
4282 res.match = match;
4283 res.isDefault = info.hasDefault;
4284 res.labelRes = info.labelRes;
4285 res.nonLocalizedLabel = info.nonLocalizedLabel;
4286 res.icon = info.icon;
4287 return res;
4288 }
4289
4290 @Override
4291 protected void sortResults(List<ResolveInfo> results) {
4292 Collections.sort(results, mResolvePrioritySorter);
4293 }
4294
4295 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004296 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004298 out.print(prefix); out.print(
4299 Integer.toHexString(System.identityHashCode(filter.service)));
4300 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004301 out.print(filter.service.getComponentShortName());
4302 out.print(" filter ");
4303 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 }
4305
4306// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4307// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4308// final List<ResolveInfo> retList = Lists.newArrayList();
4309// while (i.hasNext()) {
4310// final ResolveInfo resolveInfo = (ResolveInfo) i;
4311// if (isEnabledLP(resolveInfo.serviceInfo)) {
4312// retList.add(resolveInfo);
4313// }
4314// }
4315// return retList;
4316// }
4317
4318 // Keys are String (activity class name), values are Activity.
4319 private final HashMap<ComponentName, PackageParser.Service> mServices
4320 = new HashMap<ComponentName, PackageParser.Service>();
4321 private int mFlags;
4322 };
4323
4324 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4325 new Comparator<ResolveInfo>() {
4326 public int compare(ResolveInfo r1, ResolveInfo r2) {
4327 int v1 = r1.priority;
4328 int v2 = r2.priority;
4329 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4330 if (v1 != v2) {
4331 return (v1 > v2) ? -1 : 1;
4332 }
4333 v1 = r1.preferredOrder;
4334 v2 = r2.preferredOrder;
4335 if (v1 != v2) {
4336 return (v1 > v2) ? -1 : 1;
4337 }
4338 if (r1.isDefault != r2.isDefault) {
4339 return r1.isDefault ? -1 : 1;
4340 }
4341 v1 = r1.match;
4342 v2 = r2.match;
4343 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4344 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4345 }
4346 };
4347
4348 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4349 new Comparator<ProviderInfo>() {
4350 public int compare(ProviderInfo p1, ProviderInfo p2) {
4351 final int v1 = p1.initOrder;
4352 final int v2 = p2.initOrder;
4353 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4354 }
4355 };
4356
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004357 private static final void sendPackageBroadcast(String action, String pkg,
4358 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 IActivityManager am = ActivityManagerNative.getDefault();
4360 if (am != null) {
4361 try {
4362 final Intent intent = new Intent(action,
4363 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4364 if (extras != null) {
4365 intent.putExtras(extras);
4366 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004367 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004368 am.broadcastIntent(null, intent, null, finishedReceiver,
4369 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 } catch (RemoteException ex) {
4371 }
4372 }
4373 }
Kenny Root300c13a2011-01-18 13:04:40 -08004374
4375 /**
4376 * Check if the external storage media is available. This is true if there
4377 * is a mounted external storage medium or if the external storage is
4378 * emulated.
4379 */
4380 private boolean isExternalMediaAvailable() {
4381 return mMediaMounted || Environment.isExternalStorageEmulated();
4382 }
4383
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004384 public String nextPackageToClean(String lastPackage) {
4385 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08004386 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004387 // If the external storage is no longer mounted at this point,
4388 // the caller may not have been able to delete all of this
4389 // packages files and can not delete any more. Bail.
4390 return null;
4391 }
4392 if (lastPackage != null) {
4393 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4394 }
4395 return mSettings.mPackagesToBeCleaned.size() > 0
4396 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4397 }
4398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004400 void schedulePackageCleaning(String packageName) {
4401 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4402 }
4403
4404 void startCleaningPackages() {
4405 synchronized (mPackages) {
Kenny Root300c13a2011-01-18 13:04:40 -08004406 if (!isExternalMediaAvailable()) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004407 return;
4408 }
4409 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4410 return;
4411 }
4412 }
4413 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4414 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4415 IActivityManager am = ActivityManagerNative.getDefault();
4416 if (am != null) {
4417 try {
4418 am.startService(null, intent, null);
4419 } catch (RemoteException e) {
4420 }
4421 }
4422 }
4423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 private final class AppDirObserver extends FileObserver {
4425 public AppDirObserver(String path, int mask, boolean isrom) {
4426 super(path, mask);
4427 mRootDir = path;
4428 mIsRom = isrom;
4429 }
4430
4431 public void onEvent(int event, String path) {
4432 String removedPackage = null;
4433 int removedUid = -1;
4434 String addedPackage = null;
4435 int addedUid = -1;
4436
4437 synchronized (mInstallLock) {
4438 String fullPathStr = null;
4439 File fullPath = null;
4440 if (path != null) {
4441 fullPath = new File(mRootDir, path);
4442 fullPathStr = fullPath.getPath();
4443 }
4444
4445 if (Config.LOGV) Log.v(
4446 TAG, "File " + fullPathStr + " changed: "
4447 + Integer.toHexString(event));
4448
4449 if (!isPackageFilename(path)) {
4450 if (Config.LOGV) Log.v(
4451 TAG, "Ignoring change of non-package file: " + fullPathStr);
4452 return;
4453 }
4454
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004455 // Ignore packages that are being installed or
4456 // have just been installed.
4457 if (ignoreCodePath(fullPathStr)) {
4458 return;
4459 }
4460 PackageParser.Package p = null;
4461 synchronized (mPackages) {
4462 p = mAppDirs.get(fullPathStr);
4463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004465 if (p != null) {
4466 removePackageLI(p, true);
4467 removedPackage = p.applicationInfo.packageName;
4468 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 }
4470 }
4471
4472 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004474 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004475 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4476 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 PackageParser.PARSE_CHATTY |
4478 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004479 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4480 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 if (p != null) {
4482 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004483 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004484 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 }
4486 addedPackage = p.applicationInfo.packageName;
4487 addedUid = p.applicationInfo.uid;
4488 }
4489 }
4490 }
4491
4492 synchronized (mPackages) {
4493 mSettings.writeLP();
4494 }
4495 }
4496
4497 if (removedPackage != null) {
4498 Bundle extras = new Bundle(1);
4499 extras.putInt(Intent.EXTRA_UID, removedUid);
4500 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004501 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4502 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 }
4504 if (addedPackage != null) {
4505 Bundle extras = new Bundle(1);
4506 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004507 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4508 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 }
4510 }
4511
4512 private final String mRootDir;
4513 private final boolean mIsRom;
4514 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 /* Called when a downloaded package installation has been confirmed by the user */
4517 public void installPackage(
4518 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004519 installPackage(packageURI, observer, flags, null);
4520 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004521
Jacek Surazski65e13172009-04-28 15:26:38 +02004522 /* Called when a downloaded package installation has been confirmed by the user */
4523 public void installPackage(
4524 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4525 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526 mContext.enforceCallingOrSelfPermission(
4527 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004528
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004529 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004530 msg.obj = new InstallParams(packageURI, observer, flags,
4531 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004532 mHandler.sendMessage(msg);
4533 }
4534
Christopher Tate1bb69062010-02-19 17:02:12 -08004535 public void finishPackageInstall(int token) {
4536 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4537 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4538 mHandler.sendMessage(msg);
4539 }
4540
Dianne Hackborn880119b2010-11-18 22:26:40 -08004541 public void setInstallerPackageName(String targetPackage,
4542 String installerPackageName) {
4543 PackageSetting pkgSetting;
4544 final int uid = Binder.getCallingUid();
4545 final int permission = mContext.checkCallingPermission(
4546 android.Manifest.permission.INSTALL_PACKAGES);
4547 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4548 synchronized (mPackages) {
4549 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
4550 if (targetPackageSetting == null) {
4551 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
4552 }
4553
4554 PackageSetting installerPackageSetting;
4555 if (installerPackageName != null) {
4556 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
4557 if (installerPackageSetting == null) {
4558 throw new IllegalArgumentException("Unknown installer package: "
4559 + installerPackageName);
4560 }
4561 } else {
4562 installerPackageSetting = null;
4563 }
4564
4565 Signature[] callerSignature;
4566 Object obj = mSettings.getUserIdLP(uid);
4567 if (obj != null) {
4568 if (obj instanceof SharedUserSetting) {
4569 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
4570 } else if (obj instanceof PackageSetting) {
4571 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
4572 } else {
4573 throw new SecurityException("Bad object " + obj + " for uid " + uid);
4574 }
4575 } else {
4576 throw new SecurityException("Unknown calling uid " + uid);
4577 }
4578
4579 // Verify: can't set installerPackageName to a package that is
4580 // not signed with the same cert as the caller.
4581 if (installerPackageSetting != null) {
4582 if (checkSignaturesLP(callerSignature,
4583 installerPackageSetting.signatures.mSignatures)
4584 != PackageManager.SIGNATURE_MATCH) {
4585 throw new SecurityException(
4586 "Caller does not have same cert as new installer package "
4587 + installerPackageName);
4588 }
4589 }
4590
4591 // Verify: if target already has an installer package, it must
4592 // be signed with the same cert as the caller.
4593 if (targetPackageSetting.installerPackageName != null) {
4594 PackageSetting setting = mSettings.mPackages.get(
4595 targetPackageSetting.installerPackageName);
4596 // If the currently set package isn't valid, then it's always
4597 // okay to change it.
4598 if (setting != null) {
4599 if (checkSignaturesLP(callerSignature,
4600 setting.signatures.mSignatures)
4601 != PackageManager.SIGNATURE_MATCH) {
4602 throw new SecurityException(
4603 "Caller does not have same cert as old installer package "
4604 + targetPackageSetting.installerPackageName);
4605 }
4606 }
4607 }
4608
4609 // Okay!
4610 targetPackageSetting.installerPackageName = installerPackageName;
4611 scheduleWriteSettingsLocked();
4612 }
4613 }
4614
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004615 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 // Queue up an async operation since the package installation may take a little while.
4617 mHandler.post(new Runnable() {
4618 public void run() {
4619 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004620 // Result object to be returned
4621 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004622 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004623 res.uid = -1;
4624 res.pkg = null;
4625 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004626 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004627 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004628 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004629 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004630 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004631 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004633
4634 // A restore should be performed at this point if (a) the install
4635 // succeeded, (b) the operation is not an update, and (c) the new
4636 // package has a backupAgent defined.
4637 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004638 boolean doRestore = (!update
4639 && res.pkg != null
4640 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004641
4642 // Set up the post-install work request bookkeeping. This will be used
4643 // and cleaned up by the post-install event handling regardless of whether
4644 // there's a restore pass performed. Token values are >= 1.
4645 int token;
4646 if (mNextInstallToken < 0) mNextInstallToken = 1;
4647 token = mNextInstallToken++;
4648
4649 PostInstallData data = new PostInstallData(args, res);
4650 mRunningInstalls.put(token, data);
4651 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4652
4653 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4654 // Pass responsibility to the Backup Manager. It will perform a
4655 // restore if appropriate, then pass responsibility back to the
4656 // Package Manager to run the post-install observer callbacks
4657 // and broadcasts.
4658 IBackupManager bm = IBackupManager.Stub.asInterface(
4659 ServiceManager.getService(Context.BACKUP_SERVICE));
4660 if (bm != null) {
4661 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4662 + " to BM for possible restore");
4663 try {
4664 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4665 } catch (RemoteException e) {
4666 // can't happen; the backup manager is local
4667 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004668 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004669 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004670 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004671 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004672 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004673 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004676
4677 if (!doRestore) {
4678 // No restore possible, or the Backup Manager was mysteriously not
4679 // available -- just fire the post-install work request directly.
4680 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4681 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4682 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 }
4685 });
4686 }
4687
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004688 abstract class HandlerParams {
4689 final static int MAX_RETRIES = 4;
4690 int retry = 0;
4691 final void startCopy() {
4692 try {
4693 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4694 retry++;
4695 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004696 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004697 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4698 handleServiceError();
4699 return;
4700 } else {
4701 handleStartCopy();
4702 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4703 mHandler.sendEmptyMessage(MCS_UNBIND);
4704 }
4705 } catch (RemoteException e) {
4706 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4707 mHandler.sendEmptyMessage(MCS_RECONNECT);
4708 }
4709 handleReturnCode();
4710 }
4711
4712 final void serviceError() {
4713 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4714 handleServiceError();
4715 handleReturnCode();
4716 }
4717 abstract void handleStartCopy() throws RemoteException;
4718 abstract void handleServiceError();
4719 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004720 }
4721
Kenny Root366949c2011-01-14 17:18:14 -08004722 class MeasureParams extends HandlerParams {
4723 private final PackageStats mStats;
4724 private boolean mSuccess;
4725
4726 private final IPackageStatsObserver mObserver;
4727
4728 public MeasureParams(PackageStats stats, boolean success,
4729 IPackageStatsObserver observer) {
4730 mObserver = observer;
4731 mStats = stats;
4732 mSuccess = success;
4733 }
4734
4735 @Override
4736 void handleStartCopy() throws RemoteException {
4737 final boolean mounted;
4738
4739 if (Environment.isExternalStorageEmulated()) {
4740 mounted = true;
4741 } else {
4742 final String status = Environment.getExternalStorageState();
4743
4744 mounted = status.equals(Environment.MEDIA_MOUNTED)
4745 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
4746 }
4747
4748 if (mounted) {
4749 final File externalCacheDir = Environment
4750 .getExternalStorageAppCacheDirectory(mStats.packageName);
4751 final long externalCacheSize = mContainerService
4752 .calculateDirectorySize(externalCacheDir.getPath());
4753 mStats.externalCacheSize = externalCacheSize;
4754
4755 final File externalDataDir = Environment
4756 .getExternalStorageAppDataDirectory(mStats.packageName);
4757 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir
4758 .getPath());
4759
4760 if (externalCacheDir.getParentFile().equals(externalDataDir)) {
4761 externalDataSize -= externalCacheSize;
4762 }
4763 mStats.externalDataSize = externalDataSize;
4764
4765 final File externalMediaDir = Environment
4766 .getExternalStorageAppMediaDirectory(mStats.packageName);
4767 mStats.externalMediaSize = mContainerService
4768 .calculateDirectorySize(externalCacheDir.getPath());
Kenny Rootbcd6c962011-01-17 11:21:49 -08004769
4770 final File externalObbDir = Environment
4771 .getExternalStorageAppObbDirectory(mStats.packageName);
4772 mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir
4773 .getPath());
Kenny Root366949c2011-01-14 17:18:14 -08004774 }
4775 }
4776
4777 @Override
4778 void handleReturnCode() {
4779 if (mObserver != null) {
4780 try {
4781 mObserver.onGetStatsCompleted(mStats, mSuccess);
4782 } catch (RemoteException e) {
4783 Slog.i(TAG, "Observer no longer exists.");
4784 }
4785 }
4786 }
4787
4788 @Override
4789 void handleServiceError() {
4790 Slog.e(TAG, "Could not measure application " + mStats.packageName
4791 + " external storage");
4792 }
4793 }
4794
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004795 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004796 final IPackageInstallObserver observer;
4797 int flags;
4798 final Uri packageURI;
4799 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004800 private InstallArgs mArgs;
4801 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004802 InstallParams(Uri packageURI,
4803 IPackageInstallObserver observer, int flags,
4804 String installerPackageName) {
4805 this.packageURI = packageURI;
4806 this.flags = flags;
4807 this.observer = observer;
4808 this.installerPackageName = installerPackageName;
4809 }
4810
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004811 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4812 String packageName = pkgLite.packageName;
4813 int installLocation = pkgLite.installLocation;
4814 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4815 synchronized (mPackages) {
4816 PackageParser.Package pkg = mPackages.get(packageName);
4817 if (pkg != null) {
4818 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4819 // Check for updated system application.
4820 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4821 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004822 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004823 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4824 }
4825 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4826 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004827 if (onSd) {
4828 // Install flag overrides everything.
4829 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4830 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004831 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004832 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4833 // Application explicitly specified internal.
4834 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4835 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4836 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004837 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004838 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004839 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004840 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4841 }
4842 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004843 }
4844 }
4845 } else {
4846 // Invalid install. Return error code
4847 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4848 }
4849 }
4850 }
4851 // All the special cases have been taken care of.
4852 // Return result based on recommended install location.
4853 if (onSd) {
4854 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4855 }
4856 return pkgLite.recommendedInstallLocation;
4857 }
4858
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004859 /*
4860 * Invoke remote method to get package information and install
4861 * location values. Override install location based on default
4862 * policy if needed and then create install arguments based
4863 * on the install location.
4864 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004865 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004866 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004867 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4868 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004869 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4870 if (onInt && onSd) {
4871 // Check if both bits are set.
4872 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4873 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4874 } else if (fwdLocked && onSd) {
4875 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004876 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004877 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004878 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004879 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07004880 final PackageInfoLite pkgLite;
4881 try {
4882 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4883 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4884 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
4885 } finally {
4886 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4887 }
4888
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004889 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004890 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4891 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4892 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4893 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4894 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004895 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4896 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4897 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004898 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4899 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004900 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004901 // Override with defaults if needed.
4902 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004903 if (!onSd && !onInt) {
4904 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004905 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4906 // Set the flag to install on external media.
4907 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004908 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004909 } else {
4910 // Make sure the flag for installing on external
4911 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004912 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004913 flags &= ~PackageManager.INSTALL_EXTERNAL;
4914 }
4915 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004916 }
4917 }
4918 // Create the file args now.
4919 mArgs = createInstallArgs(this);
4920 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4921 // Create copy only if we are not in an erroneous state.
4922 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004923 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004924 }
4925 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004926 }
4927
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004928 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004929 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004930 // If mArgs is null, then MCS couldn't be reached. When it
4931 // reconnects, it will try again to install. At that point, this
4932 // will succeed.
4933 if (mArgs != null) {
4934 processPendingInstall(mArgs, mRet);
4935 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004936 }
4937
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004938 @Override
4939 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004940 mArgs = createInstallArgs(this);
4941 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004942 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004943 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004944
4945 /*
4946 * Utility class used in movePackage api.
4947 * srcArgs and targetArgs are not set for invalid flags and make
4948 * sure to do null checks when invoking methods on them.
4949 * We probably want to return ErrorPrams for both failed installs
4950 * and moves.
4951 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004952 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004953 final IPackageMoveObserver observer;
4954 final int flags;
4955 final String packageName;
4956 final InstallArgs srcArgs;
4957 final InstallArgs targetArgs;
4958 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004959
4960 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4961 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004962 this.srcArgs = srcArgs;
4963 this.observer = observer;
4964 this.flags = flags;
4965 this.packageName = packageName;
4966 if (srcArgs != null) {
4967 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004968 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004969 } else {
4970 targetArgs = null;
4971 }
4972 }
4973
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004974 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004975 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4976 // Check for storage space on target medium
4977 if (!targetArgs.checkFreeStorage(mContainerService)) {
4978 Log.w(TAG, "Insufficient storage to install");
4979 return;
4980 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004981 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004982 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004983 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004984 if (DEBUG_SD_INSTALL) {
4985 StringBuilder builder = new StringBuilder();
4986 if (srcArgs != null) {
4987 builder.append("src: ");
4988 builder.append(srcArgs.getCodePath());
4989 }
4990 if (targetArgs != null) {
4991 builder.append(" target : ");
4992 builder.append(targetArgs.getCodePath());
4993 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004994 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004995 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004996 }
4997
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004998 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004999 void handleReturnCode() {
5000 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005001 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5002 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5003 currentStatus = PackageManager.MOVE_SUCCEEDED;
5004 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5005 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5006 }
5007 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005008 }
5009
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005010 @Override
5011 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005012 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005013 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005014 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005015
5016 private InstallArgs createInstallArgs(InstallParams params) {
5017 if (installOnSd(params.flags)) {
5018 return new SdInstallArgs(params);
5019 } else {
5020 return new FileInstallArgs(params);
5021 }
5022 }
5023
Kenny Root85387d72010-08-26 10:13:11 -07005024 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
5025 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005026 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07005027 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005028 } else {
Kenny Root85387d72010-08-26 10:13:11 -07005029 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005030 }
5031 }
5032
Kenny Root85387d72010-08-26 10:13:11 -07005033 // Used by package mover
5034 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005035 if (installOnSd(flags)) {
5036 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5037 return new SdInstallArgs(packageURI, cid);
5038 } else {
Kenny Root85387d72010-08-26 10:13:11 -07005039 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005040 }
5041 }
5042
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005043 static abstract class InstallArgs {
5044 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005045 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005046 final int flags;
5047 final Uri packageURI;
5048 final String installerPackageName;
5049
5050 InstallArgs(Uri packageURI,
5051 IPackageInstallObserver observer, int flags,
5052 String installerPackageName) {
5053 this.packageURI = packageURI;
5054 this.flags = flags;
5055 this.observer = observer;
5056 this.installerPackageName = installerPackageName;
5057 }
5058
5059 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005060 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005061 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005062 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005063 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005064 abstract String getCodePath();
5065 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07005066 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005067 // Need installer lock especially for dex file removal.
5068 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005069 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005070 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005071 }
5072
5073 class FileInstallArgs extends InstallArgs {
5074 File installDir;
5075 String codeFileName;
5076 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07005077 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005078 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005079
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005080 FileInstallArgs(InstallParams params) {
5081 super(params.packageURI, params.observer,
5082 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005083 }
5084
Kenny Root85387d72010-08-26 10:13:11 -07005085 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005086 super(null, null, 0, null);
5087 File codeFile = new File(fullCodePath);
5088 installDir = codeFile.getParentFile();
5089 codeFileName = fullCodePath;
5090 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07005091 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005092 }
5093
Kenny Root85387d72010-08-26 10:13:11 -07005094 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005095 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07005096 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005097 String apkName = getNextCodePath(null, pkgName, ".apk");
5098 codeFileName = new File(installDir, apkName + ".apk").getPath();
5099 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07005100 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005101 }
5102
Kenny Root11128572010-10-11 10:51:32 -07005103 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5104 try {
5105 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5106 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5107 return imcs.checkFreeStorage(false, packageURI);
5108 } finally {
5109 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5110 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005111 }
5112
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005113 String getCodePath() {
5114 return codeFileName;
5115 }
5116
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005117 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005118 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005119 codeFileName = createTempPackageFile(installDir).getPath();
5120 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005121 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005122 }
5123
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005124 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005125 if (temp) {
5126 // Generate temp file name
5127 createCopyFile();
5128 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005129 // Get a ParcelFileDescriptor to write to the output file
5130 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005131 if (!created) {
5132 try {
5133 codeFile.createNewFile();
5134 // Set permissions
5135 if (!setPermissions()) {
5136 // Failed setting permissions.
5137 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5138 }
5139 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005140 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005141 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5142 }
5143 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005144 ParcelFileDescriptor out = null;
5145 try {
Kenny Root85387d72010-08-26 10:13:11 -07005146 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005147 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005148 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005149 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5150 }
5151 // Copy the resource now
5152 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5153 try {
Kenny Root11128572010-10-11 10:51:32 -07005154 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5155 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005156 if (imcs.copyResource(packageURI, out)) {
5157 ret = PackageManager.INSTALL_SUCCEEDED;
5158 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005159 } finally {
5160 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005161 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005162 }
Kenny Root85387d72010-08-26 10:13:11 -07005163
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005164 return ret;
5165 }
5166
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005167 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005168 if (status != PackageManager.INSTALL_SUCCEEDED) {
5169 cleanUp();
5170 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005171 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005172 }
5173
5174 boolean doRename(int status, final String pkgName, String oldCodePath) {
5175 if (status != PackageManager.INSTALL_SUCCEEDED) {
5176 cleanUp();
5177 return false;
5178 } else {
5179 // Rename based on packageName
5180 File codeFile = new File(getCodePath());
5181 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5182 File desFile = new File(installDir, apkName + ".apk");
5183 if (!codeFile.renameTo(desFile)) {
5184 return false;
5185 }
5186 // Reset paths since the file has been renamed.
5187 codeFileName = desFile.getPath();
5188 resourceFileName = getResourcePathFromCodePath();
5189 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005190 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005191 // Failed setting permissions.
5192 return false;
5193 }
5194 return true;
5195 }
5196 }
5197
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005198 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005199 if (status != PackageManager.INSTALL_SUCCEEDED) {
5200 cleanUp();
5201 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005202 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005203 }
5204
5205 String getResourcePath() {
5206 return resourceFileName;
5207 }
5208
5209 String getResourcePathFromCodePath() {
5210 String codePath = getCodePath();
5211 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5212 String apkNameOnly = getApkName(codePath);
5213 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5214 } else {
5215 return codePath;
5216 }
5217 }
5218
Kenny Root85387d72010-08-26 10:13:11 -07005219 @Override
5220 String getNativeLibraryPath() {
5221 return libraryPath;
5222 }
5223
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005224 private boolean cleanUp() {
5225 boolean ret = true;
5226 String sourceDir = getCodePath();
5227 String publicSourceDir = getResourcePath();
5228 if (sourceDir != null) {
5229 File sourceFile = new File(sourceDir);
5230 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005231 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005232 ret = false;
5233 }
5234 // Delete application's code and resources
5235 sourceFile.delete();
5236 }
5237 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5238 final File publicSourceFile = new File(publicSourceDir);
5239 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005240 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 }
5242 if (publicSourceFile.exists()) {
5243 publicSourceFile.delete();
5244 }
5245 }
5246 return ret;
5247 }
5248
5249 void cleanUpResourcesLI() {
5250 String sourceDir = getCodePath();
5251 if (cleanUp() && mInstaller != null) {
5252 int retCode = mInstaller.rmdex(sourceDir);
5253 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005254 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005255 + " at location "
5256 + sourceDir + ", retcode=" + retCode);
5257 // we don't consider this to be a failure of the core package deletion
5258 }
5259 }
5260 }
5261
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005262 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005263 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005264 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005265 final int filePermissions =
5266 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5267 |FileUtils.S_IROTH;
5268 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5269 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005270 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005271 getCodePath()
5272 + ". The return code was: " + retCode);
5273 // TODO Define new internal error
5274 return false;
5275 }
5276 return true;
5277 }
5278 return true;
5279 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005280
5281 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005282 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005283 cleanUpResourcesLI();
5284 return true;
5285 }
Kenny Root85387d72010-08-26 10:13:11 -07005286
5287 private boolean isFwdLocked() {
5288 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5289 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005290 }
5291
5292 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005293 static final String RES_FILE_NAME = "pkg.apk";
5294
Kenny Root85387d72010-08-26 10:13:11 -07005295 String cid;
5296 String packagePath;
5297 String libraryPath;
5298
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005299 SdInstallArgs(InstallParams params) {
5300 super(params.packageURI, params.observer,
5301 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005302 }
5303
Kenny Root85387d72010-08-26 10:13:11 -07005304 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005305 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005306 // Extract cid from fullCodePath
5307 int eidx = fullCodePath.lastIndexOf("/");
5308 String subStr1 = fullCodePath.substring(0, eidx);
5309 int sidx = subStr1.lastIndexOf("/");
5310 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005311 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005312 }
5313
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005314 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005315 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5316 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005317 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005318 }
5319
5320 SdInstallArgs(Uri packageURI, String cid) {
5321 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005322 this.cid = cid;
5323 }
5324
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005325 void createCopyFile() {
5326 cid = getTempContainerId();
5327 }
5328
Kenny Root11128572010-10-11 10:51:32 -07005329 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5330 try {
5331 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5332 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5333 return imcs.checkFreeStorage(true, packageURI);
5334 } finally {
5335 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5336 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005337 }
5338
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005339 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005340 if (temp) {
5341 createCopyFile();
5342 }
Kenny Root11128572010-10-11 10:51:32 -07005343
5344 final String newCachePath;
5345 try {
5346 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5347 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5348 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5349 getEncryptKey(), RES_FILE_NAME);
5350 } finally {
5351 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5352 }
5353
Kenny Root85387d72010-08-26 10:13:11 -07005354 if (newCachePath != null) {
5355 setCachePath(newCachePath);
5356 return PackageManager.INSTALL_SUCCEEDED;
5357 } else {
5358 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5359 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005360 }
5361
5362 @Override
5363 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005364 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005365 }
5366
5367 @Override
5368 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005369 return packagePath;
5370 }
5371
5372 @Override
5373 String getNativeLibraryPath() {
5374 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005375 }
5376
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005377 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005378 if (status != PackageManager.INSTALL_SUCCEEDED) {
5379 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005380 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005381 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005382 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005383 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005384 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5385 Process.SYSTEM_UID);
5386 if (newCachePath != null) {
5387 setCachePath(newCachePath);
5388 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005389 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5390 }
5391 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005392 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005393 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005394 }
5395
5396 boolean doRename(int status, final String pkgName,
5397 String oldCodePath) {
5398 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005399 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005400 if (PackageHelper.isContainerMounted(cid)) {
5401 // Unmount the container
5402 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005403 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005404 return false;
5405 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005406 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005407 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005408 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5409 " which might be stale. Will try to clean up.");
5410 // Clean up the stale container and proceed to recreate.
5411 if (!PackageHelper.destroySdDir(newCacheId)) {
5412 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5413 return false;
5414 }
5415 // Successfully cleaned up stale container. Try to rename again.
5416 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5417 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5418 + " inspite of cleaning it up.");
5419 return false;
5420 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005421 }
5422 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005423 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005424 newCachePath = PackageHelper.mountSdDir(newCacheId,
5425 getEncryptKey(), Process.SYSTEM_UID);
5426 } else {
5427 newCachePath = PackageHelper.getSdDir(newCacheId);
5428 }
5429 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005430 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005431 return false;
5432 }
5433 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005434 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005435 " at new path: " + newCachePath);
5436 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005437 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005438 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005439 }
5440
Kenny Root85387d72010-08-26 10:13:11 -07005441 private void setCachePath(String newCachePath) {
5442 File cachePath = new File(newCachePath);
5443 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5444 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5445 }
5446
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005447 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005448 if (status != PackageManager.INSTALL_SUCCEEDED) {
5449 cleanUp();
5450 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005451 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005452 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005453 PackageHelper.mountSdDir(cid,
5454 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005455 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005456 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005457 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005458 }
5459
5460 private void cleanUp() {
5461 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005462 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005463 }
5464
5465 void cleanUpResourcesLI() {
5466 String sourceFile = getCodePath();
5467 // Remove dex file
5468 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005469 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005470 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005471 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005472 + " at location "
5473 + sourceFile.toString() + ", retcode=" + retCode);
5474 // we don't consider this to be a failure of the core package deletion
5475 }
5476 }
5477 cleanUp();
5478 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005479
5480 boolean matchContainer(String app) {
5481 if (cid.startsWith(app)) {
5482 return true;
5483 }
5484 return false;
5485 }
5486
5487 String getPackageName() {
5488 int idx = cid.lastIndexOf("-");
5489 if (idx == -1) {
5490 return cid;
5491 }
5492 return cid.substring(0, idx);
5493 }
5494
5495 boolean doPostDeleteLI(boolean delete) {
5496 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005497 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005498 if (mounted) {
5499 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005500 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005501 }
5502 if (ret && delete) {
5503 cleanUpResourcesLI();
5504 }
5505 return ret;
5506 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005507 };
5508
5509 // Utility method used to create code paths based on package name and available index.
5510 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5511 String idxStr = "";
5512 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005513 // Fall back to default value of idx=1 if prefix is not
5514 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005515 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005516 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005517 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005518 if (subStr.endsWith(suffix)) {
5519 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005520 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005521 // If oldCodePath already contains prefix find out the
5522 // ending index to either increment or decrement.
5523 int sidx = subStr.lastIndexOf(prefix);
5524 if (sidx != -1) {
5525 subStr = subStr.substring(sidx + prefix.length());
5526 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005527 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5528 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005529 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005530 try {
5531 idx = Integer.parseInt(subStr);
5532 if (idx <= 1) {
5533 idx++;
5534 } else {
5535 idx--;
5536 }
5537 } catch(NumberFormatException e) {
5538 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005539 }
5540 }
5541 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005542 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005543 return prefix + idxStr;
5544 }
5545
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005546 // Utility method used to ignore ADD/REMOVE events
5547 // by directory observer.
5548 private static boolean ignoreCodePath(String fullPathStr) {
5549 String apkName = getApkName(fullPathStr);
5550 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5551 if (idx != -1 && ((idx+1) < apkName.length())) {
5552 // Make sure the package ends with a numeral
5553 String version = apkName.substring(idx+1);
5554 try {
5555 Integer.parseInt(version);
5556 return true;
5557 } catch (NumberFormatException e) {}
5558 }
5559 return false;
5560 }
5561
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005562 // Utility method that returns the relative package path with respect
5563 // to the installation directory. Like say for /data/data/com.test-1.apk
5564 // string com.test-1 is returned.
5565 static String getApkName(String codePath) {
5566 if (codePath == null) {
5567 return null;
5568 }
5569 int sidx = codePath.lastIndexOf("/");
5570 int eidx = codePath.lastIndexOf(".");
5571 if (eidx == -1) {
5572 eidx = codePath.length();
5573 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005574 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005575 return null;
5576 }
5577 return codePath.substring(sidx+1, eidx);
5578 }
5579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 class PackageInstalledInfo {
5581 String name;
5582 int uid;
5583 PackageParser.Package pkg;
5584 int returnCode;
5585 PackageRemovedInfo removedInfo;
5586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005588 /*
5589 * Install a non-existing package.
5590 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005591 private void installNewPackageLI(PackageParser.Package pkg,
5592 int parseFlags,
5593 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005594 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005596 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005597
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005598 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 res.name = pkgName;
5600 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005601 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5602 // A package with the same name is already installed, though
5603 // it has been renamed to an older name. The package we
5604 // are trying to install should be installed as an update to
5605 // the existing one, but that has not been requested, so bail.
5606 Slog.w(TAG, "Attempt to re-install " + pkgName
5607 + " without first uninstalling package running as "
5608 + mSettings.mRenamedPackages.get(pkgName));
5609 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5610 return;
5611 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005612 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005614 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 + " without first uninstalling.");
5616 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5617 return;
5618 }
5619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005621 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5622 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005624 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5626 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5627 }
5628 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005629 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005630 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 res);
5632 // delete the partially installed application. the data directory will have to be
5633 // restored if it was already existing
5634 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5635 // remove package from internal structures. Note that we want deletePackageX to
5636 // delete the package data and cache directories that it created in
5637 // scanPackageLocked, unless those directories existed before we even tried to
5638 // install.
5639 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005640 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005642 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 }
5644 }
5645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005646
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005647 private void replacePackageLI(PackageParser.Package pkg,
5648 int parseFlags,
5649 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005650 String installerPackageName, PackageInstalledInfo res) {
5651
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005652 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005653 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 // First find the old package info and check signatures
5655 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005656 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005657 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005658 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5660 return;
5661 }
5662 }
Kenny Root85387d72010-08-26 10:13:11 -07005663 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005664 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005665 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005667 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 }
5669 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005672 PackageParser.Package pkg,
5673 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005674 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 PackageParser.Package newPackage = null;
5676 String pkgName = deletedPackage.packageName;
5677 boolean deletedPkg = true;
5678 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005679
Jacek Surazski65e13172009-04-28 15:26:38 +02005680 String oldInstallerPackageName = null;
5681 synchronized (mPackages) {
5682 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5683 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005684
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005685 long origUpdateTime;
5686 if (pkg.mExtras != null) {
5687 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5688 } else {
5689 origUpdateTime = 0;
5690 }
5691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005693 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005694 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005695 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5697 deletedPkg = false;
5698 } else {
5699 // Successfully deleted the old package. Now proceed with re-installation
5700 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005701 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5702 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005704 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5706 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005707 }
5708 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005709 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005710 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 res);
5712 updatedSettings = true;
5713 }
5714 }
5715
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005716 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 // remove package from internal structures. Note that we want deletePackageX to
5718 // delete the package data and cache directories that it created in
5719 // scanPackageLocked, unless those directories existed before we even tried to
5720 // install.
5721 if(updatedSettings) {
5722 deletePackageLI(
5723 pkgName, true,
5724 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005725 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 }
5727 // Since we failed to install the new package we need to restore the old
5728 // package that we deleted.
5729 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005730 File restoreFile = new File(deletedPackage.mPath);
5731 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005732 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005733 return;
5734 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005735 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005736 boolean oldOnSd = isExternal(deletedPackage);
5737 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5738 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5739 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005740 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5741 | SCAN_UPDATE_TIME;
5742 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5743 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005744 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5745 return;
5746 }
5747 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005748 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005749 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005750 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005751 mSettings.writeLP();
5752 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005753 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 }
5755 }
5756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005759 PackageParser.Package pkg,
5760 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005761 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 PackageParser.Package newPackage = null;
5763 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005764 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 PackageParser.PARSE_IS_SYSTEM;
5766 String packageName = deletedPackage.packageName;
5767 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5768 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005769 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 return;
5771 }
5772 PackageParser.Package oldPkg;
5773 PackageSetting oldPkgSetting;
5774 synchronized (mPackages) {
5775 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005776 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5778 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005779 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 return;
5781 }
5782 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005783
5784 killApplication(packageName, oldPkg.applicationInfo.uid);
5785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5787 res.removedInfo.removedPackage = packageName;
5788 // Remove existing system package
5789 removePackageLI(oldPkg, true);
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005790 synchronized (mPackages) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005791 if (!mSettings.disableSystemPackageLP(packageName) && deletedPackage != null) {
5792 // We didn't need to disable the .apk as a current system package,
5793 // which means we are replacing another update that is already
5794 // installed. We need to make sure to delete the older one's .apk.
5795 res.removedInfo.args = createInstallArgs(isExternal(pkg)
5796 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL,
5797 deletedPackage.applicationInfo.sourceDir,
5798 deletedPackage.applicationInfo.publicSourceDir,
5799 deletedPackage.applicationInfo.nativeLibraryDir);
5800 } else {
5801 res.removedInfo.args = null;
5802 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005803 }
5804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 // Successfully disabled the old package. Now proceed with re-installation
5806 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5807 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005808 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005810 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5812 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5813 }
5814 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005815 if (newPackage.mExtras != null) {
5816 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5817 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5818 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5819 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005820 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 updatedSettings = true;
5822 }
5823
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005824 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 // Re installation failed. Restore old information
5826 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005827 if (newPackage != null) {
5828 removePackageLI(newPackage, true);
5829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005830 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005831 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 // Restore the old system information in Settings
5833 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005834 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005836 mSettings.setInstallerPackageName(packageName,
5837 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 }
5839 mSettings.writeLP();
5840 }
5841 }
5842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005843
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005844 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005845 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005846 int retCode;
5847 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5848 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5849 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005850 if (mNoDexOpt) {
5851 /*
5852 * If we're in an engineering build, programs are lazily run
5853 * through dexopt. If the .dex file doesn't exist yet, it
5854 * will be created when the program is run next.
5855 */
5856 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5857 } else {
5858 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5859 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5860 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005861 }
5862 }
5863 return PackageManager.INSTALL_SUCCEEDED;
5864 }
5865
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005866 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005867 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005868 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 synchronized (mPackages) {
5870 //write settings. the installStatus will be incomplete at this stage.
5871 //note that the new package setting would have already been
5872 //added to mPackages. It hasn't been persisted yet.
5873 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5874 mSettings.writeLP();
5875 }
5876
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005877 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005878 != PackageManager.INSTALL_SUCCEEDED) {
5879 // Discontinue if moving dex files failed.
5880 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005882 if((res.returnCode = setPermissionsLI(newPackage))
5883 != PackageManager.INSTALL_SUCCEEDED) {
5884 if (mInstaller != null) {
5885 mInstaller.rmdex(newPackage.mScanPath);
5886 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005887 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005889 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005891 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005892 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005893 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 res.name = pkgName;
5895 res.uid = newPackage.applicationInfo.uid;
5896 res.pkg = newPackage;
5897 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005898 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5900 //to update install status
5901 mSettings.writeLP();
5902 }
5903 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005904
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005905 private void installPackageLI(InstallArgs args,
5906 boolean newInstall, PackageInstalledInfo res) {
5907 int pFlags = args.flags;
5908 String installerPackageName = args.installerPackageName;
5909 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005910 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005911 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005912 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005913 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005914 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005915 // Result object to be returned
5916 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5917
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005918 // Retrieve PackageSettings and parse package
5919 int parseFlags = PackageParser.PARSE_CHATTY |
5920 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5921 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5922 parseFlags |= mDefParseFlags;
5923 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5924 pp.setSeparateProcesses(mSeparateProcesses);
5925 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5926 null, mMetrics, parseFlags);
5927 if (pkg == null) {
5928 res.returnCode = pp.getParseError();
5929 return;
5930 }
5931 String pkgName = res.name = pkg.packageName;
5932 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5933 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5934 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5935 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005936 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005937 }
5938 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5939 res.returnCode = pp.getParseError();
5940 return;
5941 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005942 // Get rid of all references to package scan path via parser.
5943 pp = null;
5944 String oldCodePath = null;
5945 boolean systemApp = false;
5946 synchronized (mPackages) {
5947 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005948 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5949 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005950 if (pkg.mOriginalPackages != null
5951 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005952 && mPackages.containsKey(oldName)) {
5953 // This package is derived from an original package,
5954 // and this device has been updating from that original
5955 // name. We must continue using the original name, so
5956 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005957 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005958 pkgName = pkg.packageName;
5959 replace = true;
5960 } else if (mPackages.containsKey(pkgName)) {
5961 // This package, under its official name, already exists
5962 // on the device; we should replace it.
5963 replace = true;
5964 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005965 }
5966 PackageSetting ps = mSettings.mPackages.get(pkgName);
5967 if (ps != null) {
5968 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5969 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5970 systemApp = (ps.pkg.applicationInfo.flags &
5971 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005972 }
5973 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005974 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005975
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005976 if (systemApp && onSd) {
5977 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005978 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005979 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5980 return;
5981 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005982
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005983 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5984 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5985 return;
5986 }
5987 // Set application objects path explicitly after the rename
5988 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005989 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005990 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005991 replacePackageLI(pkg, parseFlags, scanMode,
5992 installerPackageName, res);
5993 } else {
5994 installNewPackageLI(pkg, parseFlags, scanMode,
5995 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 }
5997 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005998
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005999 private int setPermissionsLI(PackageParser.Package newPackage) {
6000 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006001 int retCode = 0;
6002 // TODO Gross hack but fix later. Ideally move this to be a post installation
6003 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07006004 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006005 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 try {
6007 extractPublicFiles(newPackage, destResourceFile);
6008 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006009 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 -08006010 " forward-locked app.");
6011 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6012 } finally {
6013 //TODO clean up the extracted public files
6014 }
6015 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006016 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 newPackage.applicationInfo.uid);
6018 } else {
6019 final int filePermissions =
6020 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006021 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 newPackage.applicationInfo.uid);
6023 }
6024 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006025 // The permissions on the resource file was set when it was copied for
6026 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006030 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006031 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006033 // TODO Define new internal error
6034 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 }
6036 return PackageManager.INSTALL_SUCCEEDED;
6037 }
6038
Kenny Root85387d72010-08-26 10:13:11 -07006039 private static boolean isForwardLocked(PackageParser.Package pkg) {
6040 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 }
6042
Kenny Root85387d72010-08-26 10:13:11 -07006043 private static boolean isExternal(PackageParser.Package pkg) {
6044 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
6045 }
6046
6047 private static boolean isSystemApp(PackageParser.Package pkg) {
6048 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6049 }
6050
Kenny Root502e9a42011-01-10 13:48:15 -08006051 private static boolean isSystemApp(ApplicationInfo info) {
6052 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6053 }
6054
Kenny Root85387d72010-08-26 10:13:11 -07006055 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
6056 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006057 }
6058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 private void extractPublicFiles(PackageParser.Package newPackage,
6060 File publicZipFile) throws IOException {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006061 final FileOutputStream fstr = new FileOutputStream(publicZipFile);
6062 final ZipOutputStream publicZipOutStream = new ZipOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6064
6065 // Copy manifest, resources.arsc and res directory to public zip
6066
6067 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6068 while (privateZipEntries.hasMoreElements()) {
6069 final ZipEntry zipEntry = privateZipEntries.nextElement();
6070 final String zipEntryName = zipEntry.getName();
6071 if ("AndroidManifest.xml".equals(zipEntryName)
6072 || "resources.arsc".equals(zipEntryName)
6073 || zipEntryName.startsWith("res/")) {
6074 try {
6075 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6076 } catch (IOException e) {
6077 try {
6078 publicZipOutStream.close();
6079 throw e;
6080 } finally {
6081 publicZipFile.delete();
6082 }
6083 }
6084 }
6085 }
6086
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006087 publicZipOutStream.finish();
6088 publicZipOutStream.flush();
6089 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006090 publicZipOutStream.close();
6091 FileUtils.setPermissions(
6092 publicZipFile.getAbsolutePath(),
6093 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6094 -1, -1);
6095 }
6096
6097 private static void copyZipEntry(ZipEntry zipEntry,
6098 ZipFile inZipFile,
6099 ZipOutputStream outZipStream) throws IOException {
6100 byte[] buffer = new byte[4096];
6101 int num;
6102
6103 ZipEntry newEntry;
6104 if (zipEntry.getMethod() == ZipEntry.STORED) {
6105 // Preserve the STORED method of the input entry.
6106 newEntry = new ZipEntry(zipEntry);
6107 } else {
6108 // Create a new entry so that the compressed len is recomputed.
6109 newEntry = new ZipEntry(zipEntry.getName());
6110 }
6111 outZipStream.putNextEntry(newEntry);
6112
6113 InputStream data = inZipFile.getInputStream(zipEntry);
6114 while ((num = data.read(buffer)) > 0) {
6115 outZipStream.write(buffer, 0, num);
6116 }
6117 outZipStream.flush();
6118 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 private void deleteTempPackageFiles() {
6121 FilenameFilter filter = new FilenameFilter() {
6122 public boolean accept(File dir, String name) {
6123 return name.startsWith("vmdl") && name.endsWith(".tmp");
6124 }
6125 };
6126 String tmpFilesList[] = mAppInstallDir.list(filter);
6127 if(tmpFilesList == null) {
6128 return;
6129 }
6130 for(int i = 0; i < tmpFilesList.length; i++) {
6131 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6132 tmpFile.delete();
6133 }
6134 }
6135
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006136 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 File tmpPackageFile;
6138 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006139 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006141 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 return null;
6143 }
6144 try {
6145 FileUtils.setPermissions(
6146 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6147 -1, -1);
6148 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006149 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 return null;
6151 }
6152 return tmpPackageFile;
6153 }
6154
6155 public void deletePackage(final String packageName,
6156 final IPackageDeleteObserver observer,
6157 final int flags) {
6158 mContext.enforceCallingOrSelfPermission(
6159 android.Manifest.permission.DELETE_PACKAGES, null);
6160 // Queue up an async operation since the package deletion may take a little while.
6161 mHandler.post(new Runnable() {
6162 public void run() {
6163 mHandler.removeCallbacks(this);
6164 final boolean succeded = deletePackageX(packageName, true, true, flags);
6165 if (observer != null) {
6166 try {
6167 observer.packageDeleted(succeded);
6168 } catch (RemoteException e) {
6169 Log.i(TAG, "Observer no longer exists.");
6170 } //end catch
6171 } //end if
6172 } //end run
6173 });
6174 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 /**
6177 * This method is an internal method that could be get invoked either
6178 * to delete an installed package or to clean up a failed installation.
6179 * After deleting an installed package, a broadcast is sent to notify any
6180 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006181 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 * installation wouldn't have sent the initial broadcast either
6183 * The key steps in deleting a package are
6184 * deleting the package information in internal structures like mPackages,
6185 * deleting the packages base directories through installd
6186 * updating mSettings to reflect current status
6187 * persisting settings for later use
6188 * sending a broadcast if necessary
6189 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6191 boolean deleteCodeAndResources, int flags) {
6192 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006193 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006195 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6196 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6197 try {
6198 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006199 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006200 return false;
6201 }
6202 } catch (RemoteException e) {
6203 }
6204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006206 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006207 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006211 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006212 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006213
6214 // If the removed package was a system update, the old system packaged
6215 // was re-enabled; we need to broadcast this information
6216 if (systemUpdate) {
6217 Bundle extras = new Bundle(1);
6218 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6219 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6220
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006221 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6222 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006225 // Force a gc here.
6226 Runtime.getRuntime().gc();
6227 // Delete the resources here after sending the broadcast to let
6228 // other processes clean up before deleting resources.
6229 if (info.args != null) {
6230 synchronized (mInstallLock) {
6231 info.args.doPostDeleteLI(deleteCodeAndResources);
6232 }
6233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 return res;
6235 }
6236
6237 static class PackageRemovedInfo {
6238 String removedPackage;
6239 int uid = -1;
6240 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006241 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006242 // Clean up resources deleted packages.
6243 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006244
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006245 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 Bundle extras = new Bundle(1);
6247 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6248 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6249 if (replacing) {
6250 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6251 }
6252 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006253 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 }
6255 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006256 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 }
6258 }
6259 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 /*
6262 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6263 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006264 * 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 -08006265 * delete a partially installed application.
6266 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006267 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006268 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006270 if (outInfo != null) {
6271 outInfo.removedPackage = packageName;
6272 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006273 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 // Retrieve object to delete permissions for shared user later on
6275 PackageSetting deletedPs;
6276 synchronized (mPackages) {
6277 deletedPs = mSettings.mPackages.get(packageName);
6278 }
6279 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6280 if (mInstaller != null) {
Kenny Root35ab3ad2011-02-02 16:42:14 -08006281 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006283 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 + packageName + ", retcode=" + retCode);
6285 // we don't consider this to be a failure of the core package deletion
6286 }
6287 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006288 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289 PackageParser.Package pkg = mPackages.get(packageName);
6290 File dataDir = new File(pkg.applicationInfo.dataDir);
6291 dataDir.delete();
6292 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006293 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 }
6295 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006296 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006297 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6298 if (outInfo != null) {
6299 outInfo.removedUid = mSettings.removePackageLP(packageName);
6300 }
6301 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006302 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006303 if (deletedPs.sharedUser != null) {
6304 // remove permissions associated with package
6305 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6306 }
6307 }
6308 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006309 // remove from preferred activities.
6310 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6311 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6312 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6313 removed.add(pa);
6314 }
6315 }
6316 for (PreferredActivity pa : removed) {
6317 mSettings.mPreferredActivities.removeFilter(pa);
6318 }
6319 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006320 if (writeSettings) {
6321 // Save settings now
6322 mSettings.writeLP();
6323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 }
6325 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 /*
6328 * Tries to delete system package.
6329 */
6330 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006331 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 ApplicationInfo applicationInfo = p.applicationInfo;
6333 //applicable for non-partially installed applications only
6334 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006335 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 return false;
6337 }
6338 PackageSetting ps = null;
6339 // Confirm if the system package has been updated
6340 // An updated system app can be deleted. This will also have to restore
6341 // the system pkg from system partition
6342 synchronized (mPackages) {
6343 ps = mSettings.getDisabledSystemPkg(p.packageName);
6344 }
6345 if (ps == null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006346 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 return false;
6348 } else {
6349 Log.i(TAG, "Deleting system pkg from data partition");
6350 }
6351 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006352 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006353 if (ps.versionCode < p.mVersionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006354 // Delete data for downgrades
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006355 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006356 } else {
6357 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006358 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006359 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006360 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006361 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 if (!ret) {
6363 return false;
6364 }
6365 synchronized (mPackages) {
6366 // Reinstate the old system package
6367 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006368 // Remove any native libraries from the upgraded package.
6369 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 }
6371 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006372 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006374 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006377 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 return false;
6379 }
6380 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006381 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006382 if (writeSettings) {
6383 mSettings.writeLP();
6384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 }
6386 return true;
6387 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006390 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6391 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 ApplicationInfo applicationInfo = p.applicationInfo;
6393 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006394 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 return false;
6396 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006397 if (outInfo != null) {
6398 outInfo.uid = applicationInfo.uid;
6399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400
6401 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006402 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403
6404 // Delete application code and resources
6405 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006406 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006407 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6408 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6409 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6410 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 }
6412 return true;
6413 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 /*
6416 * This method handles package deletion in general
6417 */
6418 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006419 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6420 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006422 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 return false;
6424 }
6425 PackageParser.Package p;
6426 boolean dataOnly = false;
6427 synchronized (mPackages) {
6428 p = mPackages.get(packageName);
6429 if (p == null) {
6430 //this retrieves partially installed apps
6431 dataOnly = true;
6432 PackageSetting ps = mSettings.mPackages.get(packageName);
6433 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006434 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006435 return false;
6436 }
6437 p = ps.pkg;
6438 }
6439 }
6440 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006441 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 return false;
6443 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 if (dataOnly) {
6446 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006447 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 return true;
6449 }
6450 // At this point the package should have ApplicationInfo associated with it
6451 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006452 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 return false;
6454 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006455 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006456 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 Log.i(TAG, "Removing system package:"+p.packageName);
6458 // When an updated system application is deleted we delete the existing resources as well and
6459 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006460 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006461 } else {
6462 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006463 // Kill application pre-emptively especially for apps on sd.
6464 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006465 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6466 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006468 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 public void clearApplicationUserData(final String packageName,
6472 final IPackageDataObserver observer) {
6473 mContext.enforceCallingOrSelfPermission(
6474 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6475 // Queue up an async operation since the package deletion may take a little while.
6476 mHandler.post(new Runnable() {
6477 public void run() {
6478 mHandler.removeCallbacks(this);
6479 final boolean succeeded;
6480 synchronized (mInstallLock) {
6481 succeeded = clearApplicationUserDataLI(packageName);
6482 }
6483 if (succeeded) {
6484 // invoke DeviceStorageMonitor's update method to clear any notifications
6485 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6486 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6487 if (dsm != null) {
6488 dsm.updateMemory();
6489 }
6490 }
6491 if(observer != null) {
6492 try {
6493 observer.onRemoveCompleted(packageName, succeeded);
6494 } catch (RemoteException e) {
6495 Log.i(TAG, "Observer no longer exists.");
6496 }
6497 } //end if observer
6498 } //end run
6499 });
6500 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 private boolean clearApplicationUserDataLI(String packageName) {
6503 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006504 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 return false;
6506 }
6507 PackageParser.Package p;
6508 boolean dataOnly = false;
6509 synchronized (mPackages) {
6510 p = mPackages.get(packageName);
6511 if(p == null) {
6512 dataOnly = true;
6513 PackageSetting ps = mSettings.mPackages.get(packageName);
6514 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006515 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 return false;
6517 }
6518 p = ps.pkg;
6519 }
6520 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006521
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08006522 if (!dataOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 //need to check this only for fully installed applications
6524 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006525 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 return false;
6527 }
6528 final ApplicationInfo applicationInfo = p.applicationInfo;
6529 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006530 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 return false;
6532 }
6533 }
6534 if (mInstaller != null) {
Kenny Root35ab3ad2011-02-02 16:42:14 -08006535 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006537 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 + packageName);
6539 return false;
6540 }
6541 }
6542 return true;
6543 }
6544
6545 public void deleteApplicationCacheFiles(final String packageName,
6546 final IPackageDataObserver observer) {
6547 mContext.enforceCallingOrSelfPermission(
6548 android.Manifest.permission.DELETE_CACHE_FILES, null);
6549 // Queue up an async operation since the package deletion may take a little while.
6550 mHandler.post(new Runnable() {
6551 public void run() {
6552 mHandler.removeCallbacks(this);
6553 final boolean succeded;
6554 synchronized (mInstallLock) {
6555 succeded = deleteApplicationCacheFilesLI(packageName);
6556 }
6557 if(observer != null) {
6558 try {
6559 observer.onRemoveCompleted(packageName, succeded);
6560 } catch (RemoteException e) {
6561 Log.i(TAG, "Observer no longer exists.");
6562 }
6563 } //end if observer
6564 } //end run
6565 });
6566 }
6567
6568 private boolean deleteApplicationCacheFilesLI(String packageName) {
6569 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006570 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 return false;
6572 }
6573 PackageParser.Package p;
6574 synchronized (mPackages) {
6575 p = mPackages.get(packageName);
6576 }
6577 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006578 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 return false;
6580 }
6581 final ApplicationInfo applicationInfo = p.applicationInfo;
6582 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006583 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 return false;
6585 }
6586 if (mInstaller != null) {
Kenny Root35ab3ad2011-02-02 16:42:14 -08006587 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006589 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 + packageName);
6591 return false;
6592 }
6593 }
6594 return true;
6595 }
6596
6597 public void getPackageSizeInfo(final String packageName,
6598 final IPackageStatsObserver observer) {
6599 mContext.enforceCallingOrSelfPermission(
6600 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6601 // Queue up an async operation since the package deletion may take a little while.
6602 mHandler.post(new Runnable() {
6603 public void run() {
6604 mHandler.removeCallbacks(this);
Kenny Root366949c2011-01-14 17:18:14 -08006605 PackageStats stats = new PackageStats(packageName);
6606
6607 final boolean success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 synchronized (mInstallLock) {
Kenny Root366949c2011-01-14 17:18:14 -08006609 success = getPackageSizeInfoLI(packageName, stats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 }
Kenny Root366949c2011-01-14 17:18:14 -08006611
6612 Message msg = mHandler.obtainMessage(INIT_COPY);
6613 msg.obj = new MeasureParams(stats, success, observer);
6614 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 } //end run
6616 });
6617 }
6618
6619 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6620 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006621 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006622 return false;
6623 }
6624 PackageParser.Package p;
6625 boolean dataOnly = false;
6626 synchronized (mPackages) {
6627 p = mPackages.get(packageName);
6628 if(p == null) {
6629 dataOnly = true;
6630 PackageSetting ps = mSettings.mPackages.get(packageName);
6631 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006632 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 return false;
6634 }
6635 p = ps.pkg;
6636 }
6637 }
6638 String publicSrcDir = null;
6639 if(!dataOnly) {
6640 final ApplicationInfo applicationInfo = p.applicationInfo;
6641 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006642 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 return false;
6644 }
6645 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6646 }
6647 if (mInstaller != null) {
Kenny Root35ab3ad2011-02-02 16:42:14 -08006648 int res = mInstaller.getSizeInfo(packageName, p.mPath, publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006649 if (res < 0) {
6650 return false;
6651 } else {
6652 return true;
6653 }
6654 }
6655 return true;
6656 }
6657
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006660 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 }
6662
6663 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006664 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 }
6666
6667 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006668 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 }
6670
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006671 int getUidTargetSdkVersionLockedLP(int uid) {
6672 Object obj = mSettings.getUserIdLP(uid);
6673 if (obj instanceof SharedUserSetting) {
6674 SharedUserSetting sus = (SharedUserSetting)obj;
6675 final int N = sus.packages.size();
6676 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6677 Iterator<PackageSetting> it = sus.packages.iterator();
6678 int i=0;
6679 while (it.hasNext()) {
6680 PackageSetting ps = it.next();
6681 if (ps.pkg != null) {
6682 int v = ps.pkg.applicationInfo.targetSdkVersion;
6683 if (v < vers) vers = v;
6684 }
6685 }
6686 return vers;
6687 } else if (obj instanceof PackageSetting) {
6688 PackageSetting ps = (PackageSetting)obj;
6689 if (ps.pkg != null) {
6690 return ps.pkg.applicationInfo.targetSdkVersion;
6691 }
6692 }
6693 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6694 }
6695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 public void addPreferredActivity(IntentFilter filter, int match,
6697 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006699 if (mContext.checkCallingOrSelfPermission(
6700 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6701 != PackageManager.PERMISSION_GRANTED) {
6702 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6703 < Build.VERSION_CODES.FROYO) {
6704 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6705 + Binder.getCallingUid());
6706 return;
6707 }
6708 mContext.enforceCallingOrSelfPermission(
6709 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6710 }
6711
6712 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6714 mSettings.mPreferredActivities.addFilter(
6715 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006716 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 }
6718 }
6719
Satish Sampath8dbe6122009-06-02 23:35:54 +01006720 public void replacePreferredActivity(IntentFilter filter, int match,
6721 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006722 if (filter.countActions() != 1) {
6723 throw new IllegalArgumentException(
6724 "replacePreferredActivity expects filter to have only 1 action.");
6725 }
6726 if (filter.countCategories() != 1) {
6727 throw new IllegalArgumentException(
6728 "replacePreferredActivity expects filter to have only 1 category.");
6729 }
6730 if (filter.countDataAuthorities() != 0
6731 || filter.countDataPaths() != 0
6732 || filter.countDataSchemes() != 0
6733 || filter.countDataTypes() != 0) {
6734 throw new IllegalArgumentException(
6735 "replacePreferredActivity expects filter to have no data authorities, " +
6736 "paths, schemes or types.");
6737 }
6738 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006739 if (mContext.checkCallingOrSelfPermission(
6740 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6741 != PackageManager.PERMISSION_GRANTED) {
6742 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6743 < Build.VERSION_CODES.FROYO) {
6744 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6745 + Binder.getCallingUid());
6746 return;
6747 }
6748 mContext.enforceCallingOrSelfPermission(
6749 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6750 }
6751
Satish Sampath8dbe6122009-06-02 23:35:54 +01006752 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6753 String action = filter.getAction(0);
6754 String category = filter.getCategory(0);
6755 while (it.hasNext()) {
6756 PreferredActivity pa = it.next();
6757 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6758 it.remove();
6759 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6760 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6761 }
6762 }
6763 addPreferredActivity(filter, match, set, activity);
6764 }
6765 }
6766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006769 int uid = Binder.getCallingUid();
6770 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006771 if (pkg == null || pkg.applicationInfo.uid != uid) {
6772 if (mContext.checkCallingOrSelfPermission(
6773 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6774 != PackageManager.PERMISSION_GRANTED) {
6775 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6776 < Build.VERSION_CODES.FROYO) {
6777 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6778 + Binder.getCallingUid());
6779 return;
6780 }
6781 mContext.enforceCallingOrSelfPermission(
6782 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6783 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006784 }
6785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006786 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006787 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 }
6789 }
6790 }
6791
6792 boolean clearPackagePreferredActivitiesLP(String packageName) {
6793 boolean changed = false;
6794 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6795 while (it.hasNext()) {
6796 PreferredActivity pa = it.next();
6797 if (pa.mActivity.getPackageName().equals(packageName)) {
6798 it.remove();
6799 changed = true;
6800 }
6801 }
6802 return changed;
6803 }
6804
6805 public int getPreferredActivities(List<IntentFilter> outFilters,
6806 List<ComponentName> outActivities, String packageName) {
6807
6808 int num = 0;
6809 synchronized (mPackages) {
6810 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6811 while (it.hasNext()) {
6812 PreferredActivity pa = it.next();
6813 if (packageName == null
6814 || pa.mActivity.getPackageName().equals(packageName)) {
6815 if (outFilters != null) {
6816 outFilters.add(new IntentFilter(pa));
6817 }
6818 if (outActivities != null) {
6819 outActivities.add(pa.mActivity);
6820 }
6821 }
6822 }
6823 }
6824
6825 return num;
6826 }
6827
6828 public void setApplicationEnabledSetting(String appPackageName,
6829 int newState, int flags) {
6830 setEnabledSetting(appPackageName, null, newState, flags);
6831 }
6832
6833 public void setComponentEnabledSetting(ComponentName componentName,
6834 int newState, int flags) {
6835 setEnabledSetting(componentName.getPackageName(),
6836 componentName.getClassName(), newState, flags);
6837 }
6838
6839 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006840 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6842 || newState == COMPONENT_ENABLED_STATE_ENABLED
6843 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6844 throw new IllegalArgumentException("Invalid new component state: "
6845 + newState);
6846 }
6847 PackageSetting pkgSetting;
6848 final int uid = Binder.getCallingUid();
6849 final int permission = mContext.checkCallingPermission(
6850 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6851 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006852 boolean sendNow = false;
6853 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006854 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006855 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006856 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006858 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006859 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006860 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006862 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 }
6864 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006865 "Unknown component: " + packageName
6866 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867 }
6868 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6869 throw new SecurityException(
6870 "Permission Denial: attempt to change component state from pid="
6871 + Binder.getCallingPid()
6872 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6873 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006874 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006875 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006876 if (pkgSetting.enabled == newState) {
6877 // Nothing to do
6878 return;
6879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006881 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 } else {
6883 // We're dealing with a component level state change
6884 switch (newState) {
6885 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006886 if (!pkgSetting.enableComponentLP(className)) {
6887 return;
6888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006889 break;
6890 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006891 if (!pkgSetting.disableComponentLP(className)) {
6892 return;
6893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006894 break;
6895 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006896 if (!pkgSetting.restoreComponentLP(className)) {
6897 return;
6898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006899 break;
6900 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006901 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006902 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 }
6904 }
6905 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006906 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006907 components = mPendingBroadcasts.get(packageName);
6908 boolean newPackage = components == null;
6909 if (newPackage) {
6910 components = new ArrayList<String>();
6911 }
6912 if (!components.contains(componentName)) {
6913 components.add(componentName);
6914 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006915 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6916 sendNow = true;
6917 // Purge entry from pending broadcast list if another one exists already
6918 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006919 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006920 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006921 if (newPackage) {
6922 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006923 }
6924 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6925 // Schedule a message
6926 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6927 }
6928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006929 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931 long callingId = Binder.clearCallingIdentity();
6932 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006933 if (sendNow) {
6934 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006935 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 } finally {
6938 Binder.restoreCallingIdentity(callingId);
6939 }
6940 }
6941
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006942 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006943 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6944 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6945 + " components=" + componentNames);
6946 Bundle extras = new Bundle(4);
6947 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6948 String nameList[] = new String[componentNames.size()];
6949 componentNames.toArray(nameList);
6950 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006951 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6952 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006953 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006954 }
6955
Jacek Surazski65e13172009-04-28 15:26:38 +02006956 public String getInstallerPackageName(String packageName) {
6957 synchronized (mPackages) {
6958 PackageSetting pkg = mSettings.mPackages.get(packageName);
6959 if (pkg == null) {
6960 throw new IllegalArgumentException("Unknown package: " + packageName);
6961 }
6962 return pkg.installerPackageName;
6963 }
6964 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006966 public int getApplicationEnabledSetting(String appPackageName) {
6967 synchronized (mPackages) {
6968 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6969 if (pkg == null) {
6970 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6971 }
6972 return pkg.enabled;
6973 }
6974 }
6975
6976 public int getComponentEnabledSetting(ComponentName componentName) {
6977 synchronized (mPackages) {
6978 final String packageNameStr = componentName.getPackageName();
6979 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6980 if (pkg == null) {
6981 throw new IllegalArgumentException("Unknown component: " + componentName);
6982 }
6983 final String classNameStr = componentName.getClassName();
6984 return pkg.currentEnabledStateLP(classNameStr);
6985 }
6986 }
6987
6988 public void enterSafeMode() {
6989 if (!mSystemReady) {
6990 mSafeMode = true;
6991 }
6992 }
6993
6994 public void systemReady() {
6995 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006996
6997 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006998 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006999 mContext.getContentResolver(),
7000 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007001 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007002 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007003 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007005 }
7006
7007 public boolean isSafeMode() {
7008 return mSafeMode;
7009 }
7010
7011 public boolean hasSystemUidErrors() {
7012 return mHasSystemUidErrors;
7013 }
7014
7015 static String arrayToString(int[] array) {
7016 StringBuffer buf = new StringBuffer(128);
7017 buf.append('[');
7018 if (array != null) {
7019 for (int i=0; i<array.length; i++) {
7020 if (i > 0) buf.append(", ");
7021 buf.append(array[i]);
7022 }
7023 }
7024 buf.append(']');
7025 return buf.toString();
7026 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 @Override
7029 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7030 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7031 != PackageManager.PERMISSION_GRANTED) {
7032 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7033 + Binder.getCallingPid()
7034 + ", uid=" + Binder.getCallingUid()
7035 + " without permission "
7036 + android.Manifest.permission.DUMP);
7037 return;
7038 }
7039
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007040 boolean dumpStar = true;
7041 boolean dumpLibs = false;
7042 boolean dumpFeatures = false;
7043 boolean dumpResolvers = false;
7044 boolean dumpPermissions = false;
7045 boolean dumpPackages = false;
7046 boolean dumpSharedUsers = false;
7047 boolean dumpMessages = false;
7048 boolean dumpProviders = false;
7049
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007050 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007051 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007052
7053 int opti = 0;
7054 while (opti < args.length) {
7055 String opt = args[opti];
7056 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7057 break;
7058 }
7059 opti++;
7060 if ("-a".equals(opt)) {
7061 // Right now we only know how to print all.
7062 } else if ("-h".equals(opt)) {
7063 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007064 pw.println(" [-h] [-f] [cmd] ...");
7065 pw.println(" -f: print details of intent filters");
7066 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007067 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007068 pw.println(" l[ibraries]: list known shared libraries");
7069 pw.println(" f[ibraries]: list device features");
7070 pw.println(" r[esolvers]: dump intent resolvers");
7071 pw.println(" perm[issions]: dump permissions");
7072 pw.println(" prov[iders]: dump content providers");
7073 pw.println(" p[ackages]: dump installed packages");
7074 pw.println(" s[hared-users]: dump shared user IDs");
7075 pw.println(" m[essages]: print collected runtime messages");
7076 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007077 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007078 } else if ("-f".equals(opt)) {
7079 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007080 } else {
7081 pw.println("Unknown argument: " + opt + "; use -h for help");
7082 }
7083 }
7084
7085 // Is the caller requesting to dump a particular piece of data?
7086 if (opti < args.length) {
7087 String cmd = args[opti];
7088 opti++;
7089 // Is this a package name?
7090 if ("android".equals(cmd) || cmd.contains(".")) {
7091 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007092 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
7093 dumpStar = false;
7094 dumpLibs = true;
7095 } else if ("f".equals(cmd) || "features".equals(cmd)) {
7096 dumpStar = false;
7097 dumpFeatures = true;
7098 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
7099 dumpStar = false;
7100 dumpResolvers = true;
7101 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
7102 dumpStar = false;
7103 dumpPermissions = true;
7104 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
7105 dumpStar = false;
7106 dumpPackages = true;
7107 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
7108 dumpStar = false;
7109 dumpSharedUsers = true;
7110 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
7111 dumpStar = false;
7112 dumpProviders = true;
7113 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
7114 dumpStar = false;
7115 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007116 }
7117 }
7118
7119 boolean printedTitle = false;
7120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007122 if ((dumpStar || dumpLibs) && packageName == null) {
7123 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007124 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007125 pw.println("Libraries:");
7126 Iterator<String> it = mSharedLibraries.keySet().iterator();
7127 while (it.hasNext()) {
7128 String name = it.next();
7129 pw.print(" ");
7130 pw.print(name);
7131 pw.print(" -> ");
7132 pw.println(mSharedLibraries.get(name));
7133 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007134 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007135
7136 if ((dumpStar || dumpFeatures) && packageName == null) {
7137 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007138 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007139 pw.println("Features:");
7140 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7141 while (it.hasNext()) {
7142 String name = it.next();
7143 pw.print(" ");
7144 pw.println(name);
7145 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007146 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007147
7148 if (dumpStar || dumpResolvers) {
7149 if (mActivities.dump(pw, printedTitle
7150 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7151 " ", packageName, showFilters)) {
7152 printedTitle = true;
7153 }
7154 if (mReceivers.dump(pw, printedTitle
7155 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7156 " ", packageName, showFilters)) {
7157 printedTitle = true;
7158 }
7159 if (mServices.dump(pw, printedTitle
7160 ? "\nService Resolver Table:" : "Service Resolver Table:",
7161 " ", packageName, showFilters)) {
7162 printedTitle = true;
7163 }
7164 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7165 ? "\nPreferred Activities:" : "Preferred Activities:",
7166 " ", packageName, showFilters)) {
7167 printedTitle = true;
7168 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007169 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007170
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007171 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007172 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007174 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7175 continue;
7176 }
7177 if (!printedSomething) {
7178 if (printedTitle) pw.println(" ");
7179 pw.println("Permissions:");
7180 printedSomething = true;
7181 printedTitle = true;
7182 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007183 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7184 pw.print(Integer.toHexString(System.identityHashCode(p)));
7185 pw.println("):");
7186 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7187 pw.print(" uid="); pw.print(p.uid);
7188 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007189 pw.print(" type="); pw.print(p.type);
7190 pw.print(" prot="); pw.println(p.protectionLevel);
7191 if (p.packageSetting != null) {
7192 pw.print(" packageSetting="); pw.println(p.packageSetting);
7193 }
7194 if (p.perm != null) {
7195 pw.print(" perm="); pw.println(p.perm);
7196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 }
7198 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007199
7200 if (dumpStar || dumpProviders) {
7201 printedSomething = false;
7202 for (PackageParser.Provider p : mProviders.values()) {
7203 if (packageName != null && !packageName.equals(p.info.packageName)) {
7204 continue;
7205 }
7206 if (!printedSomething) {
7207 if (printedTitle) pw.println(" ");
7208 pw.println("Registered ContentProviders:");
7209 printedSomething = true;
7210 printedTitle = true;
7211 }
7212 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7213 pw.println(p.toString());
7214 }
7215 }
7216
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007217 printedSomething = false;
7218 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007219 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007220 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7221 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007222 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007223 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("Packages:");
7230 printedSomething = true;
7231 printedTitle = true;
7232 }
7233 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007234 pw.print(" Package [");
7235 pw.print(ps.realName != null ? ps.realName : ps.name);
7236 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007237 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7238 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007239 if (ps.realName != null) {
7240 pw.print(" compat name="); pw.println(ps.name);
7241 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007242 pw.print(" userId="); pw.print(ps.userId);
7243 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7244 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7245 pw.print(" pkg="); pw.println(ps.pkg);
7246 pw.print(" codePath="); pw.println(ps.codePathString);
7247 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007248 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root1174f712010-10-22 10:07:11 -07007249 pw.print(" versionCode="); pw.println(ps.versionCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 if (ps.pkg != null) {
Kenny Root1174f712010-10-22 10:07:11 -07007251 pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007252 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007253 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007254 if (ps.pkg.mOperationPending) {
7255 pw.println(" mOperationPending=true");
7256 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007257 pw.print(" supportsScreens=[");
7258 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007259 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007260 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7261 if (!first) pw.print(", ");
7262 first = false;
7263 pw.print("small");
7264 }
7265 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007266 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007267 if (!first) pw.print(", ");
7268 first = false;
7269 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007270 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007271 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007272 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007273 if (!first) pw.print(", ");
7274 first = false;
7275 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007276 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007277 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007278 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007279 if (!first) pw.print(", ");
7280 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007281 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007283 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007284 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007285 if (!first) pw.print(", ");
7286 first = false;
7287 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007289 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007290 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7291 if (!first) pw.print(", ");
7292 first = false;
7293 pw.print("anyDensity");
7294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007296 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007297 pw.print(" timeStamp=");
7298 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7299 pw.print(" firstInstallTime=");
7300 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7301 pw.print(" lastUpdateTime=");
7302 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007303 pw.print(" signatures="); pw.println(ps.signatures);
7304 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007305 pw.print(" haveGids="); pw.println(ps.haveGids);
7306 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007307 pw.print(" installStatus="); pw.print(ps.installStatus);
7308 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 if (ps.disabledComponents.size() > 0) {
7310 pw.println(" disabledComponents:");
7311 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007312 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 }
7314 }
7315 if (ps.enabledComponents.size() > 0) {
7316 pw.println(" enabledComponents:");
7317 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007318 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007319 }
7320 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007321 if (ps.grantedPermissions.size() > 0) {
7322 pw.println(" grantedPermissions:");
7323 for (String s : ps.grantedPermissions) {
7324 pw.print(" "); pw.println(s);
7325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007327 }
7328 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007329 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007330 if (dumpStar || dumpPackages) {
7331 if (mSettings.mRenamedPackages.size() > 0) {
7332 for (HashMap.Entry<String, String> e
7333 : mSettings.mRenamedPackages.entrySet()) {
7334 if (packageName != null && !packageName.equals(e.getKey())
7335 && !packageName.equals(e.getValue())) {
7336 continue;
7337 }
7338 if (!printedSomething) {
7339 if (printedTitle) pw.println(" ");
7340 pw.println("Renamed packages:");
7341 printedSomething = true;
7342 printedTitle = true;
7343 }
7344 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7345 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007346 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007347 }
7348 printedSomething = false;
7349 if (mSettings.mDisabledSysPackages.size() > 0) {
7350 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7351 if (packageName != null && !packageName.equals(ps.realName)
7352 && !packageName.equals(ps.name)) {
7353 continue;
7354 }
7355 if (!printedSomething) {
7356 if (printedTitle) pw.println(" ");
7357 pw.println("Hidden system packages:");
7358 printedSomething = true;
7359 printedTitle = true;
7360 }
7361 pw.print(" Package [");
7362 pw.print(ps.realName != null ? ps.realName : ps.name);
7363 pw.print("] (");
7364 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7365 pw.println("):");
7366 if (ps.realName != null) {
7367 pw.print(" compat name="); pw.println(ps.name);
7368 }
7369 pw.print(" userId="); pw.println(ps.userId);
7370 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7371 pw.print(" codePath="); pw.println(ps.codePathString);
7372 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007373 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007374 }
7375 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007376 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007377 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007378 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007379 if (packageName != null && su != packageSharedUser) {
7380 continue;
7381 }
7382 if (!printedSomething) {
7383 if (printedTitle) pw.println(" ");
7384 pw.println("Shared users:");
7385 printedSomething = true;
7386 printedTitle = true;
7387 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007388 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7389 pw.print(Integer.toHexString(System.identityHashCode(su)));
7390 pw.println("):");
7391 pw.print(" userId="); pw.print(su.userId);
7392 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 pw.println(" grantedPermissions:");
7394 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007395 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 }
7398 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007399
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007400 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007401 if (printedTitle) pw.println(" ");
7402 printedTitle = true;
7403 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007404 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007405
7406 pw.println(" ");
7407 pw.println("Package warning messages:");
7408 File fname = getSettingsProblemFile();
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08007409 FileInputStream in = null;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007410 try {
7411 in = new FileInputStream(fname);
7412 int avail = in.available();
7413 byte[] data = new byte[avail];
7414 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007415 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007416 } catch (FileNotFoundException e) {
7417 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08007418 } finally {
7419 if (in != null) {
7420 try {
7421 in.close();
7422 } catch (IOException e) {
7423 }
7424 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007425 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007427 }
7428 }
7429
7430 static final class BasePermission {
7431 final static int TYPE_NORMAL = 0;
7432 final static int TYPE_BUILTIN = 1;
7433 final static int TYPE_DYNAMIC = 2;
7434
7435 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007436 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007437 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007438 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007439 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 PackageParser.Permission perm;
7441 PermissionInfo pendingInfo;
7442 int uid;
7443 int[] gids;
7444
7445 BasePermission(String _name, String _sourcePackage, int _type) {
7446 name = _name;
7447 sourcePackage = _sourcePackage;
7448 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007449 // Default to most conservative protection level.
7450 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7451 }
7452
7453 public String toString() {
7454 return "BasePermission{"
7455 + Integer.toHexString(System.identityHashCode(this))
7456 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 }
7458 }
7459
7460 static class PackageSignatures {
7461 private Signature[] mSignatures;
7462
Kenny Root291e78c2011-01-13 14:53:17 -08007463 PackageSignatures(PackageSignatures orig) {
Kenny Rootbd392c52011-01-14 10:34:56 -08007464 if (orig != null && orig.mSignatures != null) {
7465 mSignatures = orig.mSignatures.clone();
7466 }
Kenny Root291e78c2011-01-13 14:53:17 -08007467 }
7468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 PackageSignatures(Signature[] sigs) {
7470 assignSignatures(sigs);
7471 }
7472
7473 PackageSignatures() {
7474 }
7475
7476 void writeXml(XmlSerializer serializer, String tagName,
7477 ArrayList<Signature> pastSignatures) throws IOException {
7478 if (mSignatures == null) {
7479 return;
7480 }
7481 serializer.startTag(null, tagName);
7482 serializer.attribute(null, "count",
7483 Integer.toString(mSignatures.length));
7484 for (int i=0; i<mSignatures.length; i++) {
7485 serializer.startTag(null, "cert");
7486 final Signature sig = mSignatures[i];
7487 final int sigHash = sig.hashCode();
7488 final int numPast = pastSignatures.size();
7489 int j;
7490 for (j=0; j<numPast; j++) {
7491 Signature pastSig = pastSignatures.get(j);
7492 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7493 serializer.attribute(null, "index", Integer.toString(j));
7494 break;
7495 }
7496 }
7497 if (j >= numPast) {
7498 pastSignatures.add(sig);
7499 serializer.attribute(null, "index", Integer.toString(numPast));
7500 serializer.attribute(null, "key", sig.toCharsString());
7501 }
7502 serializer.endTag(null, "cert");
7503 }
7504 serializer.endTag(null, tagName);
7505 }
7506
7507 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7508 throws IOException, XmlPullParserException {
7509 String countStr = parser.getAttributeValue(null, "count");
7510 if (countStr == null) {
7511 reportSettingsProblem(Log.WARN,
7512 "Error in package manager settings: <signatures> has"
7513 + " no count at " + parser.getPositionDescription());
7514 XmlUtils.skipCurrentTag(parser);
7515 }
7516 final int count = Integer.parseInt(countStr);
7517 mSignatures = new Signature[count];
7518 int pos = 0;
7519
7520 int outerDepth = parser.getDepth();
7521 int type;
7522 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7523 && (type != XmlPullParser.END_TAG
7524 || parser.getDepth() > outerDepth)) {
7525 if (type == XmlPullParser.END_TAG
7526 || type == XmlPullParser.TEXT) {
7527 continue;
7528 }
7529
7530 String tagName = parser.getName();
7531 if (tagName.equals("cert")) {
7532 if (pos < count) {
7533 String index = parser.getAttributeValue(null, "index");
7534 if (index != null) {
7535 try {
7536 int idx = Integer.parseInt(index);
7537 String key = parser.getAttributeValue(null, "key");
7538 if (key == null) {
7539 if (idx >= 0 && idx < pastSignatures.size()) {
7540 Signature sig = pastSignatures.get(idx);
7541 if (sig != null) {
7542 mSignatures[pos] = pastSignatures.get(idx);
7543 pos++;
7544 } else {
7545 reportSettingsProblem(Log.WARN,
7546 "Error in package manager settings: <cert> "
7547 + "index " + index + " is not defined at "
7548 + parser.getPositionDescription());
7549 }
7550 } else {
7551 reportSettingsProblem(Log.WARN,
7552 "Error in package manager settings: <cert> "
7553 + "index " + index + " is out of bounds at "
7554 + parser.getPositionDescription());
7555 }
7556 } else {
7557 while (pastSignatures.size() <= idx) {
7558 pastSignatures.add(null);
7559 }
7560 Signature sig = new Signature(key);
7561 pastSignatures.set(idx, sig);
7562 mSignatures[pos] = sig;
7563 pos++;
7564 }
7565 } catch (NumberFormatException e) {
7566 reportSettingsProblem(Log.WARN,
7567 "Error in package manager settings: <cert> "
7568 + "index " + index + " is not a number at "
7569 + parser.getPositionDescription());
7570 }
7571 } else {
7572 reportSettingsProblem(Log.WARN,
7573 "Error in package manager settings: <cert> has"
7574 + " no index at " + parser.getPositionDescription());
7575 }
7576 } else {
7577 reportSettingsProblem(Log.WARN,
7578 "Error in package manager settings: too "
7579 + "many <cert> tags, expected " + count
7580 + " at " + parser.getPositionDescription());
7581 }
7582 } else {
7583 reportSettingsProblem(Log.WARN,
7584 "Unknown element under <cert>: "
7585 + parser.getName());
7586 }
7587 XmlUtils.skipCurrentTag(parser);
7588 }
7589
7590 if (pos < count) {
7591 // Should never happen -- there is an error in the written
7592 // settings -- but if it does we don't want to generate
7593 // a bad array.
7594 Signature[] newSigs = new Signature[pos];
7595 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7596 mSignatures = newSigs;
7597 }
7598 }
7599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 private void assignSignatures(Signature[] sigs) {
7601 if (sigs == null) {
7602 mSignatures = null;
7603 return;
7604 }
7605 mSignatures = new Signature[sigs.length];
7606 for (int i=0; i<sigs.length; i++) {
7607 mSignatures[i] = sigs[i];
7608 }
7609 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 @Override
7612 public String toString() {
7613 StringBuffer buf = new StringBuffer(128);
7614 buf.append("PackageSignatures{");
7615 buf.append(Integer.toHexString(System.identityHashCode(this)));
7616 buf.append(" [");
7617 if (mSignatures != null) {
7618 for (int i=0; i<mSignatures.length; i++) {
7619 if (i > 0) buf.append(", ");
7620 buf.append(Integer.toHexString(
7621 System.identityHashCode(mSignatures[i])));
7622 }
7623 }
7624 buf.append("]}");
7625 return buf.toString();
7626 }
7627 }
7628
7629 static class PreferredActivity extends IntentFilter {
7630 final int mMatch;
7631 final String[] mSetPackages;
7632 final String[] mSetClasses;
7633 final String[] mSetComponents;
7634 final ComponentName mActivity;
7635 final String mShortActivity;
7636 String mParseError;
7637
7638 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7639 ComponentName activity) {
7640 super(filter);
7641 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7642 mActivity = activity;
7643 mShortActivity = activity.flattenToShortString();
7644 mParseError = null;
7645 if (set != null) {
7646 final int N = set.length;
7647 String[] myPackages = new String[N];
7648 String[] myClasses = new String[N];
7649 String[] myComponents = new String[N];
7650 for (int i=0; i<N; i++) {
7651 ComponentName cn = set[i];
7652 if (cn == null) {
7653 mSetPackages = null;
7654 mSetClasses = null;
7655 mSetComponents = null;
7656 return;
7657 }
7658 myPackages[i] = cn.getPackageName().intern();
7659 myClasses[i] = cn.getClassName().intern();
7660 myComponents[i] = cn.flattenToShortString().intern();
7661 }
7662 mSetPackages = myPackages;
7663 mSetClasses = myClasses;
7664 mSetComponents = myComponents;
7665 } else {
7666 mSetPackages = null;
7667 mSetClasses = null;
7668 mSetComponents = null;
7669 }
7670 }
7671
7672 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7673 IOException {
7674 mShortActivity = parser.getAttributeValue(null, "name");
7675 mActivity = ComponentName.unflattenFromString(mShortActivity);
7676 if (mActivity == null) {
7677 mParseError = "Bad activity name " + mShortActivity;
7678 }
7679 String matchStr = parser.getAttributeValue(null, "match");
7680 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7681 String setCountStr = parser.getAttributeValue(null, "set");
7682 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7683
7684 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7685 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7686 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7687
7688 int setPos = 0;
7689
7690 int outerDepth = parser.getDepth();
7691 int type;
7692 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7693 && (type != XmlPullParser.END_TAG
7694 || parser.getDepth() > outerDepth)) {
7695 if (type == XmlPullParser.END_TAG
7696 || type == XmlPullParser.TEXT) {
7697 continue;
7698 }
7699
7700 String tagName = parser.getName();
7701 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7702 // + parser.getDepth() + " tag=" + tagName);
7703 if (tagName.equals("set")) {
7704 String name = parser.getAttributeValue(null, "name");
7705 if (name == null) {
7706 if (mParseError == null) {
7707 mParseError = "No name in set tag in preferred activity "
7708 + mShortActivity;
7709 }
7710 } else if (setPos >= setCount) {
7711 if (mParseError == null) {
7712 mParseError = "Too many set tags in preferred activity "
7713 + mShortActivity;
7714 }
7715 } else {
7716 ComponentName cn = ComponentName.unflattenFromString(name);
7717 if (cn == null) {
7718 if (mParseError == null) {
7719 mParseError = "Bad set name " + name + " in preferred activity "
7720 + mShortActivity;
7721 }
7722 } else {
7723 myPackages[setPos] = cn.getPackageName();
7724 myClasses[setPos] = cn.getClassName();
7725 myComponents[setPos] = name;
7726 setPos++;
7727 }
7728 }
7729 XmlUtils.skipCurrentTag(parser);
7730 } else if (tagName.equals("filter")) {
7731 //Log.i(TAG, "Starting to parse filter...");
7732 readFromXml(parser);
7733 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7734 // + parser.getDepth() + " tag=" + parser.getName());
7735 } else {
7736 reportSettingsProblem(Log.WARN,
7737 "Unknown element under <preferred-activities>: "
7738 + parser.getName());
7739 XmlUtils.skipCurrentTag(parser);
7740 }
7741 }
7742
7743 if (setPos != setCount) {
7744 if (mParseError == null) {
7745 mParseError = "Not enough set tags (expected " + setCount
7746 + " but found " + setPos + ") in " + mShortActivity;
7747 }
7748 }
7749
7750 mSetPackages = myPackages;
7751 mSetClasses = myClasses;
7752 mSetComponents = myComponents;
7753 }
7754
7755 public void writeToXml(XmlSerializer serializer) throws IOException {
7756 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7757 serializer.attribute(null, "name", mShortActivity);
7758 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7759 serializer.attribute(null, "set", Integer.toString(NS));
7760 for (int s=0; s<NS; s++) {
7761 serializer.startTag(null, "set");
7762 serializer.attribute(null, "name", mSetComponents[s]);
7763 serializer.endTag(null, "set");
7764 }
7765 serializer.startTag(null, "filter");
7766 super.writeToXml(serializer);
7767 serializer.endTag(null, "filter");
7768 }
7769
7770 boolean sameSet(List<ResolveInfo> query, int priority) {
7771 if (mSetPackages == null) return false;
7772 final int NQ = query.size();
7773 final int NS = mSetPackages.length;
7774 int numMatch = 0;
7775 for (int i=0; i<NQ; i++) {
7776 ResolveInfo ri = query.get(i);
7777 if (ri.priority != priority) continue;
7778 ActivityInfo ai = ri.activityInfo;
7779 boolean good = false;
7780 for (int j=0; j<NS; j++) {
7781 if (mSetPackages[j].equals(ai.packageName)
7782 && mSetClasses[j].equals(ai.name)) {
7783 numMatch++;
7784 good = true;
7785 break;
7786 }
7787 }
7788 if (!good) return false;
7789 }
7790 return numMatch == NS;
7791 }
7792 }
7793
7794 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007795 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 HashSet<String> grantedPermissions = new HashSet<String>();
7798 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007801 setFlags(pkgFlags);
7802 }
7803
Kenny Root291e78c2011-01-13 14:53:17 -08007804 GrantedPermissions(GrantedPermissions base) {
7805 pkgFlags = base.pkgFlags;
7806 grantedPermissions = (HashSet<String>) base.grantedPermissions.clone();
Kenny Rootbd392c52011-01-14 10:34:56 -08007807
7808 if (base.gids != null) {
7809 gids = base.gids.clone();
7810 }
Kenny Root291e78c2011-01-13 14:53:17 -08007811 }
7812
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007813 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007814 this.pkgFlags = pkgFlags & (
7815 ApplicationInfo.FLAG_SYSTEM |
7816 ApplicationInfo.FLAG_FORWARD_LOCK |
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08007817 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 }
7819 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 /**
7822 * Settings base class for pending and resolved classes.
7823 */
7824 static class PackageSettingBase extends GrantedPermissions {
7825 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007826 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007827 File codePath;
7828 String codePathString;
7829 File resourcePath;
7830 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007831 String nativeLibraryPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007832 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007833 long firstInstallTime;
7834 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007835 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007837 boolean uidError;
Kenny Root291e78c2011-01-13 14:53:17 -08007838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 PackageSignatures signatures = new PackageSignatures();
7840
7841 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007842 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 /* Explicitly disabled components */
7845 HashSet<String> disabledComponents = new HashSet<String>(0);
7846 /* Explicitly enabled components */
7847 HashSet<String> enabledComponents = new HashSet<String>(0);
7848 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7849 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007850
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007851 PackageSettingBase origPackage;
7852
Jacek Surazski65e13172009-04-28 15:26:38 +02007853 /* package name of the app that installed this package */
7854 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007855
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007856 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007857 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007858 super(pkgFlags);
7859 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007860 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007861 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007862 }
7863
Kenny Root291e78c2011-01-13 14:53:17 -08007864 /**
7865 * New instance of PackageSetting with one-level-deep cloning.
7866 */
7867 PackageSettingBase(PackageSettingBase base) {
7868 super(base);
7869
7870 name = base.name;
7871 realName = base.realName;
7872 codePath = base.codePath;
7873 codePathString = base.codePathString;
7874 resourcePath = base.resourcePath;
7875 resourcePathString = base.resourcePathString;
7876 nativeLibraryPathString = base.nativeLibraryPathString;
Kenny Root291e78c2011-01-13 14:53:17 -08007877 timeStamp = base.timeStamp;
7878 firstInstallTime = base.firstInstallTime;
7879 lastUpdateTime = base.lastUpdateTime;
7880 versionCode = base.versionCode;
7881
7882 uidError = base.uidError;
7883
7884 signatures = new PackageSignatures(base.signatures);
7885
7886 permissionsFixed = base.permissionsFixed;
7887 haveGids = base.haveGids;
7888
7889 disabledComponents = (HashSet<String>) base.disabledComponents.clone();
7890
7891 enabledComponents = (HashSet<String>) base.enabledComponents.clone();
7892
7893 enabled = base.enabled;
7894 installStatus = base.installStatus;
7895
7896 origPackage = base.origPackage;
7897
7898 installerPackageName = base.installerPackageName;
7899 }
7900
Kenny Root806cc132010-09-12 08:34:19 -07007901 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7902 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 this.codePath = codePath;
7904 this.codePathString = codePath.toString();
7905 this.resourcePath = resourcePath;
7906 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007907 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007908 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 }
Kenny Root85387d72010-08-26 10:13:11 -07007910
Jacek Surazski65e13172009-04-28 15:26:38 +02007911 public void setInstallerPackageName(String packageName) {
7912 installerPackageName = packageName;
7913 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007914
Jacek Surazski65e13172009-04-28 15:26:38 +02007915 String getInstallerPackageName() {
7916 return installerPackageName;
7917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 public void setInstallStatus(int newStatus) {
7920 installStatus = newStatus;
7921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007923 public int getInstallStatus() {
7924 return installStatus;
7925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 }
7930
Kenny Root291e78c2011-01-13 14:53:17 -08007931 /**
7932 * Make a shallow copy of this package settings.
7933 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007934 public void copyFrom(PackageSettingBase base) {
7935 grantedPermissions = base.grantedPermissions;
7936 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007938 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007939 firstInstallTime = base.firstInstallTime;
7940 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007941 signatures = base.signatures;
7942 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007943 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 disabledComponents = base.disabledComponents;
7945 enabledComponents = base.enabledComponents;
7946 enabled = base.enabled;
7947 installStatus = base.installStatus;
7948 }
7949
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007950 boolean enableComponentLP(String componentClassName) {
7951 boolean changed = disabledComponents.remove(componentClassName);
7952 changed |= enabledComponents.add(componentClassName);
7953 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007954 }
7955
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007956 boolean disableComponentLP(String componentClassName) {
7957 boolean changed = enabledComponents.remove(componentClassName);
7958 changed |= disabledComponents.add(componentClassName);
7959 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 }
7961
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007962 boolean restoreComponentLP(String componentClassName) {
7963 boolean changed = enabledComponents.remove(componentClassName);
7964 changed |= disabledComponents.remove(componentClassName);
7965 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 }
7967
7968 int currentEnabledStateLP(String componentName) {
7969 if (enabledComponents.contains(componentName)) {
7970 return COMPONENT_ENABLED_STATE_ENABLED;
7971 } else if (disabledComponents.contains(componentName)) {
7972 return COMPONENT_ENABLED_STATE_DISABLED;
7973 } else {
7974 return COMPONENT_ENABLED_STATE_DEFAULT;
7975 }
7976 }
7977 }
7978
7979 /**
7980 * Settings data for a particular package we know about.
7981 */
7982 static final class PackageSetting extends PackageSettingBase {
7983 int userId;
7984 PackageParser.Package pkg;
7985 SharedUserSetting sharedUser;
7986
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007987 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007988 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7989 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7990 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007992
Kenny Root291e78c2011-01-13 14:53:17 -08007993 /**
7994 * New instance of PackageSetting replicating the original settings.
7995 * Note that it keeps the same PackageParser.Package instance.
7996 */
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007997 PackageSetting(PackageSetting orig) {
Kenny Root291e78c2011-01-13 14:53:17 -08007998 super(orig);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007999
Kenny Root291e78c2011-01-13 14:53:17 -08008000 userId = orig.userId;
8001 pkg = orig.pkg;
8002 sharedUser = orig.sharedUser;
Kenny Root97ef63b2011-01-11 11:15:35 -08008003 }
8004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 @Override
8006 public String toString() {
8007 return "PackageSetting{"
8008 + Integer.toHexString(System.identityHashCode(this))
8009 + " " + name + "/" + userId + "}";
8010 }
8011 }
8012
8013 /**
8014 * Settings data for a particular shared user ID we know about.
8015 */
8016 static final class SharedUserSetting extends GrantedPermissions {
8017 final String name;
8018 int userId;
8019 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
8020 final PackageSignatures signatures = new PackageSignatures();
8021
8022 SharedUserSetting(String _name, int _pkgFlags) {
8023 super(_pkgFlags);
8024 name = _name;
8025 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 @Override
8028 public String toString() {
8029 return "SharedUserSetting{"
8030 + Integer.toHexString(System.identityHashCode(this))
8031 + " " + name + "/" + userId + "}";
8032 }
8033 }
8034
8035 /**
8036 * Holds information about dynamic settings.
8037 */
8038 private static final class Settings {
8039 private final File mSettingsFilename;
8040 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008041 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 private final HashMap<String, PackageSetting> mPackages =
8043 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008044 // List of replaced system applications
8045 final HashMap<String, PackageSetting> mDisabledSysPackages =
8046 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008047
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008048 // These are the last platform API version we were using for
8049 // the apps installed on internal and external storage. It is
8050 // used to grant newer permissions one time during a system upgrade.
8051 int mInternalSdkPlatform;
8052 int mExternalSdkPlatform;
8053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008054 // The user's preferred activities associated with particular intent
8055 // filters.
8056 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
8057 new IntentResolver<PreferredActivity, PreferredActivity>() {
8058 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008059 protected String packageForFilter(PreferredActivity filter) {
8060 return filter.mActivity.getPackageName();
8061 }
8062 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008063 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008065 out.print(prefix); out.print(
8066 Integer.toHexString(System.identityHashCode(filter)));
8067 out.print(' ');
8068 out.print(filter.mActivity.flattenToShortString());
8069 out.print(" match=0x");
8070 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008071 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008072 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008073 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008074 out.print(prefix); out.print(" ");
8075 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008076 }
8077 }
8078 }
8079 };
8080 private final HashMap<String, SharedUserSetting> mSharedUsers =
8081 new HashMap<String, SharedUserSetting>();
8082 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
8083 private final SparseArray<Object> mOtherUserIds =
8084 new SparseArray<Object>();
8085
8086 // For reading/writing settings file.
8087 private final ArrayList<Signature> mPastSignatures =
8088 new ArrayList<Signature>();
8089
8090 // Mapping from permission names to info about them.
8091 final HashMap<String, BasePermission> mPermissions =
8092 new HashMap<String, BasePermission>();
8093
8094 // Mapping from permission tree names to info about them.
8095 final HashMap<String, BasePermission> mPermissionTrees =
8096 new HashMap<String, BasePermission>();
8097
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008098 // Packages that have been uninstalled and still need their external
8099 // storage data deleted.
8100 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
8101
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008102 // Packages that have been renamed since they were first installed.
8103 // Keys are the new names of the packages, values are the original
8104 // names. The packages appear everwhere else under their original
8105 // names.
8106 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
8107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 private final StringBuilder mReadMessages = new StringBuilder();
8109
8110 private static final class PendingPackage extends PackageSettingBase {
8111 final int sharedId;
8112
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008113 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008114 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
8115 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
8116 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 this.sharedId = sharedId;
8118 }
8119 }
8120 private final ArrayList<PendingPackage> mPendingPackages
8121 = new ArrayList<PendingPackage>();
8122
8123 Settings() {
8124 File dataDir = Environment.getDataDirectory();
8125 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08008126 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
8127 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008129 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008130 FileUtils.setPermissions(systemDir.toString(),
8131 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8132 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8133 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08008134 FileUtils.setPermissions(systemSecureDir.toString(),
8135 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8136 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8137 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 mSettingsFilename = new File(systemDir, "packages.xml");
8139 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008140 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 }
8142
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008143 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008144 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008145 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008147 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07008148 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 return p;
8150 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008151
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008152 PackageSetting peekPackageLP(String name) {
8153 return mPackages.get(name);
8154 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 PackageSetting p = mPackages.get(name);
8156 if (p != null && p.codePath.getPath().equals(codePath)) {
8157 return p;
8158 }
8159 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008160 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008161 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 void setInstallStatus(String pkgName, int status) {
8164 PackageSetting p = mPackages.get(pkgName);
8165 if(p != null) {
8166 if(p.getInstallStatus() != status) {
8167 p.setInstallStatus(status);
8168 }
8169 }
8170 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008171
Jacek Surazski65e13172009-04-28 15:26:38 +02008172 void setInstallerPackageName(String pkgName,
8173 String installerPkgName) {
8174 PackageSetting p = mPackages.get(pkgName);
8175 if(p != null) {
8176 p.setInstallerPackageName(installerPkgName);
8177 }
8178 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008179
Jacek Surazski65e13172009-04-28 15:26:38 +02008180 String getInstallerPackageName(String pkgName) {
8181 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008182 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008183 }
8184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 int getInstallStatus(String pkgName) {
8186 PackageSetting p = mPackages.get(pkgName);
8187 if(p != null) {
8188 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 return -1;
8191 }
8192
8193 SharedUserSetting getSharedUserLP(String name,
8194 int pkgFlags, boolean create) {
8195 SharedUserSetting s = mSharedUsers.get(name);
8196 if (s == null) {
8197 if (!create) {
8198 return null;
8199 }
8200 s = new SharedUserSetting(name, pkgFlags);
8201 if (MULTIPLE_APPLICATION_UIDS) {
8202 s.userId = newUserIdLP(s);
8203 } else {
8204 s.userId = FIRST_APPLICATION_UID;
8205 }
8206 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8207 // < 0 means we couldn't assign a userid; fall out and return
8208 // s, which is currently null
8209 if (s.userId >= 0) {
8210 mSharedUsers.put(name, s);
8211 }
8212 }
8213
8214 return s;
8215 }
8216
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008217 boolean disableSystemPackageLP(String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 PackageSetting p = mPackages.get(name);
8219 if(p == null) {
8220 Log.w(TAG, "Package:"+name+" is not an installed package");
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008221 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 }
8223 PackageSetting dp = mDisabledSysPackages.get(name);
8224 // always make sure the system package code and resource paths dont change
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008225 if (dp == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008226 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8227 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8228 }
8229 mDisabledSysPackages.put(name, p);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008230
8231 // a little trick... when we install the new package, we don't
8232 // want to modify the existing PackageSetting for the built-in
8233 // version. so at this point we need a new PackageSetting that
Kenny Root291e78c2011-01-13 14:53:17 -08008234 // is okay to muck with.
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008235 PackageSetting newp = new PackageSetting(p);
8236 replacePackageLP(name, newp);
8237 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008239 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008242 PackageSetting enableSystemPackageLP(String name) {
8243 PackageSetting p = mDisabledSysPackages.get(name);
8244 if(p == null) {
8245 Log.w(TAG, "Package:"+name+" is not disabled");
8246 return null;
8247 }
8248 // Reset flag in ApplicationInfo object
8249 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8250 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8251 }
Kenny Root806cc132010-09-12 08:34:19 -07008252 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8253 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008254 mDisabledSysPackages.remove(name);
8255 return ret;
8256 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008257
Kenny Root806cc132010-09-12 08:34:19 -07008258 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8259 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260 PackageSetting p = mPackages.get(name);
8261 if (p != null) {
8262 if (p.userId == uid) {
8263 return p;
8264 }
8265 reportSettingsProblem(Log.ERROR,
8266 "Adding duplicate package, keeping first: " + name);
8267 return null;
8268 }
Kenny Root806cc132010-09-12 08:34:19 -07008269 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8270 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 p.userId = uid;
8272 if (addUserIdLP(uid, p, name)) {
8273 mPackages.put(name, p);
8274 return p;
8275 }
8276 return null;
8277 }
8278
8279 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8280 SharedUserSetting s = mSharedUsers.get(name);
8281 if (s != null) {
8282 if (s.userId == uid) {
8283 return s;
8284 }
8285 reportSettingsProblem(Log.ERROR,
8286 "Adding duplicate shared user, keeping first: " + name);
8287 return null;
8288 }
8289 s = new SharedUserSetting(name, pkgFlags);
8290 s.userId = uid;
8291 if (addUserIdLP(uid, s, name)) {
8292 mSharedUsers.put(name, s);
8293 return s;
8294 }
8295 return null;
8296 }
8297
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008298 // Transfer ownership of permissions from one package to another.
8299 private void transferPermissions(String origPkg, String newPkg) {
8300 // Transfer ownership of permissions to the new package.
8301 for (int i=0; i<2; i++) {
8302 HashMap<String, BasePermission> permissions =
8303 i == 0 ? mPermissionTrees : mPermissions;
8304 for (BasePermission bp : permissions.values()) {
8305 if (origPkg.equals(bp.sourcePackage)) {
8306 if (DEBUG_UPGRADE) Log.v(TAG,
8307 "Moving permission " + bp.name
8308 + " from pkg " + bp.sourcePackage
8309 + " to " + newPkg);
8310 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008311 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008312 bp.perm = null;
8313 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008314 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008315 }
8316 bp.uid = 0;
8317 bp.gids = null;
8318 }
8319 }
8320 }
8321 }
8322
8323 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008324 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008325 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008326 PackageSetting p = mPackages.get(name);
8327 if (p != null) {
8328 if (!p.codePath.equals(codePath)) {
8329 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008330 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008331 // This is an updated system app with versions in both system
8332 // and data partition. Just let the most recent version
8333 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008334 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008335 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008336 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008337 // Just a change in the code path is not an issue, but
8338 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008339 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008340 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008341 /*
8342 * Since we've changed paths, we need to prefer the new
8343 * native library path over the one stored in the
8344 * package settings since we might have moved from
8345 * internal to external storage or vice versa.
8346 */
8347 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008348 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008349 }
8350 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008351 reportSettingsProblem(Log.WARN,
8352 "Package " + name + " shared user changed from "
8353 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8354 + " to "
8355 + (sharedUser != null ? sharedUser.name : "<nothing>")
8356 + "; replacing with new");
8357 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008358 } else {
8359 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8360 // If what we are scanning is a system package, then
8361 // make it so, regardless of whether it was previously
8362 // installed only in the data partition.
8363 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008365 }
8366 }
8367 if (p == null) {
8368 // Create a new PackageSettings entry. this can end up here because
8369 // of code path mismatch or user id mismatch of an updated system partition
8370 if (!create) {
8371 return null;
8372 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008373 if (origPackage != null) {
8374 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008375 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8376 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008377 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8378 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008379 // Note that we will retain the new package's signature so
8380 // that we can keep its data.
8381 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008382 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008383 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008384 p.sharedUser = origPackage.sharedUser;
8385 p.userId = origPackage.userId;
8386 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008387 mRenamedPackages.put(name, origPackage.name);
8388 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008389 // Update new package state.
8390 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008391 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008392 p = new PackageSetting(name, realName, codePath, resourcePath,
8393 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008394 p.setTimeStamp(codePath.lastModified());
8395 p.sharedUser = sharedUser;
8396 if (sharedUser != null) {
8397 p.userId = sharedUser.userId;
8398 } else if (MULTIPLE_APPLICATION_UIDS) {
8399 // Clone the setting here for disabled system packages
8400 PackageSetting dis = mDisabledSysPackages.get(name);
8401 if (dis != null) {
8402 // For disabled packages a new setting is created
8403 // from the existing user id. This still has to be
8404 // added to list of user id's
8405 // Copy signatures from previous setting
8406 if (dis.signatures.mSignatures != null) {
8407 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8408 }
8409 p.userId = dis.userId;
8410 // Clone permissions
8411 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008412 // Clone component info
8413 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8414 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8415 // Add new setting to list of user ids
8416 addUserIdLP(p.userId, p, name);
8417 } else {
8418 // Assign new user id
8419 p.userId = newUserIdLP(p);
8420 }
8421 } else {
8422 p.userId = FIRST_APPLICATION_UID;
8423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008424 }
8425 if (p.userId < 0) {
8426 reportSettingsProblem(Log.WARN,
8427 "Package " + name + " could not be assigned a valid uid");
8428 return null;
8429 }
8430 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008431 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008432 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008433 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008434 }
8435 }
8436 return p;
8437 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008438
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008439 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008440 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008441 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008442 final String codePath = pkg.applicationInfo.sourceDir;
8443 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008444 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008445 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008446 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008447 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008448 p.codePath = new File(codePath);
8449 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008450 }
8451 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008452 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008453 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008454 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008455 p.resourcePath = new File(resourcePath);
8456 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008457 }
Kenny Root85387d72010-08-26 10:13:11 -07008458 // Update the native library path if needed
8459 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8460 if (nativeLibraryPath != null
8461 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8462 p.nativeLibraryPathString = nativeLibraryPath;
8463 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008464 // Update version code if needed
8465 if (pkg.mVersionCode != p.versionCode) {
8466 p.versionCode = pkg.mVersionCode;
8467 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008468 // Update signatures if needed.
8469 if (p.signatures.mSignatures == null) {
8470 p.signatures.assignSignatures(pkg.mSignatures);
8471 }
8472 // If this app defines a shared user id initialize
8473 // the shared user signatures as well.
8474 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8475 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8476 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008477 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8478 }
8479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008480 // Utility method that adds a PackageSetting to mPackages and
8481 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008482 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483 SharedUserSetting sharedUser) {
8484 mPackages.put(name, p);
8485 if (sharedUser != null) {
8486 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8487 reportSettingsProblem(Log.ERROR,
8488 "Package " + p.name + " was user "
8489 + p.sharedUser + " but is now " + sharedUser
8490 + "; I am not changing its files so it will probably fail!");
8491 p.sharedUser.packages.remove(p);
8492 } else if (p.userId != sharedUser.userId) {
8493 reportSettingsProblem(Log.ERROR,
8494 "Package " + p.name + " was user id " + p.userId
8495 + " but is now user " + sharedUser
8496 + " with id " + sharedUser.userId
8497 + "; I am not changing its files so it will probably fail!");
8498 }
8499
8500 sharedUser.packages.add(p);
8501 p.sharedUser = sharedUser;
8502 p.userId = sharedUser.userId;
8503 }
8504 }
8505
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008506 /*
8507 * Update the shared user setting when a package using
8508 * specifying the shared user id is removed. The gids
8509 * associated with each permission of the deleted package
8510 * are removed from the shared user's gid list only if its
8511 * not in use by other permissions of packages in the
8512 * shared user setting.
8513 */
8514 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008515 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008516 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 return;
8518 }
8519 // No sharedUserId
8520 if (deletedPs.sharedUser == null) {
8521 return;
8522 }
8523 SharedUserSetting sus = deletedPs.sharedUser;
8524 // Update permissions
8525 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8526 boolean used = false;
8527 if (!sus.grantedPermissions.contains (eachPerm)) {
8528 continue;
8529 }
8530 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008531 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008532 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008533 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008534 used = true;
8535 break;
8536 }
8537 }
8538 if (!used) {
8539 // can safely delete this permission from list
8540 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 }
8542 }
8543 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008544 int newGids[] = globalGids;
8545 for (String eachPerm : sus.grantedPermissions) {
8546 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008547 if (bp != null) {
8548 newGids = appendInts(newGids, bp.gids);
8549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550 }
8551 sus.gids = newGids;
8552 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 private int removePackageLP(String name) {
8555 PackageSetting p = mPackages.get(name);
8556 if (p != null) {
8557 mPackages.remove(name);
8558 if (p.sharedUser != null) {
8559 p.sharedUser.packages.remove(p);
8560 if (p.sharedUser.packages.size() == 0) {
8561 mSharedUsers.remove(p.sharedUser.name);
8562 removeUserIdLP(p.sharedUser.userId);
8563 return p.sharedUser.userId;
8564 }
8565 } else {
8566 removeUserIdLP(p.userId);
8567 return p.userId;
8568 }
8569 }
8570 return -1;
8571 }
8572
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008573 private void replacePackageLP(String name, PackageSetting newp) {
8574 PackageSetting p = mPackages.get(name);
8575 if (p != null) {
8576 if (p.sharedUser != null) {
8577 p.sharedUser.packages.remove(p);
8578 p.sharedUser.packages.add(newp);
8579 } else {
8580 replaceUserIdLP(p.userId, newp);
8581 }
8582 }
8583 mPackages.put(name, newp);
8584 }
8585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008586 private boolean addUserIdLP(int uid, Object obj, Object name) {
8587 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8588 return false;
8589 }
8590
8591 if (uid >= FIRST_APPLICATION_UID) {
8592 int N = mUserIds.size();
8593 final int index = uid - FIRST_APPLICATION_UID;
8594 while (index >= N) {
8595 mUserIds.add(null);
8596 N++;
8597 }
8598 if (mUserIds.get(index) != null) {
8599 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008600 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 + " name=" + name);
8602 return false;
8603 }
8604 mUserIds.set(index, obj);
8605 } else {
8606 if (mOtherUserIds.get(uid) != null) {
8607 reportSettingsProblem(Log.ERROR,
8608 "Adding duplicate shared id: " + uid
8609 + " name=" + name);
8610 return false;
8611 }
8612 mOtherUserIds.put(uid, obj);
8613 }
8614 return true;
8615 }
8616
8617 public Object getUserIdLP(int uid) {
8618 if (uid >= FIRST_APPLICATION_UID) {
8619 int N = mUserIds.size();
8620 final int index = uid - FIRST_APPLICATION_UID;
8621 return index < N ? mUserIds.get(index) : null;
8622 } else {
8623 return mOtherUserIds.get(uid);
8624 }
8625 }
8626
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008627 private Set<String> findPackagesWithFlag(int flag) {
8628 Set<String> ret = new HashSet<String>();
8629 for (PackageSetting ps : mPackages.values()) {
8630 // Has to match atleast all the flag bits set on flag
8631 if ((ps.pkgFlags & flag) == flag) {
8632 ret.add(ps.name);
8633 }
8634 }
8635 return ret;
8636 }
8637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638 private void removeUserIdLP(int uid) {
8639 if (uid >= FIRST_APPLICATION_UID) {
8640 int N = mUserIds.size();
8641 final int index = uid - FIRST_APPLICATION_UID;
8642 if (index < N) mUserIds.set(index, null);
8643 } else {
8644 mOtherUserIds.remove(uid);
8645 }
8646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008647
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008648 private void replaceUserIdLP(int uid, Object obj) {
8649 if (uid >= FIRST_APPLICATION_UID) {
8650 int N = mUserIds.size();
8651 final int index = uid - FIRST_APPLICATION_UID;
8652 if (index < N) mUserIds.set(index, obj);
8653 } else {
8654 mOtherUserIds.put(uid, obj);
8655 }
8656 }
8657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658 void writeLP() {
8659 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8660
8661 // Keep the old settings around until we know the new ones have
8662 // been successfully written.
8663 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008664 // Presence of backup settings file indicates that we failed
8665 // to persist settings earlier. So preserve the older
8666 // backup for future reference since the current settings
8667 // might have been corrupted.
8668 if (!mBackupSettingsFilename.exists()) {
8669 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008670 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008671 return;
8672 }
8673 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008674 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008675 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008677 }
8678
8679 mPastSignatures.clear();
8680
8681 try {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008682 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
8683 BufferedOutputStream str = new BufferedOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684
8685 //XmlSerializer serializer = XmlUtils.serializerInstance();
8686 XmlSerializer serializer = new FastXmlSerializer();
8687 serializer.setOutput(str, "utf-8");
8688 serializer.startDocument(null, true);
8689 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8690
8691 serializer.startTag(null, "packages");
8692
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008693 serializer.startTag(null, "last-platform-version");
8694 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8695 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8696 serializer.endTag(null, "last-platform-version");
8697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698 serializer.startTag(null, "permission-trees");
8699 for (BasePermission bp : mPermissionTrees.values()) {
8700 writePermission(serializer, bp);
8701 }
8702 serializer.endTag(null, "permission-trees");
8703
8704 serializer.startTag(null, "permissions");
8705 for (BasePermission bp : mPermissions.values()) {
8706 writePermission(serializer, bp);
8707 }
8708 serializer.endTag(null, "permissions");
8709
8710 for (PackageSetting pkg : mPackages.values()) {
8711 writePackage(serializer, pkg);
8712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8715 writeDisabledSysPackage(serializer, pkg);
8716 }
8717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 serializer.startTag(null, "preferred-activities");
8719 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8720 serializer.startTag(null, "item");
8721 pa.writeToXml(serializer);
8722 serializer.endTag(null, "item");
8723 }
8724 serializer.endTag(null, "preferred-activities");
8725
8726 for (SharedUserSetting usr : mSharedUsers.values()) {
8727 serializer.startTag(null, "shared-user");
8728 serializer.attribute(null, "name", usr.name);
8729 serializer.attribute(null, "userId",
8730 Integer.toString(usr.userId));
8731 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8732 serializer.startTag(null, "perms");
8733 for (String name : usr.grantedPermissions) {
8734 serializer.startTag(null, "item");
8735 serializer.attribute(null, "name", name);
8736 serializer.endTag(null, "item");
8737 }
8738 serializer.endTag(null, "perms");
8739 serializer.endTag(null, "shared-user");
8740 }
8741
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008742 if (mPackagesToBeCleaned.size() > 0) {
8743 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8744 serializer.startTag(null, "cleaning-package");
8745 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8746 serializer.endTag(null, "cleaning-package");
8747 }
8748 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008749
8750 if (mRenamedPackages.size() > 0) {
8751 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8752 serializer.startTag(null, "renamed-package");
8753 serializer.attribute(null, "new", e.getKey());
8754 serializer.attribute(null, "old", e.getValue());
8755 serializer.endTag(null, "renamed-package");
8756 }
8757 }
8758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 serializer.endTag(null, "packages");
8760
8761 serializer.endDocument();
8762
8763 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008764 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008765 str.close();
8766
8767 // New settings successfully written, old ones are no longer
8768 // needed.
8769 mBackupSettingsFilename.delete();
8770 FileUtils.setPermissions(mSettingsFilename.toString(),
8771 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8772 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8773 |FileUtils.S_IROTH,
8774 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008775
8776 // Write package list file now, use a JournaledFile.
8777 //
8778 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8779 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8780
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008781 fstr = new FileOutputStream(journal.chooseForWrite());
8782 str = new BufferedOutputStream(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008783 try {
8784 StringBuilder sb = new StringBuilder();
8785 for (PackageSetting pkg : mPackages.values()) {
8786 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008787 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008788 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8789
8790 // Avoid any application that has a space in its path
8791 // or that is handled by the system.
8792 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8793 continue;
8794
8795 // we store on each line the following information for now:
8796 //
8797 // pkgName - package name
8798 // userId - application-specific user id
8799 // debugFlag - 0 or 1 if the package is debuggable.
8800 // dataPath - path to package's data path
8801 //
8802 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8803 //
8804 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8805 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8806 // system/core/run-as/run-as.c
8807 //
8808 sb.setLength(0);
8809 sb.append(ai.packageName);
8810 sb.append(" ");
Jason parksa3cdaa52011-01-13 14:15:43 -06008811 sb.append((int)ai.uid);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008812 sb.append(isDebug ? " 1 " : " 0 ");
8813 sb.append(dataPath);
8814 sb.append("\n");
8815 str.write(sb.toString().getBytes());
8816 }
8817 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008818 FileUtils.sync(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008819 str.close();
8820 journal.commit();
8821 }
8822 catch (Exception e) {
8823 journal.rollback();
8824 }
8825
8826 FileUtils.setPermissions(mPackageListFilename.toString(),
8827 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8828 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8829 |FileUtils.S_IROTH,
8830 -1, -1);
8831
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008832 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833
8834 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008835 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 -08008836 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008837 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 -08008838 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008839 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008840 if (mSettingsFilename.exists()) {
8841 if (!mSettingsFilename.delete()) {
8842 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8843 }
8844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 //Debug.stopMethodTracing();
8846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008847
8848 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008849 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 serializer.startTag(null, "updated-package");
8851 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008852 if (pkg.realName != null) {
8853 serializer.attribute(null, "realName", pkg.realName);
8854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008855 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008856 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8857 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8858 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008859 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008860 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8861 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8862 }
Kenny Root85387d72010-08-26 10:13:11 -07008863 if (pkg.nativeLibraryPathString != null) {
8864 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 if (pkg.sharedUser == null) {
8867 serializer.attribute(null, "userId",
8868 Integer.toString(pkg.userId));
8869 } else {
8870 serializer.attribute(null, "sharedUserId",
8871 Integer.toString(pkg.userId));
8872 }
8873 serializer.startTag(null, "perms");
8874 if (pkg.sharedUser == null) {
8875 // If this is a shared user, the permissions will
8876 // be written there. We still need to write an
8877 // empty permissions list so permissionsFixed will
8878 // be set.
8879 for (final String name : pkg.grantedPermissions) {
8880 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008881 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882 // We only need to write signature or system permissions but this wont
8883 // match the semantics of grantedPermissions. So write all permissions.
8884 serializer.startTag(null, "item");
8885 serializer.attribute(null, "name", name);
8886 serializer.endTag(null, "item");
8887 }
8888 }
8889 }
8890 serializer.endTag(null, "perms");
8891 serializer.endTag(null, "updated-package");
8892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008893
8894 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008895 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896 serializer.startTag(null, "package");
8897 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008898 if (pkg.realName != null) {
8899 serializer.attribute(null, "realName", pkg.realName);
8900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008901 serializer.attribute(null, "codePath", pkg.codePathString);
8902 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8903 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8904 }
Kenny Root85387d72010-08-26 10:13:11 -07008905 if (pkg.nativeLibraryPathString != null) {
8906 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8907 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008908 serializer.attribute(null, "flags",
8909 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008910 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8911 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8912 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008913 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914 if (pkg.sharedUser == null) {
8915 serializer.attribute(null, "userId",
8916 Integer.toString(pkg.userId));
8917 } else {
8918 serializer.attribute(null, "sharedUserId",
8919 Integer.toString(pkg.userId));
8920 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008921 if (pkg.uidError) {
8922 serializer.attribute(null, "uidError", "true");
8923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008924 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8925 serializer.attribute(null, "enabled",
8926 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8927 ? "true" : "false");
8928 }
8929 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8930 serializer.attribute(null, "installStatus", "false");
8931 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008932 if (pkg.installerPackageName != null) {
8933 serializer.attribute(null, "installer", pkg.installerPackageName);
8934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8936 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8937 serializer.startTag(null, "perms");
8938 if (pkg.sharedUser == null) {
8939 // If this is a shared user, the permissions will
8940 // be written there. We still need to write an
8941 // empty permissions list so permissionsFixed will
8942 // be set.
8943 for (final String name : pkg.grantedPermissions) {
8944 serializer.startTag(null, "item");
8945 serializer.attribute(null, "name", name);
8946 serializer.endTag(null, "item");
8947 }
8948 }
8949 serializer.endTag(null, "perms");
8950 }
8951 if (pkg.disabledComponents.size() > 0) {
8952 serializer.startTag(null, "disabled-components");
8953 for (final String name : pkg.disabledComponents) {
8954 serializer.startTag(null, "item");
8955 serializer.attribute(null, "name", name);
8956 serializer.endTag(null, "item");
8957 }
8958 serializer.endTag(null, "disabled-components");
8959 }
8960 if (pkg.enabledComponents.size() > 0) {
8961 serializer.startTag(null, "enabled-components");
8962 for (final String name : pkg.enabledComponents) {
8963 serializer.startTag(null, "item");
8964 serializer.attribute(null, "name", name);
8965 serializer.endTag(null, "item");
8966 }
8967 serializer.endTag(null, "enabled-components");
8968 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008970 serializer.endTag(null, "package");
8971 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008973 void writePermission(XmlSerializer serializer, BasePermission bp)
8974 throws XmlPullParserException, java.io.IOException {
8975 if (bp.type != BasePermission.TYPE_BUILTIN
8976 && bp.sourcePackage != null) {
8977 serializer.startTag(null, "item");
8978 serializer.attribute(null, "name", bp.name);
8979 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008980 if (bp.protectionLevel !=
8981 PermissionInfo.PROTECTION_NORMAL) {
8982 serializer.attribute(null, "protection",
8983 Integer.toString(bp.protectionLevel));
8984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 if (DEBUG_SETTINGS) Log.v(TAG,
8986 "Writing perm: name=" + bp.name + " type=" + bp.type);
8987 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8988 PermissionInfo pi = bp.perm != null ? bp.perm.info
8989 : bp.pendingInfo;
8990 if (pi != null) {
8991 serializer.attribute(null, "type", "dynamic");
8992 if (pi.icon != 0) {
8993 serializer.attribute(null, "icon",
8994 Integer.toString(pi.icon));
8995 }
8996 if (pi.nonLocalizedLabel != null) {
8997 serializer.attribute(null, "label",
8998 pi.nonLocalizedLabel.toString());
8999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009000 }
9001 }
9002 serializer.endTag(null, "item");
9003 }
9004 }
9005
9006 String getReadMessagesLP() {
9007 return mReadMessages.toString();
9008 }
9009
Oscar Montemayora8529f62009-11-18 10:14:20 -08009010 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
9012 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08009013 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014 while(its.hasNext()) {
9015 String key = its.next();
9016 PackageSetting ps = mPackages.get(key);
9017 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08009018 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009019 }
9020 }
9021 return ret;
9022 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 boolean readLP() {
9025 FileInputStream str = null;
9026 if (mBackupSettingsFilename.exists()) {
9027 try {
9028 str = new FileInputStream(mBackupSettingsFilename);
9029 mReadMessages.append("Reading from backup settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009030 reportSettingsProblem(Log.INFO, "Need to read from backup settings file");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07009031 if (mSettingsFilename.exists()) {
9032 // If both the backup and settings file exist, we
9033 // ignore the settings since it might have been
9034 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009035 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07009036 mSettingsFilename.delete();
9037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009038 } catch (java.io.IOException e) {
9039 // We'll try for the normal settings file.
9040 }
9041 }
9042
9043 mPastSignatures.clear();
9044
9045 try {
9046 if (str == null) {
9047 if (!mSettingsFilename.exists()) {
9048 mReadMessages.append("No settings file found\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009049 reportSettingsProblem(Log.INFO, "No settings file; creating initial state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050 return false;
9051 }
9052 str = new FileInputStream(mSettingsFilename);
9053 }
9054 XmlPullParser parser = Xml.newPullParser();
9055 parser.setInput(str, null);
9056
9057 int type;
9058 while ((type=parser.next()) != XmlPullParser.START_TAG
9059 && type != XmlPullParser.END_DOCUMENT) {
9060 ;
9061 }
9062
9063 if (type != XmlPullParser.START_TAG) {
9064 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009065 reportSettingsProblem(Log.WARN, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 return false;
9067 }
9068
9069 int outerDepth = parser.getDepth();
9070 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9071 && (type != XmlPullParser.END_TAG
9072 || parser.getDepth() > outerDepth)) {
9073 if (type == XmlPullParser.END_TAG
9074 || type == XmlPullParser.TEXT) {
9075 continue;
9076 }
9077
9078 String tagName = parser.getName();
9079 if (tagName.equals("package")) {
9080 readPackageLP(parser);
9081 } else if (tagName.equals("permissions")) {
9082 readPermissionsLP(mPermissions, parser);
9083 } else if (tagName.equals("permission-trees")) {
9084 readPermissionsLP(mPermissionTrees, parser);
9085 } else if (tagName.equals("shared-user")) {
9086 readSharedUserLP(parser);
9087 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08009088 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009089 } else if (tagName.equals("preferred-activities")) {
9090 readPreferredActivitiesLP(parser);
9091 } else if(tagName.equals("updated-package")) {
9092 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009093 } else if (tagName.equals("cleaning-package")) {
9094 String name = parser.getAttributeValue(null, "name");
9095 if (name != null) {
9096 mPackagesToBeCleaned.add(name);
9097 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009098 } else if (tagName.equals("renamed-package")) {
9099 String nname = parser.getAttributeValue(null, "new");
9100 String oname = parser.getAttributeValue(null, "old");
9101 if (nname != null && oname != null) {
9102 mRenamedPackages.put(nname, oname);
9103 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009104 } else if (tagName.equals("last-platform-version")) {
9105 mInternalSdkPlatform = mExternalSdkPlatform = 0;
9106 try {
9107 String internal = parser.getAttributeValue(null, "internal");
9108 if (internal != null) {
9109 mInternalSdkPlatform = Integer.parseInt(internal);
9110 }
9111 String external = parser.getAttributeValue(null, "external");
9112 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01009113 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009114 }
9115 } catch (NumberFormatException e) {
9116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009117 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009118 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009119 + parser.getName());
9120 XmlUtils.skipCurrentTag(parser);
9121 }
9122 }
9123
9124 str.close();
9125
9126 } catch(XmlPullParserException e) {
9127 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07009128 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009129 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009130
9131 } catch(java.io.IOException e) {
9132 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07009133 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009134 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009135
9136 }
9137
9138 int N = mPendingPackages.size();
9139 for (int i=0; i<N; i++) {
9140 final PendingPackage pp = mPendingPackages.get(i);
9141 Object idObj = getUserIdLP(pp.sharedId);
9142 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009143 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07009144 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
9145 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146 if (p == null) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07009147 reportSettingsProblem(Log.WARN, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009148 + pp.name);
9149 continue;
9150 }
9151 p.copyFrom(pp);
9152 } else if (idObj != null) {
9153 String msg = "Bad package setting: package " + pp.name
9154 + " has shared uid " + pp.sharedId
9155 + " that is not a shared uid\n";
9156 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009157 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009158 } else {
9159 String msg = "Bad package setting: package " + pp.name
9160 + " has shared uid " + pp.sharedId
9161 + " that is not defined\n";
9162 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009163 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009164 }
9165 }
9166 mPendingPackages.clear();
9167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009168 mReadMessages.append("Read completed successfully: "
9169 + mPackages.size() + " packages, "
9170 + mSharedUsers.size() + " shared uids\n");
9171
9172 return true;
9173 }
9174
9175 private int readInt(XmlPullParser parser, String ns, String name,
9176 int defValue) {
9177 String v = parser.getAttributeValue(ns, name);
9178 try {
9179 if (v == null) {
9180 return defValue;
9181 }
9182 return Integer.parseInt(v);
9183 } catch (NumberFormatException e) {
9184 reportSettingsProblem(Log.WARN,
9185 "Error in package manager settings: attribute " +
9186 name + " has bad integer value " + v + " at "
9187 + parser.getPositionDescription());
9188 }
9189 return defValue;
9190 }
9191
9192 private void readPermissionsLP(HashMap<String, BasePermission> out,
9193 XmlPullParser parser)
9194 throws IOException, XmlPullParserException {
9195 int outerDepth = parser.getDepth();
9196 int type;
9197 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9198 && (type != XmlPullParser.END_TAG
9199 || parser.getDepth() > outerDepth)) {
9200 if (type == XmlPullParser.END_TAG
9201 || type == XmlPullParser.TEXT) {
9202 continue;
9203 }
9204
9205 String tagName = parser.getName();
9206 if (tagName.equals("item")) {
9207 String name = parser.getAttributeValue(null, "name");
9208 String sourcePackage = parser.getAttributeValue(null, "package");
9209 String ptype = parser.getAttributeValue(null, "type");
9210 if (name != null && sourcePackage != null) {
9211 boolean dynamic = "dynamic".equals(ptype);
9212 BasePermission bp = new BasePermission(name, sourcePackage,
9213 dynamic
9214 ? BasePermission.TYPE_DYNAMIC
9215 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009216 bp.protectionLevel = readInt(parser, null, "protection",
9217 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009218 if (dynamic) {
9219 PermissionInfo pi = new PermissionInfo();
9220 pi.packageName = sourcePackage.intern();
9221 pi.name = name.intern();
9222 pi.icon = readInt(parser, null, "icon", 0);
9223 pi.nonLocalizedLabel = parser.getAttributeValue(
9224 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009225 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009226 bp.pendingInfo = pi;
9227 }
9228 out.put(bp.name, bp);
9229 } else {
9230 reportSettingsProblem(Log.WARN,
9231 "Error in package manager settings: permissions has"
9232 + " no name at " + parser.getPositionDescription());
9233 }
9234 } else {
9235 reportSettingsProblem(Log.WARN,
9236 "Unknown element reading permissions: "
9237 + parser.getName() + " at "
9238 + parser.getPositionDescription());
9239 }
9240 XmlUtils.skipCurrentTag(parser);
9241 }
9242 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009244 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009245 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009247 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009248 String codePathStr = parser.getAttributeValue(null, "codePath");
9249 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009250 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009251 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009252 resourcePathStr = codePathStr;
9253 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009254 String version = parser.getAttributeValue(null, "version");
9255 int versionCode = 0;
9256 if (version != null) {
9257 try {
9258 versionCode = Integer.parseInt(version);
9259 } catch (NumberFormatException e) {
9260 }
9261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009263 int pkgFlags = 0;
9264 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009265 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9266 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009267 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009268 if (timeStampStr != null) {
9269 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009270 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009271 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009272 } catch (NumberFormatException e) {
9273 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009274 } else {
9275 timeStampStr = parser.getAttributeValue(null, "ts");
9276 if (timeStampStr != null) {
9277 try {
9278 long timeStamp = Long.parseLong(timeStampStr);
9279 ps.setTimeStamp(timeStamp);
9280 } catch (NumberFormatException e) {
9281 }
9282 }
9283 }
9284 timeStampStr = parser.getAttributeValue(null, "it");
9285 if (timeStampStr != null) {
9286 try {
9287 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9288 } catch (NumberFormatException e) {
9289 }
9290 }
9291 timeStampStr = parser.getAttributeValue(null, "ut");
9292 if (timeStampStr != null) {
9293 try {
9294 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9295 } catch (NumberFormatException e) {
9296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 }
9298 String idStr = parser.getAttributeValue(null, "userId");
9299 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9300 if(ps.userId <= 0) {
9301 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9302 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9303 }
9304 int outerDepth = parser.getDepth();
9305 int type;
9306 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9307 && (type != XmlPullParser.END_TAG
9308 || parser.getDepth() > outerDepth)) {
9309 if (type == XmlPullParser.END_TAG
9310 || type == XmlPullParser.TEXT) {
9311 continue;
9312 }
9313
9314 String tagName = parser.getName();
9315 if (tagName.equals("perms")) {
9316 readGrantedPermissionsLP(parser,
9317 ps.grantedPermissions);
9318 } else {
9319 reportSettingsProblem(Log.WARN,
9320 "Unknown element under <updated-package>: "
9321 + parser.getName());
9322 XmlUtils.skipCurrentTag(parser);
9323 }
9324 }
9325 mDisabledSysPackages.put(name, ps);
9326 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009328 private void readPackageLP(XmlPullParser parser)
9329 throws XmlPullParserException, IOException {
9330 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009331 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 String idStr = null;
9333 String sharedIdStr = null;
9334 String codePathStr = null;
9335 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009336 String nativeLibraryPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009338 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009339 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009340 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009341 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009342 long firstInstallTime = 0;
9343 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009344 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009345 String version = null;
9346 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009347 try {
9348 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009349 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009350 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009351 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9353 codePathStr = parser.getAttributeValue(null, "codePath");
9354 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009355 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009356 version = parser.getAttributeValue(null, "version");
9357 if (version != null) {
9358 try {
9359 versionCode = Integer.parseInt(version);
9360 } catch (NumberFormatException e) {
9361 }
9362 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009363 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009364
9365 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009366 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009367 try {
9368 pkgFlags = Integer.parseInt(systemStr);
9369 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009370 }
9371 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009372 // For backward compatibility
9373 systemStr = parser.getAttributeValue(null, "system");
9374 if (systemStr != null) {
9375 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9376 } else {
9377 // Old settings that don't specify system... just treat
9378 // them as system, good enough.
9379 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009382 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009383 if (timeStampStr != null) {
9384 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009385 timeStamp = Long.parseLong(timeStampStr, 16);
9386 } catch (NumberFormatException e) {
9387 }
9388 } else {
9389 timeStampStr = parser.getAttributeValue(null, "ts");
9390 if (timeStampStr != null) {
9391 try {
9392 timeStamp = Long.parseLong(timeStampStr);
9393 } catch (NumberFormatException e) {
9394 }
9395 }
9396 }
9397 timeStampStr = parser.getAttributeValue(null, "it");
9398 if (timeStampStr != null) {
9399 try {
9400 firstInstallTime = Long.parseLong(timeStampStr, 16);
9401 } catch (NumberFormatException e) {
9402 }
9403 }
9404 timeStampStr = parser.getAttributeValue(null, "ut");
9405 if (timeStampStr != null) {
9406 try {
9407 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009408 } catch (NumberFormatException e) {
9409 }
9410 }
9411 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9412 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9413 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9414 if (resourcePathStr == null) {
9415 resourcePathStr = codePathStr;
9416 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009417 if (realName != null) {
9418 realName = realName.intern();
9419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009420 if (name == null) {
9421 reportSettingsProblem(Log.WARN,
9422 "Error in package manager settings: <package> has no name at "
9423 + parser.getPositionDescription());
9424 } else if (codePathStr == null) {
9425 reportSettingsProblem(Log.WARN,
9426 "Error in package manager settings: <package> has no codePath at "
9427 + parser.getPositionDescription());
9428 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009429 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9430 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9431 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009432 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9433 + ": userId=" + userId + " pkg=" + packageSetting);
9434 if (packageSetting == null) {
9435 reportSettingsProblem(Log.ERROR,
9436 "Failure adding uid " + userId
9437 + " while parsing settings at "
9438 + parser.getPositionDescription());
9439 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009440 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009441 packageSetting.firstInstallTime = firstInstallTime;
9442 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009443 }
9444 } else if (sharedIdStr != null) {
9445 userId = sharedIdStr != null
9446 ? Integer.parseInt(sharedIdStr) : 0;
9447 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009448 packageSetting = new PendingPackage(name.intern(), realName,
9449 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009450 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009451 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009452 packageSetting.firstInstallTime = firstInstallTime;
9453 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 mPendingPackages.add((PendingPackage) packageSetting);
9455 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9456 + ": sharedUserId=" + userId + " pkg="
9457 + packageSetting);
9458 } else {
9459 reportSettingsProblem(Log.WARN,
9460 "Error in package manager settings: package "
9461 + name + " has bad sharedId " + sharedIdStr
9462 + " at " + parser.getPositionDescription());
9463 }
9464 } else {
9465 reportSettingsProblem(Log.WARN,
9466 "Error in package manager settings: package "
9467 + name + " has bad userId " + idStr + " at "
9468 + parser.getPositionDescription());
9469 }
9470 } catch (NumberFormatException e) {
9471 reportSettingsProblem(Log.WARN,
9472 "Error in package manager settings: package "
9473 + name + " has bad userId " + idStr + " at "
9474 + parser.getPositionDescription());
9475 }
9476 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009477 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009478 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009479 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009480 final String enabledStr = parser.getAttributeValue(null, "enabled");
9481 if (enabledStr != null) {
9482 if (enabledStr.equalsIgnoreCase("true")) {
9483 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9484 } else if (enabledStr.equalsIgnoreCase("false")) {
9485 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9486 } else if (enabledStr.equalsIgnoreCase("default")) {
9487 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9488 } else {
9489 reportSettingsProblem(Log.WARN,
9490 "Error in package manager settings: package "
9491 + name + " has bad enabled value: " + idStr
9492 + " at " + parser.getPositionDescription());
9493 }
9494 } else {
9495 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9496 }
9497 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9498 if (installStatusStr != null) {
9499 if (installStatusStr.equalsIgnoreCase("false")) {
9500 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9501 } else {
9502 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9503 }
9504 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009506 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("disabled-components")) {
9518 readDisabledComponentsLP(packageSetting, parser);
9519 } else if (tagName.equals("enabled-components")) {
9520 readEnabledComponentsLP(packageSetting, parser);
9521 } else if (tagName.equals("sigs")) {
9522 packageSetting.signatures.readXml(parser, mPastSignatures);
9523 } else if (tagName.equals("perms")) {
9524 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009525 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009526 packageSetting.permissionsFixed = true;
9527 } else {
9528 reportSettingsProblem(Log.WARN,
9529 "Unknown element under <package>: "
9530 + parser.getName());
9531 XmlUtils.skipCurrentTag(parser);
9532 }
9533 }
9534 } else {
9535 XmlUtils.skipCurrentTag(parser);
9536 }
9537 }
9538
9539 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9540 XmlPullParser parser)
9541 throws IOException, XmlPullParserException {
9542 int outerDepth = parser.getDepth();
9543 int type;
9544 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9545 && (type != XmlPullParser.END_TAG
9546 || parser.getDepth() > outerDepth)) {
9547 if (type == XmlPullParser.END_TAG
9548 || type == XmlPullParser.TEXT) {
9549 continue;
9550 }
9551
9552 String tagName = parser.getName();
9553 if (tagName.equals("item")) {
9554 String name = parser.getAttributeValue(null, "name");
9555 if (name != null) {
9556 packageSetting.disabledComponents.add(name.intern());
9557 } else {
9558 reportSettingsProblem(Log.WARN,
9559 "Error in package manager settings: <disabled-components> has"
9560 + " no name at " + parser.getPositionDescription());
9561 }
9562 } else {
9563 reportSettingsProblem(Log.WARN,
9564 "Unknown element under <disabled-components>: "
9565 + parser.getName());
9566 }
9567 XmlUtils.skipCurrentTag(parser);
9568 }
9569 }
9570
9571 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9572 XmlPullParser parser)
9573 throws IOException, XmlPullParserException {
9574 int outerDepth = parser.getDepth();
9575 int type;
9576 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9577 && (type != XmlPullParser.END_TAG
9578 || parser.getDepth() > outerDepth)) {
9579 if (type == XmlPullParser.END_TAG
9580 || type == XmlPullParser.TEXT) {
9581 continue;
9582 }
9583
9584 String tagName = parser.getName();
9585 if (tagName.equals("item")) {
9586 String name = parser.getAttributeValue(null, "name");
9587 if (name != null) {
9588 packageSetting.enabledComponents.add(name.intern());
9589 } else {
9590 reportSettingsProblem(Log.WARN,
9591 "Error in package manager settings: <enabled-components> has"
9592 + " no name at " + parser.getPositionDescription());
9593 }
9594 } else {
9595 reportSettingsProblem(Log.WARN,
9596 "Unknown element under <enabled-components>: "
9597 + parser.getName());
9598 }
9599 XmlUtils.skipCurrentTag(parser);
9600 }
9601 }
9602
9603 private void readSharedUserLP(XmlPullParser parser)
9604 throws XmlPullParserException, IOException {
9605 String name = null;
9606 String idStr = null;
9607 int pkgFlags = 0;
9608 SharedUserSetting su = null;
9609 try {
9610 name = parser.getAttributeValue(null, "name");
9611 idStr = parser.getAttributeValue(null, "userId");
9612 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9613 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9614 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9615 }
9616 if (name == null) {
9617 reportSettingsProblem(Log.WARN,
9618 "Error in package manager settings: <shared-user> has no name at "
9619 + parser.getPositionDescription());
9620 } else if (userId == 0) {
9621 reportSettingsProblem(Log.WARN,
9622 "Error in package manager settings: shared-user "
9623 + name + " has bad userId " + idStr + " at "
9624 + parser.getPositionDescription());
9625 } else {
9626 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9627 reportSettingsProblem(Log.ERROR,
9628 "Occurred while parsing settings at "
9629 + parser.getPositionDescription());
9630 }
9631 }
9632 } catch (NumberFormatException e) {
9633 reportSettingsProblem(Log.WARN,
9634 "Error in package manager settings: package "
9635 + name + " has bad userId " + idStr + " at "
9636 + parser.getPositionDescription());
9637 };
9638
9639 if (su != null) {
9640 int outerDepth = parser.getDepth();
9641 int type;
9642 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9643 && (type != XmlPullParser.END_TAG
9644 || parser.getDepth() > outerDepth)) {
9645 if (type == XmlPullParser.END_TAG
9646 || type == XmlPullParser.TEXT) {
9647 continue;
9648 }
9649
9650 String tagName = parser.getName();
9651 if (tagName.equals("sigs")) {
9652 su.signatures.readXml(parser, mPastSignatures);
9653 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009654 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009655 } else {
9656 reportSettingsProblem(Log.WARN,
9657 "Unknown element under <shared-user>: "
9658 + parser.getName());
9659 XmlUtils.skipCurrentTag(parser);
9660 }
9661 }
9662
9663 } else {
9664 XmlUtils.skipCurrentTag(parser);
9665 }
9666 }
9667
9668 private void readGrantedPermissionsLP(XmlPullParser parser,
9669 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9670 int outerDepth = parser.getDepth();
9671 int type;
9672 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9673 && (type != XmlPullParser.END_TAG
9674 || parser.getDepth() > outerDepth)) {
9675 if (type == XmlPullParser.END_TAG
9676 || type == XmlPullParser.TEXT) {
9677 continue;
9678 }
9679
9680 String tagName = parser.getName();
9681 if (tagName.equals("item")) {
9682 String name = parser.getAttributeValue(null, "name");
9683 if (name != null) {
9684 outPerms.add(name.intern());
9685 } else {
9686 reportSettingsProblem(Log.WARN,
9687 "Error in package manager settings: <perms> has"
9688 + " no name at " + parser.getPositionDescription());
9689 }
9690 } else {
9691 reportSettingsProblem(Log.WARN,
9692 "Unknown element under <perms>: "
9693 + parser.getName());
9694 }
9695 XmlUtils.skipCurrentTag(parser);
9696 }
9697 }
9698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009699 private void readPreferredActivitiesLP(XmlPullParser parser)
9700 throws XmlPullParserException, IOException {
9701 int outerDepth = parser.getDepth();
9702 int type;
9703 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9704 && (type != XmlPullParser.END_TAG
9705 || parser.getDepth() > outerDepth)) {
9706 if (type == XmlPullParser.END_TAG
9707 || type == XmlPullParser.TEXT) {
9708 continue;
9709 }
9710
9711 String tagName = parser.getName();
9712 if (tagName.equals("item")) {
9713 PreferredActivity pa = new PreferredActivity(parser);
9714 if (pa.mParseError == null) {
9715 mPreferredActivities.addFilter(pa);
9716 } else {
9717 reportSettingsProblem(Log.WARN,
9718 "Error in package manager settings: <preferred-activity> "
9719 + pa.mParseError + " at "
9720 + parser.getPositionDescription());
9721 }
9722 } else {
9723 reportSettingsProblem(Log.WARN,
9724 "Unknown element under <preferred-activities>: "
9725 + parser.getName());
9726 XmlUtils.skipCurrentTag(parser);
9727 }
9728 }
9729 }
9730
9731 // Returns -1 if we could not find an available UserId to assign
9732 private int newUserIdLP(Object obj) {
9733 // Let's be stupidly inefficient for now...
9734 final int N = mUserIds.size();
9735 for (int i=0; i<N; i++) {
9736 if (mUserIds.get(i) == null) {
9737 mUserIds.set(i, obj);
9738 return FIRST_APPLICATION_UID + i;
9739 }
9740 }
9741
9742 // None left?
9743 if (N >= MAX_APPLICATION_UIDS) {
9744 return -1;
9745 }
9746
9747 mUserIds.add(obj);
9748 return FIRST_APPLICATION_UID + N;
9749 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009751 public PackageSetting getDisabledSystemPkg(String name) {
9752 synchronized(mPackages) {
9753 PackageSetting ps = mDisabledSysPackages.get(name);
9754 return ps;
9755 }
9756 }
9757
9758 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009759 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9760 return true;
9761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009762 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9763 if (Config.LOGV) {
9764 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9765 + " componentName = " + componentInfo.name);
9766 Log.v(TAG, "enabledComponents: "
9767 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9768 Log.v(TAG, "disabledComponents: "
9769 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9770 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009771 if (packageSettings == null) {
9772 if (false) {
9773 Log.w(TAG, "WAITING FOR DEBUGGER");
9774 Debug.waitForDebugger();
9775 Log.i(TAG, "We will crash!");
9776 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009777 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009778 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009779 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9780 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9781 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9782 return false;
9783 }
9784 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9785 return true;
9786 }
9787 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9788 return false;
9789 }
9790 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009791 }
9792 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009793
9794 // ------- apps on sdcard specific code -------
9795 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009796 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9797 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9798 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009799 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009800
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009801 private String getEncryptKey() {
9802 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009803 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9804 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009805 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009806 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9807 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009808 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009809 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009810 return null;
9811 }
9812 }
9813 return sdEncKey;
9814 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009815 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009816 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009817 } catch (IOException ioe) {
9818 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9819 + ioe);
9820 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009821 }
Rich Cannings8d578832010-09-09 15:12:40 -07009822
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009823 }
9824
Kenny Rootc78a8072010-07-27 15:18:38 -07009825 /* package */ static String getTempContainerId() {
9826 int tmpIdx = 1;
9827 String list[] = PackageHelper.getSecureContainerList();
9828 if (list != null) {
9829 for (final String name : list) {
9830 // Ignore null and non-temporary container entries
9831 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9832 continue;
9833 }
9834
9835 String subStr = name.substring(mTempContainerPrefix.length());
9836 try {
9837 int cid = Integer.parseInt(subStr);
9838 if (cid >= tmpIdx) {
9839 tmpIdx = cid + 1;
9840 }
9841 } catch (NumberFormatException e) {
9842 }
9843 }
9844 }
9845 return mTempContainerPrefix + tmpIdx;
9846 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009847
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009848 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009849 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009850 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009851 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
Marco Nelissen584f1372010-05-24 16:34:30 -07009852 int callingUid = Binder.getCallingUid();
9853 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009854 throw new SecurityException("Media status can only be updated by the system");
9855 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009856 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009857 Log.i(TAG, "Updating external media status from " +
9858 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9859 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009860 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9861 mediaStatus+", mMediaMounted=" + mMediaMounted);
9862 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009863 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9864 reportStatus ? 1 : 0, -1);
9865 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009866 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009867 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009868 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009869 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009870 // Queue up an async operation since the package installation may take a little while.
9871 mHandler.post(new Runnable() {
9872 public void run() {
9873 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009874 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009875 }
9876 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009877 }
9878
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009879 /*
9880 * Collect information of applications on external media, map them
9881 * against existing containers and update information based on current
9882 * mount status. Please note that we always have to report status
9883 * if reportStatus has been set to true especially when unloading packages.
9884 */
9885 private void updateExternalMediaStatusInner(boolean mediaStatus,
9886 boolean reportStatus) {
9887 // Collection of uids
9888 int uidArr[] = null;
9889 // Collection of stale containers
9890 HashSet<String> removeCids = new HashSet<String>();
9891 // Collection of packages on external media with valid containers.
9892 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9893 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009894 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009895 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009896 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009897 } else {
9898 // Process list of secure containers and categorize them
9899 // as active or stale based on their package internal state.
9900 int uidList[] = new int[list.length];
9901 int num = 0;
9902 synchronized (mPackages) {
9903 for (String cid : list) {
9904 SdInstallArgs args = new SdInstallArgs(cid);
9905 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009906 String pkgName = args.getPackageName();
9907 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009908 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9909 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009910 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009911 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009912 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9913 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009914 // The package status is changed only if the code path
9915 // matches between settings and the container id.
9916 if (ps != null && ps.codePathString != null &&
9917 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009918 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9919 " corresponds to pkg : " + pkgName +
9920 " at code path: " + ps.codePathString);
9921 // We do have a valid package installed on sdcard
9922 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009923 int uid = ps.userId;
9924 if (uid != -1) {
9925 uidList[num++] = uid;
9926 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009927 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009928 // Stale container on sdcard. Just delete
9929 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9930 removeCids.add(cid);
9931 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009932 }
9933 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009934
9935 if (num > 0) {
9936 // Sort uid list
9937 Arrays.sort(uidList, 0, num);
9938 // Throw away duplicates
9939 uidArr = new int[num];
9940 uidArr[0] = uidList[0];
9941 int di = 0;
9942 for (int i = 1; i < num; i++) {
9943 if (uidList[i-1] != uidList[i]) {
9944 uidArr[di++] = uidList[i];
9945 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009946 }
9947 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009948 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009949 // Process packages with valid entries.
9950 if (mediaStatus) {
9951 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009952 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009953 startCleaningPackages();
9954 } else {
9955 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009956 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009957 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009958 }
9959
9960 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009961 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009962 int size = pkgList.size();
9963 if (size > 0) {
9964 // Send broadcasts here
9965 Bundle extras = new Bundle();
9966 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9967 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009968 if (uidArr != null) {
9969 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9970 }
9971 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9972 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009973 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009974 }
9975 }
9976
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009977 /*
9978 * Look at potentially valid container ids from processCids
9979 * If package information doesn't match the one on record
9980 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009981 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009982 */
9983 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009984 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009985 ArrayList<String> pkgList = new ArrayList<String>();
9986 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009987 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009988 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009989 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009990 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9991 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009992 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009993 try {
9994 // Make sure there are no container errors first.
9995 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9996 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009997 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009998 " when installing from sdcard");
9999 continue;
10000 }
10001 // Check code path here.
10002 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -080010003 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010004 " does not match one in settings " + codePath);
10005 continue;
10006 }
10007 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -070010008 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010009 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010010 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010011 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -070010012 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010013 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010014 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010015 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010016 retCode = PackageManager.INSTALL_SUCCEEDED;
10017 pkgList.add(pkg.packageName);
10018 // Post process args
10019 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
10020 }
10021 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -070010022 Slog.i(TAG, "Failed to install pkg from " +
10023 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010024 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010025 }
10026
10027 } finally {
10028 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
10029 // Don't destroy container here. Wait till gc clears things up.
10030 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010031 }
10032 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010033 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010034 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -070010035 // If the platform SDK has changed since the last time we booted,
10036 // we need to re-grant app permission to catch any new ones that
10037 // appear. This is really a hack, and means that apps can in some
10038 // cases get permissions that the user didn't initially explicitly
10039 // allow... it would be nice to have some better way to handle
10040 // this situation.
10041 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
10042 != mSdkVersion;
10043 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
10044 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
10045 + "; regranting permissions for external storage");
10046 mSettings.mExternalSdkPlatform = mSdkVersion;
10047
Dianne Hackbornaf7cea32010-03-24 12:59:52 -070010048 // Make sure group IDs have been assigned, and any permission
10049 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -070010050 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -070010051 // Persist settings
10052 mSettings.writeLP();
10053 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080010054 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010055 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010056 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010057 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010058 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010059 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010060 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010061 }
Kenny Rootf369a9b2010-07-28 14:47:01 -070010062 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010063 if (removeCids != null) {
10064 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -070010065 if (cid.startsWith(mTempContainerPrefix)) {
10066 Log.i(TAG, "Destroying stale temporary container " + cid);
10067 PackageHelper.destroySdDir(cid);
10068 } else {
10069 Log.w(TAG, "Container " + cid + " is stale");
10070 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010071 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010072 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010073 }
10074
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010075 /*
10076 * Utility method to unload a list of specified containers
10077 */
10078 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
10079 // Just unmount all valid containers.
10080 for (SdInstallArgs arg : cidArgs) {
10081 synchronized (mInstallLock) {
10082 arg.doPostDeleteLI(false);
10083 }
10084 }
10085 }
10086
10087 /*
10088 * Unload packages mounted on external media. This involves deleting
10089 * package data from internal structures, sending broadcasts about
10090 * diabled packages, gc'ing to free up references, unmounting all
10091 * secure containers corresponding to packages on external media, and
10092 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
10093 * Please note that we always have to post this message if status has
10094 * been requested no matter what.
10095 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010096 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010097 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010098 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010099 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010100 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010101 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010102 for (SdInstallArgs args : keys) {
10103 String cid = args.cid;
10104 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010106 // Delete package internally
10107 PackageRemovedInfo outInfo = new PackageRemovedInfo();
10108 synchronized (mInstallLock) {
10109 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010110 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010111 if (res) {
10112 pkgList.add(pkgName);
10113 } else {
Jeff Brown07330792010-03-30 19:57:08 -070010114 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010115 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010116 }
10117 }
10118 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010119
10120 synchronized (mPackages) {
10121 // We didn't update the settings after removing each package;
10122 // write them now for all packages.
10123 mSettings.writeLP();
10124 }
10125
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010126 // We have to absolutely send UPDATED_MEDIA_STATUS only
10127 // after confirming that all the receivers processed the ordered
10128 // broadcast when packages get disabled, force a gc to clean things up.
10129 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010130 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010131 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
10132 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
10133 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010134 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10135 reportStatus ? 1 : 0, 1, keys);
10136 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010137 }
10138 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010139 } else {
10140 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10141 reportStatus ? 1 : 0, -1, keys);
10142 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010143 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -080010144 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010145
10146 public void movePackage(final String packageName,
10147 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010148 mContext.enforceCallingOrSelfPermission(
10149 android.Manifest.permission.MOVE_PACKAGE, null);
10150 int returnCode = PackageManager.MOVE_SUCCEEDED;
10151 int currFlags = 0;
10152 int newFlags = 0;
10153 synchronized (mPackages) {
10154 PackageParser.Package pkg = mPackages.get(packageName);
10155 if (pkg == null) {
10156 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010157 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010158 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -070010159 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010160 Slog.w(TAG, "Cannot move system application");
10161 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -070010162 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010163 Slog.w(TAG, "Cannot move forward locked app.");
10164 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -070010165 } else if (pkg.mOperationPending) {
10166 Slog.w(TAG, "Attempt to move package which has pending operations");
10167 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010168 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010169 // Find install location first
10170 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
10171 (flags & PackageManager.MOVE_INTERNAL) != 0) {
10172 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010173 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010174 } else {
10175 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
10176 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -070010177 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
10178 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010179 if (newFlags == currFlags) {
10180 Slog.w(TAG, "No move required. Trying to move to same location");
10181 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
10182 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010183 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010184 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10185 pkg.mOperationPending = true;
10186 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010187 }
10188 }
10189 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -070010190 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010191 } else {
10192 Message msg = mHandler.obtainMessage(INIT_COPY);
10193 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -070010194 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
10195 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
10196 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010197 msg.obj = mp;
10198 mHandler.sendMessage(msg);
10199 }
10200 }
10201 }
10202
10203 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10204 // Queue up an async operation since the package deletion may take a little while.
10205 mHandler.post(new Runnable() {
10206 public void run() {
10207 mHandler.removeCallbacks(this);
10208 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010209 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10210 int uidArr[] = null;
10211 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010212 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010213 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010214 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010215 Slog.w(TAG, " Package " + mp.packageName +
10216 " doesn't exist. Aborting move");
10217 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10218 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10219 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10220 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10221 " Aborting move and returning error");
10222 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10223 } else {
10224 uidArr = new int[] { pkg.applicationInfo.uid };
10225 pkgList = new ArrayList<String>();
10226 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010227 }
10228 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010229 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10230 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010231 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010232 // Update package code and resource paths
10233 synchronized (mInstallLock) {
10234 synchronized (mPackages) {
10235 PackageParser.Package pkg = mPackages.get(mp.packageName);
10236 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010237 if (pkg == null) {
10238 Slog.w(TAG, " Package " + mp.packageName
10239 + " doesn't exist. Aborting move");
10240 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010241 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10242 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10243 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10244 " Aborting move and returning error");
10245 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10246 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010247 final String oldCodePath = pkg.mPath;
10248 final String newCodePath = mp.targetArgs.getCodePath();
10249 final String newResPath = mp.targetArgs.getResourcePath();
10250 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010251
10252 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10253 if (mInstaller
10254 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10255 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10256 } else {
10257 NativeLibraryHelper.copyNativeBinariesLI(
10258 new File(newCodePath), new File(newNativePath));
10259 }
10260 } else {
10261 if (mInstaller.linkNativeLibraryDirectory(
10262 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10263 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10264 }
10265 }
10266
10267 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10268 pkg.mPath = newCodePath;
10269 // Move dex files around
10270 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10271 // Moving of dex files failed. Set
10272 // error code and abort move.
10273 pkg.mPath = pkg.mScanPath;
10274 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10275 }
10276 }
10277
10278 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010279 pkg.mScanPath = newCodePath;
10280 pkg.applicationInfo.sourceDir = newCodePath;
10281 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010282 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010283 PackageSetting ps = (PackageSetting) pkg.mExtras;
10284 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10285 ps.codePathString = ps.codePath.getPath();
10286 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10287 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010288 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010289 // Set the application info flag correctly.
10290 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10291 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10292 } else {
10293 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10294 }
10295 ps.setFlags(pkg.applicationInfo.flags);
10296 mAppDirs.remove(oldCodePath);
10297 mAppDirs.put(newCodePath, pkg);
10298 // Persist settings
10299 mSettings.writeLP();
10300 }
10301 }
10302 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010303 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010304 // Send resources available broadcast
10305 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010306 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010307 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010308 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010309 // Clean up failed installation
10310 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010311 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010312 }
10313 } else {
10314 // Force a gc to clear things up.
10315 Runtime.getRuntime().gc();
10316 // Delete older code
10317 synchronized (mInstallLock) {
10318 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010319 }
10320 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010321
10322 // Allow more operations on this file if we didn't fail because
10323 // an operation was already pending for this package.
10324 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10325 synchronized (mPackages) {
10326 PackageParser.Package pkg = mPackages.get(mp.packageName);
10327 if (pkg != null) {
10328 pkg.mOperationPending = false;
10329 }
10330 }
10331 }
10332
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010333 IPackageMoveObserver observer = mp.observer;
10334 if (observer != null) {
10335 try {
10336 observer.packageMoved(mp.packageName, returnCode);
10337 } catch (RemoteException e) {
10338 Log.i(TAG, "Observer no longer exists.");
10339 }
10340 }
10341 }
10342 });
10343 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010344
10345 public boolean setInstallLocation(int loc) {
10346 mContext.enforceCallingOrSelfPermission(
10347 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10348 if (getInstallLocation() == loc) {
10349 return true;
10350 }
10351 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10352 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10353 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10354 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10355 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10356 return true;
10357 }
10358 return false;
10359 }
10360
10361 public int getInstallLocation() {
10362 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10363 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010365}