blob: b7ab9fe607034a0608d4a4662fc4180ebd4854b5 [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;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070023import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080024import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080033import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070035import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070036import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.Intent;
38import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080040import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070041import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.ActivityInfo;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070045import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.IPackageDataObserver;
47import android.content.pm.IPackageDeleteObserver;
48import android.content.pm.IPackageInstallObserver;
49import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080050import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.IPackageStatsObserver;
52import android.content.pm.InstrumentationInfo;
53import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080054import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.pm.PackageManager;
56import android.content.pm.PackageStats;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.pm.PackageParser;
61import android.content.pm.PermissionInfo;
62import android.content.pm.PermissionGroupInfo;
63import android.content.pm.ProviderInfo;
64import android.content.pm.ResolveInfo;
65import android.content.pm.ServiceInfo;
66import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.Uri;
68import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070069import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080071import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080073import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070074import android.os.Looper;
75import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Parcel;
77import android.os.RemoteException;
78import android.os.Environment;
79import android.os.FileObserver;
80import android.os.FileUtils;
81import android.os.Handler;
82import android.os.ParcelFileDescriptor;
83import android.os.Process;
84import android.os.ServiceManager;
85import android.os.SystemClock;
86import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070087import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080088import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.util.*;
90import android.view.Display;
91import android.view.WindowManager;
92
93import java.io.File;
94import java.io.FileDescriptor;
95import java.io.FileInputStream;
96import java.io.FileNotFoundException;
97import java.io.FileOutputStream;
98import java.io.FileReader;
99import java.io.FilenameFilter;
100import java.io.IOException;
101import java.io.InputStream;
102import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800103import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800104import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.ArrayList;
106import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700107import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.Collections;
109import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800110import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.Enumeration;
112import java.util.HashMap;
113import java.util.HashSet;
114import java.util.Iterator;
115import java.util.List;
116import java.util.Map;
117import java.util.Set;
118import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800119import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import java.util.zip.ZipFile;
121import java.util.zip.ZipOutputStream;
122
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700123/**
124 * Keep track of all those .apks everywhere.
125 *
126 * This is very central to the platform's security; please run the unit
127 * tests whenever making modifications here:
128 *
129mmm frameworks/base/tests/AndroidTests
130adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
131adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
132 *
133 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134class PackageManagerService extends IPackageManager.Stub {
135 private static final String TAG = "PackageManager";
136 private static final boolean DEBUG_SETTINGS = false;
137 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800138 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800139 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
141 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
142 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400143 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 private static final int FIRST_APPLICATION_UID =
145 Process.FIRST_APPLICATION_UID;
146 private static final int MAX_APPLICATION_UIDS = 1000;
147
148 private static final boolean SHOW_INFO = false;
149
150 private static final boolean GET_CERTIFICATES = true;
151
152 private static final int REMOVE_EVENTS =
153 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
154 private static final int ADD_EVENTS =
155 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
156
157 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800158 // Suffix used during package installation when copying/moving
159 // package apks to install directory.
160 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800162 /**
163 * Indicates the state of installation. Used by PackageManager to
164 * figure out incomplete installations. Say a package is being installed
165 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
166 * the package installation is successful or unsuccesful lin which case
167 * the PackageManager will no longer maintain state information associated
168 * with the package. If some exception(like device freeze or battery being
169 * pulled out) occurs during installation of a package, the PackageManager
170 * needs this information to clean up the previously failed installation.
171 */
172 private static final int PKG_INSTALL_INCOMPLETE = 0;
173 private static final int PKG_INSTALL_COMPLETE = 1;
174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final int SCAN_MONITOR = 1<<0;
176 static final int SCAN_NO_DEX = 1<<1;
177 static final int SCAN_FORCE_DEX = 1<<2;
178 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800179 static final int SCAN_NEW_INSTALL = 1<<4;
180 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700182 static final int REMOVE_CHATTY = 1<<16;
183
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800184 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
185 "com.android.defcontainer",
186 "com.android.defcontainer.DefaultContainerService");
187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
189 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700190 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Dianne Hackborn851a5412009-05-08 12:06:44 -0700192 final int mSdkVersion = Build.VERSION.SDK_INT;
193 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
194 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 final Context mContext;
197 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700198 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 final DisplayMetrics mMetrics;
200 final int mDefParseFlags;
201 final String[] mSeparateProcesses;
202
203 // This is where all application persistent data goes.
204 final File mAppDataDir;
205
206 // This is the object monitoring the framework dir.
207 final FileObserver mFrameworkInstallObserver;
208
209 // This is the object monitoring the system app dir.
210 final FileObserver mSystemInstallObserver;
211
212 // This is the object monitoring mAppInstallDir.
213 final FileObserver mAppInstallObserver;
214
215 // This is the object monitoring mDrmAppPrivateInstallDir.
216 final FileObserver mDrmAppInstallObserver;
217
218 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
219 // LOCK HELD. Can be called with mInstallLock held.
220 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 final File mFrameworkDir;
223 final File mSystemAppDir;
224 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700225 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
227 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
228 // apps.
229 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // Lock for state used when installing and doing other long running
234 // operations. Methods that must be called with this lock held have
235 // the prefix "LI".
236 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 // These are the directories in the 3rd party applications installed dir
239 // that we have currently loaded packages from. Keys are the application's
240 // installed zip file (absolute codePath), and values are Package.
241 final HashMap<String, PackageParser.Package> mAppDirs =
242 new HashMap<String, PackageParser.Package>();
243
244 // Information for the parser to write more useful error messages.
245 File mScanningPath;
246 int mLastScanError;
247
248 final int[] mOutPermissions = new int[3];
249
250 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // Keys are String (package name), values are Package. This also serves
253 // as the lock for the global state. Methods that must be called with
254 // this lock held have the prefix "LP".
255 final HashMap<String, PackageParser.Package> mPackages =
256 new HashMap<String, PackageParser.Package>();
257
258 final Settings mSettings;
259 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260
261 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
262 int[] mGlobalGids;
263
264 // These are the built-in uid -> permission mappings that were read from the
265 // etc/permissions.xml file.
266 final SparseArray<HashSet<String>> mSystemPermissions =
267 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 // These are the built-in shared libraries that were read from the
270 // etc/permissions.xml file.
271 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800272
Dianne Hackborn49237342009-08-27 20:08:01 -0700273 // Temporary for building the final shared libraries for an .apk.
274 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800275
Dianne Hackborn49237342009-08-27 20:08:01 -0700276 // These are the features this devices supports that were read from the
277 // etc/permissions.xml file.
278 final HashMap<String, FeatureInfo> mAvailableFeatures =
279 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 // All available activities, for your resolving pleasure.
282 final ActivityIntentResolver mActivities =
283 new ActivityIntentResolver();
284
285 // All available receivers, for your resolving pleasure.
286 final ActivityIntentResolver mReceivers =
287 new ActivityIntentResolver();
288
289 // All available services, for your resolving pleasure.
290 final ServiceIntentResolver mServices = new ServiceIntentResolver();
291
292 // Keys are String (provider class name), values are Provider.
293 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
294 new HashMap<ComponentName, PackageParser.Provider>();
295
296 // Mapping from provider base names (first directory in content URI codePath)
297 // to the provider information.
298 final HashMap<String, PackageParser.Provider> mProviders =
299 new HashMap<String, PackageParser.Provider>();
300
301 // Mapping from instrumentation class names to info about them.
302 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
303 new HashMap<ComponentName, PackageParser.Instrumentation>();
304
305 // Mapping from permission names to info about them.
306 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
307 new HashMap<String, PackageParser.PermissionGroup>();
308
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800309 // Packages whose data we have transfered into another package, thus
310 // should no longer exist.
311 final HashSet<String> mTransferedPackages = new HashSet<String>();
312
Dianne Hackborn854060af2009-07-09 18:14:31 -0700313 // Broadcast actions that are only available to the system.
314 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 boolean mSystemReady;
317 boolean mSafeMode;
318 boolean mHasSystemUidErrors;
319
320 ApplicationInfo mAndroidApplication;
321 final ActivityInfo mResolveActivity = new ActivityInfo();
322 final ResolveInfo mResolveInfo = new ResolveInfo();
323 ComponentName mResolveComponentName;
324 PackageParser.Package mPlatformPackage;
325
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700326 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800327 final HashMap<String, ArrayList<String>> mPendingBroadcasts
328 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800329 // Service Connection to remote media container service to copy
330 // package uri's from external media onto secure containers
331 // or internal storage.
332 private IMediaContainerService mContainerService = null;
333
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700334 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800335 static final int MCS_BOUND = 3;
336 static final int END_COPY = 4;
337 static final int INIT_COPY = 5;
338 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800339 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800340 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800341 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800342 static final int MCS_RECONNECT = 10;
343 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700344 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700345 static final int WRITE_SETTINGS = 13;
346
347 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800348
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700349 // Delay time in millisecs
350 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800351 final private DefaultContainerConnection mDefContainerConn =
352 new DefaultContainerConnection();
353 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800354 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800355 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800356 IMediaContainerService imcs =
357 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800358 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800359 }
360
361 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800362 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800363 }
364 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700365
Christopher Tate1bb69062010-02-19 17:02:12 -0800366 // Recordkeeping of restore-after-install operations that are currently in flight
367 // between the Package Manager and the Backup Manager
368 class PostInstallData {
369 public InstallArgs args;
370 public PackageInstalledInfo res;
371
372 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
373 args = _a;
374 res = _r;
375 }
376 };
377 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
378 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
379
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700380 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800381 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800382 final ArrayList<HandlerParams> mPendingInstalls =
383 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800384
385 private boolean connectToService() {
386 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
387 " DefaultContainerService");
388 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700389 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800390 if (mContext.bindService(service, mDefContainerConn,
391 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700392 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800393 mBound = true;
394 return true;
395 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700396 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397 return false;
398 }
399
400 private void disconnectService() {
401 mContainerService = null;
402 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700403 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800404 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800407
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700408 PackageHandler(Looper looper) {
409 super(looper);
410 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700411
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700412 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700413 try {
414 doHandleMessage(msg);
415 } finally {
416 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
417 }
418 }
419
420 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800422 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800423 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800424 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800425 int idx = mPendingInstalls.size();
426 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
427 // If a bind was already initiated we dont really
428 // need to do anything. The pending install
429 // will be processed later on.
430 if (!mBound) {
431 // If this is the only one pending we might
432 // have to bind to the service again.
433 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800434 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800435 params.serviceError();
436 return;
437 } else {
438 // Once we bind to the service, the first
439 // pending request will be processed.
440 mPendingInstalls.add(idx, params);
441 }
442 } else {
443 mPendingInstalls.add(idx, params);
444 // Already bound to the service. Just make
445 // sure we trigger off processing the first request.
446 if (idx == 0) {
447 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800448 }
449 }
450 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800451 }
452 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800453 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800454 if (msg.obj != null) {
455 mContainerService = (IMediaContainerService) msg.obj;
456 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800457 if (mContainerService == null) {
458 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800459 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800460 for (HandlerParams params : mPendingInstalls) {
461 mPendingInstalls.remove(0);
462 // Indicate service bind error
463 params.serviceError();
464 }
465 mPendingInstalls.clear();
466 } else if (mPendingInstalls.size() > 0) {
467 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800468 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800469 params.startCopy();
470 }
471 } else {
472 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800473 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800474 }
475 break;
476 }
477 case MCS_RECONNECT : {
478 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
479 if (mPendingInstalls.size() > 0) {
480 if (mBound) {
481 disconnectService();
482 }
483 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800484 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800485 for (HandlerParams params : mPendingInstalls) {
486 mPendingInstalls.remove(0);
487 // Indicate service bind error
488 params.serviceError();
489 }
490 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800491 }
492 }
493 break;
494 }
495 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800496 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
497 // Delete pending install
498 if (mPendingInstalls.size() > 0) {
499 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800500 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800501 if (mPendingInstalls.size() == 0) {
502 if (mBound) {
503 disconnectService();
504 }
505 } else {
506 // There are more pending requests in queue.
507 // Just post MCS_BOUND message to trigger processing
508 // of next pending install.
509 mHandler.sendEmptyMessage(MCS_BOUND);
510 }
511 break;
512 }
513 case MCS_GIVE_UP: {
514 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
515 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800516 break;
517 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700518 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800519 String packages[];
520 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700521 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700522 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700523 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700524 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800525 if (mPendingBroadcasts == null) {
526 return;
527 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700528 size = mPendingBroadcasts.size();
529 if (size <= 0) {
530 // Nothing to be done. Just return
531 return;
532 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800533 packages = new String[size];
534 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800536 Iterator<HashMap.Entry<String, ArrayList<String>>>
537 it = mPendingBroadcasts.entrySet().iterator();
538 int i = 0;
539 while (it.hasNext() && i < size) {
540 HashMap.Entry<String, ArrayList<String>> ent = it.next();
541 packages[i] = ent.getKey();
542 components[i] = ent.getValue();
543 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700544 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800545 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700546 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800547 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700548 mPendingBroadcasts.clear();
549 }
550 // Send broadcasts
551 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800552 sendPackageChangedBroadcast(packages[i], true,
553 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700554 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700555 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700556 break;
557 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800558 case START_CLEANING_PACKAGE: {
559 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700560 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800561 synchronized (mPackages) {
562 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
563 mSettings.mPackagesToBeCleaned.add(packageName);
564 }
565 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700566 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800567 startCleaningPackages();
568 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800569 case POST_INSTALL: {
570 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
571 PostInstallData data = mRunningInstalls.get(msg.arg1);
572 mRunningInstalls.delete(msg.arg1);
573
574 if (data != null) {
575 InstallArgs args = data.args;
576 PackageInstalledInfo res = data.res;
577
578 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -0700579 res.removedInfo.sendBroadcast(false, true,
580 new PackageRemovedIntentReceiver(res.removedInfo.args,
581 res.removedInfo.args != null));
Christopher Tate1bb69062010-02-19 17:02:12 -0800582 Bundle extras = new Bundle(1);
583 extras.putInt(Intent.EXTRA_UID, res.uid);
584 final boolean update = res.removedInfo.removedPackage != null;
585 if (update) {
586 extras.putBoolean(Intent.EXTRA_REPLACING, true);
587 }
588 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
589 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700590 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800591 if (update) {
592 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
593 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700594 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800595 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800596 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800597 if (args.observer != null) {
598 try {
599 args.observer.packageInstalled(res.name, res.returnCode);
600 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800601 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800602 }
603 }
604 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800605 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800606 }
607 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700608 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700609 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
610 boolean reportStatus = msg.arg1 == 1;
611 boolean doGc = msg.arg2 == 1;
612 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
613 if (doGc) {
614 // Force a gc to clear up stale containers.
615 Runtime.getRuntime().gc();
616 }
617 if (msg.obj != null) {
618 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
619 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
620 // Unload containers
621 unloadAllContainers(args);
622 }
623 if (reportStatus) {
624 try {
625 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
626 PackageHelper.getMountService().finishMediaUpdate();
627 } catch (RemoteException e) {
628 Log.e(TAG, "MountService not running?");
629 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700630 }
631 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700632 case WRITE_SETTINGS: {
633 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
634 synchronized (mPackages) {
635 removeMessages(WRITE_SETTINGS);
636 mSettings.writeLP();
637 }
638 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
639 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700640 }
641 }
642 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800643
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700644 void scheduleWriteSettingsLocked() {
645 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
646 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
647 }
648 }
649
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800650 static boolean installOnSd(int flags) {
651 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700652 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800653 return false;
654 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700655 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
656 return true;
657 }
658 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800659 }
660
661 static boolean isFwdLocked(int flags) {
662 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
663 return true;
664 }
665 return false;
666 }
667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 public static final IPackageManager main(Context context, boolean factoryTest) {
669 PackageManagerService m = new PackageManagerService(context, factoryTest);
670 ServiceManager.addService("package", m);
671 return m;
672 }
673
674 static String[] splitString(String str, char sep) {
675 int count = 1;
676 int i = 0;
677 while ((i=str.indexOf(sep, i)) >= 0) {
678 count++;
679 i++;
680 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 String[] res = new String[count];
683 i=0;
684 count = 0;
685 int lastI=0;
686 while ((i=str.indexOf(sep, i)) >= 0) {
687 res[count] = str.substring(lastI, i);
688 count++;
689 i++;
690 lastI = i;
691 }
692 res[count] = str.substring(lastI, str.length());
693 return res;
694 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800697 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800701 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 mContext = context;
705 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700706 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 mMetrics = new DisplayMetrics();
708 mSettings = new Settings();
709 mSettings.addSharedUserLP("android.uid.system",
710 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
711 mSettings.addSharedUserLP("android.uid.phone",
712 MULTIPLE_APPLICATION_UIDS
713 ? RADIO_UID : FIRST_APPLICATION_UID,
714 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400715 mSettings.addSharedUserLP("android.uid.log",
716 MULTIPLE_APPLICATION_UIDS
717 ? LOG_UID : FIRST_APPLICATION_UID,
718 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719
720 String separateProcesses = SystemProperties.get("debug.separate_processes");
721 if (separateProcesses != null && separateProcesses.length() > 0) {
722 if ("*".equals(separateProcesses)) {
723 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
724 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800725 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 } else {
727 mDefParseFlags = 0;
728 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800729 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 + separateProcesses);
731 }
732 } else {
733 mDefParseFlags = 0;
734 mSeparateProcesses = null;
735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 Installer installer = new Installer();
738 // Little hacky thing to check if installd is here, to determine
739 // whether we are running on the simulator and thus need to take
740 // care of building the /data file structure ourself.
741 // (apparently the sim now has a working installer)
742 if (installer.ping() && Process.supportsProcesses()) {
743 mInstaller = installer;
744 } else {
745 mInstaller = null;
746 }
747
748 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
749 Display d = wm.getDefaultDisplay();
750 d.getMetrics(mMetrics);
751
752 synchronized (mInstallLock) {
753 synchronized (mPackages) {
754 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700755 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 File dataDir = Environment.getDataDirectory();
758 mAppDataDir = new File(dataDir, "data");
759 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
760
761 if (mInstaller == null) {
762 // Make sure these dirs exist, when we are running in
763 // the simulator.
764 // Make a wide-open directory for random misc stuff.
765 File miscDir = new File(dataDir, "misc");
766 miscDir.mkdirs();
767 mAppDataDir.mkdirs();
768 mDrmAppPrivateInstallDir.mkdirs();
769 }
770
771 readPermissions();
772
773 mRestoredSettings = mSettings.readLP();
774 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800775
776 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800778
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800779 // Set flag to monitor and not change apk file paths when
780 // scanning install directories.
781 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700782 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800783 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800784 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700790 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700793 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 /**
796 * Out of paranoia, ensure that everything in the boot class
797 * path has been dexed.
798 */
799 String bootClassPath = System.getProperty("java.boot.class.path");
800 if (bootClassPath != null) {
801 String[] paths = splitString(bootClassPath, ':');
802 for (int i=0; i<paths.length; i++) {
803 try {
804 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
805 libFiles.add(paths[i]);
806 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700807 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 }
809 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800810 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800812 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 }
814 }
815 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800816 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 /**
820 * Also ensure all external libraries have had dexopt run on them.
821 */
822 if (mSharedLibraries.size() > 0) {
823 Iterator<String> libs = mSharedLibraries.values().iterator();
824 while (libs.hasNext()) {
825 String lib = libs.next();
826 try {
827 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
828 libFiles.add(lib);
829 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700830 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 }
832 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800833 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800835 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
837 }
838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 // Gross hack for now: we know this file doesn't contain any
841 // code, so don't dexopt it to avoid the resulting log spew.
842 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 /**
845 * And there are a number of commands implemented in Java, which
846 * we currently need to do the dexopt on so that they can be
847 * run from a non-root shell.
848 */
849 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700850 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 for (int i=0; i<frameworkFiles.length; i++) {
852 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
853 String path = libPath.getPath();
854 // Skip the file if we alrady did it.
855 if (libFiles.contains(path)) {
856 continue;
857 }
858 // Skip the file if it is not a type we want to dexopt.
859 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
860 continue;
861 }
862 try {
863 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
864 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700865 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 }
867 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800868 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800870 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 }
872 }
873 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800874
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700875 if (didDexOpt) {
876 // If we had to do a dexopt of one of the previous
877 // things, then something on the system has changed.
878 // Consider this significant, and wipe away all other
879 // existing dexopt files to ensure we don't leave any
880 // dangling around.
881 String[] files = mDalvikCacheDir.list();
882 if (files != null) {
883 for (int i=0; i<files.length; i++) {
884 String fn = files[i];
885 if (fn.startsWith("data@app@")
886 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800887 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700888 (new File(mDalvikCacheDir, fn)).delete();
889 }
890 }
891 }
892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800894
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800895 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 mFrameworkInstallObserver = new AppDirObserver(
897 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
898 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700899 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
900 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800901 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800902
903 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
905 mSystemInstallObserver = new AppDirObserver(
906 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
907 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700908 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
909 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800910
911 if (mInstaller != null) {
912 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
913 mInstaller.moveFiles();
914 }
915
916 // Prune any system packages that no longer exist.
917 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
918 while (psit.hasNext()) {
919 PackageSetting ps = psit.next();
920 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800921 && !mPackages.containsKey(ps.name)
922 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800923 psit.remove();
924 String msg = "System package " + ps.name
925 + " no longer exists; wiping its data";
926 reportSettingsProblem(Log.WARN, msg);
927 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700928 mInstaller.remove(ps.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800929 }
930 }
931 }
932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 mAppInstallDir = new File(dataDir, "app");
934 if (mInstaller == null) {
935 // Make sure these dirs exist, when we are running in
936 // the simulator.
937 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
938 }
939 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800940 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 //clean up list
942 for(int i = 0; i < deletePkgsList.size(); i++) {
943 //clean up here
944 cleanupInstallFailedPackage(deletePkgsList.get(i));
945 }
946 //delete tmp files
947 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800948
949 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 SystemClock.uptimeMillis());
951 mAppInstallObserver = new AppDirObserver(
952 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
953 mAppInstallObserver.startWatching();
954 scanDirLI(mAppInstallDir, 0, scanMode);
955
956 mDrmAppInstallObserver = new AppDirObserver(
957 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
958 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800959 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800961 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800963 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 + ((SystemClock.uptimeMillis()-startTime)/1000f)
965 + " seconds");
966
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700967 // If the platform SDK has changed since the last time we booted,
968 // we need to re-grant app permission to catch any new ones that
969 // appear. This is really a hack, and means that apps can in some
970 // cases get permissions that the user didn't initially explicitly
971 // allow... it would be nice to have some better way to handle
972 // this situation.
973 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
974 != mSdkVersion;
975 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
976 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
977 + "; regranting permissions for internal storage");
978 mSettings.mInternalSdkPlatform = mSdkVersion;
979
980 updatePermissionsLP(null, null, true, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
982 mSettings.writeLP();
983
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800984 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 // Now after opening every single application zip, make sure they
988 // are all flushed. Not really needed, but keeps things nice and
989 // tidy.
990 Runtime.getRuntime().gc();
991 } // synchronized (mPackages)
992 } // synchronized (mInstallLock)
993 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 @Override
996 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
997 throws RemoteException {
998 try {
999 return super.onTransact(code, data, reply, flags);
1000 } catch (RuntimeException e) {
1001 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001002 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 }
1004 throw e;
1005 }
1006 }
1007
Dianne Hackborne6620b22010-01-22 14:46:21 -08001008 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001009 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07001011 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001013 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001014 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 }
1016 } else {
1017 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001018 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 File dataDir = new File(pkg.applicationInfo.dataDir);
1020 dataDir.delete();
1021 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001022 if (ps.codePath != null) {
1023 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001024 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001025 }
1026 }
1027 if (ps.resourcePath != null) {
1028 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001029 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001030 }
1031 }
1032 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 }
1034
1035 void readPermissions() {
1036 // Read permissions from .../etc/permission directory.
1037 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1038 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001039 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 return;
1041 }
1042 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001043 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 return;
1045 }
1046
1047 // Iterate over the files in the directory and scan .xml files
1048 for (File f : libraryDir.listFiles()) {
1049 // We'll read platform.xml last
1050 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1051 continue;
1052 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001055 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 continue;
1057 }
1058 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001059 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 continue;
1061 }
1062
1063 readPermissionsFromXml(f);
1064 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1067 final File permFile = new File(Environment.getRootDirectory(),
1068 "etc/permissions/platform.xml");
1069 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001070
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001071 StringBuilder sb = new StringBuilder(128);
1072 sb.append("Libs:");
1073 Iterator<String> it = mSharedLibraries.keySet().iterator();
1074 while (it.hasNext()) {
1075 sb.append(' ');
1076 String name = it.next();
1077 sb.append(name);
1078 sb.append(':');
1079 sb.append(mSharedLibraries.get(name));
1080 }
1081 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001082
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001083 sb.setLength(0);
1084 sb.append("Features:");
1085 it = mAvailableFeatures.keySet().iterator();
1086 while (it.hasNext()) {
1087 sb.append(' ');
1088 sb.append(it.next());
1089 }
1090 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
1093 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 FileReader permReader = null;
1095 try {
1096 permReader = new FileReader(permFile);
1097 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001098 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 return;
1100 }
1101
1102 try {
1103 XmlPullParser parser = Xml.newPullParser();
1104 parser.setInput(permReader);
1105
1106 XmlUtils.beginDocument(parser, "permissions");
1107
1108 while (true) {
1109 XmlUtils.nextElement(parser);
1110 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1111 break;
1112 }
1113
1114 String name = parser.getName();
1115 if ("group".equals(name)) {
1116 String gidStr = parser.getAttributeValue(null, "gid");
1117 if (gidStr != null) {
1118 int gid = Integer.parseInt(gidStr);
1119 mGlobalGids = appendInt(mGlobalGids, gid);
1120 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001121 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 + parser.getPositionDescription());
1123 }
1124
1125 XmlUtils.skipCurrentTag(parser);
1126 continue;
1127 } else if ("permission".equals(name)) {
1128 String perm = parser.getAttributeValue(null, "name");
1129 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001130 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 + parser.getPositionDescription());
1132 XmlUtils.skipCurrentTag(parser);
1133 continue;
1134 }
1135 perm = perm.intern();
1136 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 } else if ("assign-permission".equals(name)) {
1139 String perm = parser.getAttributeValue(null, "name");
1140 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001141 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 + parser.getPositionDescription());
1143 XmlUtils.skipCurrentTag(parser);
1144 continue;
1145 }
1146 String uidStr = parser.getAttributeValue(null, "uid");
1147 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001148 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 + parser.getPositionDescription());
1150 XmlUtils.skipCurrentTag(parser);
1151 continue;
1152 }
1153 int uid = Process.getUidForName(uidStr);
1154 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001155 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 + uidStr + "\" at "
1157 + parser.getPositionDescription());
1158 XmlUtils.skipCurrentTag(parser);
1159 continue;
1160 }
1161 perm = perm.intern();
1162 HashSet<String> perms = mSystemPermissions.get(uid);
1163 if (perms == null) {
1164 perms = new HashSet<String>();
1165 mSystemPermissions.put(uid, perms);
1166 }
1167 perms.add(perm);
1168 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 } else if ("library".equals(name)) {
1171 String lname = parser.getAttributeValue(null, "name");
1172 String lfile = parser.getAttributeValue(null, "file");
1173 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001174 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 + parser.getPositionDescription());
1176 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 + parser.getPositionDescription());
1179 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001180 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001181 mSharedLibraries.put(lname, lfile);
1182 }
1183 XmlUtils.skipCurrentTag(parser);
1184 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001185
Dianne Hackborn49237342009-08-27 20:08:01 -07001186 } else if ("feature".equals(name)) {
1187 String fname = parser.getAttributeValue(null, "name");
1188 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001189 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001190 + parser.getPositionDescription());
1191 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001192 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001193 FeatureInfo fi = new FeatureInfo();
1194 fi.name = fname;
1195 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 }
1197 XmlUtils.skipCurrentTag(parser);
1198 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 } else {
1201 XmlUtils.skipCurrentTag(parser);
1202 continue;
1203 }
1204
1205 }
1206 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001207 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001209 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211 }
1212
1213 void readPermission(XmlPullParser parser, String name)
1214 throws IOException, XmlPullParserException {
1215
1216 name = name.intern();
1217
1218 BasePermission bp = mSettings.mPermissions.get(name);
1219 if (bp == null) {
1220 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1221 mSettings.mPermissions.put(name, bp);
1222 }
1223 int outerDepth = parser.getDepth();
1224 int type;
1225 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1226 && (type != XmlPullParser.END_TAG
1227 || parser.getDepth() > outerDepth)) {
1228 if (type == XmlPullParser.END_TAG
1229 || type == XmlPullParser.TEXT) {
1230 continue;
1231 }
1232
1233 String tagName = parser.getName();
1234 if ("group".equals(tagName)) {
1235 String gidStr = parser.getAttributeValue(null, "gid");
1236 if (gidStr != null) {
1237 int gid = Process.getGidForName(gidStr);
1238 bp.gids = appendInt(bp.gids, gid);
1239 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001240 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 + parser.getPositionDescription());
1242 }
1243 }
1244 XmlUtils.skipCurrentTag(parser);
1245 }
1246 }
1247
1248 static int[] appendInt(int[] cur, int val) {
1249 if (cur == null) {
1250 return new int[] { val };
1251 }
1252 final int N = cur.length;
1253 for (int i=0; i<N; i++) {
1254 if (cur[i] == val) {
1255 return cur;
1256 }
1257 }
1258 int[] ret = new int[N+1];
1259 System.arraycopy(cur, 0, ret, 0, N);
1260 ret[N] = val;
1261 return ret;
1262 }
1263
1264 static int[] appendInts(int[] cur, int[] add) {
1265 if (add == null) return cur;
1266 if (cur == null) return add;
1267 final int N = add.length;
1268 for (int i=0; i<N; i++) {
1269 cur = appendInt(cur, add[i]);
1270 }
1271 return cur;
1272 }
1273
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001274 static int[] removeInt(int[] cur, int val) {
1275 if (cur == null) {
1276 return null;
1277 }
1278 final int N = cur.length;
1279 for (int i=0; i<N; i++) {
1280 if (cur[i] == val) {
1281 int[] ret = new int[N-1];
1282 if (i > 0) {
1283 System.arraycopy(cur, 0, ret, 0, i);
1284 }
1285 if (i < (N-1)) {
1286 System.arraycopy(cur, i, ret, i+1, N-i-1);
1287 }
1288 return ret;
1289 }
1290 }
1291 return cur;
1292 }
1293
1294 static int[] removeInts(int[] cur, int[] rem) {
1295 if (rem == null) return cur;
1296 if (cur == null) return cur;
1297 final int N = rem.length;
1298 for (int i=0; i<N; i++) {
1299 cur = removeInt(cur, rem[i]);
1300 }
1301 return cur;
1302 }
1303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001305 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1306 // The package has been uninstalled but has retained data and resources.
1307 return PackageParser.generatePackageInfo(p, null, flags);
1308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 final PackageSetting ps = (PackageSetting)p.mExtras;
1310 if (ps == null) {
1311 return null;
1312 }
1313 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1314 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1315 }
1316
1317 public PackageInfo getPackageInfo(String packageName, int flags) {
1318 synchronized (mPackages) {
1319 PackageParser.Package p = mPackages.get(packageName);
1320 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001321 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 + ": " + p);
1323 if (p != null) {
1324 return generatePackageInfo(p, flags);
1325 }
1326 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1327 return generatePackageInfoFromSettingsLP(packageName, flags);
1328 }
1329 }
1330 return null;
1331 }
1332
Dianne Hackborn47096932010-02-11 15:57:09 -08001333 public String[] currentToCanonicalPackageNames(String[] names) {
1334 String[] out = new String[names.length];
1335 synchronized (mPackages) {
1336 for (int i=names.length-1; i>=0; i--) {
1337 PackageSetting ps = mSettings.mPackages.get(names[i]);
1338 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1339 }
1340 }
1341 return out;
1342 }
1343
1344 public String[] canonicalToCurrentPackageNames(String[] names) {
1345 String[] out = new String[names.length];
1346 synchronized (mPackages) {
1347 for (int i=names.length-1; i>=0; i--) {
1348 String cur = mSettings.mRenamedPackages.get(names[i]);
1349 out[i] = cur != null ? cur : names[i];
1350 }
1351 }
1352 return out;
1353 }
1354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 public int getPackageUid(String packageName) {
1356 synchronized (mPackages) {
1357 PackageParser.Package p = mPackages.get(packageName);
1358 if(p != null) {
1359 return p.applicationInfo.uid;
1360 }
1361 PackageSetting ps = mSettings.mPackages.get(packageName);
1362 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1363 return -1;
1364 }
1365 p = ps.pkg;
1366 return p != null ? p.applicationInfo.uid : -1;
1367 }
1368 }
1369
1370 public int[] getPackageGids(String packageName) {
1371 synchronized (mPackages) {
1372 PackageParser.Package p = mPackages.get(packageName);
1373 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001374 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 + ": " + p);
1376 if (p != null) {
1377 final PackageSetting ps = (PackageSetting)p.mExtras;
1378 final SharedUserSetting suid = ps.sharedUser;
1379 return suid != null ? suid.gids : ps.gids;
1380 }
1381 }
1382 // stupid thing to indicate an error.
1383 return new int[0];
1384 }
1385
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001386 static final PermissionInfo generatePermissionInfo(
1387 BasePermission bp, int flags) {
1388 if (bp.perm != null) {
1389 return PackageParser.generatePermissionInfo(bp.perm, flags);
1390 }
1391 PermissionInfo pi = new PermissionInfo();
1392 pi.name = bp.name;
1393 pi.packageName = bp.sourcePackage;
1394 pi.nonLocalizedLabel = bp.name;
1395 pi.protectionLevel = bp.protectionLevel;
1396 return pi;
1397 }
1398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 public PermissionInfo getPermissionInfo(String name, int flags) {
1400 synchronized (mPackages) {
1401 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001402 if (p != null) {
1403 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
1405 return null;
1406 }
1407 }
1408
1409 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1410 synchronized (mPackages) {
1411 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1412 for (BasePermission p : mSettings.mPermissions.values()) {
1413 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001414 if (p.perm == null || p.perm.info.group == null) {
1415 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001418 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1420 }
1421 }
1422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 if (out.size() > 0) {
1425 return out;
1426 }
1427 return mPermissionGroups.containsKey(group) ? out : null;
1428 }
1429 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1432 synchronized (mPackages) {
1433 return PackageParser.generatePermissionGroupInfo(
1434 mPermissionGroups.get(name), flags);
1435 }
1436 }
1437
1438 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1439 synchronized (mPackages) {
1440 final int N = mPermissionGroups.size();
1441 ArrayList<PermissionGroupInfo> out
1442 = new ArrayList<PermissionGroupInfo>(N);
1443 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1444 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1445 }
1446 return out;
1447 }
1448 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1451 PackageSetting ps = mSettings.mPackages.get(packageName);
1452 if(ps != null) {
1453 if(ps.pkg == null) {
1454 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1455 if(pInfo != null) {
1456 return pInfo.applicationInfo;
1457 }
1458 return null;
1459 }
1460 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1461 }
1462 return null;
1463 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1466 PackageSetting ps = mSettings.mPackages.get(packageName);
1467 if(ps != null) {
1468 if(ps.pkg == null) {
1469 ps.pkg = new PackageParser.Package(packageName);
1470 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001471 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1472 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1473 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1474 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
1476 return generatePackageInfo(ps.pkg, flags);
1477 }
1478 return null;
1479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1482 synchronized (mPackages) {
1483 PackageParser.Package p = mPackages.get(packageName);
1484 if (Config.LOGV) Log.v(
1485 TAG, "getApplicationInfo " + packageName
1486 + ": " + p);
1487 if (p != null) {
1488 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001489 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 }
1491 if ("android".equals(packageName)||"system".equals(packageName)) {
1492 return mAndroidApplication;
1493 }
1494 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1495 return generateApplicationInfoFromSettingsLP(packageName, flags);
1496 }
1497 }
1498 return null;
1499 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001500
1501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1503 mContext.enforceCallingOrSelfPermission(
1504 android.Manifest.permission.CLEAR_APP_CACHE, null);
1505 // Queue up an async operation since clearing cache may take a little while.
1506 mHandler.post(new Runnable() {
1507 public void run() {
1508 mHandler.removeCallbacks(this);
1509 int retCode = -1;
1510 if (mInstaller != null) {
1511 retCode = mInstaller.freeCache(freeStorageSize);
1512 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001513 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
1515 } //end if mInstaller
1516 if (observer != null) {
1517 try {
1518 observer.onRemoveCompleted(null, (retCode >= 0));
1519 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001520 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522 }
1523 }
1524 });
1525 }
1526
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001527 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001528 mContext.enforceCallingOrSelfPermission(
1529 android.Manifest.permission.CLEAR_APP_CACHE, null);
1530 // Queue up an async operation since clearing cache may take a little while.
1531 mHandler.post(new Runnable() {
1532 public void run() {
1533 mHandler.removeCallbacks(this);
1534 int retCode = -1;
1535 if (mInstaller != null) {
1536 retCode = mInstaller.freeCache(freeStorageSize);
1537 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001538 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001539 }
1540 }
1541 if(pi != null) {
1542 try {
1543 // Callback via pending intent
1544 int code = (retCode >= 0) ? 1 : 0;
1545 pi.sendIntent(null, code, null,
1546 null, null);
1547 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001548 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001549 }
1550 }
1551 }
1552 });
1553 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1556 synchronized (mPackages) {
1557 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001558
1559 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001561 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 }
1563 if (mResolveComponentName.equals(component)) {
1564 return mResolveActivity;
1565 }
1566 }
1567 return null;
1568 }
1569
1570 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1571 synchronized (mPackages) {
1572 PackageParser.Activity a = mReceivers.mActivities.get(component);
1573 if (Config.LOGV) Log.v(
1574 TAG, "getReceiverInfo " + component + ": " + a);
1575 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1576 return PackageParser.generateActivityInfo(a, flags);
1577 }
1578 }
1579 return null;
1580 }
1581
1582 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1583 synchronized (mPackages) {
1584 PackageParser.Service s = mServices.mServices.get(component);
1585 if (Config.LOGV) Log.v(
1586 TAG, "getServiceInfo " + component + ": " + s);
1587 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1588 return PackageParser.generateServiceInfo(s, flags);
1589 }
1590 }
1591 return null;
1592 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 public String[] getSystemSharedLibraryNames() {
1595 Set<String> libSet;
1596 synchronized (mPackages) {
1597 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001598 int size = libSet.size();
1599 if (size > 0) {
1600 String[] libs = new String[size];
1601 libSet.toArray(libs);
1602 return libs;
1603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001605 return null;
1606 }
1607
1608 public FeatureInfo[] getSystemAvailableFeatures() {
1609 Collection<FeatureInfo> featSet;
1610 synchronized (mPackages) {
1611 featSet = mAvailableFeatures.values();
1612 int size = featSet.size();
1613 if (size > 0) {
1614 FeatureInfo[] features = new FeatureInfo[size+1];
1615 featSet.toArray(features);
1616 FeatureInfo fi = new FeatureInfo();
1617 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1618 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1619 features[size] = fi;
1620 return features;
1621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
1623 return null;
1624 }
1625
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001626 public boolean hasSystemFeature(String name) {
1627 synchronized (mPackages) {
1628 return mAvailableFeatures.containsKey(name);
1629 }
1630 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 public int checkPermission(String permName, String pkgName) {
1633 synchronized (mPackages) {
1634 PackageParser.Package p = mPackages.get(pkgName);
1635 if (p != null && p.mExtras != null) {
1636 PackageSetting ps = (PackageSetting)p.mExtras;
1637 if (ps.sharedUser != null) {
1638 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1639 return PackageManager.PERMISSION_GRANTED;
1640 }
1641 } else if (ps.grantedPermissions.contains(permName)) {
1642 return PackageManager.PERMISSION_GRANTED;
1643 }
1644 }
1645 }
1646 return PackageManager.PERMISSION_DENIED;
1647 }
1648
1649 public int checkUidPermission(String permName, int uid) {
1650 synchronized (mPackages) {
1651 Object obj = mSettings.getUserIdLP(uid);
1652 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001653 GrantedPermissions gp = (GrantedPermissions)obj;
1654 if (gp.grantedPermissions.contains(permName)) {
1655 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
1657 } else {
1658 HashSet<String> perms = mSystemPermissions.get(uid);
1659 if (perms != null && perms.contains(permName)) {
1660 return PackageManager.PERMISSION_GRANTED;
1661 }
1662 }
1663 }
1664 return PackageManager.PERMISSION_DENIED;
1665 }
1666
1667 private BasePermission findPermissionTreeLP(String permName) {
1668 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1669 if (permName.startsWith(bp.name) &&
1670 permName.length() > bp.name.length() &&
1671 permName.charAt(bp.name.length()) == '.') {
1672 return bp;
1673 }
1674 }
1675 return null;
1676 }
1677
1678 private BasePermission checkPermissionTreeLP(String permName) {
1679 if (permName != null) {
1680 BasePermission bp = findPermissionTreeLP(permName);
1681 if (bp != null) {
1682 if (bp.uid == Binder.getCallingUid()) {
1683 return bp;
1684 }
1685 throw new SecurityException("Calling uid "
1686 + Binder.getCallingUid()
1687 + " is not allowed to add to permission tree "
1688 + bp.name + " owned by uid " + bp.uid);
1689 }
1690 }
1691 throw new SecurityException("No permission tree found for " + permName);
1692 }
1693
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001694 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1695 if (s1 == null) {
1696 return s2 == null;
1697 }
1698 if (s2 == null) {
1699 return false;
1700 }
1701 if (s1.getClass() != s2.getClass()) {
1702 return false;
1703 }
1704 return s1.equals(s2);
1705 }
1706
1707 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1708 if (pi1.icon != pi2.icon) return false;
1709 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1710 if (!compareStrings(pi1.name, pi2.name)) return false;
1711 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1712 // We'll take care of setting this one.
1713 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1714 // These are not currently stored in settings.
1715 //if (!compareStrings(pi1.group, pi2.group)) return false;
1716 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1717 //if (pi1.labelRes != pi2.labelRes) return false;
1718 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1719 return true;
1720 }
1721
1722 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1723 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1724 throw new SecurityException("Label must be specified in permission");
1725 }
1726 BasePermission tree = checkPermissionTreeLP(info.name);
1727 BasePermission bp = mSettings.mPermissions.get(info.name);
1728 boolean added = bp == null;
1729 boolean changed = true;
1730 if (added) {
1731 bp = new BasePermission(info.name, tree.sourcePackage,
1732 BasePermission.TYPE_DYNAMIC);
1733 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1734 throw new SecurityException(
1735 "Not allowed to modify non-dynamic permission "
1736 + info.name);
1737 } else {
1738 if (bp.protectionLevel == info.protectionLevel
1739 && bp.perm.owner.equals(tree.perm.owner)
1740 && bp.uid == tree.uid
1741 && comparePermissionInfos(bp.perm.info, info)) {
1742 changed = false;
1743 }
1744 }
1745 bp.protectionLevel = info.protectionLevel;
1746 bp.perm = new PackageParser.Permission(tree.perm.owner,
1747 new PermissionInfo(info));
1748 bp.perm.info.packageName = tree.perm.info.packageName;
1749 bp.uid = tree.uid;
1750 if (added) {
1751 mSettings.mPermissions.put(info.name, bp);
1752 }
1753 if (changed) {
1754 if (!async) {
1755 mSettings.writeLP();
1756 } else {
1757 scheduleWriteSettingsLocked();
1758 }
1759 }
1760 return added;
1761 }
1762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 public boolean addPermission(PermissionInfo info) {
1764 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001765 return addPermissionLocked(info, false);
1766 }
1767 }
1768
1769 public boolean addPermissionAsync(PermissionInfo info) {
1770 synchronized (mPackages) {
1771 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 }
1773 }
1774
1775 public void removePermission(String name) {
1776 synchronized (mPackages) {
1777 checkPermissionTreeLP(name);
1778 BasePermission bp = mSettings.mPermissions.get(name);
1779 if (bp != null) {
1780 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1781 throw new SecurityException(
1782 "Not allowed to modify non-dynamic permission "
1783 + name);
1784 }
1785 mSettings.mPermissions.remove(name);
1786 mSettings.writeLP();
1787 }
1788 }
1789 }
1790
Dianne Hackborn854060af2009-07-09 18:14:31 -07001791 public boolean isProtectedBroadcast(String actionName) {
1792 synchronized (mPackages) {
1793 return mProtectedBroadcasts.contains(actionName);
1794 }
1795 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 public int checkSignatures(String pkg1, String pkg2) {
1798 synchronized (mPackages) {
1799 PackageParser.Package p1 = mPackages.get(pkg1);
1800 PackageParser.Package p2 = mPackages.get(pkg2);
1801 if (p1 == null || p1.mExtras == null
1802 || p2 == null || p2.mExtras == null) {
1803 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1804 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001805 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 }
1807 }
1808
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001809 public int checkUidSignatures(int uid1, int uid2) {
1810 synchronized (mPackages) {
1811 Signature[] s1;
1812 Signature[] s2;
1813 Object obj = mSettings.getUserIdLP(uid1);
1814 if (obj != null) {
1815 if (obj instanceof SharedUserSetting) {
1816 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1817 } else if (obj instanceof PackageSetting) {
1818 s1 = ((PackageSetting)obj).signatures.mSignatures;
1819 } else {
1820 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1821 }
1822 } else {
1823 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1824 }
1825 obj = mSettings.getUserIdLP(uid2);
1826 if (obj != null) {
1827 if (obj instanceof SharedUserSetting) {
1828 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1829 } else if (obj instanceof PackageSetting) {
1830 s2 = ((PackageSetting)obj).signatures.mSignatures;
1831 } else {
1832 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1833 }
1834 } else {
1835 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1836 }
1837 return checkSignaturesLP(s1, s2);
1838 }
1839 }
1840
1841 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1842 if (s1 == null) {
1843 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1845 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1846 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001847 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1849 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001850 HashSet<Signature> set1 = new HashSet<Signature>();
1851 for (Signature sig : s1) {
1852 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001854 HashSet<Signature> set2 = new HashSet<Signature>();
1855 for (Signature sig : s2) {
1856 set2.add(sig);
1857 }
1858 // Make sure s2 contains all signatures in s1.
1859 if (set1.equals(set2)) {
1860 return PackageManager.SIGNATURE_MATCH;
1861 }
1862 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
1864
1865 public String[] getPackagesForUid(int uid) {
1866 synchronized (mPackages) {
1867 Object obj = mSettings.getUserIdLP(uid);
1868 if (obj instanceof SharedUserSetting) {
1869 SharedUserSetting sus = (SharedUserSetting)obj;
1870 final int N = sus.packages.size();
1871 String[] res = new String[N];
1872 Iterator<PackageSetting> it = sus.packages.iterator();
1873 int i=0;
1874 while (it.hasNext()) {
1875 res[i++] = it.next().name;
1876 }
1877 return res;
1878 } else if (obj instanceof PackageSetting) {
1879 PackageSetting ps = (PackageSetting)obj;
1880 return new String[] { ps.name };
1881 }
1882 }
1883 return null;
1884 }
1885
1886 public String getNameForUid(int uid) {
1887 synchronized (mPackages) {
1888 Object obj = mSettings.getUserIdLP(uid);
1889 if (obj instanceof SharedUserSetting) {
1890 SharedUserSetting sus = (SharedUserSetting)obj;
1891 return sus.name + ":" + sus.userId;
1892 } else if (obj instanceof PackageSetting) {
1893 PackageSetting ps = (PackageSetting)obj;
1894 return ps.name;
1895 }
1896 }
1897 return null;
1898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 public int getUidForSharedUser(String sharedUserName) {
1901 if(sharedUserName == null) {
1902 return -1;
1903 }
1904 synchronized (mPackages) {
1905 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1906 if(suid == null) {
1907 return -1;
1908 }
1909 return suid.userId;
1910 }
1911 }
1912
1913 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1914 int flags) {
1915 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001916 return chooseBestActivity(intent, resolvedType, flags, query);
1917 }
1918
Mihai Predaeae850c2009-05-13 10:13:48 +02001919 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1920 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 if (query != null) {
1922 final int N = query.size();
1923 if (N == 1) {
1924 return query.get(0);
1925 } else if (N > 1) {
1926 // If there is more than one activity with the same priority,
1927 // then let the user decide between them.
1928 ResolveInfo r0 = query.get(0);
1929 ResolveInfo r1 = query.get(1);
1930 if (false) {
1931 System.out.println(r0.activityInfo.name +
1932 "=" + r0.priority + " vs " +
1933 r1.activityInfo.name +
1934 "=" + r1.priority);
1935 }
1936 // If the first activity has a higher priority, or a different
1937 // default, then it is always desireable to pick it.
1938 if (r0.priority != r1.priority
1939 || r0.preferredOrder != r1.preferredOrder
1940 || r0.isDefault != r1.isDefault) {
1941 return query.get(0);
1942 }
1943 // If we have saved a preference for a preferred activity for
1944 // this Intent, use that.
1945 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1946 flags, query, r0.priority);
1947 if (ri != null) {
1948 return ri;
1949 }
1950 return mResolveInfo;
1951 }
1952 }
1953 return null;
1954 }
1955
1956 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1957 int flags, List<ResolveInfo> query, int priority) {
1958 synchronized (mPackages) {
1959 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1960 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001961 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1963 if (prefs != null && prefs.size() > 0) {
1964 // First figure out how good the original match set is.
1965 // We will only allow preferred activities that came
1966 // from the same match quality.
1967 int match = 0;
1968 final int N = query.size();
1969 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1970 for (int j=0; j<N; j++) {
1971 ResolveInfo ri = query.get(j);
1972 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1973 + ": 0x" + Integer.toHexString(match));
1974 if (ri.match > match) match = ri.match;
1975 }
1976 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1977 + Integer.toHexString(match));
1978 match &= IntentFilter.MATCH_CATEGORY_MASK;
1979 final int M = prefs.size();
1980 for (int i=0; i<M; i++) {
1981 PreferredActivity pa = prefs.get(i);
1982 if (pa.mMatch != match) {
1983 continue;
1984 }
1985 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1986 if (DEBUG_PREFERRED) {
1987 Log.v(TAG, "Got preferred activity:");
1988 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1989 }
1990 if (ai != null) {
1991 for (int j=0; j<N; j++) {
1992 ResolveInfo ri = query.get(j);
1993 if (!ri.activityInfo.applicationInfo.packageName
1994 .equals(ai.applicationInfo.packageName)) {
1995 continue;
1996 }
1997 if (!ri.activityInfo.name.equals(ai.name)) {
1998 continue;
1999 }
2000
2001 // Okay we found a previously set preferred app.
2002 // If the result set is different from when this
2003 // was created, we need to clear it and re-ask the
2004 // user their preference.
2005 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002006 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 + intent + " type " + resolvedType);
2008 mSettings.mPreferredActivities.removeFilter(pa);
2009 return null;
2010 }
2011
2012 // Yay!
2013 return ri;
2014 }
2015 }
2016 }
2017 }
2018 }
2019 return null;
2020 }
2021
2022 public List<ResolveInfo> queryIntentActivities(Intent intent,
2023 String resolvedType, int flags) {
2024 ComponentName comp = intent.getComponent();
2025 if (comp != null) {
2026 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2027 ActivityInfo ai = getActivityInfo(comp, flags);
2028 if (ai != null) {
2029 ResolveInfo ri = new ResolveInfo();
2030 ri.activityInfo = ai;
2031 list.add(ri);
2032 }
2033 return list;
2034 }
2035
2036 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002037 String pkgName = intent.getPackage();
2038 if (pkgName == null) {
2039 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2040 resolvedType, flags);
2041 }
2042 PackageParser.Package pkg = mPackages.get(pkgName);
2043 if (pkg != null) {
2044 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2045 resolvedType, flags, pkg.activities);
2046 }
2047 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 }
2049 }
2050
2051 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2052 Intent[] specifics, String[] specificTypes, Intent intent,
2053 String resolvedType, int flags) {
2054 final String resultsAction = intent.getAction();
2055
2056 List<ResolveInfo> results = queryIntentActivities(
2057 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2058 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2059
2060 int specificsPos = 0;
2061 int N;
2062
2063 // todo: note that the algorithm used here is O(N^2). This
2064 // isn't a problem in our current environment, but if we start running
2065 // into situations where we have more than 5 or 10 matches then this
2066 // should probably be changed to something smarter...
2067
2068 // First we go through and resolve each of the specific items
2069 // that were supplied, taking care of removing any corresponding
2070 // duplicate items in the generic resolve list.
2071 if (specifics != null) {
2072 for (int i=0; i<specifics.length; i++) {
2073 final Intent sintent = specifics[i];
2074 if (sintent == null) {
2075 continue;
2076 }
2077
2078 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2079 String action = sintent.getAction();
2080 if (resultsAction != null && resultsAction.equals(action)) {
2081 // If this action was explicitly requested, then don't
2082 // remove things that have it.
2083 action = null;
2084 }
2085 ComponentName comp = sintent.getComponent();
2086 ResolveInfo ri = null;
2087 ActivityInfo ai = null;
2088 if (comp == null) {
2089 ri = resolveIntent(
2090 sintent,
2091 specificTypes != null ? specificTypes[i] : null,
2092 flags);
2093 if (ri == null) {
2094 continue;
2095 }
2096 if (ri == mResolveInfo) {
2097 // ACK! Must do something better with this.
2098 }
2099 ai = ri.activityInfo;
2100 comp = new ComponentName(ai.applicationInfo.packageName,
2101 ai.name);
2102 } else {
2103 ai = getActivityInfo(comp, flags);
2104 if (ai == null) {
2105 continue;
2106 }
2107 }
2108
2109 // Look for any generic query activities that are duplicates
2110 // of this specific one, and remove them from the results.
2111 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2112 N = results.size();
2113 int j;
2114 for (j=specificsPos; j<N; j++) {
2115 ResolveInfo sri = results.get(j);
2116 if ((sri.activityInfo.name.equals(comp.getClassName())
2117 && sri.activityInfo.applicationInfo.packageName.equals(
2118 comp.getPackageName()))
2119 || (action != null && sri.filter.matchAction(action))) {
2120 results.remove(j);
2121 if (Config.LOGV) Log.v(
2122 TAG, "Removing duplicate item from " + j
2123 + " due to specific " + specificsPos);
2124 if (ri == null) {
2125 ri = sri;
2126 }
2127 j--;
2128 N--;
2129 }
2130 }
2131
2132 // Add this specific item to its proper place.
2133 if (ri == null) {
2134 ri = new ResolveInfo();
2135 ri.activityInfo = ai;
2136 }
2137 results.add(specificsPos, ri);
2138 ri.specificIndex = i;
2139 specificsPos++;
2140 }
2141 }
2142
2143 // Now we go through the remaining generic results and remove any
2144 // duplicate actions that are found here.
2145 N = results.size();
2146 for (int i=specificsPos; i<N-1; i++) {
2147 final ResolveInfo rii = results.get(i);
2148 if (rii.filter == null) {
2149 continue;
2150 }
2151
2152 // Iterate over all of the actions of this result's intent
2153 // filter... typically this should be just one.
2154 final Iterator<String> it = rii.filter.actionsIterator();
2155 if (it == null) {
2156 continue;
2157 }
2158 while (it.hasNext()) {
2159 final String action = it.next();
2160 if (resultsAction != null && resultsAction.equals(action)) {
2161 // If this action was explicitly requested, then don't
2162 // remove things that have it.
2163 continue;
2164 }
2165 for (int j=i+1; j<N; j++) {
2166 final ResolveInfo rij = results.get(j);
2167 if (rij.filter != null && rij.filter.hasAction(action)) {
2168 results.remove(j);
2169 if (Config.LOGV) Log.v(
2170 TAG, "Removing duplicate item from " + j
2171 + " due to action " + action + " at " + i);
2172 j--;
2173 N--;
2174 }
2175 }
2176 }
2177
2178 // If the caller didn't request filter information, drop it now
2179 // so we don't have to marshall/unmarshall it.
2180 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2181 rii.filter = null;
2182 }
2183 }
2184
2185 // Filter out the caller activity if so requested.
2186 if (caller != null) {
2187 N = results.size();
2188 for (int i=0; i<N; i++) {
2189 ActivityInfo ainfo = results.get(i).activityInfo;
2190 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2191 && caller.getClassName().equals(ainfo.name)) {
2192 results.remove(i);
2193 break;
2194 }
2195 }
2196 }
2197
2198 // If the caller didn't request filter information,
2199 // drop them now so we don't have to
2200 // marshall/unmarshall it.
2201 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2202 N = results.size();
2203 for (int i=0; i<N; i++) {
2204 results.get(i).filter = null;
2205 }
2206 }
2207
2208 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2209 return results;
2210 }
2211
2212 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2213 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002214 ComponentName comp = intent.getComponent();
2215 if (comp != null) {
2216 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2217 ActivityInfo ai = getReceiverInfo(comp, flags);
2218 if (ai != null) {
2219 ResolveInfo ri = new ResolveInfo();
2220 ri.activityInfo = ai;
2221 list.add(ri);
2222 }
2223 return list;
2224 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002227 String pkgName = intent.getPackage();
2228 if (pkgName == null) {
2229 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2230 resolvedType, flags);
2231 }
2232 PackageParser.Package pkg = mPackages.get(pkgName);
2233 if (pkg != null) {
2234 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2235 resolvedType, flags, pkg.receivers);
2236 }
2237 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 }
2239 }
2240
2241 public ResolveInfo resolveService(Intent intent, String resolvedType,
2242 int flags) {
2243 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2244 flags);
2245 if (query != null) {
2246 if (query.size() >= 1) {
2247 // If there is more than one service with the same priority,
2248 // just arbitrarily pick the first one.
2249 return query.get(0);
2250 }
2251 }
2252 return null;
2253 }
2254
2255 public List<ResolveInfo> queryIntentServices(Intent intent,
2256 String resolvedType, int flags) {
2257 ComponentName comp = intent.getComponent();
2258 if (comp != null) {
2259 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2260 ServiceInfo si = getServiceInfo(comp, flags);
2261 if (si != null) {
2262 ResolveInfo ri = new ResolveInfo();
2263 ri.serviceInfo = si;
2264 list.add(ri);
2265 }
2266 return list;
2267 }
2268
2269 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002270 String pkgName = intent.getPackage();
2271 if (pkgName == null) {
2272 return (List<ResolveInfo>)mServices.queryIntent(intent,
2273 resolvedType, flags);
2274 }
2275 PackageParser.Package pkg = mPackages.get(pkgName);
2276 if (pkg != null) {
2277 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2278 resolvedType, flags, pkg.services);
2279 }
2280 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
2282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 public List<PackageInfo> getInstalledPackages(int flags) {
2285 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2286
2287 synchronized (mPackages) {
2288 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2289 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2290 while (i.hasNext()) {
2291 final PackageSetting ps = i.next();
2292 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2293 if(psPkg != null) {
2294 finalList.add(psPkg);
2295 }
2296 }
2297 }
2298 else {
2299 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2300 while (i.hasNext()) {
2301 final PackageParser.Package p = i.next();
2302 if (p.applicationInfo != null) {
2303 PackageInfo pi = generatePackageInfo(p, flags);
2304 if(pi != null) {
2305 finalList.add(pi);
2306 }
2307 }
2308 }
2309 }
2310 }
2311 return finalList;
2312 }
2313
2314 public List<ApplicationInfo> getInstalledApplications(int flags) {
2315 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2316 synchronized(mPackages) {
2317 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2318 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2319 while (i.hasNext()) {
2320 final PackageSetting ps = i.next();
2321 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2322 if(ai != null) {
2323 finalList.add(ai);
2324 }
2325 }
2326 }
2327 else {
2328 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2329 while (i.hasNext()) {
2330 final PackageParser.Package p = i.next();
2331 if (p.applicationInfo != null) {
2332 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2333 if(ai != null) {
2334 finalList.add(ai);
2335 }
2336 }
2337 }
2338 }
2339 }
2340 return finalList;
2341 }
2342
2343 public List<ApplicationInfo> getPersistentApplications(int flags) {
2344 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2345
2346 synchronized (mPackages) {
2347 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2348 while (i.hasNext()) {
2349 PackageParser.Package p = i.next();
2350 if (p.applicationInfo != null
2351 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2352 && (!mSafeMode || (p.applicationInfo.flags
2353 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2354 finalList.add(p.applicationInfo);
2355 }
2356 }
2357 }
2358
2359 return finalList;
2360 }
2361
2362 public ProviderInfo resolveContentProvider(String name, int flags) {
2363 synchronized (mPackages) {
2364 final PackageParser.Provider provider = mProviders.get(name);
2365 return provider != null
2366 && mSettings.isEnabledLP(provider.info, flags)
2367 && (!mSafeMode || (provider.info.applicationInfo.flags
2368 &ApplicationInfo.FLAG_SYSTEM) != 0)
2369 ? PackageParser.generateProviderInfo(provider, flags)
2370 : null;
2371 }
2372 }
2373
Fred Quintana718d8a22009-04-29 17:53:20 -07002374 /**
2375 * @deprecated
2376 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 public void querySyncProviders(List outNames, List outInfo) {
2378 synchronized (mPackages) {
2379 Iterator<Map.Entry<String, PackageParser.Provider>> i
2380 = mProviders.entrySet().iterator();
2381
2382 while (i.hasNext()) {
2383 Map.Entry<String, PackageParser.Provider> entry = i.next();
2384 PackageParser.Provider p = entry.getValue();
2385
2386 if (p.syncable
2387 && (!mSafeMode || (p.info.applicationInfo.flags
2388 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2389 outNames.add(entry.getKey());
2390 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2391 }
2392 }
2393 }
2394 }
2395
2396 public List<ProviderInfo> queryContentProviders(String processName,
2397 int uid, int flags) {
2398 ArrayList<ProviderInfo> finalList = null;
2399
2400 synchronized (mPackages) {
2401 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2402 while (i.hasNext()) {
2403 PackageParser.Provider p = i.next();
2404 if (p.info.authority != null
2405 && (processName == null ||
2406 (p.info.processName.equals(processName)
2407 && p.info.applicationInfo.uid == uid))
2408 && mSettings.isEnabledLP(p.info, flags)
2409 && (!mSafeMode || (p.info.applicationInfo.flags
2410 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2411 if (finalList == null) {
2412 finalList = new ArrayList<ProviderInfo>(3);
2413 }
2414 finalList.add(PackageParser.generateProviderInfo(p,
2415 flags));
2416 }
2417 }
2418 }
2419
2420 if (finalList != null) {
2421 Collections.sort(finalList, mProviderInitOrderSorter);
2422 }
2423
2424 return finalList;
2425 }
2426
2427 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2428 int flags) {
2429 synchronized (mPackages) {
2430 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2431 return PackageParser.generateInstrumentationInfo(i, flags);
2432 }
2433 }
2434
2435 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2436 int flags) {
2437 ArrayList<InstrumentationInfo> finalList =
2438 new ArrayList<InstrumentationInfo>();
2439
2440 synchronized (mPackages) {
2441 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2442 while (i.hasNext()) {
2443 PackageParser.Instrumentation p = i.next();
2444 if (targetPackage == null
2445 || targetPackage.equals(p.info.targetPackage)) {
2446 finalList.add(PackageParser.generateInstrumentationInfo(p,
2447 flags));
2448 }
2449 }
2450 }
2451
2452 return finalList;
2453 }
2454
2455 private void scanDirLI(File dir, int flags, int scanMode) {
2456 Log.d(TAG, "Scanning app dir " + dir);
2457
2458 String[] files = dir.list();
2459
2460 int i;
2461 for (i=0; i<files.length; i++) {
2462 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002463 if (!isPackageFilename(files[i])) {
2464 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002465 continue;
2466 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002467 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002469 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002470 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2471 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002472 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002473 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002474 file.delete();
2475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 }
2477 }
2478
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002479 private static File getSettingsProblemFile() {
2480 File dataDir = Environment.getDataDirectory();
2481 File systemDir = new File(dataDir, "system");
2482 File fname = new File(systemDir, "uiderrors.txt");
2483 return fname;
2484 }
2485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 private static void reportSettingsProblem(int priority, String msg) {
2487 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002488 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 FileOutputStream out = new FileOutputStream(fname, true);
2490 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002491 SimpleDateFormat formatter = new SimpleDateFormat();
2492 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2493 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 pw.close();
2495 FileUtils.setPermissions(
2496 fname.toString(),
2497 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2498 -1, -1);
2499 } catch (java.io.IOException e) {
2500 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002501 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 }
2503
2504 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2505 PackageParser.Package pkg, File srcFile, int parseFlags) {
2506 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002507 if (ps != null
2508 && ps.codePath.equals(srcFile)
2509 && ps.getTimeStamp() == srcFile.lastModified()) {
2510 if (ps.signatures.mSignatures != null
2511 && ps.signatures.mSignatures.length != 0) {
2512 // Optimization: reuse the existing cached certificates
2513 // if the package appears to be unchanged.
2514 pkg.mSignatures = ps.signatures.mSignatures;
2515 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
Jeff Browne7600722010-04-07 18:28:23 -07002517
2518 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002519 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002520 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2521 }
2522
2523 if (!pp.collectCertificates(pkg, parseFlags)) {
2524 mLastScanError = pp.getParseError();
2525 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
2527 }
2528 return true;
2529 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 /*
2532 * Scan a package and return the newly parsed package.
2533 * Returns null in case of errors and the error code is stored in mLastScanError
2534 */
2535 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002536 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002538 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002540 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002543 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 if (pkg == null) {
2545 mLastScanError = pp.getParseError();
2546 return null;
2547 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002548 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 PackageSetting updatedPkg;
2550 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002551 // Look to see if we already know about this package.
2552 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002553 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002554 // This package has been renamed to its original name. Let's
2555 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002556 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002557 }
2558 // If there was no original package, see one for the real package name.
2559 if (ps == null) {
2560 ps = mSettings.peekPackageLP(pkg.packageName);
2561 }
2562 // Check to see if this package could be hiding/updating a system
2563 // package. Must look for it either under the original or real
2564 // package name depending on our state.
2565 updatedPkg = mSettings.mDisabledSysPackages.get(
2566 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002568 // First check if this is a system package that may involve an update
2569 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2570 if (!ps.codePath.equals(scanFile)) {
2571 // The path has changed from what was last scanned... check the
2572 // version of the new path against what we have stored to determine
2573 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002574 if (pkg.mVersionCode < ps.versionCode) {
2575 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002576 // Ignore entry. Skip it.
2577 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2578 + "ignored: updated version " + ps.versionCode
2579 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002580 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2581 return null;
2582 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002583 // The current app on the system partion is better than
2584 // what we have updated to on the data partition; switch
2585 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002586 // At this point, its safely assumed that package installation for
2587 // apps in system partition will go through. If not there won't be a working
2588 // version of the app
2589 synchronized (mPackages) {
2590 // Just remove the loaded entries from package lists.
2591 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002592 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002593 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002594 + "reverting from " + ps.codePathString
2595 + ": new version " + pkg.mVersionCode
2596 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002597 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2598 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002599 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 }
2602 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002603 if (updatedPkg != null) {
2604 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2605 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2606 }
2607 // Verify certificates against what was last scanned
2608 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002609 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002610 return null;
2611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 // The apk is forward locked (not public) if its code and resources
2613 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002614 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002616 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002617 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002618
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002619 String codePath = null;
2620 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002621 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2622 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002623 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002624 } else {
2625 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002626 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002627 }
2628 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002629 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002630 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002631 codePath = pkg.mScanPath;
2632 // Set application objects path explicitly.
2633 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002635 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 }
2637
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002638 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2639 String destCodePath, String destResPath) {
2640 pkg.mPath = pkg.mScanPath = destCodePath;
2641 pkg.applicationInfo.sourceDir = destCodePath;
2642 pkg.applicationInfo.publicSourceDir = destResPath;
2643 }
2644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 private static String fixProcessName(String defProcessName,
2646 String processName, int uid) {
2647 if (processName == null) {
2648 return defProcessName;
2649 }
2650 return processName;
2651 }
2652
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002653 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002654 PackageParser.Package pkg) {
2655 if (pkgSetting.signatures.mSignatures != null) {
2656 // Already existing package. Make sure signatures match
2657 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2658 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002659 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002660 + " signatures do not match the previously installed version; ignoring!");
2661 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 return false;
2663 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002664 }
2665 // Check for shared user signatures
2666 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2667 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2668 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2669 Slog.e(TAG, "Package " + pkg.packageName
2670 + " has no signatures that match those in shared user "
2671 + pkgSetting.sharedUser.name + "; ignoring!");
2672 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2673 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 }
2676 return true;
2677 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002678
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002679 public boolean performDexOpt(String packageName) {
2680 if (!mNoDexOpt) {
2681 return false;
2682 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002683
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002684 PackageParser.Package p;
2685 synchronized (mPackages) {
2686 p = mPackages.get(packageName);
2687 if (p == null || p.mDidDexOpt) {
2688 return false;
2689 }
2690 }
2691 synchronized (mInstallLock) {
2692 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2693 }
2694 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002695
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002696 static final int DEX_OPT_SKIPPED = 0;
2697 static final int DEX_OPT_PERFORMED = 1;
2698 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002699
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002700 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2701 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002702 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002703 String path = pkg.mScanPath;
2704 int ret = 0;
2705 try {
2706 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002707 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002708 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002709 pkg.mDidDexOpt = true;
2710 performed = true;
2711 }
2712 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002713 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002714 ret = -1;
2715 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002716 Slog.w(TAG, "IOException reading apk: " + path, e);
2717 ret = -1;
2718 } catch (dalvik.system.StaleDexCacheError e) {
2719 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2720 ret = -1;
2721 } catch (Exception e) {
2722 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002723 ret = -1;
2724 }
2725 if (ret < 0) {
2726 //error from installer
2727 return DEX_OPT_FAILED;
2728 }
2729 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002730
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002731 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2732 }
2733
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002734 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2735 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002736 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002737 + " to " + newPkg.packageName
2738 + ": old package not in system partition");
2739 return false;
2740 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002741 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002742 + " to " + newPkg.packageName
2743 + ": old package still exists");
2744 return false;
2745 }
2746 return true;
2747 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002748
2749 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002750 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002751 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002752
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002753 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2754 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002755 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002756 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2757 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002758 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002759 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002760 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2761 return null;
2762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 mScanningPath = scanFile;
2764 if (pkg == null) {
2765 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2766 return null;
2767 }
2768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2770 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2771 }
2772
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002773 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 synchronized (mPackages) {
2775 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002776 Slog.w(TAG, "*************************************************");
2777 Slog.w(TAG, "Core android package being redefined. Skipping.");
2778 Slog.w(TAG, " file=" + mScanningPath);
2779 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2781 return null;
2782 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 // Set up information for our fall-back user intent resolution
2785 // activity.
2786 mPlatformPackage = pkg;
2787 pkg.mVersionCode = mSdkVersion;
2788 mAndroidApplication = pkg.applicationInfo;
2789 mResolveActivity.applicationInfo = mAndroidApplication;
2790 mResolveActivity.name = ResolverActivity.class.getName();
2791 mResolveActivity.packageName = mAndroidApplication.packageName;
2792 mResolveActivity.processName = mAndroidApplication.processName;
2793 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2794 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2795 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2796 mResolveActivity.exported = true;
2797 mResolveActivity.enabled = true;
2798 mResolveInfo.activityInfo = mResolveActivity;
2799 mResolveInfo.priority = 0;
2800 mResolveInfo.preferredOrder = 0;
2801 mResolveInfo.match = 0;
2802 mResolveComponentName = new ComponentName(
2803 mAndroidApplication.packageName, mResolveActivity.name);
2804 }
2805 }
2806
2807 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002808 TAG, "Scanning package " + pkg.packageName);
2809 if (mPackages.containsKey(pkg.packageName)
2810 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002811 Slog.w(TAG, "*************************************************");
2812 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002814 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2816 return null;
2817 }
2818
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002819 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002820 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2821 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 SharedUserSetting suid = null;
2824 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002825
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002826 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2827 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002828 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002829 pkg.mRealPackage = null;
2830 pkg.mAdoptPermissions = null;
2831 }
2832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 synchronized (mPackages) {
2834 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002835 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2836 if (mTmpSharedLibraries == null ||
2837 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2838 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2839 }
2840 int num = 0;
2841 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2842 for (int i=0; i<N; i++) {
2843 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002845 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002847 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2849 return null;
2850 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002851 mTmpSharedLibraries[num] = file;
2852 num++;
2853 }
2854 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2855 for (int i=0; i<N; i++) {
2856 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2857 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002858 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002859 + " desires unavailable shared library "
2860 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2861 } else {
2862 mTmpSharedLibraries[num] = file;
2863 num++;
2864 }
2865 }
2866 if (num > 0) {
2867 pkg.usesLibraryFiles = new String[num];
2868 System.arraycopy(mTmpSharedLibraries, 0,
2869 pkg.usesLibraryFiles, 0, num);
2870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002871
Dianne Hackborn49237342009-08-27 20:08:01 -07002872 if (pkg.reqFeatures != null) {
2873 N = pkg.reqFeatures.size();
2874 for (int i=0; i<N; i++) {
2875 FeatureInfo fi = pkg.reqFeatures.get(i);
2876 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2877 // Don't care.
2878 continue;
2879 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002880
Dianne Hackborn49237342009-08-27 20:08:01 -07002881 if (fi.name != null) {
2882 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002883 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002884 + " requires unavailable feature "
2885 + fi.name + "; failing!");
2886 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2887 return null;
2888 }
2889 }
2890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 }
2892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 if (pkg.mSharedUserId != null) {
2895 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2896 pkg.applicationInfo.flags, true);
2897 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002898 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 + " for shared user failed");
2900 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2901 return null;
2902 }
2903 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2904 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2905 + suid.userId + "): packages=" + suid.packages);
2906 }
2907 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002908
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002909 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002910 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002911 Log.w(TAG, "WAITING FOR DEBUGGER");
2912 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002913 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2914 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002915 }
2916 }
2917
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002918 // Check if we are renaming from an original package name.
2919 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002920 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002921 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002922 // This package may need to be renamed to a previously
2923 // installed name. Let's check on that...
2924 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002925 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002926 // This package had originally been installed as the
2927 // original name, and we have already taken care of
2928 // transitioning to the new one. Just update the new
2929 // one to continue using the old name.
2930 realName = pkg.mRealPackage;
2931 if (!pkg.packageName.equals(renamed)) {
2932 // Callers into this function may have already taken
2933 // care of renaming the package; only do it here if
2934 // it is not already done.
2935 pkg.setPackageName(renamed);
2936 }
2937
Dianne Hackbornc1552392010-03-03 16:19:01 -08002938 } else {
2939 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2940 if ((origPackage=mSettings.peekPackageLP(
2941 pkg.mOriginalPackages.get(i))) != null) {
2942 // We do have the package already installed under its
2943 // original name... should we use it?
2944 if (!verifyPackageUpdate(origPackage, pkg)) {
2945 // New package is not compatible with original.
2946 origPackage = null;
2947 continue;
2948 } else if (origPackage.sharedUser != null) {
2949 // Make sure uid is compatible between packages.
2950 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002951 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002952 + " to " + pkg.packageName + ": old uid "
2953 + origPackage.sharedUser.name
2954 + " differs from " + pkg.mSharedUserId);
2955 origPackage = null;
2956 continue;
2957 }
2958 } else {
2959 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2960 + pkg.packageName + " to old name " + origPackage.name);
2961 }
2962 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002963 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002964 }
2965 }
2966 }
2967
2968 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002969 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002970 + " was transferred to another, but its .apk remains");
2971 }
2972
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002973 // Just create the setting, don't add it yet. For already existing packages
2974 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 destResourceFile, pkg.applicationInfo.flags, true, false);
2977 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002978 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2980 return null;
2981 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002982
2983 if (pkgSetting.origPackage != null) {
2984 // If we are first transitioning from an original package,
2985 // fix up the new package's name now. We need to do this after
2986 // looking up the package under its new name, so getPackageLP
2987 // can take care of fiddling things correctly.
2988 pkg.setPackageName(origPackage.name);
2989
2990 // File a report about this.
2991 String msg = "New package " + pkgSetting.realName
2992 + " renamed to replace old package " + pkgSetting.name;
2993 reportSettingsProblem(Log.WARN, msg);
2994
2995 // Make a note of it.
2996 mTransferedPackages.add(origPackage.name);
2997
2998 // No longer need to retain this.
2999 pkgSetting.origPackage = null;
3000 }
3001
3002 if (realName != null) {
3003 // Make a note of it.
3004 mTransferedPackages.add(pkg.packageName);
3005 }
3006
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003007 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3009 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 pkg.applicationInfo.uid = pkgSetting.userId;
3012 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003013
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003014 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003015 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 return null;
3017 }
3018 // The signature has changed, but this package is in the system
3019 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003020 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 // However... if this package is part of a shared user, but it
3022 // doesn't match the signature of the shared user, let's fail.
3023 // What this means is that you can't change the signatures
3024 // associated with an overall shared user, which doesn't seem all
3025 // that unreasonable.
3026 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003027 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3028 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3029 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3031 return null;
3032 }
3033 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003034 // File a report about this.
3035 String msg = "System package " + pkg.packageName
3036 + " signature changed; retaining data.";
3037 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003039
The Android Open Source Project10592532009-03-18 17:39:46 -07003040 // Verify that this new package doesn't have any content providers
3041 // that conflict with existing packages. Only do this if the
3042 // package isn't already installed, since we don't want to break
3043 // things that are installed.
3044 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3045 int N = pkg.providers.size();
3046 int i;
3047 for (i=0; i<N; i++) {
3048 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003049 if (p.info.authority != null) {
3050 String names[] = p.info.authority.split(";");
3051 for (int j = 0; j < names.length; j++) {
3052 if (mProviders.containsKey(names[j])) {
3053 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003054 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003055 " (in package " + pkg.applicationInfo.packageName +
3056 ") is already used by "
3057 + ((other != null && other.getComponentName() != null)
3058 ? other.getComponentName().getPackageName() : "?"));
3059 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3060 return null;
3061 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003062 }
3063 }
3064 }
3065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 }
3067
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003068 final String pkgName = pkg.packageName;
3069
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003070 if (pkg.mAdoptPermissions != null) {
3071 // This package wants to adopt ownership of permissions from
3072 // another package.
3073 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3074 String origName = pkg.mAdoptPermissions.get(i);
3075 PackageSetting orig = mSettings.peekPackageLP(origName);
3076 if (orig != null) {
3077 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003078 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003079 + origName + " to " + pkg.packageName);
3080 mSettings.transferPermissions(origName, pkg.packageName);
3081 }
3082 }
3083 }
3084 }
3085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 long scanFileTime = scanFile.lastModified();
3087 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3088 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3089 pkg.applicationInfo.processName = fixProcessName(
3090 pkg.applicationInfo.packageName,
3091 pkg.applicationInfo.processName,
3092 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093
3094 File dataPath;
3095 if (mPlatformPackage == pkg) {
3096 // The system package is special.
3097 dataPath = new File (Environment.getDataDirectory(), "system");
3098 pkg.applicationInfo.dataDir = dataPath.getPath();
3099 } else {
3100 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003101 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003102
3103 boolean uidError = false;
3104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 if (dataPath.exists()) {
3106 mOutPermissions[1] = 0;
3107 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3108 if (mOutPermissions[1] == pkg.applicationInfo.uid
3109 || !Process.supportsProcesses()) {
3110 pkg.applicationInfo.dataDir = dataPath.getPath();
3111 } else {
3112 boolean recovered = false;
3113 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3114 // If this is a system app, we can at least delete its
3115 // current data so the application will still work.
3116 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003117 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003118 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 // Old data gone!
3120 String msg = "System package " + pkg.packageName
3121 + " has changed from uid: "
3122 + mOutPermissions[1] + " to "
3123 + pkg.applicationInfo.uid + "; old data erased";
3124 reportSettingsProblem(Log.WARN, msg);
3125 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003128 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 pkg.applicationInfo.uid);
3130 if (ret == -1) {
3131 // Ack should not happen!
3132 msg = "System package " + pkg.packageName
3133 + " could not have data directory re-created after delete.";
3134 reportSettingsProblem(Log.WARN, msg);
3135 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3136 return null;
3137 }
3138 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 if (!recovered) {
3141 mHasSystemUidErrors = true;
3142 }
3143 }
3144 if (!recovered) {
3145 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3146 + pkg.applicationInfo.uid + "/fs_"
3147 + mOutPermissions[1];
3148 String msg = "Package " + pkg.packageName
3149 + " has mismatched uid: "
3150 + mOutPermissions[1] + " on disk, "
3151 + pkg.applicationInfo.uid + " in settings";
3152 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003153 mSettings.mReadMessages.append(msg);
3154 mSettings.mReadMessages.append('\n');
3155 uidError = true;
3156 if (!pkgSetting.uidError) {
3157 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 }
3160 }
3161 }
3162 pkg.applicationInfo.dataDir = dataPath.getPath();
3163 } else {
3164 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3165 Log.v(TAG, "Want this data dir: " + dataPath);
3166 //invoke installer to do the actual installation
3167 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003168 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 pkg.applicationInfo.uid);
3170 if(ret < 0) {
3171 // Error from installer
3172 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3173 return null;
3174 }
3175 } else {
3176 dataPath.mkdirs();
3177 if (dataPath.exists()) {
3178 FileUtils.setPermissions(
3179 dataPath.toString(),
3180 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3181 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3182 }
3183 }
3184 if (dataPath.exists()) {
3185 pkg.applicationInfo.dataDir = dataPath.getPath();
3186 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003187 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 pkg.applicationInfo.dataDir = null;
3189 }
3190 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003191
3192 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 }
3194
3195 // Perform shared library installation and dex validation and
3196 // optimization, if this is not a system app.
3197 if (mInstaller != null) {
3198 String path = scanFile.getPath();
3199 if (scanFileNewer) {
3200 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003201 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3202 if (err != PackageManager.INSTALL_SUCCEEDED) {
3203 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 return null;
3205 }
3206 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003207 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003208
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003209 if ((scanMode&SCAN_NO_DEX) == 0) {
3210 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3212 return null;
3213 }
3214 }
3215 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 if (mFactoryTest && pkg.requestedPermissions.contains(
3218 android.Manifest.permission.FACTORY_TEST)) {
3219 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3220 }
3221
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003222 // Request the ActivityManager to kill the process(only for existing packages)
3223 // so that we do not end up in a confused state while the user is still using the older
3224 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003225 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003226 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003227 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003228 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003231 // We don't expect installation to fail beyond this point,
3232 if ((scanMode&SCAN_MONITOR) != 0) {
3233 mAppDirs.put(pkg.mPath, pkg);
3234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003236 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003238 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003239 // Make sure we don't accidentally delete its data.
3240 mSettings.mPackagesToBeCleaned.remove(pkgName);
3241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 int N = pkg.providers.size();
3243 StringBuilder r = null;
3244 int i;
3245 for (i=0; i<N; i++) {
3246 PackageParser.Provider p = pkg.providers.get(i);
3247 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3248 p.info.processName, pkg.applicationInfo.uid);
3249 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3250 p.info.name), p);
3251 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003252 if (p.info.authority != null) {
3253 String names[] = p.info.authority.split(";");
3254 p.info.authority = null;
3255 for (int j = 0; j < names.length; j++) {
3256 if (j == 1 && p.syncable) {
3257 // We only want the first authority for a provider to possibly be
3258 // syncable, so if we already added this provider using a different
3259 // authority clear the syncable flag. We copy the provider before
3260 // changing it because the mProviders object contains a reference
3261 // to a provider that we don't want to change.
3262 // Only do this for the second authority since the resulting provider
3263 // object can be the same for all future authorities for this provider.
3264 p = new PackageParser.Provider(p);
3265 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003267 if (!mProviders.containsKey(names[j])) {
3268 mProviders.put(names[j], p);
3269 if (p.info.authority == null) {
3270 p.info.authority = names[j];
3271 } else {
3272 p.info.authority = p.info.authority + ";" + names[j];
3273 }
3274 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3275 Log.d(TAG, "Registered content provider: " + names[j] +
3276 ", className = " + p.info.name +
3277 ", isSyncable = " + p.info.isSyncable);
3278 } else {
3279 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003280 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003281 " (in package " + pkg.applicationInfo.packageName +
3282 "): name already used by "
3283 + ((other != null && other.getComponentName() != null)
3284 ? other.getComponentName().getPackageName() : "?"));
3285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 }
3287 }
3288 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3289 if (r == null) {
3290 r = new StringBuilder(256);
3291 } else {
3292 r.append(' ');
3293 }
3294 r.append(p.info.name);
3295 }
3296 }
3297 if (r != null) {
3298 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3299 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 N = pkg.services.size();
3302 r = null;
3303 for (i=0; i<N; i++) {
3304 PackageParser.Service s = pkg.services.get(i);
3305 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3306 s.info.processName, pkg.applicationInfo.uid);
3307 mServices.addService(s);
3308 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3309 if (r == null) {
3310 r = new StringBuilder(256);
3311 } else {
3312 r.append(' ');
3313 }
3314 r.append(s.info.name);
3315 }
3316 }
3317 if (r != null) {
3318 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 N = pkg.receivers.size();
3322 r = null;
3323 for (i=0; i<N; i++) {
3324 PackageParser.Activity a = pkg.receivers.get(i);
3325 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3326 a.info.processName, pkg.applicationInfo.uid);
3327 mReceivers.addActivity(a, "receiver");
3328 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3329 if (r == null) {
3330 r = new StringBuilder(256);
3331 } else {
3332 r.append(' ');
3333 }
3334 r.append(a.info.name);
3335 }
3336 }
3337 if (r != null) {
3338 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3339 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 N = pkg.activities.size();
3342 r = null;
3343 for (i=0; i<N; i++) {
3344 PackageParser.Activity a = pkg.activities.get(i);
3345 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3346 a.info.processName, pkg.applicationInfo.uid);
3347 mActivities.addActivity(a, "activity");
3348 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3349 if (r == null) {
3350 r = new StringBuilder(256);
3351 } else {
3352 r.append(' ');
3353 }
3354 r.append(a.info.name);
3355 }
3356 }
3357 if (r != null) {
3358 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3359 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 N = pkg.permissionGroups.size();
3362 r = null;
3363 for (i=0; i<N; i++) {
3364 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3365 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3366 if (cur == null) {
3367 mPermissionGroups.put(pg.info.name, pg);
3368 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3369 if (r == null) {
3370 r = new StringBuilder(256);
3371 } else {
3372 r.append(' ');
3373 }
3374 r.append(pg.info.name);
3375 }
3376 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003377 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 + pg.info.packageName + " ignored: original from "
3379 + cur.info.packageName);
3380 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3381 if (r == null) {
3382 r = new StringBuilder(256);
3383 } else {
3384 r.append(' ');
3385 }
3386 r.append("DUP:");
3387 r.append(pg.info.name);
3388 }
3389 }
3390 }
3391 if (r != null) {
3392 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3393 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 N = pkg.permissions.size();
3396 r = null;
3397 for (i=0; i<N; i++) {
3398 PackageParser.Permission p = pkg.permissions.get(i);
3399 HashMap<String, BasePermission> permissionMap =
3400 p.tree ? mSettings.mPermissionTrees
3401 : mSettings.mPermissions;
3402 p.group = mPermissionGroups.get(p.info.group);
3403 if (p.info.group == null || p.group != null) {
3404 BasePermission bp = permissionMap.get(p.info.name);
3405 if (bp == null) {
3406 bp = new BasePermission(p.info.name, p.info.packageName,
3407 BasePermission.TYPE_NORMAL);
3408 permissionMap.put(p.info.name, bp);
3409 }
3410 if (bp.perm == null) {
3411 if (bp.sourcePackage == null
3412 || bp.sourcePackage.equals(p.info.packageName)) {
3413 BasePermission tree = findPermissionTreeLP(p.info.name);
3414 if (tree == null
3415 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003416 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 bp.perm = p;
3418 bp.uid = pkg.applicationInfo.uid;
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(p.info.name);
3426 }
3427 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003428 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 + p.info.packageName + " ignored: base tree "
3430 + tree.name + " is from package "
3431 + tree.sourcePackage);
3432 }
3433 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003434 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 + p.info.packageName + " ignored: original from "
3436 + bp.sourcePackage);
3437 }
3438 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3439 if (r == null) {
3440 r = new StringBuilder(256);
3441 } else {
3442 r.append(' ');
3443 }
3444 r.append("DUP:");
3445 r.append(p.info.name);
3446 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003447 if (bp.perm == p) {
3448 bp.protectionLevel = p.info.protectionLevel;
3449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003451 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 + p.info.packageName + " ignored: no group "
3453 + p.group);
3454 }
3455 }
3456 if (r != null) {
3457 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3458 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 N = pkg.instrumentation.size();
3461 r = null;
3462 for (i=0; i<N; i++) {
3463 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3464 a.info.packageName = pkg.applicationInfo.packageName;
3465 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3466 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3467 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003468 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3470 if (r == null) {
3471 r = new StringBuilder(256);
3472 } else {
3473 r.append(' ');
3474 }
3475 r.append(a.info.name);
3476 }
3477 }
3478 if (r != null) {
3479 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3480 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003481
Dianne Hackborn854060af2009-07-09 18:14:31 -07003482 if (pkg.protectedBroadcasts != null) {
3483 N = pkg.protectedBroadcasts.size();
3484 for (i=0; i<N; i++) {
3485 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3486 }
3487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 pkgSetting.setTimeStamp(scanFileTime);
3490 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 return pkg;
3493 }
3494
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003495 private void killApplication(String pkgName, int uid) {
3496 // Request the ActivityManager to kill the process(only for existing packages)
3497 // so that we do not end up in a confused state while the user is still using the older
3498 // version of the application while the new one gets installed.
3499 IActivityManager am = ActivityManagerNative.getDefault();
3500 if (am != null) {
3501 try {
3502 am.killApplicationWithUid(pkgName, uid);
3503 } catch (RemoteException e) {
3504 }
3505 }
3506 }
3507
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003508 // The following constants are returned by cachePackageSharedLibsForAbiLI
3509 // to indicate if native shared libraries were found in the package.
3510 // Values are:
3511 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3512 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3513 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3514 // in package (and not installed)
3515 //
3516 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3517 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3518 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003520 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3521 // and automatically copy them to /data/data/<appname>/lib if present.
3522 //
3523 // NOTE: this method may throw an IOException if the library cannot
3524 // be copied to its final destination, e.g. if there isn't enough
3525 // room left on the data partition, or a ZipException if the package
3526 // file is malformed.
3527 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003528 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3529 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003530 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3531 final String apkLib = "lib/";
3532 final int apkLibLen = apkLib.length();
3533 final int cpuAbiLen = cpuAbi.length();
3534 final String libPrefix = "lib";
3535 final int libPrefixLen = libPrefix.length();
3536 final String libSuffix = ".so";
3537 final int libSuffixLen = libSuffix.length();
3538 boolean hasNativeLibraries = false;
3539 boolean installedNativeLibraries = false;
3540
3541 // the minimum length of a valid native shared library of the form
3542 // lib/<something>/lib<name>.so.
3543 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3544
3545 ZipFile zipFile = new ZipFile(scanFile);
3546 Enumeration<ZipEntry> entries =
3547 (Enumeration<ZipEntry>) zipFile.entries();
3548
3549 while (entries.hasMoreElements()) {
3550 ZipEntry entry = entries.nextElement();
3551 // skip directories
3552 if (entry.isDirectory()) {
3553 continue;
3554 }
3555 String entryName = entry.getName();
3556
3557 // check that the entry looks like lib/<something>/lib<name>.so
3558 // here, but don't check the ABI just yet.
3559 //
3560 // - must be sufficiently long
3561 // - must end with libSuffix, i.e. ".so"
3562 // - must start with apkLib, i.e. "lib/"
3563 if (entryName.length() < minEntryLen ||
3564 !entryName.endsWith(libSuffix) ||
3565 !entryName.startsWith(apkLib) ) {
3566 continue;
3567 }
3568
3569 // file name must start with libPrefix, i.e. "lib"
3570 int lastSlash = entryName.lastIndexOf('/');
3571
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003572 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003573 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3574 continue;
3575 }
3576
3577 hasNativeLibraries = true;
3578
3579 // check the cpuAbi now, between lib/ and /lib<name>.so
3580 //
3581 if (lastSlash != apkLibLen + cpuAbiLen ||
3582 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3583 continue;
3584
3585 // extract the library file name, ensure it doesn't contain
3586 // weird characters. we're guaranteed here that it doesn't contain
3587 // a directory separator though.
3588 String libFileName = entryName.substring(lastSlash+1);
3589 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3590 continue;
3591 }
3592
3593 installedNativeLibraries = true;
3594
3595 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3596 File.separator + libFileName;
3597 File sharedLibraryFile = new File(sharedLibraryFilePath);
3598 if (! sharedLibraryFile.exists() ||
3599 sharedLibraryFile.length() != entry.getSize() ||
3600 sharedLibraryFile.lastModified() != entry.getTime()) {
3601 if (Config.LOGD) {
3602 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003603 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003604 if (mInstaller == null) {
3605 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003606 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003607 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003608 sharedLibraryFile);
3609 }
3610 }
3611 if (!hasNativeLibraries)
3612 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3613
3614 if (!installedNativeLibraries)
3615 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3616
3617 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3618 }
3619
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003620 // Find the gdbserver executable program in a package at
3621 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3622 //
3623 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3624 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3625 //
3626 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3627 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3628 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3629 final String GDBSERVER = "gdbserver";
3630 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3631
3632 ZipFile zipFile = new ZipFile(scanFile);
3633 Enumeration<ZipEntry> entries =
3634 (Enumeration<ZipEntry>) zipFile.entries();
3635
3636 while (entries.hasMoreElements()) {
3637 ZipEntry entry = entries.nextElement();
3638 // skip directories
3639 if (entry.isDirectory()) {
3640 continue;
3641 }
3642 String entryName = entry.getName();
3643
3644 if (!entryName.equals(apkGdbServerPath)) {
3645 continue;
3646 }
3647
3648 String installGdbServerPath = installGdbServerDir.getPath() +
3649 "/" + GDBSERVER;
3650 File installGdbServerFile = new File(installGdbServerPath);
3651 if (! installGdbServerFile.exists() ||
3652 installGdbServerFile.length() != entry.getSize() ||
3653 installGdbServerFile.lastModified() != entry.getTime()) {
3654 if (Config.LOGD) {
3655 Log.d(TAG, "Caching gdbserver " + entry.getName());
3656 }
3657 if (mInstaller == null) {
3658 installGdbServerDir.mkdir();
3659 }
3660 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3661 installGdbServerFile);
3662 }
3663 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3664 }
3665 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3666 }
3667
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003668 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3669 // and copy them to /data/data/<appname>/lib.
3670 //
3671 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3672 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3673 // one if ro.product.cpu.abi2 is defined.
3674 //
3675 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3676 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003677 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003678 try {
3679 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3680
3681 // some architectures are capable of supporting several CPU ABIs
3682 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3683 // this is indicated by the definition of the ro.product.cpu.abi2
3684 // system property.
3685 //
3686 // only scan the package twice in case of ABI mismatch
3687 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003688 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003689 if (cpuAbi2 != null) {
3690 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003692
3693 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003694 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003695 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003697
3698 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3699 cpuAbi = cpuAbi2;
3700 }
3701 }
3702
3703 // for debuggable packages, also extract gdbserver from lib/<abi>
3704 // into /data/data/<appname>/lib too.
3705 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3706 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3707 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3708 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3709 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003712 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003713 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003714 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003716 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003717 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003719 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 }
3721
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003722 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003724 File binaryDir,
3725 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 InputStream inputStream = zipFile.getInputStream(entry);
3727 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003728 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003730 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 // now need to be left as world readable and owned by the system.
3732 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3733 ! tempFile.setLastModified(entry.getTime()) ||
3734 FileUtils.setPermissions(tempFilePath,
3735 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003736 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003738 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 // Failed to properly write file.
3740 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003741 throw new IOException("Couldn't create cached binary "
3742 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 }
3744 } finally {
3745 inputStream.close();
3746 }
3747 }
3748
3749 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3750 if (chatty && Config.LOGD) Log.d(
3751 TAG, "Removing package " + pkg.applicationInfo.packageName );
3752
3753 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 mPackages.remove(pkg.applicationInfo.packageName);
3757 if (pkg.mPath != null) {
3758 mAppDirs.remove(pkg.mPath);
3759 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 PackageSetting ps = (PackageSetting)pkg.mExtras;
3762 if (ps != null && ps.sharedUser != null) {
3763 // XXX don't do this until the data is removed.
3764 if (false) {
3765 ps.sharedUser.packages.remove(ps);
3766 if (ps.sharedUser.packages.size() == 0) {
3767 // Remove.
3768 }
3769 }
3770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 int N = pkg.providers.size();
3773 StringBuilder r = null;
3774 int i;
3775 for (i=0; i<N; i++) {
3776 PackageParser.Provider p = pkg.providers.get(i);
3777 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3778 p.info.name));
3779 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 /* The is another ContentProvider with this authority when
3782 * this app was installed so this authority is null,
3783 * Ignore it as we don't have to unregister the provider.
3784 */
3785 continue;
3786 }
3787 String names[] = p.info.authority.split(";");
3788 for (int j = 0; j < names.length; j++) {
3789 if (mProviders.get(names[j]) == p) {
3790 mProviders.remove(names[j]);
3791 if (chatty && Config.LOGD) Log.d(
3792 TAG, "Unregistered content provider: " + names[j] +
3793 ", className = " + p.info.name +
3794 ", isSyncable = " + p.info.isSyncable);
3795 }
3796 }
3797 if (chatty) {
3798 if (r == null) {
3799 r = new StringBuilder(256);
3800 } else {
3801 r.append(' ');
3802 }
3803 r.append(p.info.name);
3804 }
3805 }
3806 if (r != null) {
3807 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 N = pkg.services.size();
3811 r = null;
3812 for (i=0; i<N; i++) {
3813 PackageParser.Service s = pkg.services.get(i);
3814 mServices.removeService(s);
3815 if (chatty) {
3816 if (r == null) {
3817 r = new StringBuilder(256);
3818 } else {
3819 r.append(' ');
3820 }
3821 r.append(s.info.name);
3822 }
3823 }
3824 if (r != null) {
3825 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3826 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828 N = pkg.receivers.size();
3829 r = null;
3830 for (i=0; i<N; i++) {
3831 PackageParser.Activity a = pkg.receivers.get(i);
3832 mReceivers.removeActivity(a, "receiver");
3833 if (chatty) {
3834 if (r == null) {
3835 r = new StringBuilder(256);
3836 } else {
3837 r.append(' ');
3838 }
3839 r.append(a.info.name);
3840 }
3841 }
3842 if (r != null) {
3843 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3844 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 N = pkg.activities.size();
3847 r = null;
3848 for (i=0; i<N; i++) {
3849 PackageParser.Activity a = pkg.activities.get(i);
3850 mActivities.removeActivity(a, "activity");
3851 if (chatty) {
3852 if (r == null) {
3853 r = new StringBuilder(256);
3854 } else {
3855 r.append(' ');
3856 }
3857 r.append(a.info.name);
3858 }
3859 }
3860 if (r != null) {
3861 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 N = pkg.permissions.size();
3865 r = null;
3866 for (i=0; i<N; i++) {
3867 PackageParser.Permission p = pkg.permissions.get(i);
3868 boolean tree = false;
3869 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3870 if (bp == null) {
3871 tree = true;
3872 bp = mSettings.mPermissionTrees.get(p.info.name);
3873 }
3874 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003875 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 if (chatty) {
3877 if (r == null) {
3878 r = new StringBuilder(256);
3879 } else {
3880 r.append(' ');
3881 }
3882 r.append(p.info.name);
3883 }
3884 }
3885 }
3886 if (r != null) {
3887 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 N = pkg.instrumentation.size();
3891 r = null;
3892 for (i=0; i<N; i++) {
3893 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003894 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 if (chatty) {
3896 if (r == null) {
3897 r = new StringBuilder(256);
3898 } else {
3899 r.append(' ');
3900 }
3901 r.append(a.info.name);
3902 }
3903 }
3904 if (r != null) {
3905 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3906 }
3907 }
3908 }
3909
3910 private static final boolean isPackageFilename(String name) {
3911 return name != null && name.endsWith(".apk");
3912 }
3913
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003914 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3915 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3916 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3917 return true;
3918 }
3919 }
3920 return false;
3921 }
3922
3923 private void updatePermissionsLP(String changingPkg,
3924 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 // Make sure there are no dangling permission trees.
3926 Iterator<BasePermission> it = mSettings.mPermissionTrees
3927 .values().iterator();
3928 while (it.hasNext()) {
3929 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003930 if (bp.packageSetting == null) {
3931 // We may not yet have parsed the package, so just see if
3932 // we still know about its settings.
3933 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3934 }
3935 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003936 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 + " from package " + bp.sourcePackage);
3938 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003939 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3940 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3941 Slog.i(TAG, "Removing old permission tree: " + bp.name
3942 + " from package " + bp.sourcePackage);
3943 grantPermissions = true;
3944 it.remove();
3945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 }
3947 }
3948
3949 // Make sure all dynamic permissions have been assigned to a package,
3950 // and make sure there are no dangling permissions.
3951 it = mSettings.mPermissions.values().iterator();
3952 while (it.hasNext()) {
3953 BasePermission bp = it.next();
3954 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3955 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3956 + bp.name + " pkg=" + bp.sourcePackage
3957 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003958 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 BasePermission tree = findPermissionTreeLP(bp.name);
3960 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003961 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 bp.perm = new PackageParser.Permission(tree.perm.owner,
3963 new PermissionInfo(bp.pendingInfo));
3964 bp.perm.info.packageName = tree.perm.info.packageName;
3965 bp.perm.info.name = bp.name;
3966 bp.uid = tree.uid;
3967 }
3968 }
3969 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003970 if (bp.packageSetting == null) {
3971 // We may not yet have parsed the package, so just see if
3972 // we still know about its settings.
3973 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3974 }
3975 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003976 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 + " from package " + bp.sourcePackage);
3978 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003979 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3980 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3981 Slog.i(TAG, "Removing old permission: " + bp.name
3982 + " from package " + bp.sourcePackage);
3983 grantPermissions = true;
3984 it.remove();
3985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 }
3987 }
3988
3989 // Now update the permissions for all packages, in particular
3990 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003991 if (grantPermissions) {
3992 for (PackageParser.Package pkg : mPackages.values()) {
3993 if (pkg != pkgInfo) {
3994 grantPermissionsLP(pkg, false);
3995 }
3996 }
3997 }
3998
3999 if (pkgInfo != null) {
4000 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 }
4002 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
4005 final PackageSetting ps = (PackageSetting)pkg.mExtras;
4006 if (ps == null) {
4007 return;
4008 }
4009 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004010 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 if (replace) {
4013 ps.permissionsFixed = false;
4014 if (gp == ps) {
4015 gp.grantedPermissions.clear();
4016 gp.gids = mGlobalGids;
4017 }
4018 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 if (gp.gids == null) {
4021 gp.gids = mGlobalGids;
4022 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 final int N = pkg.requestedPermissions.size();
4025 for (int i=0; i<N; i++) {
4026 String name = pkg.requestedPermissions.get(i);
4027 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 if (false) {
4029 if (gp != ps) {
4030 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004031 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 }
4033 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004034 if (bp != null && bp.packageSetting != null) {
4035 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004037 boolean allowedSig = false;
4038 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4039 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004041 } else if (bp.packageSetting == null) {
4042 // This permission is invalid; skip it.
4043 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004044 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4045 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4046 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004048 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004050 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4052 // For updated system applications, the signatureOrSystem permission
4053 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004054 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4056 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4057 if(sysPs.grantedPermissions.contains(perm)) {
4058 allowed = true;
4059 } else {
4060 allowed = false;
4061 }
4062 } else {
4063 allowed = true;
4064 }
4065 }
4066 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004067 if (allowed) {
4068 allowedSig = true;
4069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 } else {
4071 allowed = false;
4072 }
4073 if (false) {
4074 if (gp != ps) {
4075 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4076 }
4077 }
4078 if (allowed) {
4079 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4080 && ps.permissionsFixed) {
4081 // If this is an existing, non-system package, then
4082 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004083 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004085 // Except... if this is a permission that was added
4086 // to the platform (note: need to only do this when
4087 // updating the platform).
4088 final int NP = PackageParser.NEW_PERMISSIONS.length;
4089 for (int ip=0; ip<NP; ip++) {
4090 final PackageParser.NewPermissionInfo npi
4091 = PackageParser.NEW_PERMISSIONS[ip];
4092 if (npi.name.equals(perm)
4093 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4094 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004095 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004096 + pkg.packageName);
4097 break;
4098 }
4099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 }
4101 }
4102 if (allowed) {
4103 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004104 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 gp.grantedPermissions.add(perm);
4106 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004107 } else if (!ps.haveGids) {
4108 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 }
4110 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004111 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 + " to package " + pkg.packageName
4113 + " because it was previously installed without");
4114 }
4115 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004116 if (gp.grantedPermissions.remove(perm)) {
4117 changedPermission = true;
4118 gp.gids = removeInts(gp.gids, bp.gids);
4119 Slog.i(TAG, "Un-granting permission " + perm
4120 + " from package " + pkg.packageName
4121 + " (protectionLevel=" + bp.protectionLevel
4122 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4123 + ")");
4124 } else {
4125 Slog.w(TAG, "Not granting permission " + perm
4126 + " to package " + pkg.packageName
4127 + " (protectionLevel=" + bp.protectionLevel
4128 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4129 + ")");
4130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 }
4132 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004133 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 + " in package " + pkg.packageName);
4135 }
4136 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004137
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004138 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004139 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4140 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 // This is the first that we have heard about this package, so the
4142 // permissions we have now selected are fixed until explicitly
4143 // changed.
4144 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004146 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 private final class ActivityIntentResolver
4150 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004151 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004152 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004153 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 }
4155
Mihai Preda074edef2009-05-18 17:13:31 +02004156 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004158 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4160 }
4161
Mihai Predaeae850c2009-05-13 10:13:48 +02004162 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4163 ArrayList<PackageParser.Activity> packageActivities) {
4164 if (packageActivities == null) {
4165 return null;
4166 }
4167 mFlags = flags;
4168 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4169 int N = packageActivities.size();
4170 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4171 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004172
4173 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004174 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004175 intentFilters = packageActivities.get(i).intents;
4176 if (intentFilters != null && intentFilters.size() > 0) {
4177 listCut.add(intentFilters);
4178 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004179 }
4180 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4181 }
4182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004184 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 if (SHOW_INFO || Config.LOGV) Log.v(
4186 TAG, " " + type + " " +
4187 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4188 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4189 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004190 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4192 if (SHOW_INFO || Config.LOGV) {
4193 Log.v(TAG, " IntentFilter:");
4194 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4195 }
4196 if (!intent.debugCheck()) {
4197 Log.w(TAG, "==> For Activity " + a.info.name);
4198 }
4199 addFilter(intent);
4200 }
4201 }
4202
4203 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004204 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 if (SHOW_INFO || Config.LOGV) Log.v(
4206 TAG, " " + type + " " +
4207 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4208 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4209 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004210 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4212 if (SHOW_INFO || Config.LOGV) {
4213 Log.v(TAG, " IntentFilter:");
4214 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4215 }
4216 removeFilter(intent);
4217 }
4218 }
4219
4220 @Override
4221 protected boolean allowFilterResult(
4222 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4223 ActivityInfo filterAi = filter.activity.info;
4224 for (int i=dest.size()-1; i>=0; i--) {
4225 ActivityInfo destAi = dest.get(i).activityInfo;
4226 if (destAi.name == filterAi.name
4227 && destAi.packageName == filterAi.packageName) {
4228 return false;
4229 }
4230 }
4231 return true;
4232 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004235 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4236 return info.activity.owner.packageName;
4237 }
4238
4239 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4241 int match) {
4242 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4243 return null;
4244 }
4245 final PackageParser.Activity activity = info.activity;
4246 if (mSafeMode && (activity.info.applicationInfo.flags
4247 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4248 return null;
4249 }
4250 final ResolveInfo res = new ResolveInfo();
4251 res.activityInfo = PackageParser.generateActivityInfo(activity,
4252 mFlags);
4253 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4254 res.filter = info;
4255 }
4256 res.priority = info.getPriority();
4257 res.preferredOrder = activity.owner.mPreferredOrder;
4258 //System.out.println("Result: " + res.activityInfo.className +
4259 // " = " + res.priority);
4260 res.match = match;
4261 res.isDefault = info.hasDefault;
4262 res.labelRes = info.labelRes;
4263 res.nonLocalizedLabel = info.nonLocalizedLabel;
4264 res.icon = info.icon;
4265 return res;
4266 }
4267
4268 @Override
4269 protected void sortResults(List<ResolveInfo> results) {
4270 Collections.sort(results, mResolvePrioritySorter);
4271 }
4272
4273 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004274 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004275 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004276 out.print(prefix); out.print(
4277 Integer.toHexString(System.identityHashCode(filter.activity)));
4278 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004279 out.print(filter.activity.getComponentShortName());
4280 out.print(" filter ");
4281 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 }
4283
4284// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4285// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4286// final List<ResolveInfo> retList = Lists.newArrayList();
4287// while (i.hasNext()) {
4288// final ResolveInfo resolveInfo = i.next();
4289// if (isEnabledLP(resolveInfo.activityInfo)) {
4290// retList.add(resolveInfo);
4291// }
4292// }
4293// return retList;
4294// }
4295
4296 // Keys are String (activity class name), values are Activity.
4297 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4298 = new HashMap<ComponentName, PackageParser.Activity>();
4299 private int mFlags;
4300 }
4301
4302 private final class ServiceIntentResolver
4303 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004304 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004306 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 }
4308
Mihai Preda074edef2009-05-18 17:13:31 +02004309 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004310 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004311 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4313 }
4314
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004315 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4316 ArrayList<PackageParser.Service> packageServices) {
4317 if (packageServices == null) {
4318 return null;
4319 }
4320 mFlags = flags;
4321 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4322 int N = packageServices.size();
4323 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4324 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4325
4326 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4327 for (int i = 0; i < N; ++i) {
4328 intentFilters = packageServices.get(i).intents;
4329 if (intentFilters != null && intentFilters.size() > 0) {
4330 listCut.add(intentFilters);
4331 }
4332 }
4333 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4334 }
4335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004337 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 if (SHOW_INFO || Config.LOGV) Log.v(
4339 TAG, " " + (s.info.nonLocalizedLabel != null
4340 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4341 if (SHOW_INFO || Config.LOGV) Log.v(
4342 TAG, " Class=" + s.info.name);
4343 int NI = s.intents.size();
4344 int j;
4345 for (j=0; j<NI; j++) {
4346 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4347 if (SHOW_INFO || Config.LOGV) {
4348 Log.v(TAG, " IntentFilter:");
4349 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4350 }
4351 if (!intent.debugCheck()) {
4352 Log.w(TAG, "==> For Service " + s.info.name);
4353 }
4354 addFilter(intent);
4355 }
4356 }
4357
4358 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004359 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 if (SHOW_INFO || Config.LOGV) Log.v(
4361 TAG, " " + (s.info.nonLocalizedLabel != null
4362 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4363 if (SHOW_INFO || Config.LOGV) Log.v(
4364 TAG, " Class=" + s.info.name);
4365 int NI = s.intents.size();
4366 int j;
4367 for (j=0; j<NI; j++) {
4368 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4369 if (SHOW_INFO || Config.LOGV) {
4370 Log.v(TAG, " IntentFilter:");
4371 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4372 }
4373 removeFilter(intent);
4374 }
4375 }
4376
4377 @Override
4378 protected boolean allowFilterResult(
4379 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4380 ServiceInfo filterSi = filter.service.info;
4381 for (int i=dest.size()-1; i>=0; i--) {
4382 ServiceInfo destAi = dest.get(i).serviceInfo;
4383 if (destAi.name == filterSi.name
4384 && destAi.packageName == filterSi.packageName) {
4385 return false;
4386 }
4387 }
4388 return true;
4389 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004392 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4393 return info.service.owner.packageName;
4394 }
4395
4396 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4398 int match) {
4399 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4400 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4401 return null;
4402 }
4403 final PackageParser.Service service = info.service;
4404 if (mSafeMode && (service.info.applicationInfo.flags
4405 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4406 return null;
4407 }
4408 final ResolveInfo res = new ResolveInfo();
4409 res.serviceInfo = PackageParser.generateServiceInfo(service,
4410 mFlags);
4411 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4412 res.filter = filter;
4413 }
4414 res.priority = info.getPriority();
4415 res.preferredOrder = service.owner.mPreferredOrder;
4416 //System.out.println("Result: " + res.activityInfo.className +
4417 // " = " + res.priority);
4418 res.match = match;
4419 res.isDefault = info.hasDefault;
4420 res.labelRes = info.labelRes;
4421 res.nonLocalizedLabel = info.nonLocalizedLabel;
4422 res.icon = info.icon;
4423 return res;
4424 }
4425
4426 @Override
4427 protected void sortResults(List<ResolveInfo> results) {
4428 Collections.sort(results, mResolvePrioritySorter);
4429 }
4430
4431 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004432 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004434 out.print(prefix); out.print(
4435 Integer.toHexString(System.identityHashCode(filter.service)));
4436 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004437 out.print(filter.service.getComponentShortName());
4438 out.print(" filter ");
4439 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 }
4441
4442// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4443// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4444// final List<ResolveInfo> retList = Lists.newArrayList();
4445// while (i.hasNext()) {
4446// final ResolveInfo resolveInfo = (ResolveInfo) i;
4447// if (isEnabledLP(resolveInfo.serviceInfo)) {
4448// retList.add(resolveInfo);
4449// }
4450// }
4451// return retList;
4452// }
4453
4454 // Keys are String (activity class name), values are Activity.
4455 private final HashMap<ComponentName, PackageParser.Service> mServices
4456 = new HashMap<ComponentName, PackageParser.Service>();
4457 private int mFlags;
4458 };
4459
4460 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4461 new Comparator<ResolveInfo>() {
4462 public int compare(ResolveInfo r1, ResolveInfo r2) {
4463 int v1 = r1.priority;
4464 int v2 = r2.priority;
4465 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4466 if (v1 != v2) {
4467 return (v1 > v2) ? -1 : 1;
4468 }
4469 v1 = r1.preferredOrder;
4470 v2 = r2.preferredOrder;
4471 if (v1 != v2) {
4472 return (v1 > v2) ? -1 : 1;
4473 }
4474 if (r1.isDefault != r2.isDefault) {
4475 return r1.isDefault ? -1 : 1;
4476 }
4477 v1 = r1.match;
4478 v2 = r2.match;
4479 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4480 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4481 }
4482 };
4483
4484 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4485 new Comparator<ProviderInfo>() {
4486 public int compare(ProviderInfo p1, ProviderInfo p2) {
4487 final int v1 = p1.initOrder;
4488 final int v2 = p2.initOrder;
4489 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4490 }
4491 };
4492
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004493 private static final void sendPackageBroadcast(String action, String pkg,
4494 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 IActivityManager am = ActivityManagerNative.getDefault();
4496 if (am != null) {
4497 try {
4498 final Intent intent = new Intent(action,
4499 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4500 if (extras != null) {
4501 intent.putExtras(extras);
4502 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004503 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004504 am.broadcastIntent(null, intent, null, finishedReceiver,
4505 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 } catch (RemoteException ex) {
4507 }
4508 }
4509 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004510
4511 public String nextPackageToClean(String lastPackage) {
4512 synchronized (mPackages) {
4513 if (!mMediaMounted) {
4514 // If the external storage is no longer mounted at this point,
4515 // the caller may not have been able to delete all of this
4516 // packages files and can not delete any more. Bail.
4517 return null;
4518 }
4519 if (lastPackage != null) {
4520 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4521 }
4522 return mSettings.mPackagesToBeCleaned.size() > 0
4523 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4524 }
4525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004527 void schedulePackageCleaning(String packageName) {
4528 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4529 }
4530
4531 void startCleaningPackages() {
4532 synchronized (mPackages) {
4533 if (!mMediaMounted) {
4534 return;
4535 }
4536 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4537 return;
4538 }
4539 }
4540 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4541 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4542 IActivityManager am = ActivityManagerNative.getDefault();
4543 if (am != null) {
4544 try {
4545 am.startService(null, intent, null);
4546 } catch (RemoteException e) {
4547 }
4548 }
4549 }
4550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 private final class AppDirObserver extends FileObserver {
4552 public AppDirObserver(String path, int mask, boolean isrom) {
4553 super(path, mask);
4554 mRootDir = path;
4555 mIsRom = isrom;
4556 }
4557
4558 public void onEvent(int event, String path) {
4559 String removedPackage = null;
4560 int removedUid = -1;
4561 String addedPackage = null;
4562 int addedUid = -1;
4563
4564 synchronized (mInstallLock) {
4565 String fullPathStr = null;
4566 File fullPath = null;
4567 if (path != null) {
4568 fullPath = new File(mRootDir, path);
4569 fullPathStr = fullPath.getPath();
4570 }
4571
4572 if (Config.LOGV) Log.v(
4573 TAG, "File " + fullPathStr + " changed: "
4574 + Integer.toHexString(event));
4575
4576 if (!isPackageFilename(path)) {
4577 if (Config.LOGV) Log.v(
4578 TAG, "Ignoring change of non-package file: " + fullPathStr);
4579 return;
4580 }
4581
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004582 // Ignore packages that are being installed or
4583 // have just been installed.
4584 if (ignoreCodePath(fullPathStr)) {
4585 return;
4586 }
4587 PackageParser.Package p = null;
4588 synchronized (mPackages) {
4589 p = mAppDirs.get(fullPathStr);
4590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004592 if (p != null) {
4593 removePackageLI(p, true);
4594 removedPackage = p.applicationInfo.packageName;
4595 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 }
4597 }
4598
4599 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004601 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004602 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4603 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 PackageParser.PARSE_CHATTY |
4605 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004606 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 if (p != null) {
4608 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004609 updatePermissionsLP(p.packageName, p,
4610 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 }
4612 addedPackage = p.applicationInfo.packageName;
4613 addedUid = p.applicationInfo.uid;
4614 }
4615 }
4616 }
4617
4618 synchronized (mPackages) {
4619 mSettings.writeLP();
4620 }
4621 }
4622
4623 if (removedPackage != null) {
4624 Bundle extras = new Bundle(1);
4625 extras.putInt(Intent.EXTRA_UID, removedUid);
4626 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004627 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4628 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 }
4630 if (addedPackage != null) {
4631 Bundle extras = new Bundle(1);
4632 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004633 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4634 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 }
4636 }
4637
4638 private final String mRootDir;
4639 private final boolean mIsRom;
4640 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004642 /* Called when a downloaded package installation has been confirmed by the user */
4643 public void installPackage(
4644 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004645 installPackage(packageURI, observer, flags, null);
4646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004647
Jacek Surazski65e13172009-04-28 15:26:38 +02004648 /* Called when a downloaded package installation has been confirmed by the user */
4649 public void installPackage(
4650 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4651 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004652 mContext.enforceCallingOrSelfPermission(
4653 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004654
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004655 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004656 msg.obj = new InstallParams(packageURI, observer, flags,
4657 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004658 mHandler.sendMessage(msg);
4659 }
4660
Christopher Tate1bb69062010-02-19 17:02:12 -08004661 public void finishPackageInstall(int token) {
4662 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4663 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4664 mHandler.sendMessage(msg);
4665 }
4666
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004667 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004668 // Queue up an async operation since the package installation may take a little while.
4669 mHandler.post(new Runnable() {
4670 public void run() {
4671 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004672 // Result object to be returned
4673 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004674 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004675 res.uid = -1;
4676 res.pkg = null;
4677 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004678 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004679 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004680 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004681 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004682 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004683 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004685
4686 // A restore should be performed at this point if (a) the install
4687 // succeeded, (b) the operation is not an update, and (c) the new
4688 // package has a backupAgent defined.
4689 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004690 boolean doRestore = (!update
4691 && res.pkg != null
4692 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004693
4694 // Set up the post-install work request bookkeeping. This will be used
4695 // and cleaned up by the post-install event handling regardless of whether
4696 // there's a restore pass performed. Token values are >= 1.
4697 int token;
4698 if (mNextInstallToken < 0) mNextInstallToken = 1;
4699 token = mNextInstallToken++;
4700
4701 PostInstallData data = new PostInstallData(args, res);
4702 mRunningInstalls.put(token, data);
4703 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4704
4705 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4706 // Pass responsibility to the Backup Manager. It will perform a
4707 // restore if appropriate, then pass responsibility back to the
4708 // Package Manager to run the post-install observer callbacks
4709 // and broadcasts.
4710 IBackupManager bm = IBackupManager.Stub.asInterface(
4711 ServiceManager.getService(Context.BACKUP_SERVICE));
4712 if (bm != null) {
4713 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4714 + " to BM for possible restore");
4715 try {
4716 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4717 } catch (RemoteException e) {
4718 // can't happen; the backup manager is local
4719 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004720 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004721 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004722 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004723 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004724 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004725 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004728
4729 if (!doRestore) {
4730 // No restore possible, or the Backup Manager was mysteriously not
4731 // available -- just fire the post-install work request directly.
4732 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4733 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4734 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004736 }
4737 });
4738 }
4739
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004740 abstract class HandlerParams {
4741 final static int MAX_RETRIES = 4;
4742 int retry = 0;
4743 final void startCopy() {
4744 try {
4745 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4746 retry++;
4747 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004748 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004749 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4750 handleServiceError();
4751 return;
4752 } else {
4753 handleStartCopy();
4754 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4755 mHandler.sendEmptyMessage(MCS_UNBIND);
4756 }
4757 } catch (RemoteException e) {
4758 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4759 mHandler.sendEmptyMessage(MCS_RECONNECT);
4760 }
4761 handleReturnCode();
4762 }
4763
4764 final void serviceError() {
4765 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4766 handleServiceError();
4767 handleReturnCode();
4768 }
4769 abstract void handleStartCopy() throws RemoteException;
4770 abstract void handleServiceError();
4771 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004772 }
4773
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004774 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004775 final IPackageInstallObserver observer;
4776 int flags;
4777 final Uri packageURI;
4778 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004779 private InstallArgs mArgs;
4780 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004781 InstallParams(Uri packageURI,
4782 IPackageInstallObserver observer, int flags,
4783 String installerPackageName) {
4784 this.packageURI = packageURI;
4785 this.flags = flags;
4786 this.observer = observer;
4787 this.installerPackageName = installerPackageName;
4788 }
4789
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004790 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4791 String packageName = pkgLite.packageName;
4792 int installLocation = pkgLite.installLocation;
4793 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4794 synchronized (mPackages) {
4795 PackageParser.Package pkg = mPackages.get(packageName);
4796 if (pkg != null) {
4797 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4798 // Check for updated system application.
4799 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4800 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004801 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004802 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4803 }
4804 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4805 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004806 if (onSd) {
4807 // Install flag overrides everything.
4808 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4809 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004810 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004811 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4812 // Application explicitly specified internal.
4813 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4814 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4815 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004816 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004817 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004818 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4819 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4820 }
4821 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004822 }
4823 }
4824 } else {
4825 // Invalid install. Return error code
4826 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4827 }
4828 }
4829 }
4830 // All the special cases have been taken care of.
4831 // Return result based on recommended install location.
4832 if (onSd) {
4833 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4834 }
4835 return pkgLite.recommendedInstallLocation;
4836 }
4837
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004838 /*
4839 * Invoke remote method to get package information and install
4840 * location values. Override install location based on default
4841 * policy if needed and then create install arguments based
4842 * on the install location.
4843 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004844 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004845 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004846 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4847 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004848 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4849 if (onInt && onSd) {
4850 // Check if both bits are set.
4851 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4852 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4853 } else if (fwdLocked && onSd) {
4854 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004855 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004856 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004857 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004859 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004860 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004861 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4862 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4863 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4864 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4865 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004866 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4867 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4868 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004869 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4870 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004871 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004872 // Override with defaults if needed.
4873 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004874 if (!onSd && !onInt) {
4875 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004876 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4877 // Set the flag to install on external media.
4878 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004879 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004880 } else {
4881 // Make sure the flag for installing on external
4882 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004883 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004884 flags &= ~PackageManager.INSTALL_EXTERNAL;
4885 }
4886 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004887 }
4888 }
4889 // Create the file args now.
4890 mArgs = createInstallArgs(this);
4891 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4892 // Create copy only if we are not in an erroneous state.
4893 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004894 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004895 }
4896 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004897 }
4898
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004899 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004900 void handleReturnCode() {
4901 processPendingInstall(mArgs, mRet);
4902 }
4903
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004904 @Override
4905 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004906 mArgs = createInstallArgs(this);
4907 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004908 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004909 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004910
4911 /*
4912 * Utility class used in movePackage api.
4913 * srcArgs and targetArgs are not set for invalid flags and make
4914 * sure to do null checks when invoking methods on them.
4915 * We probably want to return ErrorPrams for both failed installs
4916 * and moves.
4917 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004918 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004919 final IPackageMoveObserver observer;
4920 final int flags;
4921 final String packageName;
4922 final InstallArgs srcArgs;
4923 final InstallArgs targetArgs;
4924 int mRet;
4925 MoveParams(InstallArgs srcArgs,
4926 IPackageMoveObserver observer,
4927 int flags, String packageName) {
4928 this.srcArgs = srcArgs;
4929 this.observer = observer;
4930 this.flags = flags;
4931 this.packageName = packageName;
4932 if (srcArgs != null) {
4933 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4934 targetArgs = createInstallArgs(packageUri, flags, packageName);
4935 } else {
4936 targetArgs = null;
4937 }
4938 }
4939
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004940 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004941 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4942 // Check for storage space on target medium
4943 if (!targetArgs.checkFreeStorage(mContainerService)) {
4944 Log.w(TAG, "Insufficient storage to install");
4945 return;
4946 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004947 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004948 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004949 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004950 if (DEBUG_SD_INSTALL) {
4951 StringBuilder builder = new StringBuilder();
4952 if (srcArgs != null) {
4953 builder.append("src: ");
4954 builder.append(srcArgs.getCodePath());
4955 }
4956 if (targetArgs != null) {
4957 builder.append(" target : ");
4958 builder.append(targetArgs.getCodePath());
4959 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004960 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004961 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004962 }
4963
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004964 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004965 void handleReturnCode() {
4966 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004967 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4968 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4969 currentStatus = PackageManager.MOVE_SUCCEEDED;
4970 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4971 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4972 }
4973 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004974 }
4975
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004976 @Override
4977 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004978 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004979 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004980 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004981
4982 private InstallArgs createInstallArgs(InstallParams params) {
4983 if (installOnSd(params.flags)) {
4984 return new SdInstallArgs(params);
4985 } else {
4986 return new FileInstallArgs(params);
4987 }
4988 }
4989
4990 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4991 if (installOnSd(flags)) {
4992 return new SdInstallArgs(fullCodePath, fullResourcePath);
4993 } else {
4994 return new FileInstallArgs(fullCodePath, fullResourcePath);
4995 }
4996 }
4997
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004998 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4999 if (installOnSd(flags)) {
5000 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5001 return new SdInstallArgs(packageURI, cid);
5002 } else {
5003 return new FileInstallArgs(packageURI, pkgName);
5004 }
5005 }
5006
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005007 static abstract class InstallArgs {
5008 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005009 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005010 final int flags;
5011 final Uri packageURI;
5012 final String installerPackageName;
5013
5014 InstallArgs(Uri packageURI,
5015 IPackageInstallObserver observer, int flags,
5016 String installerPackageName) {
5017 this.packageURI = packageURI;
5018 this.flags = flags;
5019 this.observer = observer;
5020 this.installerPackageName = installerPackageName;
5021 }
5022
5023 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005024 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005025 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005026 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005027 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005028 abstract String getCodePath();
5029 abstract String getResourcePath();
5030 // Need installer lock especially for dex file removal.
5031 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005032 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005033 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005034 }
5035
5036 class FileInstallArgs extends InstallArgs {
5037 File installDir;
5038 String codeFileName;
5039 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005040 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005041
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005042 FileInstallArgs(InstallParams params) {
5043 super(params.packageURI, params.observer,
5044 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005045 }
5046
5047 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5048 super(null, null, 0, null);
5049 File codeFile = new File(fullCodePath);
5050 installDir = codeFile.getParentFile();
5051 codeFileName = fullCodePath;
5052 resourceFileName = fullResourcePath;
5053 }
5054
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005055 FileInstallArgs(Uri packageURI, String pkgName) {
5056 super(packageURI, null, 0, null);
5057 boolean fwdLocked = isFwdLocked(flags);
5058 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5059 String apkName = getNextCodePath(null, pkgName, ".apk");
5060 codeFileName = new File(installDir, apkName + ".apk").getPath();
5061 resourceFileName = getResourcePathFromCodePath();
5062 }
5063
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005064 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5065 return imcs.checkFreeStorage(false, packageURI);
5066 }
5067
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005068 String getCodePath() {
5069 return codeFileName;
5070 }
5071
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005072 void createCopyFile() {
5073 boolean fwdLocked = isFwdLocked(flags);
5074 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5075 codeFileName = createTempPackageFile(installDir).getPath();
5076 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005077 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005078 }
5079
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005080 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005081 if (temp) {
5082 // Generate temp file name
5083 createCopyFile();
5084 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005085 // Get a ParcelFileDescriptor to write to the output file
5086 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005087 if (!created) {
5088 try {
5089 codeFile.createNewFile();
5090 // Set permissions
5091 if (!setPermissions()) {
5092 // Failed setting permissions.
5093 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5094 }
5095 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005096 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005097 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5098 }
5099 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005100 ParcelFileDescriptor out = null;
5101 try {
5102 out = ParcelFileDescriptor.open(codeFile,
5103 ParcelFileDescriptor.MODE_READ_WRITE);
5104 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005105 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005106 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5107 }
5108 // Copy the resource now
5109 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5110 try {
5111 if (imcs.copyResource(packageURI, out)) {
5112 ret = PackageManager.INSTALL_SUCCEEDED;
5113 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005114 } finally {
5115 try { if (out != null) out.close(); } catch (IOException e) {}
5116 }
5117 return ret;
5118 }
5119
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005120 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005121 if (status != PackageManager.INSTALL_SUCCEEDED) {
5122 cleanUp();
5123 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005124 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005125 }
5126
5127 boolean doRename(int status, final String pkgName, String oldCodePath) {
5128 if (status != PackageManager.INSTALL_SUCCEEDED) {
5129 cleanUp();
5130 return false;
5131 } else {
5132 // Rename based on packageName
5133 File codeFile = new File(getCodePath());
5134 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5135 File desFile = new File(installDir, apkName + ".apk");
5136 if (!codeFile.renameTo(desFile)) {
5137 return false;
5138 }
5139 // Reset paths since the file has been renamed.
5140 codeFileName = desFile.getPath();
5141 resourceFileName = getResourcePathFromCodePath();
5142 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005143 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005144 // Failed setting permissions.
5145 return false;
5146 }
5147 return true;
5148 }
5149 }
5150
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005151 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005152 if (status != PackageManager.INSTALL_SUCCEEDED) {
5153 cleanUp();
5154 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005155 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005156 }
5157
5158 String getResourcePath() {
5159 return resourceFileName;
5160 }
5161
5162 String getResourcePathFromCodePath() {
5163 String codePath = getCodePath();
5164 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5165 String apkNameOnly = getApkName(codePath);
5166 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5167 } else {
5168 return codePath;
5169 }
5170 }
5171
5172 private boolean cleanUp() {
5173 boolean ret = true;
5174 String sourceDir = getCodePath();
5175 String publicSourceDir = getResourcePath();
5176 if (sourceDir != null) {
5177 File sourceFile = new File(sourceDir);
5178 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005179 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005180 ret = false;
5181 }
5182 // Delete application's code and resources
5183 sourceFile.delete();
5184 }
5185 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5186 final File publicSourceFile = new File(publicSourceDir);
5187 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005188 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005189 }
5190 if (publicSourceFile.exists()) {
5191 publicSourceFile.delete();
5192 }
5193 }
5194 return ret;
5195 }
5196
5197 void cleanUpResourcesLI() {
5198 String sourceDir = getCodePath();
5199 if (cleanUp() && mInstaller != null) {
5200 int retCode = mInstaller.rmdex(sourceDir);
5201 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005202 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005203 + " at location "
5204 + sourceDir + ", retcode=" + retCode);
5205 // we don't consider this to be a failure of the core package deletion
5206 }
5207 }
5208 }
5209
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005210 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005211 // TODO Do this in a more elegant way later on. for now just a hack
5212 if (!isFwdLocked(flags)) {
5213 final int filePermissions =
5214 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5215 |FileUtils.S_IROTH;
5216 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5217 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005218 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005219 getCodePath()
5220 + ". The return code was: " + retCode);
5221 // TODO Define new internal error
5222 return false;
5223 }
5224 return true;
5225 }
5226 return true;
5227 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005228
5229 boolean doPostDeleteLI(boolean delete) {
5230 cleanUpResourcesLI();
5231 return true;
5232 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005233 }
5234
5235 class SdInstallArgs extends InstallArgs {
5236 String cid;
5237 String cachePath;
5238 static final String RES_FILE_NAME = "pkg.apk";
5239
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005240 SdInstallArgs(InstallParams params) {
5241 super(params.packageURI, params.observer,
5242 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005243 }
5244
5245 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005246 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005247 // Extract cid from fullCodePath
5248 int eidx = fullCodePath.lastIndexOf("/");
5249 String subStr1 = fullCodePath.substring(0, eidx);
5250 int sidx = subStr1.lastIndexOf("/");
5251 cid = subStr1.substring(sidx+1, eidx);
5252 cachePath = subStr1;
5253 }
5254
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005255 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005256 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5257 this.cid = cid;
5258 }
5259
5260 SdInstallArgs(Uri packageURI, String cid) {
5261 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005262 this.cid = cid;
5263 }
5264
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005265 void createCopyFile() {
5266 cid = getTempContainerId();
5267 }
5268
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005269 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5270 return imcs.checkFreeStorage(true, packageURI);
5271 }
5272
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005273 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005274 if (temp) {
5275 createCopyFile();
5276 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005277 cachePath = imcs.copyResourceToContainer(
5278 packageURI, cid,
5279 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005280 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5281 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005282 }
5283
5284 @Override
5285 String getCodePath() {
5286 return cachePath + "/" + RES_FILE_NAME;
5287 }
5288
5289 @Override
5290 String getResourcePath() {
5291 return cachePath + "/" + RES_FILE_NAME;
5292 }
5293
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005294 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005295 if (status != PackageManager.INSTALL_SUCCEEDED) {
5296 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005297 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005298 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005299 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005300 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005301 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005302 if (cachePath == null) {
5303 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5304 }
5305 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005306 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005307 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005308 }
5309
5310 boolean doRename(int status, final String pkgName,
5311 String oldCodePath) {
5312 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005313 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005314 if (PackageHelper.isContainerMounted(cid)) {
5315 // Unmount the container
5316 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005317 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005318 return false;
5319 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005320 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005321 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005322 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5323 " which might be stale. Will try to clean up.");
5324 // Clean up the stale container and proceed to recreate.
5325 if (!PackageHelper.destroySdDir(newCacheId)) {
5326 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5327 return false;
5328 }
5329 // Successfully cleaned up stale container. Try to rename again.
5330 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5331 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5332 + " inspite of cleaning it up.");
5333 return false;
5334 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005335 }
5336 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005337 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005338 newCachePath = PackageHelper.mountSdDir(newCacheId,
5339 getEncryptKey(), Process.SYSTEM_UID);
5340 } else {
5341 newCachePath = PackageHelper.getSdDir(newCacheId);
5342 }
5343 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005344 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005345 return false;
5346 }
5347 Log.i(TAG, "Succesfully renamed " + cid +
5348 " at path: " + cachePath + " to " + newCacheId +
5349 " at new path: " + newCachePath);
5350 cid = newCacheId;
5351 cachePath = newCachePath;
5352 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005353 }
5354
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005355 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005356 if (status != PackageManager.INSTALL_SUCCEEDED) {
5357 cleanUp();
5358 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005359 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005360 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005361 PackageHelper.mountSdDir(cid,
5362 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005363 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005364 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005365 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005366 }
5367
5368 private void cleanUp() {
5369 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005370 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 }
5372
5373 void cleanUpResourcesLI() {
5374 String sourceFile = getCodePath();
5375 // Remove dex file
5376 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005377 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005378 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005379 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005380 + " at location "
5381 + sourceFile.toString() + ", retcode=" + retCode);
5382 // we don't consider this to be a failure of the core package deletion
5383 }
5384 }
5385 cleanUp();
5386 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005387
5388 boolean matchContainer(String app) {
5389 if (cid.startsWith(app)) {
5390 return true;
5391 }
5392 return false;
5393 }
5394
5395 String getPackageName() {
5396 int idx = cid.lastIndexOf("-");
5397 if (idx == -1) {
5398 return cid;
5399 }
5400 return cid.substring(0, idx);
5401 }
5402
5403 boolean doPostDeleteLI(boolean delete) {
5404 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005405 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005406 if (mounted) {
5407 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005408 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005409 }
5410 if (ret && delete) {
5411 cleanUpResourcesLI();
5412 }
5413 return ret;
5414 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005415 };
5416
5417 // Utility method used to create code paths based on package name and available index.
5418 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5419 String idxStr = "";
5420 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005421 // Fall back to default value of idx=1 if prefix is not
5422 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005423 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005424 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005425 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005426 if (subStr.endsWith(suffix)) {
5427 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005428 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005429 // If oldCodePath already contains prefix find out the
5430 // ending index to either increment or decrement.
5431 int sidx = subStr.lastIndexOf(prefix);
5432 if (sidx != -1) {
5433 subStr = subStr.substring(sidx + prefix.length());
5434 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005435 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5436 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005437 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005438 try {
5439 idx = Integer.parseInt(subStr);
5440 if (idx <= 1) {
5441 idx++;
5442 } else {
5443 idx--;
5444 }
5445 } catch(NumberFormatException e) {
5446 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005447 }
5448 }
5449 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005450 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005451 return prefix + idxStr;
5452 }
5453
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005454 // Utility method used to ignore ADD/REMOVE events
5455 // by directory observer.
5456 private static boolean ignoreCodePath(String fullPathStr) {
5457 String apkName = getApkName(fullPathStr);
5458 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5459 if (idx != -1 && ((idx+1) < apkName.length())) {
5460 // Make sure the package ends with a numeral
5461 String version = apkName.substring(idx+1);
5462 try {
5463 Integer.parseInt(version);
5464 return true;
5465 } catch (NumberFormatException e) {}
5466 }
5467 return false;
5468 }
5469
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005470 // Utility method that returns the relative package path with respect
5471 // to the installation directory. Like say for /data/data/com.test-1.apk
5472 // string com.test-1 is returned.
5473 static String getApkName(String codePath) {
5474 if (codePath == null) {
5475 return null;
5476 }
5477 int sidx = codePath.lastIndexOf("/");
5478 int eidx = codePath.lastIndexOf(".");
5479 if (eidx == -1) {
5480 eidx = codePath.length();
5481 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005482 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005483 return null;
5484 }
5485 return codePath.substring(sidx+1, eidx);
5486 }
5487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 class PackageInstalledInfo {
5489 String name;
5490 int uid;
5491 PackageParser.Package pkg;
5492 int returnCode;
5493 PackageRemovedInfo removedInfo;
5494 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 /*
5497 * Install a non-existing package.
5498 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005499 private void installNewPackageLI(PackageParser.Package pkg,
5500 int parseFlags,
5501 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005502 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005503 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005504 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005505
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005506 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 res.name = pkgName;
5508 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005509 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5510 // A package with the same name is already installed, though
5511 // it has been renamed to an older name. The package we
5512 // are trying to install should be installed as an update to
5513 // the existing one, but that has not been requested, so bail.
5514 Slog.w(TAG, "Attempt to re-install " + pkgName
5515 + " without first uninstalling package running as "
5516 + mSettings.mRenamedPackages.get(pkgName));
5517 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5518 return;
5519 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005520 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005522 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 + " without first uninstalling.");
5524 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5525 return;
5526 }
5527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005529 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005531 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5533 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5534 }
5535 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005536 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005537 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538 res);
5539 // delete the partially installed application. the data directory will have to be
5540 // restored if it was already existing
5541 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5542 // remove package from internal structures. Note that we want deletePackageX to
5543 // delete the package data and cache directories that it created in
5544 // scanPackageLocked, unless those directories existed before we even tried to
5545 // install.
5546 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005547 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5549 res.removedInfo);
5550 }
5551 }
5552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005553
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005554 private void replacePackageLI(PackageParser.Package pkg,
5555 int parseFlags,
5556 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005557 String installerPackageName, PackageInstalledInfo res) {
5558
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005559 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005560 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 // First find the old package info and check signatures
5562 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005563 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005564 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005565 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5567 return;
5568 }
5569 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005570 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005571 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005572 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005574 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 }
5576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005578 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005579 PackageParser.Package pkg,
5580 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005581 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 PackageParser.Package newPackage = null;
5583 String pkgName = deletedPackage.packageName;
5584 boolean deletedPkg = true;
5585 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005586
Jacek Surazski65e13172009-04-28 15:26:38 +02005587 String oldInstallerPackageName = null;
5588 synchronized (mPackages) {
5589 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005593 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 res.removedInfo)) {
5595 // If the existing package was'nt successfully deleted
5596 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5597 deletedPkg = false;
5598 } else {
5599 // Successfully deleted the old package. Now proceed with re-installation
5600 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005601 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005603 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005604 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5605 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005606 }
5607 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005608 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005609 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610 res);
5611 updatedSettings = true;
5612 }
5613 }
5614
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005615 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 // remove package from internal structures. Note that we want deletePackageX to
5617 // delete the package data and cache directories that it created in
5618 // scanPackageLocked, unless those directories existed before we even tried to
5619 // install.
5620 if(updatedSettings) {
5621 deletePackageLI(
5622 pkgName, true,
5623 PackageManager.DONT_DELETE_DATA,
5624 res.removedInfo);
5625 }
5626 // Since we failed to install the new package we need to restore the old
5627 // package that we deleted.
5628 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005629 File restoreFile = new File(deletedPackage.mPath);
5630 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005631 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005632 return;
5633 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005634 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005635 boolean oldOnSd = isExternal(deletedPackage);
5636 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5637 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5638 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5639 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5640 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5641 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5642 return;
5643 }
5644 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005645 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005646 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5647 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005648 mSettings.writeLP();
5649 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005650 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 }
5652 }
5653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005656 PackageParser.Package pkg,
5657 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005658 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 PackageParser.Package newPackage = null;
5660 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005661 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 PackageParser.PARSE_IS_SYSTEM;
5663 String packageName = deletedPackage.packageName;
5664 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5665 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005666 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 return;
5668 }
5669 PackageParser.Package oldPkg;
5670 PackageSetting oldPkgSetting;
5671 synchronized (mPackages) {
5672 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005673 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5675 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005676 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 return;
5678 }
5679 }
5680 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5681 res.removedInfo.removedPackage = packageName;
5682 // Remove existing system package
5683 removePackageLI(oldPkg, true);
5684 synchronized (mPackages) {
5685 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5686 }
5687
5688 // Successfully disabled the old package. Now proceed with re-installation
5689 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5690 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005691 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005693 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5695 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5696 }
5697 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005698 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 updatedSettings = true;
5700 }
5701
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005702 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 // Re installation failed. Restore old information
5704 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005705 if (newPackage != null) {
5706 removePackageLI(newPackage, true);
5707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005709 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005711 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005712 // Restore the old system information in Settings
5713 synchronized(mPackages) {
5714 if(updatedSettings) {
5715 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005716 mSettings.setInstallerPackageName(packageName,
5717 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005718 }
5719 mSettings.writeLP();
5720 }
5721 }
5722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005723
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005724 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005725 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005726 int retCode;
5727 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5728 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5729 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005730 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005731 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5732 }
5733 }
5734 return PackageManager.INSTALL_SUCCEEDED;
5735 }
5736
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005737 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005738 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005739 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 synchronized (mPackages) {
5741 //write settings. the installStatus will be incomplete at this stage.
5742 //note that the new package setting would have already been
5743 //added to mPackages. It hasn't been persisted yet.
5744 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5745 mSettings.writeLP();
5746 }
5747
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005748 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005749 != PackageManager.INSTALL_SUCCEEDED) {
5750 // Discontinue if moving dex files failed.
5751 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005753 if((res.returnCode = setPermissionsLI(newPackage))
5754 != PackageManager.INSTALL_SUCCEEDED) {
5755 if (mInstaller != null) {
5756 mInstaller.rmdex(newPackage.mScanPath);
5757 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005758 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005760 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005763 updatePermissionsLP(newPackage.packageName, newPackage,
5764 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 res.name = pkgName;
5766 res.uid = newPackage.applicationInfo.uid;
5767 res.pkg = newPackage;
5768 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005769 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5771 //to update install status
5772 mSettings.writeLP();
5773 }
5774 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005775
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005776 private void installPackageLI(InstallArgs args,
5777 boolean newInstall, PackageInstalledInfo res) {
5778 int pFlags = args.flags;
5779 String installerPackageName = args.installerPackageName;
5780 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005781 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005782 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005783 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005784 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005785 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005786 // Result object to be returned
5787 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5788
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005789 // Retrieve PackageSettings and parse package
5790 int parseFlags = PackageParser.PARSE_CHATTY |
5791 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5792 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5793 parseFlags |= mDefParseFlags;
5794 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5795 pp.setSeparateProcesses(mSeparateProcesses);
5796 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5797 null, mMetrics, parseFlags);
5798 if (pkg == null) {
5799 res.returnCode = pp.getParseError();
5800 return;
5801 }
5802 String pkgName = res.name = pkg.packageName;
5803 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5804 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5805 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5806 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005808 }
5809 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5810 res.returnCode = pp.getParseError();
5811 return;
5812 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005813 // Get rid of all references to package scan path via parser.
5814 pp = null;
5815 String oldCodePath = null;
5816 boolean systemApp = false;
5817 synchronized (mPackages) {
5818 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005819 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5820 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005821 if (pkg.mOriginalPackages != null
5822 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005823 && mPackages.containsKey(oldName)) {
5824 // This package is derived from an original package,
5825 // and this device has been updating from that original
5826 // name. We must continue using the original name, so
5827 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005828 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005829 pkgName = pkg.packageName;
5830 replace = true;
5831 } else if (mPackages.containsKey(pkgName)) {
5832 // This package, under its official name, already exists
5833 // on the device; we should replace it.
5834 replace = true;
5835 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005836 }
5837 PackageSetting ps = mSettings.mPackages.get(pkgName);
5838 if (ps != null) {
5839 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5840 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5841 systemApp = (ps.pkg.applicationInfo.flags &
5842 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005843 }
5844 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005846
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005847 if (systemApp && onSd) {
5848 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005849 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005850 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5851 return;
5852 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005853
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005854 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5855 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5856 return;
5857 }
5858 // Set application objects path explicitly after the rename
5859 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005860 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005861 replacePackageLI(pkg, parseFlags, scanMode,
5862 installerPackageName, res);
5863 } else {
5864 installNewPackageLI(pkg, parseFlags, scanMode,
5865 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 }
5867 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005868
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005869 private int setPermissionsLI(PackageParser.Package newPackage) {
5870 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005871 int retCode = 0;
5872 // TODO Gross hack but fix later. Ideally move this to be a post installation
5873 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005874 if ((newPackage.applicationInfo.flags
5875 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5876 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 try {
5878 extractPublicFiles(newPackage, destResourceFile);
5879 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005880 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 -08005881 " forward-locked app.");
5882 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5883 } finally {
5884 //TODO clean up the extracted public files
5885 }
5886 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005887 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 newPackage.applicationInfo.uid);
5889 } else {
5890 final int filePermissions =
5891 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005892 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 newPackage.applicationInfo.uid);
5894 }
5895 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005896 // The permissions on the resource file was set when it was copied for
5897 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005901 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005902 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005904 // TODO Define new internal error
5905 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 }
5907 return PackageManager.INSTALL_SUCCEEDED;
5908 }
5909
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005910 private boolean isForwardLocked(PackageParser.Package pkg) {
5911 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 }
5913
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005914 private boolean isExternal(PackageParser.Package pkg) {
5915 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5916 }
5917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005918 private void extractPublicFiles(PackageParser.Package newPackage,
5919 File publicZipFile) throws IOException {
5920 final ZipOutputStream publicZipOutStream =
5921 new ZipOutputStream(new FileOutputStream(publicZipFile));
5922 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5923
5924 // Copy manifest, resources.arsc and res directory to public zip
5925
5926 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5927 while (privateZipEntries.hasMoreElements()) {
5928 final ZipEntry zipEntry = privateZipEntries.nextElement();
5929 final String zipEntryName = zipEntry.getName();
5930 if ("AndroidManifest.xml".equals(zipEntryName)
5931 || "resources.arsc".equals(zipEntryName)
5932 || zipEntryName.startsWith("res/")) {
5933 try {
5934 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5935 } catch (IOException e) {
5936 try {
5937 publicZipOutStream.close();
5938 throw e;
5939 } finally {
5940 publicZipFile.delete();
5941 }
5942 }
5943 }
5944 }
5945
5946 publicZipOutStream.close();
5947 FileUtils.setPermissions(
5948 publicZipFile.getAbsolutePath(),
5949 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5950 -1, -1);
5951 }
5952
5953 private static void copyZipEntry(ZipEntry zipEntry,
5954 ZipFile inZipFile,
5955 ZipOutputStream outZipStream) throws IOException {
5956 byte[] buffer = new byte[4096];
5957 int num;
5958
5959 ZipEntry newEntry;
5960 if (zipEntry.getMethod() == ZipEntry.STORED) {
5961 // Preserve the STORED method of the input entry.
5962 newEntry = new ZipEntry(zipEntry);
5963 } else {
5964 // Create a new entry so that the compressed len is recomputed.
5965 newEntry = new ZipEntry(zipEntry.getName());
5966 }
5967 outZipStream.putNextEntry(newEntry);
5968
5969 InputStream data = inZipFile.getInputStream(zipEntry);
5970 while ((num = data.read(buffer)) > 0) {
5971 outZipStream.write(buffer, 0, num);
5972 }
5973 outZipStream.flush();
5974 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 private void deleteTempPackageFiles() {
5977 FilenameFilter filter = new FilenameFilter() {
5978 public boolean accept(File dir, String name) {
5979 return name.startsWith("vmdl") && name.endsWith(".tmp");
5980 }
5981 };
5982 String tmpFilesList[] = mAppInstallDir.list(filter);
5983 if(tmpFilesList == null) {
5984 return;
5985 }
5986 for(int i = 0; i < tmpFilesList.length; i++) {
5987 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5988 tmpFile.delete();
5989 }
5990 }
5991
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005992 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 File tmpPackageFile;
5994 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005995 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005997 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 return null;
5999 }
6000 try {
6001 FileUtils.setPermissions(
6002 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6003 -1, -1);
6004 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006005 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 return null;
6007 }
6008 return tmpPackageFile;
6009 }
6010
6011 public void deletePackage(final String packageName,
6012 final IPackageDeleteObserver observer,
6013 final int flags) {
6014 mContext.enforceCallingOrSelfPermission(
6015 android.Manifest.permission.DELETE_PACKAGES, null);
6016 // Queue up an async operation since the package deletion may take a little while.
6017 mHandler.post(new Runnable() {
6018 public void run() {
6019 mHandler.removeCallbacks(this);
6020 final boolean succeded = deletePackageX(packageName, true, true, flags);
6021 if (observer != null) {
6022 try {
6023 observer.packageDeleted(succeded);
6024 } catch (RemoteException e) {
6025 Log.i(TAG, "Observer no longer exists.");
6026 } //end catch
6027 } //end if
6028 } //end run
6029 });
6030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 /**
6033 * This method is an internal method that could be get invoked either
6034 * to delete an installed package or to clean up a failed installation.
6035 * After deleting an installed package, a broadcast is sent to notify any
6036 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006037 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 * installation wouldn't have sent the initial broadcast either
6039 * The key steps in deleting a package are
6040 * deleting the package information in internal structures like mPackages,
6041 * deleting the packages base directories through installd
6042 * updating mSettings to reflect current status
6043 * persisting settings for later use
6044 * sending a broadcast if necessary
6045 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6047 boolean deleteCodeAndResources, int flags) {
6048 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006049 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006051 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6052 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6053 try {
6054 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006055 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006056 return false;
6057 }
6058 } catch (RemoteException e) {
6059 }
6060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006062 res = deletePackageLI(packageName, deleteCodeAndResources,
6063 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006067 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07006068 info.sendBroadcast(deleteCodeAndResources, systemUpdate,
6069 new PackageRemovedIntentReceiver(info.args, deleteCodeAndResources));
Romain Guy96f43572009-03-24 20:27:49 -07006070
6071 // If the removed package was a system update, the old system packaged
6072 // was re-enabled; we need to broadcast this information
6073 if (systemUpdate) {
6074 Bundle extras = new Bundle(1);
6075 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6076 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6077
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006078 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6079 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 }
6082 return res;
6083 }
6084
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07006085 class PackageRemovedIntentReceiver extends IIntentReceiver.Stub {
6086 boolean deleteOld;
6087 InstallArgs args;
6088 PackageRemovedIntentReceiver(InstallArgs args, boolean deleteOld) {
6089 this.args = args;
6090 this.deleteOld = deleteOld;
6091 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07006092 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
6093 boolean ordered, boolean sticky) throws RemoteException {
6094 // Force a gc to clear up things
6095 Runtime.getRuntime().gc();
6096 // We delete after a gc for applications on sdcard.
6097 if (deleteOld && args != null) {
6098 synchronized (mInstallLock) {
6099 args.doPostDeleteLI(true);
6100 }
6101 }
6102 }
6103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 static class PackageRemovedInfo {
6105 String removedPackage;
6106 int uid = -1;
6107 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006108 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006109 // Clean up resources deleted packages.
6110 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006111
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07006112 void sendBroadcast(boolean fullRemove, boolean replacing,
6113 IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 Bundle extras = new Bundle(1);
6115 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6116 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6117 if (replacing) {
6118 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6119 }
6120 if (removedPackage != null) {
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07006121 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, finishedReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 }
6123 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006124 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 }
6126 }
6127 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 /*
6130 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6131 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006132 * 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 -08006133 * delete a partially installed application.
6134 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006135 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 int flags) {
6137 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006138 if (outInfo != null) {
6139 outInfo.removedPackage = packageName;
6140 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006141 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 // Retrieve object to delete permissions for shared user later on
6143 PackageSetting deletedPs;
6144 synchronized (mPackages) {
6145 deletedPs = mSettings.mPackages.get(packageName);
6146 }
6147 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6148 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006149 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006151 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 + packageName + ", retcode=" + retCode);
6153 // we don't consider this to be a failure of the core package deletion
6154 }
6155 } else {
6156 //for emulator
6157 PackageParser.Package pkg = mPackages.get(packageName);
6158 File dataDir = new File(pkg.applicationInfo.dataDir);
6159 dataDir.delete();
6160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 }
6162 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006163 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006164 schedulePackageCleaning(packageName);
6165
6166 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6167 if (outInfo != null) {
6168 outInfo.removedUid = mSettings.removePackageLP(packageName);
6169 }
6170 if (deletedPs != null) {
6171 updatePermissionsLP(deletedPs.name, null, false, false);
6172 if (deletedPs.sharedUser != null) {
6173 // remove permissions associated with package
6174 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6175 }
6176 }
6177 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006178 // remove from preferred activities.
6179 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6180 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6181 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6182 removed.add(pa);
6183 }
6184 }
6185 for (PreferredActivity pa : removed) {
6186 mSettings.mPreferredActivities.removeFilter(pa);
6187 }
6188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006190 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 }
6192 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 /*
6195 * Tries to delete system package.
6196 */
6197 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006198 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 ApplicationInfo applicationInfo = p.applicationInfo;
6200 //applicable for non-partially installed applications only
6201 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006202 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 return false;
6204 }
6205 PackageSetting ps = null;
6206 // Confirm if the system package has been updated
6207 // An updated system app can be deleted. This will also have to restore
6208 // the system pkg from system partition
6209 synchronized (mPackages) {
6210 ps = mSettings.getDisabledSystemPkg(p.packageName);
6211 }
6212 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006213 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 return false;
6215 } else {
6216 Log.i(TAG, "Deleting system pkg from data partition");
6217 }
6218 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006219 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006220 boolean deleteCodeAndResources = false;
6221 if (ps.versionCode < p.mVersionCode) {
6222 // Delete code and resources for downgrades
6223 deleteCodeAndResources = true;
6224 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6225 flags &= ~PackageManager.DONT_DELETE_DATA;
6226 }
6227 } else {
6228 // Preserve data by setting flag
6229 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6230 flags |= PackageManager.DONT_DELETE_DATA;
6231 }
6232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6234 if (!ret) {
6235 return false;
6236 }
6237 synchronized (mPackages) {
6238 // Reinstate the old system package
6239 mSettings.enableSystemPackageLP(p.packageName);
6240 }
6241 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006242 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006244 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006247 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 return false;
6249 }
6250 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006251 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 mSettings.writeLP();
6253 }
6254 return true;
6255 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6258 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6259 ApplicationInfo applicationInfo = p.applicationInfo;
6260 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006261 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 return false;
6263 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006264 if (outInfo != null) {
6265 outInfo.uid = applicationInfo.uid;
6266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267
6268 // Delete package data from internal structures and also remove data if flag is set
6269 removePackageDataLI(p, outInfo, flags);
6270
6271 // Delete application code and resources
6272 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006273 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006274 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006275 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006276 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6277 PackageManager.INSTALL_FORWARD_LOCK : 0;
6278 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006279 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 }
6281 return true;
6282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 /*
6285 * This method handles package deletion in general
6286 */
6287 private boolean deletePackageLI(String packageName,
6288 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6289 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006290 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 return false;
6292 }
6293 PackageParser.Package p;
6294 boolean dataOnly = false;
6295 synchronized (mPackages) {
6296 p = mPackages.get(packageName);
6297 if (p == null) {
6298 //this retrieves partially installed apps
6299 dataOnly = true;
6300 PackageSetting ps = mSettings.mPackages.get(packageName);
6301 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006302 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 return false;
6304 }
6305 p = ps.pkg;
6306 }
6307 }
6308 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006309 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 return false;
6311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 if (dataOnly) {
6314 // Delete application data first
6315 removePackageDataLI(p, outInfo, flags);
6316 return true;
6317 }
6318 // At this point the package should have ApplicationInfo associated with it
6319 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006320 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 return false;
6322 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006323 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6325 Log.i(TAG, "Removing system package:"+p.packageName);
6326 // When an updated system application is deleted we delete the existing resources as well and
6327 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006328 ret = deleteSystemPackageLI(p, flags, outInfo);
6329 } else {
6330 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006331 // Kill application pre-emptively especially for apps on sd.
6332 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006333 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006335 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 public void clearApplicationUserData(final String packageName,
6339 final IPackageDataObserver observer) {
6340 mContext.enforceCallingOrSelfPermission(
6341 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6342 // Queue up an async operation since the package deletion may take a little while.
6343 mHandler.post(new Runnable() {
6344 public void run() {
6345 mHandler.removeCallbacks(this);
6346 final boolean succeeded;
6347 synchronized (mInstallLock) {
6348 succeeded = clearApplicationUserDataLI(packageName);
6349 }
6350 if (succeeded) {
6351 // invoke DeviceStorageMonitor's update method to clear any notifications
6352 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6353 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6354 if (dsm != null) {
6355 dsm.updateMemory();
6356 }
6357 }
6358 if(observer != null) {
6359 try {
6360 observer.onRemoveCompleted(packageName, succeeded);
6361 } catch (RemoteException e) {
6362 Log.i(TAG, "Observer no longer exists.");
6363 }
6364 } //end if observer
6365 } //end run
6366 });
6367 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 private boolean clearApplicationUserDataLI(String packageName) {
6370 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006371 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 return false;
6373 }
6374 PackageParser.Package p;
6375 boolean dataOnly = false;
6376 synchronized (mPackages) {
6377 p = mPackages.get(packageName);
6378 if(p == null) {
6379 dataOnly = true;
6380 PackageSetting ps = mSettings.mPackages.get(packageName);
6381 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006382 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 return false;
6384 }
6385 p = ps.pkg;
6386 }
6387 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 if(!dataOnly) {
6390 //need to check this only for fully installed applications
6391 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006392 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 return false;
6394 }
6395 final ApplicationInfo applicationInfo = p.applicationInfo;
6396 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006397 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 return false;
6399 }
6400 }
6401 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006402 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006404 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 + packageName);
6406 return false;
6407 }
6408 }
6409 return true;
6410 }
6411
6412 public void deleteApplicationCacheFiles(final String packageName,
6413 final IPackageDataObserver observer) {
6414 mContext.enforceCallingOrSelfPermission(
6415 android.Manifest.permission.DELETE_CACHE_FILES, null);
6416 // Queue up an async operation since the package deletion may take a little while.
6417 mHandler.post(new Runnable() {
6418 public void run() {
6419 mHandler.removeCallbacks(this);
6420 final boolean succeded;
6421 synchronized (mInstallLock) {
6422 succeded = deleteApplicationCacheFilesLI(packageName);
6423 }
6424 if(observer != null) {
6425 try {
6426 observer.onRemoveCompleted(packageName, succeded);
6427 } catch (RemoteException e) {
6428 Log.i(TAG, "Observer no longer exists.");
6429 }
6430 } //end if observer
6431 } //end run
6432 });
6433 }
6434
6435 private boolean deleteApplicationCacheFilesLI(String packageName) {
6436 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006437 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 return false;
6439 }
6440 PackageParser.Package p;
6441 synchronized (mPackages) {
6442 p = mPackages.get(packageName);
6443 }
6444 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006445 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 return false;
6447 }
6448 final ApplicationInfo applicationInfo = p.applicationInfo;
6449 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006450 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 return false;
6452 }
6453 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006454 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006456 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 + packageName);
6458 return false;
6459 }
6460 }
6461 return true;
6462 }
6463
6464 public void getPackageSizeInfo(final String packageName,
6465 final IPackageStatsObserver observer) {
6466 mContext.enforceCallingOrSelfPermission(
6467 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6468 // Queue up an async operation since the package deletion may take a little while.
6469 mHandler.post(new Runnable() {
6470 public void run() {
6471 mHandler.removeCallbacks(this);
6472 PackageStats lStats = new PackageStats(packageName);
6473 final boolean succeded;
6474 synchronized (mInstallLock) {
6475 succeded = getPackageSizeInfoLI(packageName, lStats);
6476 }
6477 if(observer != null) {
6478 try {
6479 observer.onGetStatsCompleted(lStats, succeded);
6480 } catch (RemoteException e) {
6481 Log.i(TAG, "Observer no longer exists.");
6482 }
6483 } //end if observer
6484 } //end run
6485 });
6486 }
6487
6488 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6489 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006490 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 return false;
6492 }
6493 PackageParser.Package p;
6494 boolean dataOnly = false;
6495 synchronized (mPackages) {
6496 p = mPackages.get(packageName);
6497 if(p == null) {
6498 dataOnly = true;
6499 PackageSetting ps = mSettings.mPackages.get(packageName);
6500 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006501 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 return false;
6503 }
6504 p = ps.pkg;
6505 }
6506 }
6507 String publicSrcDir = null;
6508 if(!dataOnly) {
6509 final ApplicationInfo applicationInfo = p.applicationInfo;
6510 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006511 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 return false;
6513 }
6514 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6515 }
6516 if (mInstaller != null) {
6517 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006518 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 if (res < 0) {
6520 return false;
6521 } else {
6522 return true;
6523 }
6524 }
6525 return true;
6526 }
6527
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 public void addPackageToPreferred(String packageName) {
6530 mContext.enforceCallingOrSelfPermission(
6531 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006532 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 }
6534
6535 public void removePackageFromPreferred(String packageName) {
6536 mContext.enforceCallingOrSelfPermission(
6537 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006538 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 }
6540
6541 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006542 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 }
6544
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006545 int getUidTargetSdkVersionLockedLP(int uid) {
6546 Object obj = mSettings.getUserIdLP(uid);
6547 if (obj instanceof SharedUserSetting) {
6548 SharedUserSetting sus = (SharedUserSetting)obj;
6549 final int N = sus.packages.size();
6550 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6551 Iterator<PackageSetting> it = sus.packages.iterator();
6552 int i=0;
6553 while (it.hasNext()) {
6554 PackageSetting ps = it.next();
6555 if (ps.pkg != null) {
6556 int v = ps.pkg.applicationInfo.targetSdkVersion;
6557 if (v < vers) vers = v;
6558 }
6559 }
6560 return vers;
6561 } else if (obj instanceof PackageSetting) {
6562 PackageSetting ps = (PackageSetting)obj;
6563 if (ps.pkg != null) {
6564 return ps.pkg.applicationInfo.targetSdkVersion;
6565 }
6566 }
6567 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6568 }
6569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570 public void addPreferredActivity(IntentFilter filter, int match,
6571 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006573 if (mContext.checkCallingOrSelfPermission(
6574 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6575 != PackageManager.PERMISSION_GRANTED) {
6576 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6577 < Build.VERSION_CODES.FROYO) {
6578 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6579 + Binder.getCallingUid());
6580 return;
6581 }
6582 mContext.enforceCallingOrSelfPermission(
6583 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6584 }
6585
6586 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6588 mSettings.mPreferredActivities.addFilter(
6589 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006590 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591 }
6592 }
6593
Satish Sampath8dbe6122009-06-02 23:35:54 +01006594 public void replacePreferredActivity(IntentFilter filter, int match,
6595 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006596 if (filter.countActions() != 1) {
6597 throw new IllegalArgumentException(
6598 "replacePreferredActivity expects filter to have only 1 action.");
6599 }
6600 if (filter.countCategories() != 1) {
6601 throw new IllegalArgumentException(
6602 "replacePreferredActivity expects filter to have only 1 category.");
6603 }
6604 if (filter.countDataAuthorities() != 0
6605 || filter.countDataPaths() != 0
6606 || filter.countDataSchemes() != 0
6607 || filter.countDataTypes() != 0) {
6608 throw new IllegalArgumentException(
6609 "replacePreferredActivity expects filter to have no data authorities, " +
6610 "paths, schemes or types.");
6611 }
6612 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006613 if (mContext.checkCallingOrSelfPermission(
6614 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6615 != PackageManager.PERMISSION_GRANTED) {
6616 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6617 < Build.VERSION_CODES.FROYO) {
6618 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6619 + Binder.getCallingUid());
6620 return;
6621 }
6622 mContext.enforceCallingOrSelfPermission(
6623 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6624 }
6625
Satish Sampath8dbe6122009-06-02 23:35:54 +01006626 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6627 String action = filter.getAction(0);
6628 String category = filter.getCategory(0);
6629 while (it.hasNext()) {
6630 PreferredActivity pa = it.next();
6631 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6632 it.remove();
6633 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6634 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6635 }
6636 }
6637 addPreferredActivity(filter, match, set, activity);
6638 }
6639 }
6640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006643 int uid = Binder.getCallingUid();
6644 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006645 if (pkg == null || pkg.applicationInfo.uid != uid) {
6646 if (mContext.checkCallingOrSelfPermission(
6647 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6648 != PackageManager.PERMISSION_GRANTED) {
6649 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6650 < Build.VERSION_CODES.FROYO) {
6651 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6652 + Binder.getCallingUid());
6653 return;
6654 }
6655 mContext.enforceCallingOrSelfPermission(
6656 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6657 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006658 }
6659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006661 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 }
6663 }
6664 }
6665
6666 boolean clearPackagePreferredActivitiesLP(String packageName) {
6667 boolean changed = false;
6668 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6669 while (it.hasNext()) {
6670 PreferredActivity pa = it.next();
6671 if (pa.mActivity.getPackageName().equals(packageName)) {
6672 it.remove();
6673 changed = true;
6674 }
6675 }
6676 return changed;
6677 }
6678
6679 public int getPreferredActivities(List<IntentFilter> outFilters,
6680 List<ComponentName> outActivities, String packageName) {
6681
6682 int num = 0;
6683 synchronized (mPackages) {
6684 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6685 while (it.hasNext()) {
6686 PreferredActivity pa = it.next();
6687 if (packageName == null
6688 || pa.mActivity.getPackageName().equals(packageName)) {
6689 if (outFilters != null) {
6690 outFilters.add(new IntentFilter(pa));
6691 }
6692 if (outActivities != null) {
6693 outActivities.add(pa.mActivity);
6694 }
6695 }
6696 }
6697 }
6698
6699 return num;
6700 }
6701
6702 public void setApplicationEnabledSetting(String appPackageName,
6703 int newState, int flags) {
6704 setEnabledSetting(appPackageName, null, newState, flags);
6705 }
6706
6707 public void setComponentEnabledSetting(ComponentName componentName,
6708 int newState, int flags) {
6709 setEnabledSetting(componentName.getPackageName(),
6710 componentName.getClassName(), newState, flags);
6711 }
6712
6713 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006714 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6716 || newState == COMPONENT_ENABLED_STATE_ENABLED
6717 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6718 throw new IllegalArgumentException("Invalid new component state: "
6719 + newState);
6720 }
6721 PackageSetting pkgSetting;
6722 final int uid = Binder.getCallingUid();
6723 final int permission = mContext.checkCallingPermission(
6724 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6725 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006726 boolean sendNow = false;
6727 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006728 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006730 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006732 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006734 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006736 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 }
6738 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006739 "Unknown component: " + packageName
6740 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 }
6742 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6743 throw new SecurityException(
6744 "Permission Denial: attempt to change component state from pid="
6745 + Binder.getCallingPid()
6746 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6747 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006748 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006750 if (pkgSetting.enabled == newState) {
6751 // Nothing to do
6752 return;
6753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 pkgSetting.enabled = newState;
6755 } else {
6756 // We're dealing with a component level state change
6757 switch (newState) {
6758 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006759 if (!pkgSetting.enableComponentLP(className)) {
6760 return;
6761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006762 break;
6763 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006764 if (!pkgSetting.disableComponentLP(className)) {
6765 return;
6766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 break;
6768 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006769 if (!pkgSetting.restoreComponentLP(className)) {
6770 return;
6771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 break;
6773 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006774 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006775 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006776 }
6777 }
6778 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006779 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006780 components = mPendingBroadcasts.get(packageName);
6781 boolean newPackage = components == null;
6782 if (newPackage) {
6783 components = new ArrayList<String>();
6784 }
6785 if (!components.contains(componentName)) {
6786 components.add(componentName);
6787 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006788 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6789 sendNow = true;
6790 // Purge entry from pending broadcast list if another one exists already
6791 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006792 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006793 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006794 if (newPackage) {
6795 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006796 }
6797 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6798 // Schedule a message
6799 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6800 }
6801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006804 long callingId = Binder.clearCallingIdentity();
6805 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006806 if (sendNow) {
6807 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006808 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006810 } finally {
6811 Binder.restoreCallingIdentity(callingId);
6812 }
6813 }
6814
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006815 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006816 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6817 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6818 + " components=" + componentNames);
6819 Bundle extras = new Bundle(4);
6820 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6821 String nameList[] = new String[componentNames.size()];
6822 componentNames.toArray(nameList);
6823 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006824 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6825 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006826 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006827 }
6828
Jacek Surazski65e13172009-04-28 15:26:38 +02006829 public String getInstallerPackageName(String packageName) {
6830 synchronized (mPackages) {
6831 PackageSetting pkg = mSettings.mPackages.get(packageName);
6832 if (pkg == null) {
6833 throw new IllegalArgumentException("Unknown package: " + packageName);
6834 }
6835 return pkg.installerPackageName;
6836 }
6837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 public int getApplicationEnabledSetting(String appPackageName) {
6840 synchronized (mPackages) {
6841 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6842 if (pkg == null) {
6843 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6844 }
6845 return pkg.enabled;
6846 }
6847 }
6848
6849 public int getComponentEnabledSetting(ComponentName componentName) {
6850 synchronized (mPackages) {
6851 final String packageNameStr = componentName.getPackageName();
6852 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6853 if (pkg == null) {
6854 throw new IllegalArgumentException("Unknown component: " + componentName);
6855 }
6856 final String classNameStr = componentName.getClassName();
6857 return pkg.currentEnabledStateLP(classNameStr);
6858 }
6859 }
6860
6861 public void enterSafeMode() {
6862 if (!mSystemReady) {
6863 mSafeMode = true;
6864 }
6865 }
6866
6867 public void systemReady() {
6868 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006869
6870 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006871 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006872 mContext.getContentResolver(),
6873 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006874 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006875 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006876 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006878 }
6879
6880 public boolean isSafeMode() {
6881 return mSafeMode;
6882 }
6883
6884 public boolean hasSystemUidErrors() {
6885 return mHasSystemUidErrors;
6886 }
6887
6888 static String arrayToString(int[] array) {
6889 StringBuffer buf = new StringBuffer(128);
6890 buf.append('[');
6891 if (array != null) {
6892 for (int i=0; i<array.length; i++) {
6893 if (i > 0) buf.append(", ");
6894 buf.append(array[i]);
6895 }
6896 }
6897 buf.append(']');
6898 return buf.toString();
6899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 @Override
6902 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6903 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6904 != PackageManager.PERMISSION_GRANTED) {
6905 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6906 + Binder.getCallingPid()
6907 + ", uid=" + Binder.getCallingUid()
6908 + " without permission "
6909 + android.Manifest.permission.DUMP);
6910 return;
6911 }
6912
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006913 String packageName = null;
6914
6915 int opti = 0;
6916 while (opti < args.length) {
6917 String opt = args[opti];
6918 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6919 break;
6920 }
6921 opti++;
6922 if ("-a".equals(opt)) {
6923 // Right now we only know how to print all.
6924 } else if ("-h".equals(opt)) {
6925 pw.println("Package manager dump options:");
6926 pw.println(" [-h] [cmd] ...");
6927 pw.println(" cmd may be one of:");
6928 pw.println(" [package.name]: info about given package");
6929 return;
6930 } else {
6931 pw.println("Unknown argument: " + opt + "; use -h for help");
6932 }
6933 }
6934
6935 // Is the caller requesting to dump a particular piece of data?
6936 if (opti < args.length) {
6937 String cmd = args[opti];
6938 opti++;
6939 // Is this a package name?
6940 if ("android".equals(cmd) || cmd.contains(".")) {
6941 packageName = cmd;
6942 }
6943 }
6944
6945 boolean printedTitle = false;
6946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006948 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6949 printedTitle = true;
6950 }
6951 if (mReceivers.dump(pw, printedTitle
6952 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6953 " ", packageName)) {
6954 printedTitle = true;
6955 }
6956 if (mServices.dump(pw, printedTitle
6957 ? "\nService Resolver Table:" : "Service Resolver Table:",
6958 " ", packageName)) {
6959 printedTitle = true;
6960 }
6961 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6962 ? "\nPreferred Activities:" : "Preferred Activities:",
6963 " ", packageName)) {
6964 printedTitle = true;
6965 }
6966 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 {
6968 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006969 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6970 continue;
6971 }
6972 if (!printedSomething) {
6973 if (printedTitle) pw.println(" ");
6974 pw.println("Permissions:");
6975 printedSomething = true;
6976 printedTitle = true;
6977 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006978 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6979 pw.print(Integer.toHexString(System.identityHashCode(p)));
6980 pw.println("):");
6981 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6982 pw.print(" uid="); pw.print(p.uid);
6983 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006984 pw.print(" type="); pw.print(p.type);
6985 pw.print(" prot="); pw.println(p.protectionLevel);
6986 if (p.packageSetting != null) {
6987 pw.print(" packageSetting="); pw.println(p.packageSetting);
6988 }
6989 if (p.perm != null) {
6990 pw.print(" perm="); pw.println(p.perm);
6991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006992 }
6993 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006994 printedSomething = false;
6995 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 {
6997 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006998 if (packageName != null && !packageName.equals(ps.realName)
6999 && !packageName.equals(ps.name)) {
7000 continue;
7001 }
7002 if (!printedSomething) {
7003 if (printedTitle) pw.println(" ");
7004 pw.println("Packages:");
7005 printedSomething = true;
7006 printedTitle = true;
7007 }
7008 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007009 pw.print(" Package [");
7010 pw.print(ps.realName != null ? ps.realName : ps.name);
7011 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007012 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7013 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007014 if (ps.realName != null) {
7015 pw.print(" compat name="); pw.println(ps.name);
7016 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007017 pw.print(" userId="); pw.print(ps.userId);
7018 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7019 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7020 pw.print(" pkg="); pw.println(ps.pkg);
7021 pw.print(" codePath="); pw.println(ps.codePathString);
7022 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007023 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007024 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007025 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007026 pw.print(" supportsScreens=[");
7027 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007028 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007029 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007030 if (!first) pw.print(", ");
7031 first = false;
7032 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007033 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007034 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007035 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007036 if (!first) pw.print(", ");
7037 first = false;
7038 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007039 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007040 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007041 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007042 if (!first) pw.print(", ");
7043 first = false;
7044 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007045 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007046 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007047 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007048 if (!first) pw.print(", ");
7049 first = false;
7050 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007052 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007053 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7054 if (!first) pw.print(", ");
7055 first = false;
7056 pw.print("anyDensity");
7057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007059 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007060 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7061 pw.print(" signatures="); pw.println(ps.signatures);
7062 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007063 pw.print(" haveGids="); pw.println(ps.haveGids);
7064 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007065 pw.print(" installStatus="); pw.print(ps.installStatus);
7066 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007067 if (ps.disabledComponents.size() > 0) {
7068 pw.println(" disabledComponents:");
7069 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007070 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007071 }
7072 }
7073 if (ps.enabledComponents.size() > 0) {
7074 pw.println(" enabledComponents:");
7075 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007076 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 }
7078 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007079 if (ps.grantedPermissions.size() > 0) {
7080 pw.println(" grantedPermissions:");
7081 for (String s : ps.grantedPermissions) {
7082 pw.print(" "); pw.println(s);
7083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007085 }
7086 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007087 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007088 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007089 for (HashMap.Entry<String, String> e
7090 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007091 if (packageName != null && !packageName.equals(e.getKey())
7092 && !packageName.equals(e.getValue())) {
7093 continue;
7094 }
7095 if (!printedSomething) {
7096 if (printedTitle) pw.println(" ");
7097 pw.println("Renamed packages:");
7098 printedSomething = true;
7099 printedTitle = true;
7100 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007101 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7102 pw.println(e.getValue());
7103 }
7104 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007105 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007106 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007107 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007108 if (packageName != null && !packageName.equals(ps.realName)
7109 && !packageName.equals(ps.name)) {
7110 continue;
7111 }
7112 if (!printedSomething) {
7113 if (printedTitle) pw.println(" ");
7114 pw.println("Hidden system packages:");
7115 printedSomething = true;
7116 printedTitle = true;
7117 }
7118 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007119 pw.print(ps.realName != null ? ps.realName : ps.name);
7120 pw.print("] (");
7121 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7122 pw.println("):");
7123 if (ps.realName != null) {
7124 pw.print(" compat name="); pw.println(ps.name);
7125 }
7126 pw.print(" userId="); pw.println(ps.userId);
7127 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7128 pw.print(" codePath="); pw.println(ps.codePathString);
7129 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7130 }
7131 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007132 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007133 {
7134 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007135 if (packageName != null && su != packageSharedUser) {
7136 continue;
7137 }
7138 if (!printedSomething) {
7139 if (printedTitle) pw.println(" ");
7140 pw.println("Shared users:");
7141 printedSomething = true;
7142 printedTitle = true;
7143 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007144 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7145 pw.print(Integer.toHexString(System.identityHashCode(su)));
7146 pw.println("):");
7147 pw.print(" userId="); pw.print(su.userId);
7148 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 pw.println(" grantedPermissions:");
7150 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007151 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 }
7154 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007155
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007156 if (packageName == null) {
7157 if (printedTitle) pw.println(" ");
7158 printedTitle = true;
7159 pw.println("Settings parse messages:");
7160 pw.println(mSettings.mReadMessages.toString());
7161
7162 pw.println(" ");
7163 pw.println("Package warning messages:");
7164 File fname = getSettingsProblemFile();
7165 FileInputStream in;
7166 try {
7167 in = new FileInputStream(fname);
7168 int avail = in.available();
7169 byte[] data = new byte[avail];
7170 in.read(data);
7171 pw.println(new String(data));
7172 } catch (FileNotFoundException e) {
7173 } catch (IOException e) {
7174 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007177
7178 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007179 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007180 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007181 if (packageName != null && !packageName.equals(p.info.packageName)) {
7182 continue;
7183 }
7184 if (!printedSomething) {
7185 if (printedTitle) pw.println(" ");
7186 pw.println("Registered ContentProviders:");
7187 printedSomething = true;
7188 printedTitle = true;
7189 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007190 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007191 pw.println(p.toString());
7192 }
7193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007194 }
7195
7196 static final class BasePermission {
7197 final static int TYPE_NORMAL = 0;
7198 final static int TYPE_BUILTIN = 1;
7199 final static int TYPE_DYNAMIC = 2;
7200
7201 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007202 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007203 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007205 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007206 PackageParser.Permission perm;
7207 PermissionInfo pendingInfo;
7208 int uid;
7209 int[] gids;
7210
7211 BasePermission(String _name, String _sourcePackage, int _type) {
7212 name = _name;
7213 sourcePackage = _sourcePackage;
7214 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007215 // Default to most conservative protection level.
7216 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7217 }
7218
7219 public String toString() {
7220 return "BasePermission{"
7221 + Integer.toHexString(System.identityHashCode(this))
7222 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007223 }
7224 }
7225
7226 static class PackageSignatures {
7227 private Signature[] mSignatures;
7228
7229 PackageSignatures(Signature[] sigs) {
7230 assignSignatures(sigs);
7231 }
7232
7233 PackageSignatures() {
7234 }
7235
7236 void writeXml(XmlSerializer serializer, String tagName,
7237 ArrayList<Signature> pastSignatures) throws IOException {
7238 if (mSignatures == null) {
7239 return;
7240 }
7241 serializer.startTag(null, tagName);
7242 serializer.attribute(null, "count",
7243 Integer.toString(mSignatures.length));
7244 for (int i=0; i<mSignatures.length; i++) {
7245 serializer.startTag(null, "cert");
7246 final Signature sig = mSignatures[i];
7247 final int sigHash = sig.hashCode();
7248 final int numPast = pastSignatures.size();
7249 int j;
7250 for (j=0; j<numPast; j++) {
7251 Signature pastSig = pastSignatures.get(j);
7252 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7253 serializer.attribute(null, "index", Integer.toString(j));
7254 break;
7255 }
7256 }
7257 if (j >= numPast) {
7258 pastSignatures.add(sig);
7259 serializer.attribute(null, "index", Integer.toString(numPast));
7260 serializer.attribute(null, "key", sig.toCharsString());
7261 }
7262 serializer.endTag(null, "cert");
7263 }
7264 serializer.endTag(null, tagName);
7265 }
7266
7267 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7268 throws IOException, XmlPullParserException {
7269 String countStr = parser.getAttributeValue(null, "count");
7270 if (countStr == null) {
7271 reportSettingsProblem(Log.WARN,
7272 "Error in package manager settings: <signatures> has"
7273 + " no count at " + parser.getPositionDescription());
7274 XmlUtils.skipCurrentTag(parser);
7275 }
7276 final int count = Integer.parseInt(countStr);
7277 mSignatures = new Signature[count];
7278 int pos = 0;
7279
7280 int outerDepth = parser.getDepth();
7281 int type;
7282 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7283 && (type != XmlPullParser.END_TAG
7284 || parser.getDepth() > outerDepth)) {
7285 if (type == XmlPullParser.END_TAG
7286 || type == XmlPullParser.TEXT) {
7287 continue;
7288 }
7289
7290 String tagName = parser.getName();
7291 if (tagName.equals("cert")) {
7292 if (pos < count) {
7293 String index = parser.getAttributeValue(null, "index");
7294 if (index != null) {
7295 try {
7296 int idx = Integer.parseInt(index);
7297 String key = parser.getAttributeValue(null, "key");
7298 if (key == null) {
7299 if (idx >= 0 && idx < pastSignatures.size()) {
7300 Signature sig = pastSignatures.get(idx);
7301 if (sig != null) {
7302 mSignatures[pos] = pastSignatures.get(idx);
7303 pos++;
7304 } else {
7305 reportSettingsProblem(Log.WARN,
7306 "Error in package manager settings: <cert> "
7307 + "index " + index + " is not defined at "
7308 + parser.getPositionDescription());
7309 }
7310 } else {
7311 reportSettingsProblem(Log.WARN,
7312 "Error in package manager settings: <cert> "
7313 + "index " + index + " is out of bounds at "
7314 + parser.getPositionDescription());
7315 }
7316 } else {
7317 while (pastSignatures.size() <= idx) {
7318 pastSignatures.add(null);
7319 }
7320 Signature sig = new Signature(key);
7321 pastSignatures.set(idx, sig);
7322 mSignatures[pos] = sig;
7323 pos++;
7324 }
7325 } catch (NumberFormatException e) {
7326 reportSettingsProblem(Log.WARN,
7327 "Error in package manager settings: <cert> "
7328 + "index " + index + " is not a number at "
7329 + parser.getPositionDescription());
7330 }
7331 } else {
7332 reportSettingsProblem(Log.WARN,
7333 "Error in package manager settings: <cert> has"
7334 + " no index at " + parser.getPositionDescription());
7335 }
7336 } else {
7337 reportSettingsProblem(Log.WARN,
7338 "Error in package manager settings: too "
7339 + "many <cert> tags, expected " + count
7340 + " at " + parser.getPositionDescription());
7341 }
7342 } else {
7343 reportSettingsProblem(Log.WARN,
7344 "Unknown element under <cert>: "
7345 + parser.getName());
7346 }
7347 XmlUtils.skipCurrentTag(parser);
7348 }
7349
7350 if (pos < count) {
7351 // Should never happen -- there is an error in the written
7352 // settings -- but if it does we don't want to generate
7353 // a bad array.
7354 Signature[] newSigs = new Signature[pos];
7355 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7356 mSignatures = newSigs;
7357 }
7358 }
7359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 private void assignSignatures(Signature[] sigs) {
7361 if (sigs == null) {
7362 mSignatures = null;
7363 return;
7364 }
7365 mSignatures = new Signature[sigs.length];
7366 for (int i=0; i<sigs.length; i++) {
7367 mSignatures[i] = sigs[i];
7368 }
7369 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 @Override
7372 public String toString() {
7373 StringBuffer buf = new StringBuffer(128);
7374 buf.append("PackageSignatures{");
7375 buf.append(Integer.toHexString(System.identityHashCode(this)));
7376 buf.append(" [");
7377 if (mSignatures != null) {
7378 for (int i=0; i<mSignatures.length; i++) {
7379 if (i > 0) buf.append(", ");
7380 buf.append(Integer.toHexString(
7381 System.identityHashCode(mSignatures[i])));
7382 }
7383 }
7384 buf.append("]}");
7385 return buf.toString();
7386 }
7387 }
7388
7389 static class PreferredActivity extends IntentFilter {
7390 final int mMatch;
7391 final String[] mSetPackages;
7392 final String[] mSetClasses;
7393 final String[] mSetComponents;
7394 final ComponentName mActivity;
7395 final String mShortActivity;
7396 String mParseError;
7397
7398 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7399 ComponentName activity) {
7400 super(filter);
7401 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7402 mActivity = activity;
7403 mShortActivity = activity.flattenToShortString();
7404 mParseError = null;
7405 if (set != null) {
7406 final int N = set.length;
7407 String[] myPackages = new String[N];
7408 String[] myClasses = new String[N];
7409 String[] myComponents = new String[N];
7410 for (int i=0; i<N; i++) {
7411 ComponentName cn = set[i];
7412 if (cn == null) {
7413 mSetPackages = null;
7414 mSetClasses = null;
7415 mSetComponents = null;
7416 return;
7417 }
7418 myPackages[i] = cn.getPackageName().intern();
7419 myClasses[i] = cn.getClassName().intern();
7420 myComponents[i] = cn.flattenToShortString().intern();
7421 }
7422 mSetPackages = myPackages;
7423 mSetClasses = myClasses;
7424 mSetComponents = myComponents;
7425 } else {
7426 mSetPackages = null;
7427 mSetClasses = null;
7428 mSetComponents = null;
7429 }
7430 }
7431
7432 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7433 IOException {
7434 mShortActivity = parser.getAttributeValue(null, "name");
7435 mActivity = ComponentName.unflattenFromString(mShortActivity);
7436 if (mActivity == null) {
7437 mParseError = "Bad activity name " + mShortActivity;
7438 }
7439 String matchStr = parser.getAttributeValue(null, "match");
7440 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7441 String setCountStr = parser.getAttributeValue(null, "set");
7442 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7443
7444 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7445 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7446 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7447
7448 int setPos = 0;
7449
7450 int outerDepth = parser.getDepth();
7451 int type;
7452 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7453 && (type != XmlPullParser.END_TAG
7454 || parser.getDepth() > outerDepth)) {
7455 if (type == XmlPullParser.END_TAG
7456 || type == XmlPullParser.TEXT) {
7457 continue;
7458 }
7459
7460 String tagName = parser.getName();
7461 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7462 // + parser.getDepth() + " tag=" + tagName);
7463 if (tagName.equals("set")) {
7464 String name = parser.getAttributeValue(null, "name");
7465 if (name == null) {
7466 if (mParseError == null) {
7467 mParseError = "No name in set tag in preferred activity "
7468 + mShortActivity;
7469 }
7470 } else if (setPos >= setCount) {
7471 if (mParseError == null) {
7472 mParseError = "Too many set tags in preferred activity "
7473 + mShortActivity;
7474 }
7475 } else {
7476 ComponentName cn = ComponentName.unflattenFromString(name);
7477 if (cn == null) {
7478 if (mParseError == null) {
7479 mParseError = "Bad set name " + name + " in preferred activity "
7480 + mShortActivity;
7481 }
7482 } else {
7483 myPackages[setPos] = cn.getPackageName();
7484 myClasses[setPos] = cn.getClassName();
7485 myComponents[setPos] = name;
7486 setPos++;
7487 }
7488 }
7489 XmlUtils.skipCurrentTag(parser);
7490 } else if (tagName.equals("filter")) {
7491 //Log.i(TAG, "Starting to parse filter...");
7492 readFromXml(parser);
7493 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7494 // + parser.getDepth() + " tag=" + parser.getName());
7495 } else {
7496 reportSettingsProblem(Log.WARN,
7497 "Unknown element under <preferred-activities>: "
7498 + parser.getName());
7499 XmlUtils.skipCurrentTag(parser);
7500 }
7501 }
7502
7503 if (setPos != setCount) {
7504 if (mParseError == null) {
7505 mParseError = "Not enough set tags (expected " + setCount
7506 + " but found " + setPos + ") in " + mShortActivity;
7507 }
7508 }
7509
7510 mSetPackages = myPackages;
7511 mSetClasses = myClasses;
7512 mSetComponents = myComponents;
7513 }
7514
7515 public void writeToXml(XmlSerializer serializer) throws IOException {
7516 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7517 serializer.attribute(null, "name", mShortActivity);
7518 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7519 serializer.attribute(null, "set", Integer.toString(NS));
7520 for (int s=0; s<NS; s++) {
7521 serializer.startTag(null, "set");
7522 serializer.attribute(null, "name", mSetComponents[s]);
7523 serializer.endTag(null, "set");
7524 }
7525 serializer.startTag(null, "filter");
7526 super.writeToXml(serializer);
7527 serializer.endTag(null, "filter");
7528 }
7529
7530 boolean sameSet(List<ResolveInfo> query, int priority) {
7531 if (mSetPackages == null) return false;
7532 final int NQ = query.size();
7533 final int NS = mSetPackages.length;
7534 int numMatch = 0;
7535 for (int i=0; i<NQ; i++) {
7536 ResolveInfo ri = query.get(i);
7537 if (ri.priority != priority) continue;
7538 ActivityInfo ai = ri.activityInfo;
7539 boolean good = false;
7540 for (int j=0; j<NS; j++) {
7541 if (mSetPackages[j].equals(ai.packageName)
7542 && mSetClasses[j].equals(ai.name)) {
7543 numMatch++;
7544 good = true;
7545 break;
7546 }
7547 }
7548 if (!good) return false;
7549 }
7550 return numMatch == NS;
7551 }
7552 }
7553
7554 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007555 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557 HashSet<String> grantedPermissions = new HashSet<String>();
7558 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007561 setFlags(pkgFlags);
7562 }
7563
7564 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007565 this.pkgFlags = pkgFlags & (
7566 ApplicationInfo.FLAG_SYSTEM |
7567 ApplicationInfo.FLAG_FORWARD_LOCK |
7568 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 }
7570 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007572 /**
7573 * Settings base class for pending and resolved classes.
7574 */
7575 static class PackageSettingBase extends GrantedPermissions {
7576 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007577 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007578 File codePath;
7579 String codePathString;
7580 File resourcePath;
7581 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 private long timeStamp;
7583 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007584 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007586 boolean uidError;
7587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 PackageSignatures signatures = new PackageSignatures();
7589
7590 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007591 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007593 /* Explicitly disabled components */
7594 HashSet<String> disabledComponents = new HashSet<String>(0);
7595 /* Explicitly enabled components */
7596 HashSet<String> enabledComponents = new HashSet<String>(0);
7597 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7598 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007599
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007600 PackageSettingBase origPackage;
7601
Jacek Surazski65e13172009-04-28 15:26:38 +02007602 /* package name of the app that installed this package */
7603 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007605 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007606 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607 super(pkgFlags);
7608 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007609 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007610 init(codePath, resourcePath, pVersionCode);
7611 }
7612
7613 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 this.codePath = codePath;
7615 this.codePathString = codePath.toString();
7616 this.resourcePath = resourcePath;
7617 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007618 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007620
Jacek Surazski65e13172009-04-28 15:26:38 +02007621 public void setInstallerPackageName(String packageName) {
7622 installerPackageName = packageName;
7623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007624
Jacek Surazski65e13172009-04-28 15:26:38 +02007625 String getInstallerPackageName() {
7626 return installerPackageName;
7627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 public void setInstallStatus(int newStatus) {
7630 installStatus = newStatus;
7631 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 public int getInstallStatus() {
7634 return installStatus;
7635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 public void setTimeStamp(long newStamp) {
7638 if (newStamp != timeStamp) {
7639 timeStamp = newStamp;
7640 timeStampString = Long.toString(newStamp);
7641 }
7642 }
7643
7644 public void setTimeStamp(long newStamp, String newStampStr) {
7645 timeStamp = newStamp;
7646 timeStampString = newStampStr;
7647 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 public long getTimeStamp() {
7650 return timeStamp;
7651 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 public String getTimeStampStr() {
7654 return timeStampString;
7655 }
7656
7657 public void copyFrom(PackageSettingBase base) {
7658 grantedPermissions = base.grantedPermissions;
7659 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 timeStamp = base.timeStamp;
7662 timeStampString = base.timeStampString;
7663 signatures = base.signatures;
7664 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007665 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 disabledComponents = base.disabledComponents;
7667 enabledComponents = base.enabledComponents;
7668 enabled = base.enabled;
7669 installStatus = base.installStatus;
7670 }
7671
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007672 boolean enableComponentLP(String componentClassName) {
7673 boolean changed = disabledComponents.remove(componentClassName);
7674 changed |= enabledComponents.add(componentClassName);
7675 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007676 }
7677
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007678 boolean disableComponentLP(String componentClassName) {
7679 boolean changed = enabledComponents.remove(componentClassName);
7680 changed |= disabledComponents.add(componentClassName);
7681 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 }
7683
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007684 boolean restoreComponentLP(String componentClassName) {
7685 boolean changed = enabledComponents.remove(componentClassName);
7686 changed |= disabledComponents.remove(componentClassName);
7687 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 }
7689
7690 int currentEnabledStateLP(String componentName) {
7691 if (enabledComponents.contains(componentName)) {
7692 return COMPONENT_ENABLED_STATE_ENABLED;
7693 } else if (disabledComponents.contains(componentName)) {
7694 return COMPONENT_ENABLED_STATE_DISABLED;
7695 } else {
7696 return COMPONENT_ENABLED_STATE_DEFAULT;
7697 }
7698 }
7699 }
7700
7701 /**
7702 * Settings data for a particular package we know about.
7703 */
7704 static final class PackageSetting extends PackageSettingBase {
7705 int userId;
7706 PackageParser.Package pkg;
7707 SharedUserSetting sharedUser;
7708
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007709 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007710 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007711 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 @Override
7715 public String toString() {
7716 return "PackageSetting{"
7717 + Integer.toHexString(System.identityHashCode(this))
7718 + " " + name + "/" + userId + "}";
7719 }
7720 }
7721
7722 /**
7723 * Settings data for a particular shared user ID we know about.
7724 */
7725 static final class SharedUserSetting extends GrantedPermissions {
7726 final String name;
7727 int userId;
7728 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7729 final PackageSignatures signatures = new PackageSignatures();
7730
7731 SharedUserSetting(String _name, int _pkgFlags) {
7732 super(_pkgFlags);
7733 name = _name;
7734 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 @Override
7737 public String toString() {
7738 return "SharedUserSetting{"
7739 + Integer.toHexString(System.identityHashCode(this))
7740 + " " + name + "/" + userId + "}";
7741 }
7742 }
7743
7744 /**
7745 * Holds information about dynamic settings.
7746 */
7747 private static final class Settings {
7748 private final File mSettingsFilename;
7749 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007750 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007751 private final HashMap<String, PackageSetting> mPackages =
7752 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 // List of replaced system applications
7754 final HashMap<String, PackageSetting> mDisabledSysPackages =
7755 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007756
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007757 // These are the last platform API version we were using for
7758 // the apps installed on internal and external storage. It is
7759 // used to grant newer permissions one time during a system upgrade.
7760 int mInternalSdkPlatform;
7761 int mExternalSdkPlatform;
7762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 // The user's preferred activities associated with particular intent
7764 // filters.
7765 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7766 new IntentResolver<PreferredActivity, PreferredActivity>() {
7767 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007768 protected String packageForFilter(PreferredActivity filter) {
7769 return filter.mActivity.getPackageName();
7770 }
7771 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007772 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007774 out.print(prefix); out.print(
7775 Integer.toHexString(System.identityHashCode(filter)));
7776 out.print(' ');
7777 out.print(filter.mActivity.flattenToShortString());
7778 out.print(" match=0x");
7779 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007781 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007782 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007783 out.print(prefix); out.print(" ");
7784 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 }
7786 }
7787 }
7788 };
7789 private final HashMap<String, SharedUserSetting> mSharedUsers =
7790 new HashMap<String, SharedUserSetting>();
7791 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7792 private final SparseArray<Object> mOtherUserIds =
7793 new SparseArray<Object>();
7794
7795 // For reading/writing settings file.
7796 private final ArrayList<Signature> mPastSignatures =
7797 new ArrayList<Signature>();
7798
7799 // Mapping from permission names to info about them.
7800 final HashMap<String, BasePermission> mPermissions =
7801 new HashMap<String, BasePermission>();
7802
7803 // Mapping from permission tree names to info about them.
7804 final HashMap<String, BasePermission> mPermissionTrees =
7805 new HashMap<String, BasePermission>();
7806
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007807 // Packages that have been uninstalled and still need their external
7808 // storage data deleted.
7809 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7810
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007811 // Packages that have been renamed since they were first installed.
7812 // Keys are the new names of the packages, values are the original
7813 // names. The packages appear everwhere else under their original
7814 // names.
7815 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 private final StringBuilder mReadMessages = new StringBuilder();
7818
7819 private static final class PendingPackage extends PackageSettingBase {
7820 final int sharedId;
7821
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007822 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007823 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007824 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825 this.sharedId = sharedId;
7826 }
7827 }
7828 private final ArrayList<PendingPackage> mPendingPackages
7829 = new ArrayList<PendingPackage>();
7830
7831 Settings() {
7832 File dataDir = Environment.getDataDirectory();
7833 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007834 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007835 systemDir.mkdirs();
7836 FileUtils.setPermissions(systemDir.toString(),
7837 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7838 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7839 -1, -1);
7840 mSettingsFilename = new File(systemDir, "packages.xml");
7841 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007842 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 }
7844
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007845 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007846 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 int pkgFlags, boolean create, boolean add) {
7848 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007849 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007850 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 return p;
7852 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007853
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007854 PackageSetting peekPackageLP(String name) {
7855 return mPackages.get(name);
7856 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 PackageSetting p = mPackages.get(name);
7858 if (p != null && p.codePath.getPath().equals(codePath)) {
7859 return p;
7860 }
7861 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007862 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007865 void setInstallStatus(String pkgName, int status) {
7866 PackageSetting p = mPackages.get(pkgName);
7867 if(p != null) {
7868 if(p.getInstallStatus() != status) {
7869 p.setInstallStatus(status);
7870 }
7871 }
7872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007873
Jacek Surazski65e13172009-04-28 15:26:38 +02007874 void setInstallerPackageName(String pkgName,
7875 String installerPkgName) {
7876 PackageSetting p = mPackages.get(pkgName);
7877 if(p != null) {
7878 p.setInstallerPackageName(installerPkgName);
7879 }
7880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007881
Jacek Surazski65e13172009-04-28 15:26:38 +02007882 String getInstallerPackageName(String pkgName) {
7883 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007884 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007885 }
7886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 int getInstallStatus(String pkgName) {
7888 PackageSetting p = mPackages.get(pkgName);
7889 if(p != null) {
7890 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 return -1;
7893 }
7894
7895 SharedUserSetting getSharedUserLP(String name,
7896 int pkgFlags, boolean create) {
7897 SharedUserSetting s = mSharedUsers.get(name);
7898 if (s == null) {
7899 if (!create) {
7900 return null;
7901 }
7902 s = new SharedUserSetting(name, pkgFlags);
7903 if (MULTIPLE_APPLICATION_UIDS) {
7904 s.userId = newUserIdLP(s);
7905 } else {
7906 s.userId = FIRST_APPLICATION_UID;
7907 }
7908 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7909 // < 0 means we couldn't assign a userid; fall out and return
7910 // s, which is currently null
7911 if (s.userId >= 0) {
7912 mSharedUsers.put(name, s);
7913 }
7914 }
7915
7916 return s;
7917 }
7918
7919 int disableSystemPackageLP(String name) {
7920 PackageSetting p = mPackages.get(name);
7921 if(p == null) {
7922 Log.w(TAG, "Package:"+name+" is not an installed package");
7923 return -1;
7924 }
7925 PackageSetting dp = mDisabledSysPackages.get(name);
7926 // always make sure the system package code and resource paths dont change
7927 if(dp == null) {
7928 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7929 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7930 }
7931 mDisabledSysPackages.put(name, p);
7932 }
7933 return removePackageLP(name);
7934 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 PackageSetting enableSystemPackageLP(String name) {
7937 PackageSetting p = mDisabledSysPackages.get(name);
7938 if(p == null) {
7939 Log.w(TAG, "Package:"+name+" is not disabled");
7940 return null;
7941 }
7942 // Reset flag in ApplicationInfo object
7943 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7944 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7945 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007946 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007947 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007948 mDisabledSysPackages.remove(name);
7949 return ret;
7950 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007951
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007952 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007953 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007954 PackageSetting p = mPackages.get(name);
7955 if (p != null) {
7956 if (p.userId == uid) {
7957 return p;
7958 }
7959 reportSettingsProblem(Log.ERROR,
7960 "Adding duplicate package, keeping first: " + name);
7961 return null;
7962 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007963 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007964 p.userId = uid;
7965 if (addUserIdLP(uid, p, name)) {
7966 mPackages.put(name, p);
7967 return p;
7968 }
7969 return null;
7970 }
7971
7972 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7973 SharedUserSetting s = mSharedUsers.get(name);
7974 if (s != null) {
7975 if (s.userId == uid) {
7976 return s;
7977 }
7978 reportSettingsProblem(Log.ERROR,
7979 "Adding duplicate shared user, keeping first: " + name);
7980 return null;
7981 }
7982 s = new SharedUserSetting(name, pkgFlags);
7983 s.userId = uid;
7984 if (addUserIdLP(uid, s, name)) {
7985 mSharedUsers.put(name, s);
7986 return s;
7987 }
7988 return null;
7989 }
7990
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007991 // Transfer ownership of permissions from one package to another.
7992 private void transferPermissions(String origPkg, String newPkg) {
7993 // Transfer ownership of permissions to the new package.
7994 for (int i=0; i<2; i++) {
7995 HashMap<String, BasePermission> permissions =
7996 i == 0 ? mPermissionTrees : mPermissions;
7997 for (BasePermission bp : permissions.values()) {
7998 if (origPkg.equals(bp.sourcePackage)) {
7999 if (DEBUG_UPGRADE) Log.v(TAG,
8000 "Moving permission " + bp.name
8001 + " from pkg " + bp.sourcePackage
8002 + " to " + newPkg);
8003 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008004 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008005 bp.perm = null;
8006 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008007 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008008 }
8009 bp.uid = 0;
8010 bp.gids = null;
8011 }
8012 }
8013 }
8014 }
8015
8016 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008017 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008018 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008019 PackageSetting p = mPackages.get(name);
8020 if (p != null) {
8021 if (!p.codePath.equals(codePath)) {
8022 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008023 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008024 // This is an updated system app with versions in both system
8025 // and data partition. Just let the most recent version
8026 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008027 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008028 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008029 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008030 // Just a change in the code path is not an issue, but
8031 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008032 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008033 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008035 }
8036 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 reportSettingsProblem(Log.WARN,
8038 "Package " + name + " shared user changed from "
8039 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8040 + " to "
8041 + (sharedUser != null ? sharedUser.name : "<nothing>")
8042 + "; replacing with new");
8043 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008044 } else {
8045 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8046 // If what we are scanning is a system package, then
8047 // make it so, regardless of whether it was previously
8048 // installed only in the data partition.
8049 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 }
8052 }
8053 if (p == null) {
8054 // Create a new PackageSettings entry. this can end up here because
8055 // of code path mismatch or user id mismatch of an updated system partition
8056 if (!create) {
8057 return null;
8058 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008059 if (origPackage != null) {
8060 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008061 p = new PackageSetting(origPackage.name, name, codePath,
8062 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008063 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8064 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008065 // Note that we will retain the new package's signature so
8066 // that we can keep its data.
8067 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008068 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008069 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008070 p.sharedUser = origPackage.sharedUser;
8071 p.userId = origPackage.userId;
8072 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008073 mRenamedPackages.put(name, origPackage.name);
8074 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008075 // Update new package state.
8076 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008078 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008079 p.setTimeStamp(codePath.lastModified());
8080 p.sharedUser = sharedUser;
8081 if (sharedUser != null) {
8082 p.userId = sharedUser.userId;
8083 } else if (MULTIPLE_APPLICATION_UIDS) {
8084 // Clone the setting here for disabled system packages
8085 PackageSetting dis = mDisabledSysPackages.get(name);
8086 if (dis != null) {
8087 // For disabled packages a new setting is created
8088 // from the existing user id. This still has to be
8089 // added to list of user id's
8090 // Copy signatures from previous setting
8091 if (dis.signatures.mSignatures != null) {
8092 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8093 }
8094 p.userId = dis.userId;
8095 // Clone permissions
8096 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008097 // Clone component info
8098 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8099 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8100 // Add new setting to list of user ids
8101 addUserIdLP(p.userId, p, name);
8102 } else {
8103 // Assign new user id
8104 p.userId = newUserIdLP(p);
8105 }
8106 } else {
8107 p.userId = FIRST_APPLICATION_UID;
8108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 }
8110 if (p.userId < 0) {
8111 reportSettingsProblem(Log.WARN,
8112 "Package " + name + " could not be assigned a valid uid");
8113 return null;
8114 }
8115 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008116 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008118 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008119 }
8120 }
8121 return p;
8122 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008123
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008124 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008125 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008126 String codePath = pkg.applicationInfo.sourceDir;
8127 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008128 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008129 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008130 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008131 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008132 p.codePath = new File(codePath);
8133 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008134 }
8135 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008136 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008137 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008138 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008139 p.resourcePath = new File(resourcePath);
8140 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008141 }
8142 // Update version code if needed
8143 if (pkg.mVersionCode != p.versionCode) {
8144 p.versionCode = pkg.mVersionCode;
8145 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008146 // Update signatures if needed.
8147 if (p.signatures.mSignatures == null) {
8148 p.signatures.assignSignatures(pkg.mSignatures);
8149 }
8150 // If this app defines a shared user id initialize
8151 // the shared user signatures as well.
8152 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8153 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8154 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008155 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8156 }
8157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 // Utility method that adds a PackageSetting to mPackages and
8159 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008160 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008161 SharedUserSetting sharedUser) {
8162 mPackages.put(name, p);
8163 if (sharedUser != null) {
8164 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8165 reportSettingsProblem(Log.ERROR,
8166 "Package " + p.name + " was user "
8167 + p.sharedUser + " but is now " + sharedUser
8168 + "; I am not changing its files so it will probably fail!");
8169 p.sharedUser.packages.remove(p);
8170 } else if (p.userId != sharedUser.userId) {
8171 reportSettingsProblem(Log.ERROR,
8172 "Package " + p.name + " was user id " + p.userId
8173 + " but is now user " + sharedUser
8174 + " with id " + sharedUser.userId
8175 + "; I am not changing its files so it will probably fail!");
8176 }
8177
8178 sharedUser.packages.add(p);
8179 p.sharedUser = sharedUser;
8180 p.userId = sharedUser.userId;
8181 }
8182 }
8183
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008184 /*
8185 * Update the shared user setting when a package using
8186 * specifying the shared user id is removed. The gids
8187 * associated with each permission of the deleted package
8188 * are removed from the shared user's gid list only if its
8189 * not in use by other permissions of packages in the
8190 * shared user setting.
8191 */
8192 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008194 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008195 return;
8196 }
8197 // No sharedUserId
8198 if (deletedPs.sharedUser == null) {
8199 return;
8200 }
8201 SharedUserSetting sus = deletedPs.sharedUser;
8202 // Update permissions
8203 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8204 boolean used = false;
8205 if (!sus.grantedPermissions.contains (eachPerm)) {
8206 continue;
8207 }
8208 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008209 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008210 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008211 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008212 used = true;
8213 break;
8214 }
8215 }
8216 if (!used) {
8217 // can safely delete this permission from list
8218 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008219 }
8220 }
8221 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008222 int newGids[] = globalGids;
8223 for (String eachPerm : sus.grantedPermissions) {
8224 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008225 if (bp != null) {
8226 newGids = appendInts(newGids, bp.gids);
8227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 }
8229 sus.gids = newGids;
8230 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232 private int removePackageLP(String name) {
8233 PackageSetting p = mPackages.get(name);
8234 if (p != null) {
8235 mPackages.remove(name);
8236 if (p.sharedUser != null) {
8237 p.sharedUser.packages.remove(p);
8238 if (p.sharedUser.packages.size() == 0) {
8239 mSharedUsers.remove(p.sharedUser.name);
8240 removeUserIdLP(p.sharedUser.userId);
8241 return p.sharedUser.userId;
8242 }
8243 } else {
8244 removeUserIdLP(p.userId);
8245 return p.userId;
8246 }
8247 }
8248 return -1;
8249 }
8250
8251 private boolean addUserIdLP(int uid, Object obj, Object name) {
8252 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8253 return false;
8254 }
8255
8256 if (uid >= FIRST_APPLICATION_UID) {
8257 int N = mUserIds.size();
8258 final int index = uid - FIRST_APPLICATION_UID;
8259 while (index >= N) {
8260 mUserIds.add(null);
8261 N++;
8262 }
8263 if (mUserIds.get(index) != null) {
8264 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008265 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008266 + " name=" + name);
8267 return false;
8268 }
8269 mUserIds.set(index, obj);
8270 } else {
8271 if (mOtherUserIds.get(uid) != null) {
8272 reportSettingsProblem(Log.ERROR,
8273 "Adding duplicate shared id: " + uid
8274 + " name=" + name);
8275 return false;
8276 }
8277 mOtherUserIds.put(uid, obj);
8278 }
8279 return true;
8280 }
8281
8282 public Object getUserIdLP(int uid) {
8283 if (uid >= FIRST_APPLICATION_UID) {
8284 int N = mUserIds.size();
8285 final int index = uid - FIRST_APPLICATION_UID;
8286 return index < N ? mUserIds.get(index) : null;
8287 } else {
8288 return mOtherUserIds.get(uid);
8289 }
8290 }
8291
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008292 private Set<String> findPackagesWithFlag(int flag) {
8293 Set<String> ret = new HashSet<String>();
8294 for (PackageSetting ps : mPackages.values()) {
8295 // Has to match atleast all the flag bits set on flag
8296 if ((ps.pkgFlags & flag) == flag) {
8297 ret.add(ps.name);
8298 }
8299 }
8300 return ret;
8301 }
8302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008303 private void removeUserIdLP(int uid) {
8304 if (uid >= FIRST_APPLICATION_UID) {
8305 int N = mUserIds.size();
8306 final int index = uid - FIRST_APPLICATION_UID;
8307 if (index < N) mUserIds.set(index, null);
8308 } else {
8309 mOtherUserIds.remove(uid);
8310 }
8311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008313 void writeLP() {
8314 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8315
8316 // Keep the old settings around until we know the new ones have
8317 // been successfully written.
8318 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008319 // Presence of backup settings file indicates that we failed
8320 // to persist settings earlier. So preserve the older
8321 // backup for future reference since the current settings
8322 // might have been corrupted.
8323 if (!mBackupSettingsFilename.exists()) {
8324 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008325 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008326 return;
8327 }
8328 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008329 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008330 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008332 }
8333
8334 mPastSignatures.clear();
8335
8336 try {
8337 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8338
8339 //XmlSerializer serializer = XmlUtils.serializerInstance();
8340 XmlSerializer serializer = new FastXmlSerializer();
8341 serializer.setOutput(str, "utf-8");
8342 serializer.startDocument(null, true);
8343 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8344
8345 serializer.startTag(null, "packages");
8346
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008347 serializer.startTag(null, "last-platform-version");
8348 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8349 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8350 serializer.endTag(null, "last-platform-version");
8351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 serializer.startTag(null, "permission-trees");
8353 for (BasePermission bp : mPermissionTrees.values()) {
8354 writePermission(serializer, bp);
8355 }
8356 serializer.endTag(null, "permission-trees");
8357
8358 serializer.startTag(null, "permissions");
8359 for (BasePermission bp : mPermissions.values()) {
8360 writePermission(serializer, bp);
8361 }
8362 serializer.endTag(null, "permissions");
8363
8364 for (PackageSetting pkg : mPackages.values()) {
8365 writePackage(serializer, pkg);
8366 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008368 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8369 writeDisabledSysPackage(serializer, pkg);
8370 }
8371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008372 serializer.startTag(null, "preferred-activities");
8373 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8374 serializer.startTag(null, "item");
8375 pa.writeToXml(serializer);
8376 serializer.endTag(null, "item");
8377 }
8378 serializer.endTag(null, "preferred-activities");
8379
8380 for (SharedUserSetting usr : mSharedUsers.values()) {
8381 serializer.startTag(null, "shared-user");
8382 serializer.attribute(null, "name", usr.name);
8383 serializer.attribute(null, "userId",
8384 Integer.toString(usr.userId));
8385 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8386 serializer.startTag(null, "perms");
8387 for (String name : usr.grantedPermissions) {
8388 serializer.startTag(null, "item");
8389 serializer.attribute(null, "name", name);
8390 serializer.endTag(null, "item");
8391 }
8392 serializer.endTag(null, "perms");
8393 serializer.endTag(null, "shared-user");
8394 }
8395
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008396 if (mPackagesToBeCleaned.size() > 0) {
8397 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8398 serializer.startTag(null, "cleaning-package");
8399 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8400 serializer.endTag(null, "cleaning-package");
8401 }
8402 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008403
8404 if (mRenamedPackages.size() > 0) {
8405 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8406 serializer.startTag(null, "renamed-package");
8407 serializer.attribute(null, "new", e.getKey());
8408 serializer.attribute(null, "old", e.getValue());
8409 serializer.endTag(null, "renamed-package");
8410 }
8411 }
8412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008413 serializer.endTag(null, "packages");
8414
8415 serializer.endDocument();
8416
8417 str.flush();
8418 str.close();
8419
8420 // New settings successfully written, old ones are no longer
8421 // needed.
8422 mBackupSettingsFilename.delete();
8423 FileUtils.setPermissions(mSettingsFilename.toString(),
8424 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8425 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8426 |FileUtils.S_IROTH,
8427 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008428
8429 // Write package list file now, use a JournaledFile.
8430 //
8431 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8432 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8433
8434 str = new FileOutputStream(journal.chooseForWrite());
8435 try {
8436 StringBuilder sb = new StringBuilder();
8437 for (PackageSetting pkg : mPackages.values()) {
8438 ApplicationInfo ai = pkg.pkg.applicationInfo;
8439 String dataPath = ai.dataDir;
8440 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8441
8442 // Avoid any application that has a space in its path
8443 // or that is handled by the system.
8444 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8445 continue;
8446
8447 // we store on each line the following information for now:
8448 //
8449 // pkgName - package name
8450 // userId - application-specific user id
8451 // debugFlag - 0 or 1 if the package is debuggable.
8452 // dataPath - path to package's data path
8453 //
8454 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8455 //
8456 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8457 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8458 // system/core/run-as/run-as.c
8459 //
8460 sb.setLength(0);
8461 sb.append(ai.packageName);
8462 sb.append(" ");
8463 sb.append((int)ai.uid);
8464 sb.append(isDebug ? " 1 " : " 0 ");
8465 sb.append(dataPath);
8466 sb.append("\n");
8467 str.write(sb.toString().getBytes());
8468 }
8469 str.flush();
8470 str.close();
8471 journal.commit();
8472 }
8473 catch (Exception e) {
8474 journal.rollback();
8475 }
8476
8477 FileUtils.setPermissions(mPackageListFilename.toString(),
8478 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8479 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8480 |FileUtils.S_IROTH,
8481 -1, -1);
8482
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008483 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008484
8485 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008486 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 -08008487 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008488 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 -08008489 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008490 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008491 if (mSettingsFilename.exists()) {
8492 if (!mSettingsFilename.delete()) {
8493 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8494 }
8495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 //Debug.stopMethodTracing();
8497 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008498
8499 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008500 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008501 serializer.startTag(null, "updated-package");
8502 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008503 if (pkg.realName != null) {
8504 serializer.attribute(null, "realName", pkg.realName);
8505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 serializer.attribute(null, "codePath", pkg.codePathString);
8507 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008508 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8510 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8511 }
8512 if (pkg.sharedUser == null) {
8513 serializer.attribute(null, "userId",
8514 Integer.toString(pkg.userId));
8515 } else {
8516 serializer.attribute(null, "sharedUserId",
8517 Integer.toString(pkg.userId));
8518 }
8519 serializer.startTag(null, "perms");
8520 if (pkg.sharedUser == null) {
8521 // If this is a shared user, the permissions will
8522 // be written there. We still need to write an
8523 // empty permissions list so permissionsFixed will
8524 // be set.
8525 for (final String name : pkg.grantedPermissions) {
8526 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008527 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 // We only need to write signature or system permissions but this wont
8529 // match the semantics of grantedPermissions. So write all permissions.
8530 serializer.startTag(null, "item");
8531 serializer.attribute(null, "name", name);
8532 serializer.endTag(null, "item");
8533 }
8534 }
8535 }
8536 serializer.endTag(null, "perms");
8537 serializer.endTag(null, "updated-package");
8538 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008539
8540 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008541 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008542 serializer.startTag(null, "package");
8543 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008544 if (pkg.realName != null) {
8545 serializer.attribute(null, "realName", pkg.realName);
8546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 serializer.attribute(null, "codePath", pkg.codePathString);
8548 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8549 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8550 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008551 serializer.attribute(null, "flags",
8552 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008554 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008555 if (pkg.sharedUser == null) {
8556 serializer.attribute(null, "userId",
8557 Integer.toString(pkg.userId));
8558 } else {
8559 serializer.attribute(null, "sharedUserId",
8560 Integer.toString(pkg.userId));
8561 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008562 if (pkg.uidError) {
8563 serializer.attribute(null, "uidError", "true");
8564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8566 serializer.attribute(null, "enabled",
8567 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8568 ? "true" : "false");
8569 }
8570 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8571 serializer.attribute(null, "installStatus", "false");
8572 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008573 if (pkg.installerPackageName != null) {
8574 serializer.attribute(null, "installer", pkg.installerPackageName);
8575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8577 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8578 serializer.startTag(null, "perms");
8579 if (pkg.sharedUser == null) {
8580 // If this is a shared user, the permissions will
8581 // be written there. We still need to write an
8582 // empty permissions list so permissionsFixed will
8583 // be set.
8584 for (final String name : pkg.grantedPermissions) {
8585 serializer.startTag(null, "item");
8586 serializer.attribute(null, "name", name);
8587 serializer.endTag(null, "item");
8588 }
8589 }
8590 serializer.endTag(null, "perms");
8591 }
8592 if (pkg.disabledComponents.size() > 0) {
8593 serializer.startTag(null, "disabled-components");
8594 for (final String name : pkg.disabledComponents) {
8595 serializer.startTag(null, "item");
8596 serializer.attribute(null, "name", name);
8597 serializer.endTag(null, "item");
8598 }
8599 serializer.endTag(null, "disabled-components");
8600 }
8601 if (pkg.enabledComponents.size() > 0) {
8602 serializer.startTag(null, "enabled-components");
8603 for (final String name : pkg.enabledComponents) {
8604 serializer.startTag(null, "item");
8605 serializer.attribute(null, "name", name);
8606 serializer.endTag(null, "item");
8607 }
8608 serializer.endTag(null, "enabled-components");
8609 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 serializer.endTag(null, "package");
8612 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614 void writePermission(XmlSerializer serializer, BasePermission bp)
8615 throws XmlPullParserException, java.io.IOException {
8616 if (bp.type != BasePermission.TYPE_BUILTIN
8617 && bp.sourcePackage != null) {
8618 serializer.startTag(null, "item");
8619 serializer.attribute(null, "name", bp.name);
8620 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008621 if (bp.protectionLevel !=
8622 PermissionInfo.PROTECTION_NORMAL) {
8623 serializer.attribute(null, "protection",
8624 Integer.toString(bp.protectionLevel));
8625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008626 if (DEBUG_SETTINGS) Log.v(TAG,
8627 "Writing perm: name=" + bp.name + " type=" + bp.type);
8628 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8629 PermissionInfo pi = bp.perm != null ? bp.perm.info
8630 : bp.pendingInfo;
8631 if (pi != null) {
8632 serializer.attribute(null, "type", "dynamic");
8633 if (pi.icon != 0) {
8634 serializer.attribute(null, "icon",
8635 Integer.toString(pi.icon));
8636 }
8637 if (pi.nonLocalizedLabel != null) {
8638 serializer.attribute(null, "label",
8639 pi.nonLocalizedLabel.toString());
8640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 }
8642 }
8643 serializer.endTag(null, "item");
8644 }
8645 }
8646
8647 String getReadMessagesLP() {
8648 return mReadMessages.toString();
8649 }
8650
Oscar Montemayora8529f62009-11-18 10:14:20 -08008651 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008652 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8653 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008654 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008655 while(its.hasNext()) {
8656 String key = its.next();
8657 PackageSetting ps = mPackages.get(key);
8658 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008659 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008660 }
8661 }
8662 return ret;
8663 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008665 boolean readLP() {
8666 FileInputStream str = null;
8667 if (mBackupSettingsFilename.exists()) {
8668 try {
8669 str = new FileInputStream(mBackupSettingsFilename);
8670 mReadMessages.append("Reading from backup settings file\n");
8671 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008672 if (mSettingsFilename.exists()) {
8673 // If both the backup and settings file exist, we
8674 // ignore the settings since it might have been
8675 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008676 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008677 mSettingsFilename.delete();
8678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008679 } catch (java.io.IOException e) {
8680 // We'll try for the normal settings file.
8681 }
8682 }
8683
8684 mPastSignatures.clear();
8685
8686 try {
8687 if (str == null) {
8688 if (!mSettingsFilename.exists()) {
8689 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008690 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 return false;
8692 }
8693 str = new FileInputStream(mSettingsFilename);
8694 }
8695 XmlPullParser parser = Xml.newPullParser();
8696 parser.setInput(str, null);
8697
8698 int type;
8699 while ((type=parser.next()) != XmlPullParser.START_TAG
8700 && type != XmlPullParser.END_DOCUMENT) {
8701 ;
8702 }
8703
8704 if (type != XmlPullParser.START_TAG) {
8705 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008706 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008707 return false;
8708 }
8709
8710 int outerDepth = parser.getDepth();
8711 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8712 && (type != XmlPullParser.END_TAG
8713 || parser.getDepth() > outerDepth)) {
8714 if (type == XmlPullParser.END_TAG
8715 || type == XmlPullParser.TEXT) {
8716 continue;
8717 }
8718
8719 String tagName = parser.getName();
8720 if (tagName.equals("package")) {
8721 readPackageLP(parser);
8722 } else if (tagName.equals("permissions")) {
8723 readPermissionsLP(mPermissions, parser);
8724 } else if (tagName.equals("permission-trees")) {
8725 readPermissionsLP(mPermissionTrees, parser);
8726 } else if (tagName.equals("shared-user")) {
8727 readSharedUserLP(parser);
8728 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008729 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008730 } else if (tagName.equals("preferred-activities")) {
8731 readPreferredActivitiesLP(parser);
8732 } else if(tagName.equals("updated-package")) {
8733 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008734 } else if (tagName.equals("cleaning-package")) {
8735 String name = parser.getAttributeValue(null, "name");
8736 if (name != null) {
8737 mPackagesToBeCleaned.add(name);
8738 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008739 } else if (tagName.equals("renamed-package")) {
8740 String nname = parser.getAttributeValue(null, "new");
8741 String oname = parser.getAttributeValue(null, "old");
8742 if (nname != null && oname != null) {
8743 mRenamedPackages.put(nname, oname);
8744 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008745 } else if (tagName.equals("last-platform-version")) {
8746 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8747 try {
8748 String internal = parser.getAttributeValue(null, "internal");
8749 if (internal != null) {
8750 mInternalSdkPlatform = Integer.parseInt(internal);
8751 }
8752 String external = parser.getAttributeValue(null, "external");
8753 if (external != null) {
8754 mInternalSdkPlatform = Integer.parseInt(external);
8755 }
8756 } catch (NumberFormatException e) {
8757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008758 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008759 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008760 + parser.getName());
8761 XmlUtils.skipCurrentTag(parser);
8762 }
8763 }
8764
8765 str.close();
8766
8767 } catch(XmlPullParserException e) {
8768 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008769 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770
8771 } catch(java.io.IOException e) {
8772 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008773 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774
8775 }
8776
8777 int N = mPendingPackages.size();
8778 for (int i=0; i<N; i++) {
8779 final PendingPackage pp = mPendingPackages.get(i);
8780 Object idObj = getUserIdLP(pp.sharedId);
8781 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008782 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008783 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008784 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008786 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 + pp.name);
8788 continue;
8789 }
8790 p.copyFrom(pp);
8791 } else if (idObj != null) {
8792 String msg = "Bad package setting: package " + pp.name
8793 + " has shared uid " + pp.sharedId
8794 + " that is not a shared uid\n";
8795 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008796 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008797 } else {
8798 String msg = "Bad package setting: package " + pp.name
8799 + " has shared uid " + pp.sharedId
8800 + " that is not defined\n";
8801 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008802 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008803 }
8804 }
8805 mPendingPackages.clear();
8806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008807 mReadMessages.append("Read completed successfully: "
8808 + mPackages.size() + " packages, "
8809 + mSharedUsers.size() + " shared uids\n");
8810
8811 return true;
8812 }
8813
8814 private int readInt(XmlPullParser parser, String ns, String name,
8815 int defValue) {
8816 String v = parser.getAttributeValue(ns, name);
8817 try {
8818 if (v == null) {
8819 return defValue;
8820 }
8821 return Integer.parseInt(v);
8822 } catch (NumberFormatException e) {
8823 reportSettingsProblem(Log.WARN,
8824 "Error in package manager settings: attribute " +
8825 name + " has bad integer value " + v + " at "
8826 + parser.getPositionDescription());
8827 }
8828 return defValue;
8829 }
8830
8831 private void readPermissionsLP(HashMap<String, BasePermission> out,
8832 XmlPullParser parser)
8833 throws IOException, XmlPullParserException {
8834 int outerDepth = parser.getDepth();
8835 int type;
8836 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8837 && (type != XmlPullParser.END_TAG
8838 || parser.getDepth() > outerDepth)) {
8839 if (type == XmlPullParser.END_TAG
8840 || type == XmlPullParser.TEXT) {
8841 continue;
8842 }
8843
8844 String tagName = parser.getName();
8845 if (tagName.equals("item")) {
8846 String name = parser.getAttributeValue(null, "name");
8847 String sourcePackage = parser.getAttributeValue(null, "package");
8848 String ptype = parser.getAttributeValue(null, "type");
8849 if (name != null && sourcePackage != null) {
8850 boolean dynamic = "dynamic".equals(ptype);
8851 BasePermission bp = new BasePermission(name, sourcePackage,
8852 dynamic
8853 ? BasePermission.TYPE_DYNAMIC
8854 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008855 bp.protectionLevel = readInt(parser, null, "protection",
8856 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857 if (dynamic) {
8858 PermissionInfo pi = new PermissionInfo();
8859 pi.packageName = sourcePackage.intern();
8860 pi.name = name.intern();
8861 pi.icon = readInt(parser, null, "icon", 0);
8862 pi.nonLocalizedLabel = parser.getAttributeValue(
8863 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008864 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 bp.pendingInfo = pi;
8866 }
8867 out.put(bp.name, bp);
8868 } else {
8869 reportSettingsProblem(Log.WARN,
8870 "Error in package manager settings: permissions has"
8871 + " no name at " + parser.getPositionDescription());
8872 }
8873 } else {
8874 reportSettingsProblem(Log.WARN,
8875 "Unknown element reading permissions: "
8876 + parser.getName() + " at "
8877 + parser.getPositionDescription());
8878 }
8879 XmlUtils.skipCurrentTag(parser);
8880 }
8881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008884 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008886 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887 String codePathStr = parser.getAttributeValue(null, "codePath");
8888 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008889 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 resourcePathStr = codePathStr;
8891 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008892 String version = parser.getAttributeValue(null, "version");
8893 int versionCode = 0;
8894 if (version != null) {
8895 try {
8896 versionCode = Integer.parseInt(version);
8897 } catch (NumberFormatException e) {
8898 }
8899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008901 int pkgFlags = 0;
8902 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008903 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008904 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008905 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 String timeStampStr = parser.getAttributeValue(null, "ts");
8907 if (timeStampStr != null) {
8908 try {
8909 long timeStamp = Long.parseLong(timeStampStr);
8910 ps.setTimeStamp(timeStamp, timeStampStr);
8911 } catch (NumberFormatException e) {
8912 }
8913 }
8914 String idStr = parser.getAttributeValue(null, "userId");
8915 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8916 if(ps.userId <= 0) {
8917 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8918 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8919 }
8920 int outerDepth = parser.getDepth();
8921 int type;
8922 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8923 && (type != XmlPullParser.END_TAG
8924 || parser.getDepth() > outerDepth)) {
8925 if (type == XmlPullParser.END_TAG
8926 || type == XmlPullParser.TEXT) {
8927 continue;
8928 }
8929
8930 String tagName = parser.getName();
8931 if (tagName.equals("perms")) {
8932 readGrantedPermissionsLP(parser,
8933 ps.grantedPermissions);
8934 } else {
8935 reportSettingsProblem(Log.WARN,
8936 "Unknown element under <updated-package>: "
8937 + parser.getName());
8938 XmlUtils.skipCurrentTag(parser);
8939 }
8940 }
8941 mDisabledSysPackages.put(name, ps);
8942 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 private void readPackageLP(XmlPullParser parser)
8945 throws XmlPullParserException, IOException {
8946 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008947 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008948 String idStr = null;
8949 String sharedIdStr = null;
8950 String codePathStr = null;
8951 String resourcePathStr = null;
8952 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008953 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008954 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 int pkgFlags = 0;
8956 String timeStampStr;
8957 long timeStamp = 0;
8958 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008959 String version = null;
8960 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 try {
8962 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008963 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008965 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8967 codePathStr = parser.getAttributeValue(null, "codePath");
8968 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008969 version = parser.getAttributeValue(null, "version");
8970 if (version != null) {
8971 try {
8972 versionCode = Integer.parseInt(version);
8973 } catch (NumberFormatException e) {
8974 }
8975 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008976 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008977
8978 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008979 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008980 try {
8981 pkgFlags = Integer.parseInt(systemStr);
8982 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008983 }
8984 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008985 // For backward compatibility
8986 systemStr = parser.getAttributeValue(null, "system");
8987 if (systemStr != null) {
8988 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8989 } else {
8990 // Old settings that don't specify system... just treat
8991 // them as system, good enough.
8992 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008994 }
8995 timeStampStr = parser.getAttributeValue(null, "ts");
8996 if (timeStampStr != null) {
8997 try {
8998 timeStamp = Long.parseLong(timeStampStr);
8999 } catch (NumberFormatException e) {
9000 }
9001 }
9002 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9003 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9004 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9005 if (resourcePathStr == null) {
9006 resourcePathStr = codePathStr;
9007 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009008 if (realName != null) {
9009 realName = realName.intern();
9010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011 if (name == null) {
9012 reportSettingsProblem(Log.WARN,
9013 "Error in package manager settings: <package> has no name at "
9014 + parser.getPositionDescription());
9015 } else if (codePathStr == null) {
9016 reportSettingsProblem(Log.WARN,
9017 "Error in package manager settings: <package> has no codePath at "
9018 + parser.getPositionDescription());
9019 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009020 packageSetting = addPackageLP(name.intern(), realName,
9021 new File(codePathStr), new File(resourcePathStr),
9022 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9024 + ": userId=" + userId + " pkg=" + packageSetting);
9025 if (packageSetting == null) {
9026 reportSettingsProblem(Log.ERROR,
9027 "Failure adding uid " + userId
9028 + " while parsing settings at "
9029 + parser.getPositionDescription());
9030 } else {
9031 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9032 }
9033 } else if (sharedIdStr != null) {
9034 userId = sharedIdStr != null
9035 ? Integer.parseInt(sharedIdStr) : 0;
9036 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009037 packageSetting = new PendingPackage(name.intern(), realName,
9038 new File(codePathStr), new File(resourcePathStr),
9039 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9041 mPendingPackages.add((PendingPackage) packageSetting);
9042 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9043 + ": sharedUserId=" + userId + " pkg="
9044 + packageSetting);
9045 } else {
9046 reportSettingsProblem(Log.WARN,
9047 "Error in package manager settings: package "
9048 + name + " has bad sharedId " + sharedIdStr
9049 + " at " + parser.getPositionDescription());
9050 }
9051 } else {
9052 reportSettingsProblem(Log.WARN,
9053 "Error in package manager settings: package "
9054 + name + " has bad userId " + idStr + " at "
9055 + parser.getPositionDescription());
9056 }
9057 } catch (NumberFormatException e) {
9058 reportSettingsProblem(Log.WARN,
9059 "Error in package manager settings: package "
9060 + name + " has bad userId " + idStr + " at "
9061 + parser.getPositionDescription());
9062 }
9063 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009064 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009065 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 final String enabledStr = parser.getAttributeValue(null, "enabled");
9067 if (enabledStr != null) {
9068 if (enabledStr.equalsIgnoreCase("true")) {
9069 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9070 } else if (enabledStr.equalsIgnoreCase("false")) {
9071 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9072 } else if (enabledStr.equalsIgnoreCase("default")) {
9073 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9074 } else {
9075 reportSettingsProblem(Log.WARN,
9076 "Error in package manager settings: package "
9077 + name + " has bad enabled value: " + idStr
9078 + " at " + parser.getPositionDescription());
9079 }
9080 } else {
9081 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9082 }
9083 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9084 if (installStatusStr != null) {
9085 if (installStatusStr.equalsIgnoreCase("false")) {
9086 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9087 } else {
9088 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9089 }
9090 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 int outerDepth = parser.getDepth();
9093 int type;
9094 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9095 && (type != XmlPullParser.END_TAG
9096 || parser.getDepth() > outerDepth)) {
9097 if (type == XmlPullParser.END_TAG
9098 || type == XmlPullParser.TEXT) {
9099 continue;
9100 }
9101
9102 String tagName = parser.getName();
9103 if (tagName.equals("disabled-components")) {
9104 readDisabledComponentsLP(packageSetting, parser);
9105 } else if (tagName.equals("enabled-components")) {
9106 readEnabledComponentsLP(packageSetting, parser);
9107 } else if (tagName.equals("sigs")) {
9108 packageSetting.signatures.readXml(parser, mPastSignatures);
9109 } else if (tagName.equals("perms")) {
9110 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009111 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009112 packageSetting.permissionsFixed = true;
9113 } else {
9114 reportSettingsProblem(Log.WARN,
9115 "Unknown element under <package>: "
9116 + parser.getName());
9117 XmlUtils.skipCurrentTag(parser);
9118 }
9119 }
9120 } else {
9121 XmlUtils.skipCurrentTag(parser);
9122 }
9123 }
9124
9125 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9126 XmlPullParser parser)
9127 throws IOException, XmlPullParserException {
9128 int outerDepth = parser.getDepth();
9129 int type;
9130 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9131 && (type != XmlPullParser.END_TAG
9132 || parser.getDepth() > outerDepth)) {
9133 if (type == XmlPullParser.END_TAG
9134 || type == XmlPullParser.TEXT) {
9135 continue;
9136 }
9137
9138 String tagName = parser.getName();
9139 if (tagName.equals("item")) {
9140 String name = parser.getAttributeValue(null, "name");
9141 if (name != null) {
9142 packageSetting.disabledComponents.add(name.intern());
9143 } else {
9144 reportSettingsProblem(Log.WARN,
9145 "Error in package manager settings: <disabled-components> has"
9146 + " no name at " + parser.getPositionDescription());
9147 }
9148 } else {
9149 reportSettingsProblem(Log.WARN,
9150 "Unknown element under <disabled-components>: "
9151 + parser.getName());
9152 }
9153 XmlUtils.skipCurrentTag(parser);
9154 }
9155 }
9156
9157 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9158 XmlPullParser parser)
9159 throws IOException, XmlPullParserException {
9160 int outerDepth = parser.getDepth();
9161 int type;
9162 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9163 && (type != XmlPullParser.END_TAG
9164 || parser.getDepth() > outerDepth)) {
9165 if (type == XmlPullParser.END_TAG
9166 || type == XmlPullParser.TEXT) {
9167 continue;
9168 }
9169
9170 String tagName = parser.getName();
9171 if (tagName.equals("item")) {
9172 String name = parser.getAttributeValue(null, "name");
9173 if (name != null) {
9174 packageSetting.enabledComponents.add(name.intern());
9175 } else {
9176 reportSettingsProblem(Log.WARN,
9177 "Error in package manager settings: <enabled-components> has"
9178 + " no name at " + parser.getPositionDescription());
9179 }
9180 } else {
9181 reportSettingsProblem(Log.WARN,
9182 "Unknown element under <enabled-components>: "
9183 + parser.getName());
9184 }
9185 XmlUtils.skipCurrentTag(parser);
9186 }
9187 }
9188
9189 private void readSharedUserLP(XmlPullParser parser)
9190 throws XmlPullParserException, IOException {
9191 String name = null;
9192 String idStr = null;
9193 int pkgFlags = 0;
9194 SharedUserSetting su = null;
9195 try {
9196 name = parser.getAttributeValue(null, "name");
9197 idStr = parser.getAttributeValue(null, "userId");
9198 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9199 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9200 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9201 }
9202 if (name == null) {
9203 reportSettingsProblem(Log.WARN,
9204 "Error in package manager settings: <shared-user> has no name at "
9205 + parser.getPositionDescription());
9206 } else if (userId == 0) {
9207 reportSettingsProblem(Log.WARN,
9208 "Error in package manager settings: shared-user "
9209 + name + " has bad userId " + idStr + " at "
9210 + parser.getPositionDescription());
9211 } else {
9212 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9213 reportSettingsProblem(Log.ERROR,
9214 "Occurred while parsing settings at "
9215 + parser.getPositionDescription());
9216 }
9217 }
9218 } catch (NumberFormatException e) {
9219 reportSettingsProblem(Log.WARN,
9220 "Error in package manager settings: package "
9221 + name + " has bad userId " + idStr + " at "
9222 + parser.getPositionDescription());
9223 };
9224
9225 if (su != null) {
9226 int outerDepth = parser.getDepth();
9227 int type;
9228 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9229 && (type != XmlPullParser.END_TAG
9230 || parser.getDepth() > outerDepth)) {
9231 if (type == XmlPullParser.END_TAG
9232 || type == XmlPullParser.TEXT) {
9233 continue;
9234 }
9235
9236 String tagName = parser.getName();
9237 if (tagName.equals("sigs")) {
9238 su.signatures.readXml(parser, mPastSignatures);
9239 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009240 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009241 } else {
9242 reportSettingsProblem(Log.WARN,
9243 "Unknown element under <shared-user>: "
9244 + parser.getName());
9245 XmlUtils.skipCurrentTag(parser);
9246 }
9247 }
9248
9249 } else {
9250 XmlUtils.skipCurrentTag(parser);
9251 }
9252 }
9253
9254 private void readGrantedPermissionsLP(XmlPullParser parser,
9255 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9256 int outerDepth = parser.getDepth();
9257 int type;
9258 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9259 && (type != XmlPullParser.END_TAG
9260 || parser.getDepth() > outerDepth)) {
9261 if (type == XmlPullParser.END_TAG
9262 || type == XmlPullParser.TEXT) {
9263 continue;
9264 }
9265
9266 String tagName = parser.getName();
9267 if (tagName.equals("item")) {
9268 String name = parser.getAttributeValue(null, "name");
9269 if (name != null) {
9270 outPerms.add(name.intern());
9271 } else {
9272 reportSettingsProblem(Log.WARN,
9273 "Error in package manager settings: <perms> has"
9274 + " no name at " + parser.getPositionDescription());
9275 }
9276 } else {
9277 reportSettingsProblem(Log.WARN,
9278 "Unknown element under <perms>: "
9279 + parser.getName());
9280 }
9281 XmlUtils.skipCurrentTag(parser);
9282 }
9283 }
9284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009285 private void readPreferredActivitiesLP(XmlPullParser parser)
9286 throws XmlPullParserException, IOException {
9287 int outerDepth = parser.getDepth();
9288 int type;
9289 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9290 && (type != XmlPullParser.END_TAG
9291 || parser.getDepth() > outerDepth)) {
9292 if (type == XmlPullParser.END_TAG
9293 || type == XmlPullParser.TEXT) {
9294 continue;
9295 }
9296
9297 String tagName = parser.getName();
9298 if (tagName.equals("item")) {
9299 PreferredActivity pa = new PreferredActivity(parser);
9300 if (pa.mParseError == null) {
9301 mPreferredActivities.addFilter(pa);
9302 } else {
9303 reportSettingsProblem(Log.WARN,
9304 "Error in package manager settings: <preferred-activity> "
9305 + pa.mParseError + " at "
9306 + parser.getPositionDescription());
9307 }
9308 } else {
9309 reportSettingsProblem(Log.WARN,
9310 "Unknown element under <preferred-activities>: "
9311 + parser.getName());
9312 XmlUtils.skipCurrentTag(parser);
9313 }
9314 }
9315 }
9316
9317 // Returns -1 if we could not find an available UserId to assign
9318 private int newUserIdLP(Object obj) {
9319 // Let's be stupidly inefficient for now...
9320 final int N = mUserIds.size();
9321 for (int i=0; i<N; i++) {
9322 if (mUserIds.get(i) == null) {
9323 mUserIds.set(i, obj);
9324 return FIRST_APPLICATION_UID + i;
9325 }
9326 }
9327
9328 // None left?
9329 if (N >= MAX_APPLICATION_UIDS) {
9330 return -1;
9331 }
9332
9333 mUserIds.add(obj);
9334 return FIRST_APPLICATION_UID + N;
9335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 public PackageSetting getDisabledSystemPkg(String name) {
9338 synchronized(mPackages) {
9339 PackageSetting ps = mDisabledSysPackages.get(name);
9340 return ps;
9341 }
9342 }
9343
9344 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9345 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9346 if (Config.LOGV) {
9347 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9348 + " componentName = " + componentInfo.name);
9349 Log.v(TAG, "enabledComponents: "
9350 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9351 Log.v(TAG, "disabledComponents: "
9352 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9353 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009354 if (packageSettings == null) {
9355 if (false) {
9356 Log.w(TAG, "WAITING FOR DEBUGGER");
9357 Debug.waitForDebugger();
9358 Log.i(TAG, "We will crash!");
9359 }
9360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009361 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9362 || ((componentInfo.enabled
9363 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9364 || (componentInfo.applicationInfo.enabled
9365 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9366 && !packageSettings.disabledComponents.contains(componentInfo.name))
9367 || packageSettings.enabledComponents.contains(componentInfo.name));
9368 }
9369 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009370
9371 // ------- apps on sdcard specific code -------
9372 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009373 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009374 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009375 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009376 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009377
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009378 private String getEncryptKey() {
9379 try {
9380 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9381 if (sdEncKey == null) {
9382 sdEncKey = SystemKeyStore.getInstance().
9383 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9384 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009385 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009386 return null;
9387 }
9388 }
9389 return sdEncKey;
9390 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009391 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009392 return null;
9393 }
9394 }
9395
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009396 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009397 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009398 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009399 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009400 if (list != null) {
9401 int idx = 0;
9402 int idList[] = new int[MAX_CONTAINERS];
9403 boolean neverFound = true;
9404 for (String name : list) {
9405 // Ignore null entries
9406 if (name == null) {
9407 continue;
9408 }
9409 int sidx = name.indexOf(prefix);
9410 if (sidx == -1) {
9411 // Not a temp file. just ignore
9412 continue;
9413 }
9414 String subStr = name.substring(sidx + prefix.length());
9415 idList[idx] = -1;
9416 if (subStr != null) {
9417 try {
9418 int cid = Integer.parseInt(subStr);
9419 idList[idx++] = cid;
9420 neverFound = false;
9421 } catch (NumberFormatException e) {
9422 }
9423 }
9424 }
9425 if (!neverFound) {
9426 // Sort idList
9427 Arrays.sort(idList);
9428 for (int j = 1; j <= idList.length; j++) {
9429 if (idList[j-1] != j) {
9430 tmpIdx = j;
9431 break;
9432 }
9433 }
9434 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009435 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009436 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009437 }
9438
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009439 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009440 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009441 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009442 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9443 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9444 throw new SecurityException("Media status can only be updated by the system");
9445 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009446 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009447 Log.i(TAG, "Updating external media status from " +
9448 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9449 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009450 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9451 mediaStatus+", mMediaMounted=" + mMediaMounted);
9452 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009453 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9454 reportStatus ? 1 : 0, -1);
9455 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009456 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009457 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009458 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009459 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009460 // Queue up an async operation since the package installation may take a little while.
9461 mHandler.post(new Runnable() {
9462 public void run() {
9463 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009464 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009465 }
9466 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009467 }
9468
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009469 /*
9470 * Collect information of applications on external media, map them
9471 * against existing containers and update information based on current
9472 * mount status. Please note that we always have to report status
9473 * if reportStatus has been set to true especially when unloading packages.
9474 */
9475 private void updateExternalMediaStatusInner(boolean mediaStatus,
9476 boolean reportStatus) {
9477 // Collection of uids
9478 int uidArr[] = null;
9479 // Collection of stale containers
9480 HashSet<String> removeCids = new HashSet<String>();
9481 // Collection of packages on external media with valid containers.
9482 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9483 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009484 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009485 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009486 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009487 } else {
9488 // Process list of secure containers and categorize them
9489 // as active or stale based on their package internal state.
9490 int uidList[] = new int[list.length];
9491 int num = 0;
9492 synchronized (mPackages) {
9493 for (String cid : list) {
9494 SdInstallArgs args = new SdInstallArgs(cid);
9495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009496 String pkgName = args.getPackageName();
9497 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009498 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9499 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009500 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009501 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009502 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9503 PackageSetting ps = mSettings.mPackages.get(pkgName);
9504 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009505 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009506 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9507 " corresponds to pkg : " + pkgName +
9508 " at code path: " + ps.codePathString);
9509 // We do have a valid package installed on sdcard
9510 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009511 int uid = ps.userId;
9512 if (uid != -1) {
9513 uidList[num++] = uid;
9514 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009515 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009516 // Stale container on sdcard. Just delete
9517 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9518 removeCids.add(cid);
9519 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009520 }
9521 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009522
9523 if (num > 0) {
9524 // Sort uid list
9525 Arrays.sort(uidList, 0, num);
9526 // Throw away duplicates
9527 uidArr = new int[num];
9528 uidArr[0] = uidList[0];
9529 int di = 0;
9530 for (int i = 1; i < num; i++) {
9531 if (uidList[i-1] != uidList[i]) {
9532 uidArr[di++] = uidList[i];
9533 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009534 }
9535 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009536 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009537 // Process packages with valid entries.
9538 if (mediaStatus) {
9539 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009540 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009541 startCleaningPackages();
9542 } else {
9543 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009544 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009545 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009546 }
9547
9548 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009549 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009550 int size = pkgList.size();
9551 if (size > 0) {
9552 // Send broadcasts here
9553 Bundle extras = new Bundle();
9554 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9555 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009556 if (uidArr != null) {
9557 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9558 }
9559 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9560 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009561 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009562 }
9563 }
9564
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009565 /*
9566 * Look at potentially valid container ids from processCids
9567 * If package information doesn't match the one on record
9568 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009569 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009570 */
9571 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009572 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009573 ArrayList<String> pkgList = new ArrayList<String>();
9574 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009575 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009576 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009577 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009578 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9579 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009580 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009581 try {
9582 // Make sure there are no container errors first.
9583 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9584 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009585 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009586 " when installing from sdcard");
9587 continue;
9588 }
9589 // Check code path here.
9590 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009591 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009592 " does not match one in settings " + codePath);
9593 continue;
9594 }
9595 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009596 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009597 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009598 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009599 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9600 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009601 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009602 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009603 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009604 retCode = PackageManager.INSTALL_SUCCEEDED;
9605 pkgList.add(pkg.packageName);
9606 // Post process args
9607 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9608 }
9609 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009610 Slog.i(TAG, "Failed to install pkg from " +
9611 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009612 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009613 }
9614
9615 } finally {
9616 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9617 // Don't destroy container here. Wait till gc clears things up.
9618 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009619 }
9620 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009621 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009622 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009623 // If the platform SDK has changed since the last time we booted,
9624 // we need to re-grant app permission to catch any new ones that
9625 // appear. This is really a hack, and means that apps can in some
9626 // cases get permissions that the user didn't initially explicitly
9627 // allow... it would be nice to have some better way to handle
9628 // this situation.
9629 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9630 != mSdkVersion;
9631 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9632 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9633 + "; regranting permissions for external storage");
9634 mSettings.mExternalSdkPlatform = mSdkVersion;
9635
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009636 // Make sure group IDs have been assigned, and any permission
9637 // changes in other apps are accounted for
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009638 updatePermissionsLP(null, null, true, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009639 // Persist settings
9640 mSettings.writeLP();
9641 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009642 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009643 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009644 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009645 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009646 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009647 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009648 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009649 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009650 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009651 if (removeCids != null) {
9652 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009653 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009654 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009655 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009656 }
9657
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009658 /*
9659 * Utility method to unload a list of specified containers
9660 */
9661 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9662 // Just unmount all valid containers.
9663 for (SdInstallArgs arg : cidArgs) {
9664 synchronized (mInstallLock) {
9665 arg.doPostDeleteLI(false);
9666 }
9667 }
9668 }
9669
9670 /*
9671 * Unload packages mounted on external media. This involves deleting
9672 * package data from internal structures, sending broadcasts about
9673 * diabled packages, gc'ing to free up references, unmounting all
9674 * secure containers corresponding to packages on external media, and
9675 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9676 * Please note that we always have to post this message if status has
9677 * been requested no matter what.
9678 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009679 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009680 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009681 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009682 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009683 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009684 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009685 for (SdInstallArgs args : keys) {
9686 String cid = args.cid;
9687 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009688 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009689 // Delete package internally
9690 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9691 synchronized (mInstallLock) {
9692 boolean res = deletePackageLI(pkgName, false,
9693 PackageManager.DONT_DELETE_DATA, outInfo);
9694 if (res) {
9695 pkgList.add(pkgName);
9696 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009697 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009698 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009699 }
9700 }
9701 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009702 // We have to absolutely send UPDATED_MEDIA_STATUS only
9703 // after confirming that all the receivers processed the ordered
9704 // broadcast when packages get disabled, force a gc to clean things up.
9705 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009706 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009707 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9708 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9709 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009710 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9711 reportStatus ? 1 : 0, 1, keys);
9712 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009713 }
9714 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009715 } else {
9716 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9717 reportStatus ? 1 : 0, -1, keys);
9718 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009719 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009720 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009721
9722 public void movePackage(final String packageName,
9723 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009724 mContext.enforceCallingOrSelfPermission(
9725 android.Manifest.permission.MOVE_PACKAGE, null);
9726 int returnCode = PackageManager.MOVE_SUCCEEDED;
9727 int currFlags = 0;
9728 int newFlags = 0;
9729 synchronized (mPackages) {
9730 PackageParser.Package pkg = mPackages.get(packageName);
9731 if (pkg == null) {
9732 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009733 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009734 // Disable moving fwd locked apps and system packages
9735 if (pkg.applicationInfo != null &&
9736 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9737 Slog.w(TAG, "Cannot move system application");
9738 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9739 } else if (pkg.applicationInfo != null &&
9740 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9741 Slog.w(TAG, "Cannot move forward locked app.");
9742 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009743 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009744 // Find install location first
9745 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9746 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9747 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009748 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009749 } else {
9750 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9751 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9752 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9753 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9754 if (newFlags == currFlags) {
9755 Slog.w(TAG, "No move required. Trying to move to same location");
9756 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9757 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009758 }
9759 }
9760 }
9761 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9762 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9763 } else {
9764 Message msg = mHandler.obtainMessage(INIT_COPY);
9765 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9766 pkg.applicationInfo.publicSourceDir);
9767 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9768 packageName);
9769 msg.obj = mp;
9770 mHandler.sendMessage(msg);
9771 }
9772 }
9773 }
9774
9775 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9776 // Queue up an async operation since the package deletion may take a little while.
9777 mHandler.post(new Runnable() {
9778 public void run() {
9779 mHandler.removeCallbacks(this);
9780 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009781 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9782 int uidArr[] = null;
9783 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009784 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009785 PackageParser.Package pkg = mPackages.get(mp.packageName);
9786 if (pkg == null ) {
9787 Slog.w(TAG, " Package " + mp.packageName +
9788 " doesn't exist. Aborting move");
9789 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9790 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9791 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9792 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9793 " Aborting move and returning error");
9794 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9795 } else {
9796 uidArr = new int[] { pkg.applicationInfo.uid };
9797 pkgList = new ArrayList<String>();
9798 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009799 }
9800 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009801 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9802 // Send resources unavailable broadcast
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009803 // TODO Add an ordered broadcast receiver here.
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009804 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009805 // Update package code and resource paths
9806 synchronized (mInstallLock) {
9807 synchronized (mPackages) {
9808 PackageParser.Package pkg = mPackages.get(mp.packageName);
9809 // Recheck for package again.
9810 if (pkg == null ) {
9811 Slog.w(TAG, " Package " + mp.packageName +
9812 " doesn't exist. Aborting move");
9813 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9814 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9815 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9816 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9817 " Aborting move and returning error");
9818 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9819 } else {
9820 String oldCodePath = pkg.mPath;
9821 String newCodePath = mp.targetArgs.getCodePath();
9822 String newResPath = mp.targetArgs.getResourcePath();
9823 pkg.mPath = newCodePath;
9824 // Move dex files around
9825 if (moveDexFilesLI(pkg)
9826 != PackageManager.INSTALL_SUCCEEDED) {
9827 // Moving of dex files failed. Set
9828 // error code and abort move.
9829 pkg.mPath = pkg.mScanPath;
9830 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9831 } else {
9832 pkg.mScanPath = newCodePath;
9833 pkg.applicationInfo.sourceDir = newCodePath;
9834 pkg.applicationInfo.publicSourceDir = newResPath;
9835 PackageSetting ps = (PackageSetting) pkg.mExtras;
9836 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9837 ps.codePathString = ps.codePath.getPath();
9838 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9839 ps.resourcePathString = ps.resourcePath.getPath();
9840 // Set the application info flag correctly.
9841 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9842 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9843 } else {
9844 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9845 }
9846 ps.setFlags(pkg.applicationInfo.flags);
9847 mAppDirs.remove(oldCodePath);
9848 mAppDirs.put(newCodePath, pkg);
9849 // Persist settings
9850 mSettings.writeLP();
9851 }
9852 }
9853 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009854 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009855 // Send resources available broadcast
9856 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009857 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009858 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009859 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009860 // Clean up failed installation
9861 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009862 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009863 }
9864 } else {
9865 // Force a gc to clear things up.
9866 Runtime.getRuntime().gc();
9867 // Delete older code
9868 synchronized (mInstallLock) {
9869 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009870 }
9871 }
9872 IPackageMoveObserver observer = mp.observer;
9873 if (observer != null) {
9874 try {
9875 observer.packageMoved(mp.packageName, returnCode);
9876 } catch (RemoteException e) {
9877 Log.i(TAG, "Observer no longer exists.");
9878 }
9879 }
9880 }
9881 });
9882 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009883
9884 public boolean setInstallLocation(int loc) {
9885 mContext.enforceCallingOrSelfPermission(
9886 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9887 if (getInstallLocation() == loc) {
9888 return true;
9889 }
9890 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9891 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9892 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9893 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9894 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9895 return true;
9896 }
9897 return false;
9898 }
9899
9900 public int getInstallLocation() {
9901 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9902 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009904}
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009905