blob: 82ea6e1ee8bea79cb03c216467a5a9e64ff6d5ee [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 }
6092 @Override
6093 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
6094 boolean ordered, boolean sticky) throws RemoteException {
6095 // Force a gc to clear up things
6096 Runtime.getRuntime().gc();
6097 // We delete after a gc for applications on sdcard.
6098 if (deleteOld && args != null) {
6099 synchronized (mInstallLock) {
6100 args.doPostDeleteLI(true);
6101 }
6102 }
6103 }
6104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 static class PackageRemovedInfo {
6106 String removedPackage;
6107 int uid = -1;
6108 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006109 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006110 // Clean up resources deleted packages.
6111 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006112
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07006113 void sendBroadcast(boolean fullRemove, boolean replacing,
6114 IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 Bundle extras = new Bundle(1);
6116 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6117 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6118 if (replacing) {
6119 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6120 }
6121 if (removedPackage != null) {
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07006122 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, finishedReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 }
6124 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006125 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 }
6127 }
6128 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 /*
6131 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6132 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006133 * 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 -08006134 * delete a partially installed application.
6135 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006136 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 int flags) {
6138 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006139 if (outInfo != null) {
6140 outInfo.removedPackage = packageName;
6141 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006142 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 // Retrieve object to delete permissions for shared user later on
6144 PackageSetting deletedPs;
6145 synchronized (mPackages) {
6146 deletedPs = mSettings.mPackages.get(packageName);
6147 }
6148 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6149 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006150 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006152 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 + packageName + ", retcode=" + retCode);
6154 // we don't consider this to be a failure of the core package deletion
6155 }
6156 } else {
6157 //for emulator
6158 PackageParser.Package pkg = mPackages.get(packageName);
6159 File dataDir = new File(pkg.applicationInfo.dataDir);
6160 dataDir.delete();
6161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 }
6163 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006164 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006165 schedulePackageCleaning(packageName);
6166
6167 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6168 if (outInfo != null) {
6169 outInfo.removedUid = mSettings.removePackageLP(packageName);
6170 }
6171 if (deletedPs != null) {
6172 updatePermissionsLP(deletedPs.name, null, false, false);
6173 if (deletedPs.sharedUser != null) {
6174 // remove permissions associated with package
6175 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6176 }
6177 }
6178 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006179 // remove from preferred activities.
6180 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6181 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6182 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6183 removed.add(pa);
6184 }
6185 }
6186 for (PreferredActivity pa : removed) {
6187 mSettings.mPreferredActivities.removeFilter(pa);
6188 }
6189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006191 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 }
6193 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 /*
6196 * Tries to delete system package.
6197 */
6198 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006199 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 ApplicationInfo applicationInfo = p.applicationInfo;
6201 //applicable for non-partially installed applications only
6202 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006203 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 return false;
6205 }
6206 PackageSetting ps = null;
6207 // Confirm if the system package has been updated
6208 // An updated system app can be deleted. This will also have to restore
6209 // the system pkg from system partition
6210 synchronized (mPackages) {
6211 ps = mSettings.getDisabledSystemPkg(p.packageName);
6212 }
6213 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006214 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 return false;
6216 } else {
6217 Log.i(TAG, "Deleting system pkg from data partition");
6218 }
6219 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006220 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006221 boolean deleteCodeAndResources = false;
6222 if (ps.versionCode < p.mVersionCode) {
6223 // Delete code and resources for downgrades
6224 deleteCodeAndResources = true;
6225 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6226 flags &= ~PackageManager.DONT_DELETE_DATA;
6227 }
6228 } else {
6229 // Preserve data by setting flag
6230 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6231 flags |= PackageManager.DONT_DELETE_DATA;
6232 }
6233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6235 if (!ret) {
6236 return false;
6237 }
6238 synchronized (mPackages) {
6239 // Reinstate the old system package
6240 mSettings.enableSystemPackageLP(p.packageName);
6241 }
6242 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006243 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006245 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006248 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006249 return false;
6250 }
6251 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006252 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 mSettings.writeLP();
6254 }
6255 return true;
6256 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6259 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6260 ApplicationInfo applicationInfo = p.applicationInfo;
6261 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006262 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 return false;
6264 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006265 if (outInfo != null) {
6266 outInfo.uid = applicationInfo.uid;
6267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268
6269 // Delete package data from internal structures and also remove data if flag is set
6270 removePackageDataLI(p, outInfo, flags);
6271
6272 // Delete application code and resources
6273 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006274 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006275 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006276 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006277 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6278 PackageManager.INSTALL_FORWARD_LOCK : 0;
6279 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006280 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 }
6282 return true;
6283 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 /*
6286 * This method handles package deletion in general
6287 */
6288 private boolean deletePackageLI(String packageName,
6289 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6290 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006291 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 return false;
6293 }
6294 PackageParser.Package p;
6295 boolean dataOnly = false;
6296 synchronized (mPackages) {
6297 p = mPackages.get(packageName);
6298 if (p == null) {
6299 //this retrieves partially installed apps
6300 dataOnly = true;
6301 PackageSetting ps = mSettings.mPackages.get(packageName);
6302 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006303 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 return false;
6305 }
6306 p = ps.pkg;
6307 }
6308 }
6309 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006310 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 return false;
6312 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 if (dataOnly) {
6315 // Delete application data first
6316 removePackageDataLI(p, outInfo, flags);
6317 return true;
6318 }
6319 // At this point the package should have ApplicationInfo associated with it
6320 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006321 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 return false;
6323 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006324 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6326 Log.i(TAG, "Removing system package:"+p.packageName);
6327 // When an updated system application is deleted we delete the existing resources as well and
6328 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006329 ret = deleteSystemPackageLI(p, flags, outInfo);
6330 } else {
6331 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006332 // Kill application pre-emptively especially for apps on sd.
6333 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006334 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006336 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 public void clearApplicationUserData(final String packageName,
6340 final IPackageDataObserver observer) {
6341 mContext.enforceCallingOrSelfPermission(
6342 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6343 // Queue up an async operation since the package deletion may take a little while.
6344 mHandler.post(new Runnable() {
6345 public void run() {
6346 mHandler.removeCallbacks(this);
6347 final boolean succeeded;
6348 synchronized (mInstallLock) {
6349 succeeded = clearApplicationUserDataLI(packageName);
6350 }
6351 if (succeeded) {
6352 // invoke DeviceStorageMonitor's update method to clear any notifications
6353 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6354 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6355 if (dsm != null) {
6356 dsm.updateMemory();
6357 }
6358 }
6359 if(observer != null) {
6360 try {
6361 observer.onRemoveCompleted(packageName, succeeded);
6362 } catch (RemoteException e) {
6363 Log.i(TAG, "Observer no longer exists.");
6364 }
6365 } //end if observer
6366 } //end run
6367 });
6368 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 private boolean clearApplicationUserDataLI(String packageName) {
6371 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006372 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 return false;
6374 }
6375 PackageParser.Package p;
6376 boolean dataOnly = false;
6377 synchronized (mPackages) {
6378 p = mPackages.get(packageName);
6379 if(p == null) {
6380 dataOnly = true;
6381 PackageSetting ps = mSettings.mPackages.get(packageName);
6382 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006383 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 return false;
6385 }
6386 p = ps.pkg;
6387 }
6388 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 if(!dataOnly) {
6391 //need to check this only for fully installed applications
6392 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006393 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 return false;
6395 }
6396 final ApplicationInfo applicationInfo = p.applicationInfo;
6397 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006398 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 return false;
6400 }
6401 }
6402 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006403 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006405 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 + packageName);
6407 return false;
6408 }
6409 }
6410 return true;
6411 }
6412
6413 public void deleteApplicationCacheFiles(final String packageName,
6414 final IPackageDataObserver observer) {
6415 mContext.enforceCallingOrSelfPermission(
6416 android.Manifest.permission.DELETE_CACHE_FILES, null);
6417 // Queue up an async operation since the package deletion may take a little while.
6418 mHandler.post(new Runnable() {
6419 public void run() {
6420 mHandler.removeCallbacks(this);
6421 final boolean succeded;
6422 synchronized (mInstallLock) {
6423 succeded = deleteApplicationCacheFilesLI(packageName);
6424 }
6425 if(observer != null) {
6426 try {
6427 observer.onRemoveCompleted(packageName, succeded);
6428 } catch (RemoteException e) {
6429 Log.i(TAG, "Observer no longer exists.");
6430 }
6431 } //end if observer
6432 } //end run
6433 });
6434 }
6435
6436 private boolean deleteApplicationCacheFilesLI(String packageName) {
6437 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006438 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 return false;
6440 }
6441 PackageParser.Package p;
6442 synchronized (mPackages) {
6443 p = mPackages.get(packageName);
6444 }
6445 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006446 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 return false;
6448 }
6449 final ApplicationInfo applicationInfo = p.applicationInfo;
6450 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006451 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 return false;
6453 }
6454 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006455 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006457 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 + packageName);
6459 return false;
6460 }
6461 }
6462 return true;
6463 }
6464
6465 public void getPackageSizeInfo(final String packageName,
6466 final IPackageStatsObserver observer) {
6467 mContext.enforceCallingOrSelfPermission(
6468 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6469 // Queue up an async operation since the package deletion may take a little while.
6470 mHandler.post(new Runnable() {
6471 public void run() {
6472 mHandler.removeCallbacks(this);
6473 PackageStats lStats = new PackageStats(packageName);
6474 final boolean succeded;
6475 synchronized (mInstallLock) {
6476 succeded = getPackageSizeInfoLI(packageName, lStats);
6477 }
6478 if(observer != null) {
6479 try {
6480 observer.onGetStatsCompleted(lStats, succeded);
6481 } catch (RemoteException e) {
6482 Log.i(TAG, "Observer no longer exists.");
6483 }
6484 } //end if observer
6485 } //end run
6486 });
6487 }
6488
6489 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6490 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006491 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 return false;
6493 }
6494 PackageParser.Package p;
6495 boolean dataOnly = false;
6496 synchronized (mPackages) {
6497 p = mPackages.get(packageName);
6498 if(p == null) {
6499 dataOnly = true;
6500 PackageSetting ps = mSettings.mPackages.get(packageName);
6501 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006502 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006503 return false;
6504 }
6505 p = ps.pkg;
6506 }
6507 }
6508 String publicSrcDir = null;
6509 if(!dataOnly) {
6510 final ApplicationInfo applicationInfo = p.applicationInfo;
6511 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006512 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 return false;
6514 }
6515 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6516 }
6517 if (mInstaller != null) {
6518 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006519 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 if (res < 0) {
6521 return false;
6522 } else {
6523 return true;
6524 }
6525 }
6526 return true;
6527 }
6528
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 public void addPackageToPreferred(String packageName) {
6531 mContext.enforceCallingOrSelfPermission(
6532 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006533 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 }
6535
6536 public void removePackageFromPreferred(String packageName) {
6537 mContext.enforceCallingOrSelfPermission(
6538 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006539 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 }
6541
6542 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006543 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 }
6545
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006546 int getUidTargetSdkVersionLockedLP(int uid) {
6547 Object obj = mSettings.getUserIdLP(uid);
6548 if (obj instanceof SharedUserSetting) {
6549 SharedUserSetting sus = (SharedUserSetting)obj;
6550 final int N = sus.packages.size();
6551 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6552 Iterator<PackageSetting> it = sus.packages.iterator();
6553 int i=0;
6554 while (it.hasNext()) {
6555 PackageSetting ps = it.next();
6556 if (ps.pkg != null) {
6557 int v = ps.pkg.applicationInfo.targetSdkVersion;
6558 if (v < vers) vers = v;
6559 }
6560 }
6561 return vers;
6562 } else if (obj instanceof PackageSetting) {
6563 PackageSetting ps = (PackageSetting)obj;
6564 if (ps.pkg != null) {
6565 return ps.pkg.applicationInfo.targetSdkVersion;
6566 }
6567 }
6568 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6569 }
6570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 public void addPreferredActivity(IntentFilter filter, int match,
6572 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006574 if (mContext.checkCallingOrSelfPermission(
6575 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6576 != PackageManager.PERMISSION_GRANTED) {
6577 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6578 < Build.VERSION_CODES.FROYO) {
6579 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6580 + Binder.getCallingUid());
6581 return;
6582 }
6583 mContext.enforceCallingOrSelfPermission(
6584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6585 }
6586
6587 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6589 mSettings.mPreferredActivities.addFilter(
6590 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006591 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 }
6593 }
6594
Satish Sampath8dbe6122009-06-02 23:35:54 +01006595 public void replacePreferredActivity(IntentFilter filter, int match,
6596 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006597 if (filter.countActions() != 1) {
6598 throw new IllegalArgumentException(
6599 "replacePreferredActivity expects filter to have only 1 action.");
6600 }
6601 if (filter.countCategories() != 1) {
6602 throw new IllegalArgumentException(
6603 "replacePreferredActivity expects filter to have only 1 category.");
6604 }
6605 if (filter.countDataAuthorities() != 0
6606 || filter.countDataPaths() != 0
6607 || filter.countDataSchemes() != 0
6608 || filter.countDataTypes() != 0) {
6609 throw new IllegalArgumentException(
6610 "replacePreferredActivity expects filter to have no data authorities, " +
6611 "paths, schemes or types.");
6612 }
6613 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006614 if (mContext.checkCallingOrSelfPermission(
6615 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6616 != PackageManager.PERMISSION_GRANTED) {
6617 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6618 < Build.VERSION_CODES.FROYO) {
6619 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6620 + Binder.getCallingUid());
6621 return;
6622 }
6623 mContext.enforceCallingOrSelfPermission(
6624 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6625 }
6626
Satish Sampath8dbe6122009-06-02 23:35:54 +01006627 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6628 String action = filter.getAction(0);
6629 String category = filter.getCategory(0);
6630 while (it.hasNext()) {
6631 PreferredActivity pa = it.next();
6632 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6633 it.remove();
6634 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6635 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6636 }
6637 }
6638 addPreferredActivity(filter, match, set, activity);
6639 }
6640 }
6641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006644 int uid = Binder.getCallingUid();
6645 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006646 if (pkg == null || pkg.applicationInfo.uid != uid) {
6647 if (mContext.checkCallingOrSelfPermission(
6648 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6649 != PackageManager.PERMISSION_GRANTED) {
6650 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6651 < Build.VERSION_CODES.FROYO) {
6652 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6653 + Binder.getCallingUid());
6654 return;
6655 }
6656 mContext.enforceCallingOrSelfPermission(
6657 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6658 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006659 }
6660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006662 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 }
6664 }
6665 }
6666
6667 boolean clearPackagePreferredActivitiesLP(String packageName) {
6668 boolean changed = false;
6669 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6670 while (it.hasNext()) {
6671 PreferredActivity pa = it.next();
6672 if (pa.mActivity.getPackageName().equals(packageName)) {
6673 it.remove();
6674 changed = true;
6675 }
6676 }
6677 return changed;
6678 }
6679
6680 public int getPreferredActivities(List<IntentFilter> outFilters,
6681 List<ComponentName> outActivities, String packageName) {
6682
6683 int num = 0;
6684 synchronized (mPackages) {
6685 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6686 while (it.hasNext()) {
6687 PreferredActivity pa = it.next();
6688 if (packageName == null
6689 || pa.mActivity.getPackageName().equals(packageName)) {
6690 if (outFilters != null) {
6691 outFilters.add(new IntentFilter(pa));
6692 }
6693 if (outActivities != null) {
6694 outActivities.add(pa.mActivity);
6695 }
6696 }
6697 }
6698 }
6699
6700 return num;
6701 }
6702
6703 public void setApplicationEnabledSetting(String appPackageName,
6704 int newState, int flags) {
6705 setEnabledSetting(appPackageName, null, newState, flags);
6706 }
6707
6708 public void setComponentEnabledSetting(ComponentName componentName,
6709 int newState, int flags) {
6710 setEnabledSetting(componentName.getPackageName(),
6711 componentName.getClassName(), newState, flags);
6712 }
6713
6714 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006715 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6717 || newState == COMPONENT_ENABLED_STATE_ENABLED
6718 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6719 throw new IllegalArgumentException("Invalid new component state: "
6720 + newState);
6721 }
6722 PackageSetting pkgSetting;
6723 final int uid = Binder.getCallingUid();
6724 final int permission = mContext.checkCallingPermission(
6725 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6726 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006727 boolean sendNow = false;
6728 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006729 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006731 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006733 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006735 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006737 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 }
6739 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006740 "Unknown component: " + packageName
6741 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 }
6743 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6744 throw new SecurityException(
6745 "Permission Denial: attempt to change component state from pid="
6746 + Binder.getCallingPid()
6747 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6748 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006749 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006751 if (pkgSetting.enabled == newState) {
6752 // Nothing to do
6753 return;
6754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 pkgSetting.enabled = newState;
6756 } else {
6757 // We're dealing with a component level state change
6758 switch (newState) {
6759 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006760 if (!pkgSetting.enableComponentLP(className)) {
6761 return;
6762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 break;
6764 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006765 if (!pkgSetting.disableComponentLP(className)) {
6766 return;
6767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 break;
6769 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006770 if (!pkgSetting.restoreComponentLP(className)) {
6771 return;
6772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 break;
6774 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006775 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006776 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 }
6778 }
6779 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006780 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006781 components = mPendingBroadcasts.get(packageName);
6782 boolean newPackage = components == null;
6783 if (newPackage) {
6784 components = new ArrayList<String>();
6785 }
6786 if (!components.contains(componentName)) {
6787 components.add(componentName);
6788 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006789 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6790 sendNow = true;
6791 // Purge entry from pending broadcast list if another one exists already
6792 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006793 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006794 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006795 if (newPackage) {
6796 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006797 }
6798 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6799 // Schedule a message
6800 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6801 }
6802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 long callingId = Binder.clearCallingIdentity();
6806 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006807 if (sendNow) {
6808 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006809 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 } finally {
6812 Binder.restoreCallingIdentity(callingId);
6813 }
6814 }
6815
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006816 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006817 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6818 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6819 + " components=" + componentNames);
6820 Bundle extras = new Bundle(4);
6821 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6822 String nameList[] = new String[componentNames.size()];
6823 componentNames.toArray(nameList);
6824 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006825 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6826 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006827 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006828 }
6829
Jacek Surazski65e13172009-04-28 15:26:38 +02006830 public String getInstallerPackageName(String packageName) {
6831 synchronized (mPackages) {
6832 PackageSetting pkg = mSettings.mPackages.get(packageName);
6833 if (pkg == null) {
6834 throw new IllegalArgumentException("Unknown package: " + packageName);
6835 }
6836 return pkg.installerPackageName;
6837 }
6838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 public int getApplicationEnabledSetting(String appPackageName) {
6841 synchronized (mPackages) {
6842 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6843 if (pkg == null) {
6844 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6845 }
6846 return pkg.enabled;
6847 }
6848 }
6849
6850 public int getComponentEnabledSetting(ComponentName componentName) {
6851 synchronized (mPackages) {
6852 final String packageNameStr = componentName.getPackageName();
6853 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6854 if (pkg == null) {
6855 throw new IllegalArgumentException("Unknown component: " + componentName);
6856 }
6857 final String classNameStr = componentName.getClassName();
6858 return pkg.currentEnabledStateLP(classNameStr);
6859 }
6860 }
6861
6862 public void enterSafeMode() {
6863 if (!mSystemReady) {
6864 mSafeMode = true;
6865 }
6866 }
6867
6868 public void systemReady() {
6869 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006870
6871 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006872 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006873 mContext.getContentResolver(),
6874 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006875 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006876 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006877 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006879 }
6880
6881 public boolean isSafeMode() {
6882 return mSafeMode;
6883 }
6884
6885 public boolean hasSystemUidErrors() {
6886 return mHasSystemUidErrors;
6887 }
6888
6889 static String arrayToString(int[] array) {
6890 StringBuffer buf = new StringBuffer(128);
6891 buf.append('[');
6892 if (array != null) {
6893 for (int i=0; i<array.length; i++) {
6894 if (i > 0) buf.append(", ");
6895 buf.append(array[i]);
6896 }
6897 }
6898 buf.append(']');
6899 return buf.toString();
6900 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006902 @Override
6903 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6904 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6905 != PackageManager.PERMISSION_GRANTED) {
6906 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6907 + Binder.getCallingPid()
6908 + ", uid=" + Binder.getCallingUid()
6909 + " without permission "
6910 + android.Manifest.permission.DUMP);
6911 return;
6912 }
6913
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006914 String packageName = null;
6915
6916 int opti = 0;
6917 while (opti < args.length) {
6918 String opt = args[opti];
6919 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6920 break;
6921 }
6922 opti++;
6923 if ("-a".equals(opt)) {
6924 // Right now we only know how to print all.
6925 } else if ("-h".equals(opt)) {
6926 pw.println("Package manager dump options:");
6927 pw.println(" [-h] [cmd] ...");
6928 pw.println(" cmd may be one of:");
6929 pw.println(" [package.name]: info about given package");
6930 return;
6931 } else {
6932 pw.println("Unknown argument: " + opt + "; use -h for help");
6933 }
6934 }
6935
6936 // Is the caller requesting to dump a particular piece of data?
6937 if (opti < args.length) {
6938 String cmd = args[opti];
6939 opti++;
6940 // Is this a package name?
6941 if ("android".equals(cmd) || cmd.contains(".")) {
6942 packageName = cmd;
6943 }
6944 }
6945
6946 boolean printedTitle = false;
6947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006949 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6950 printedTitle = true;
6951 }
6952 if (mReceivers.dump(pw, printedTitle
6953 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6954 " ", packageName)) {
6955 printedTitle = true;
6956 }
6957 if (mServices.dump(pw, printedTitle
6958 ? "\nService Resolver Table:" : "Service Resolver Table:",
6959 " ", packageName)) {
6960 printedTitle = true;
6961 }
6962 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6963 ? "\nPreferred Activities:" : "Preferred Activities:",
6964 " ", packageName)) {
6965 printedTitle = true;
6966 }
6967 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006968 {
6969 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006970 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6971 continue;
6972 }
6973 if (!printedSomething) {
6974 if (printedTitle) pw.println(" ");
6975 pw.println("Permissions:");
6976 printedSomething = true;
6977 printedTitle = true;
6978 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006979 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6980 pw.print(Integer.toHexString(System.identityHashCode(p)));
6981 pw.println("):");
6982 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6983 pw.print(" uid="); pw.print(p.uid);
6984 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006985 pw.print(" type="); pw.print(p.type);
6986 pw.print(" prot="); pw.println(p.protectionLevel);
6987 if (p.packageSetting != null) {
6988 pw.print(" packageSetting="); pw.println(p.packageSetting);
6989 }
6990 if (p.perm != null) {
6991 pw.print(" perm="); pw.println(p.perm);
6992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006993 }
6994 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006995 printedSomething = false;
6996 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 {
6998 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006999 if (packageName != null && !packageName.equals(ps.realName)
7000 && !packageName.equals(ps.name)) {
7001 continue;
7002 }
7003 if (!printedSomething) {
7004 if (printedTitle) pw.println(" ");
7005 pw.println("Packages:");
7006 printedSomething = true;
7007 printedTitle = true;
7008 }
7009 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007010 pw.print(" Package [");
7011 pw.print(ps.realName != null ? ps.realName : ps.name);
7012 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007013 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7014 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007015 if (ps.realName != null) {
7016 pw.print(" compat name="); pw.println(ps.name);
7017 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007018 pw.print(" userId="); pw.print(ps.userId);
7019 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7020 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7021 pw.print(" pkg="); pw.println(ps.pkg);
7022 pw.print(" codePath="); pw.println(ps.codePathString);
7023 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007025 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007026 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007027 pw.print(" supportsScreens=[");
7028 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007029 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007030 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007031 if (!first) pw.print(", ");
7032 first = false;
7033 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007034 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007035 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007036 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007037 if (!first) pw.print(", ");
7038 first = false;
7039 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007041 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007042 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007043 if (!first) pw.print(", ");
7044 first = false;
7045 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007046 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007047 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007048 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007049 if (!first) pw.print(", ");
7050 first = false;
7051 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007052 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007053 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007054 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7055 if (!first) pw.print(", ");
7056 first = false;
7057 pw.print("anyDensity");
7058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007059 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007060 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007061 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7062 pw.print(" signatures="); pw.println(ps.signatures);
7063 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007064 pw.print(" haveGids="); pw.println(ps.haveGids);
7065 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007066 pw.print(" installStatus="); pw.print(ps.installStatus);
7067 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 if (ps.disabledComponents.size() > 0) {
7069 pw.println(" disabledComponents:");
7070 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007071 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 }
7073 }
7074 if (ps.enabledComponents.size() > 0) {
7075 pw.println(" enabledComponents:");
7076 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007077 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 }
7079 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007080 if (ps.grantedPermissions.size() > 0) {
7081 pw.println(" grantedPermissions:");
7082 for (String s : ps.grantedPermissions) {
7083 pw.print(" "); pw.println(s);
7084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007086 }
7087 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007088 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007089 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007090 for (HashMap.Entry<String, String> e
7091 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007092 if (packageName != null && !packageName.equals(e.getKey())
7093 && !packageName.equals(e.getValue())) {
7094 continue;
7095 }
7096 if (!printedSomething) {
7097 if (printedTitle) pw.println(" ");
7098 pw.println("Renamed packages:");
7099 printedSomething = true;
7100 printedTitle = true;
7101 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007102 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7103 pw.println(e.getValue());
7104 }
7105 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007106 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007107 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007108 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007109 if (packageName != null && !packageName.equals(ps.realName)
7110 && !packageName.equals(ps.name)) {
7111 continue;
7112 }
7113 if (!printedSomething) {
7114 if (printedTitle) pw.println(" ");
7115 pw.println("Hidden system packages:");
7116 printedSomething = true;
7117 printedTitle = true;
7118 }
7119 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007120 pw.print(ps.realName != null ? ps.realName : ps.name);
7121 pw.print("] (");
7122 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7123 pw.println("):");
7124 if (ps.realName != null) {
7125 pw.print(" compat name="); pw.println(ps.name);
7126 }
7127 pw.print(" userId="); pw.println(ps.userId);
7128 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7129 pw.print(" codePath="); pw.println(ps.codePathString);
7130 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7131 }
7132 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007133 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 {
7135 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007136 if (packageName != null && su != packageSharedUser) {
7137 continue;
7138 }
7139 if (!printedSomething) {
7140 if (printedTitle) pw.println(" ");
7141 pw.println("Shared users:");
7142 printedSomething = true;
7143 printedTitle = true;
7144 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007145 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7146 pw.print(Integer.toHexString(System.identityHashCode(su)));
7147 pw.println("):");
7148 pw.print(" userId="); pw.print(su.userId);
7149 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 pw.println(" grantedPermissions:");
7151 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007152 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 }
7155 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007156
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007157 if (packageName == null) {
7158 if (printedTitle) pw.println(" ");
7159 printedTitle = true;
7160 pw.println("Settings parse messages:");
7161 pw.println(mSettings.mReadMessages.toString());
7162
7163 pw.println(" ");
7164 pw.println("Package warning messages:");
7165 File fname = getSettingsProblemFile();
7166 FileInputStream in;
7167 try {
7168 in = new FileInputStream(fname);
7169 int avail = in.available();
7170 byte[] data = new byte[avail];
7171 in.read(data);
7172 pw.println(new String(data));
7173 } catch (FileNotFoundException e) {
7174 } catch (IOException e) {
7175 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007178
7179 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007180 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007181 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007182 if (packageName != null && !packageName.equals(p.info.packageName)) {
7183 continue;
7184 }
7185 if (!printedSomething) {
7186 if (printedTitle) pw.println(" ");
7187 pw.println("Registered ContentProviders:");
7188 printedSomething = true;
7189 printedTitle = true;
7190 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007191 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007192 pw.println(p.toString());
7193 }
7194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007195 }
7196
7197 static final class BasePermission {
7198 final static int TYPE_NORMAL = 0;
7199 final static int TYPE_BUILTIN = 1;
7200 final static int TYPE_DYNAMIC = 2;
7201
7202 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007203 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007204 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007206 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007207 PackageParser.Permission perm;
7208 PermissionInfo pendingInfo;
7209 int uid;
7210 int[] gids;
7211
7212 BasePermission(String _name, String _sourcePackage, int _type) {
7213 name = _name;
7214 sourcePackage = _sourcePackage;
7215 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007216 // Default to most conservative protection level.
7217 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7218 }
7219
7220 public String toString() {
7221 return "BasePermission{"
7222 + Integer.toHexString(System.identityHashCode(this))
7223 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 }
7225 }
7226
7227 static class PackageSignatures {
7228 private Signature[] mSignatures;
7229
7230 PackageSignatures(Signature[] sigs) {
7231 assignSignatures(sigs);
7232 }
7233
7234 PackageSignatures() {
7235 }
7236
7237 void writeXml(XmlSerializer serializer, String tagName,
7238 ArrayList<Signature> pastSignatures) throws IOException {
7239 if (mSignatures == null) {
7240 return;
7241 }
7242 serializer.startTag(null, tagName);
7243 serializer.attribute(null, "count",
7244 Integer.toString(mSignatures.length));
7245 for (int i=0; i<mSignatures.length; i++) {
7246 serializer.startTag(null, "cert");
7247 final Signature sig = mSignatures[i];
7248 final int sigHash = sig.hashCode();
7249 final int numPast = pastSignatures.size();
7250 int j;
7251 for (j=0; j<numPast; j++) {
7252 Signature pastSig = pastSignatures.get(j);
7253 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7254 serializer.attribute(null, "index", Integer.toString(j));
7255 break;
7256 }
7257 }
7258 if (j >= numPast) {
7259 pastSignatures.add(sig);
7260 serializer.attribute(null, "index", Integer.toString(numPast));
7261 serializer.attribute(null, "key", sig.toCharsString());
7262 }
7263 serializer.endTag(null, "cert");
7264 }
7265 serializer.endTag(null, tagName);
7266 }
7267
7268 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7269 throws IOException, XmlPullParserException {
7270 String countStr = parser.getAttributeValue(null, "count");
7271 if (countStr == null) {
7272 reportSettingsProblem(Log.WARN,
7273 "Error in package manager settings: <signatures> has"
7274 + " no count at " + parser.getPositionDescription());
7275 XmlUtils.skipCurrentTag(parser);
7276 }
7277 final int count = Integer.parseInt(countStr);
7278 mSignatures = new Signature[count];
7279 int pos = 0;
7280
7281 int outerDepth = parser.getDepth();
7282 int type;
7283 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7284 && (type != XmlPullParser.END_TAG
7285 || parser.getDepth() > outerDepth)) {
7286 if (type == XmlPullParser.END_TAG
7287 || type == XmlPullParser.TEXT) {
7288 continue;
7289 }
7290
7291 String tagName = parser.getName();
7292 if (tagName.equals("cert")) {
7293 if (pos < count) {
7294 String index = parser.getAttributeValue(null, "index");
7295 if (index != null) {
7296 try {
7297 int idx = Integer.parseInt(index);
7298 String key = parser.getAttributeValue(null, "key");
7299 if (key == null) {
7300 if (idx >= 0 && idx < pastSignatures.size()) {
7301 Signature sig = pastSignatures.get(idx);
7302 if (sig != null) {
7303 mSignatures[pos] = pastSignatures.get(idx);
7304 pos++;
7305 } else {
7306 reportSettingsProblem(Log.WARN,
7307 "Error in package manager settings: <cert> "
7308 + "index " + index + " is not defined at "
7309 + parser.getPositionDescription());
7310 }
7311 } else {
7312 reportSettingsProblem(Log.WARN,
7313 "Error in package manager settings: <cert> "
7314 + "index " + index + " is out of bounds at "
7315 + parser.getPositionDescription());
7316 }
7317 } else {
7318 while (pastSignatures.size() <= idx) {
7319 pastSignatures.add(null);
7320 }
7321 Signature sig = new Signature(key);
7322 pastSignatures.set(idx, sig);
7323 mSignatures[pos] = sig;
7324 pos++;
7325 }
7326 } catch (NumberFormatException e) {
7327 reportSettingsProblem(Log.WARN,
7328 "Error in package manager settings: <cert> "
7329 + "index " + index + " is not a number at "
7330 + parser.getPositionDescription());
7331 }
7332 } else {
7333 reportSettingsProblem(Log.WARN,
7334 "Error in package manager settings: <cert> has"
7335 + " no index at " + parser.getPositionDescription());
7336 }
7337 } else {
7338 reportSettingsProblem(Log.WARN,
7339 "Error in package manager settings: too "
7340 + "many <cert> tags, expected " + count
7341 + " at " + parser.getPositionDescription());
7342 }
7343 } else {
7344 reportSettingsProblem(Log.WARN,
7345 "Unknown element under <cert>: "
7346 + parser.getName());
7347 }
7348 XmlUtils.skipCurrentTag(parser);
7349 }
7350
7351 if (pos < count) {
7352 // Should never happen -- there is an error in the written
7353 // settings -- but if it does we don't want to generate
7354 // a bad array.
7355 Signature[] newSigs = new Signature[pos];
7356 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7357 mSignatures = newSigs;
7358 }
7359 }
7360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007361 private void assignSignatures(Signature[] sigs) {
7362 if (sigs == null) {
7363 mSignatures = null;
7364 return;
7365 }
7366 mSignatures = new Signature[sigs.length];
7367 for (int i=0; i<sigs.length; i++) {
7368 mSignatures[i] = sigs[i];
7369 }
7370 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007372 @Override
7373 public String toString() {
7374 StringBuffer buf = new StringBuffer(128);
7375 buf.append("PackageSignatures{");
7376 buf.append(Integer.toHexString(System.identityHashCode(this)));
7377 buf.append(" [");
7378 if (mSignatures != null) {
7379 for (int i=0; i<mSignatures.length; i++) {
7380 if (i > 0) buf.append(", ");
7381 buf.append(Integer.toHexString(
7382 System.identityHashCode(mSignatures[i])));
7383 }
7384 }
7385 buf.append("]}");
7386 return buf.toString();
7387 }
7388 }
7389
7390 static class PreferredActivity extends IntentFilter {
7391 final int mMatch;
7392 final String[] mSetPackages;
7393 final String[] mSetClasses;
7394 final String[] mSetComponents;
7395 final ComponentName mActivity;
7396 final String mShortActivity;
7397 String mParseError;
7398
7399 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7400 ComponentName activity) {
7401 super(filter);
7402 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7403 mActivity = activity;
7404 mShortActivity = activity.flattenToShortString();
7405 mParseError = null;
7406 if (set != null) {
7407 final int N = set.length;
7408 String[] myPackages = new String[N];
7409 String[] myClasses = new String[N];
7410 String[] myComponents = new String[N];
7411 for (int i=0; i<N; i++) {
7412 ComponentName cn = set[i];
7413 if (cn == null) {
7414 mSetPackages = null;
7415 mSetClasses = null;
7416 mSetComponents = null;
7417 return;
7418 }
7419 myPackages[i] = cn.getPackageName().intern();
7420 myClasses[i] = cn.getClassName().intern();
7421 myComponents[i] = cn.flattenToShortString().intern();
7422 }
7423 mSetPackages = myPackages;
7424 mSetClasses = myClasses;
7425 mSetComponents = myComponents;
7426 } else {
7427 mSetPackages = null;
7428 mSetClasses = null;
7429 mSetComponents = null;
7430 }
7431 }
7432
7433 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7434 IOException {
7435 mShortActivity = parser.getAttributeValue(null, "name");
7436 mActivity = ComponentName.unflattenFromString(mShortActivity);
7437 if (mActivity == null) {
7438 mParseError = "Bad activity name " + mShortActivity;
7439 }
7440 String matchStr = parser.getAttributeValue(null, "match");
7441 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7442 String setCountStr = parser.getAttributeValue(null, "set");
7443 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7444
7445 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7446 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7447 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7448
7449 int setPos = 0;
7450
7451 int outerDepth = parser.getDepth();
7452 int type;
7453 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7454 && (type != XmlPullParser.END_TAG
7455 || parser.getDepth() > outerDepth)) {
7456 if (type == XmlPullParser.END_TAG
7457 || type == XmlPullParser.TEXT) {
7458 continue;
7459 }
7460
7461 String tagName = parser.getName();
7462 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7463 // + parser.getDepth() + " tag=" + tagName);
7464 if (tagName.equals("set")) {
7465 String name = parser.getAttributeValue(null, "name");
7466 if (name == null) {
7467 if (mParseError == null) {
7468 mParseError = "No name in set tag in preferred activity "
7469 + mShortActivity;
7470 }
7471 } else if (setPos >= setCount) {
7472 if (mParseError == null) {
7473 mParseError = "Too many set tags in preferred activity "
7474 + mShortActivity;
7475 }
7476 } else {
7477 ComponentName cn = ComponentName.unflattenFromString(name);
7478 if (cn == null) {
7479 if (mParseError == null) {
7480 mParseError = "Bad set name " + name + " in preferred activity "
7481 + mShortActivity;
7482 }
7483 } else {
7484 myPackages[setPos] = cn.getPackageName();
7485 myClasses[setPos] = cn.getClassName();
7486 myComponents[setPos] = name;
7487 setPos++;
7488 }
7489 }
7490 XmlUtils.skipCurrentTag(parser);
7491 } else if (tagName.equals("filter")) {
7492 //Log.i(TAG, "Starting to parse filter...");
7493 readFromXml(parser);
7494 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7495 // + parser.getDepth() + " tag=" + parser.getName());
7496 } else {
7497 reportSettingsProblem(Log.WARN,
7498 "Unknown element under <preferred-activities>: "
7499 + parser.getName());
7500 XmlUtils.skipCurrentTag(parser);
7501 }
7502 }
7503
7504 if (setPos != setCount) {
7505 if (mParseError == null) {
7506 mParseError = "Not enough set tags (expected " + setCount
7507 + " but found " + setPos + ") in " + mShortActivity;
7508 }
7509 }
7510
7511 mSetPackages = myPackages;
7512 mSetClasses = myClasses;
7513 mSetComponents = myComponents;
7514 }
7515
7516 public void writeToXml(XmlSerializer serializer) throws IOException {
7517 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7518 serializer.attribute(null, "name", mShortActivity);
7519 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7520 serializer.attribute(null, "set", Integer.toString(NS));
7521 for (int s=0; s<NS; s++) {
7522 serializer.startTag(null, "set");
7523 serializer.attribute(null, "name", mSetComponents[s]);
7524 serializer.endTag(null, "set");
7525 }
7526 serializer.startTag(null, "filter");
7527 super.writeToXml(serializer);
7528 serializer.endTag(null, "filter");
7529 }
7530
7531 boolean sameSet(List<ResolveInfo> query, int priority) {
7532 if (mSetPackages == null) return false;
7533 final int NQ = query.size();
7534 final int NS = mSetPackages.length;
7535 int numMatch = 0;
7536 for (int i=0; i<NQ; i++) {
7537 ResolveInfo ri = query.get(i);
7538 if (ri.priority != priority) continue;
7539 ActivityInfo ai = ri.activityInfo;
7540 boolean good = false;
7541 for (int j=0; j<NS; j++) {
7542 if (mSetPackages[j].equals(ai.packageName)
7543 && mSetClasses[j].equals(ai.name)) {
7544 numMatch++;
7545 good = true;
7546 break;
7547 }
7548 }
7549 if (!good) return false;
7550 }
7551 return numMatch == NS;
7552 }
7553 }
7554
7555 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007556 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558 HashSet<String> grantedPermissions = new HashSet<String>();
7559 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007562 setFlags(pkgFlags);
7563 }
7564
7565 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007566 this.pkgFlags = pkgFlags & (
7567 ApplicationInfo.FLAG_SYSTEM |
7568 ApplicationInfo.FLAG_FORWARD_LOCK |
7569 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007570 }
7571 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 /**
7574 * Settings base class for pending and resolved classes.
7575 */
7576 static class PackageSettingBase extends GrantedPermissions {
7577 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007578 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007579 File codePath;
7580 String codePathString;
7581 File resourcePath;
7582 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 private long timeStamp;
7584 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007585 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007587 boolean uidError;
7588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 PackageSignatures signatures = new PackageSignatures();
7590
7591 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007592 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 /* Explicitly disabled components */
7595 HashSet<String> disabledComponents = new HashSet<String>(0);
7596 /* Explicitly enabled components */
7597 HashSet<String> enabledComponents = new HashSet<String>(0);
7598 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7599 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007600
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007601 PackageSettingBase origPackage;
7602
Jacek Surazski65e13172009-04-28 15:26:38 +02007603 /* package name of the app that installed this package */
7604 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007606 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007607 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 super(pkgFlags);
7609 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007610 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007611 init(codePath, resourcePath, pVersionCode);
7612 }
7613
7614 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007615 this.codePath = codePath;
7616 this.codePathString = codePath.toString();
7617 this.resourcePath = resourcePath;
7618 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007619 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007620 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007621
Jacek Surazski65e13172009-04-28 15:26:38 +02007622 public void setInstallerPackageName(String packageName) {
7623 installerPackageName = packageName;
7624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007625
Jacek Surazski65e13172009-04-28 15:26:38 +02007626 String getInstallerPackageName() {
7627 return installerPackageName;
7628 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630 public void setInstallStatus(int newStatus) {
7631 installStatus = newStatus;
7632 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007634 public int getInstallStatus() {
7635 return installStatus;
7636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007638 public void setTimeStamp(long newStamp) {
7639 if (newStamp != timeStamp) {
7640 timeStamp = newStamp;
7641 timeStampString = Long.toString(newStamp);
7642 }
7643 }
7644
7645 public void setTimeStamp(long newStamp, String newStampStr) {
7646 timeStamp = newStamp;
7647 timeStampString = newStampStr;
7648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007650 public long getTimeStamp() {
7651 return timeStamp;
7652 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007654 public String getTimeStampStr() {
7655 return timeStampString;
7656 }
7657
7658 public void copyFrom(PackageSettingBase base) {
7659 grantedPermissions = base.grantedPermissions;
7660 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 timeStamp = base.timeStamp;
7663 timeStampString = base.timeStampString;
7664 signatures = base.signatures;
7665 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007666 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 disabledComponents = base.disabledComponents;
7668 enabledComponents = base.enabledComponents;
7669 enabled = base.enabled;
7670 installStatus = base.installStatus;
7671 }
7672
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007673 boolean enableComponentLP(String componentClassName) {
7674 boolean changed = disabledComponents.remove(componentClassName);
7675 changed |= enabledComponents.add(componentClassName);
7676 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 }
7678
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007679 boolean disableComponentLP(String componentClassName) {
7680 boolean changed = enabledComponents.remove(componentClassName);
7681 changed |= disabledComponents.add(componentClassName);
7682 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007683 }
7684
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007685 boolean restoreComponentLP(String componentClassName) {
7686 boolean changed = enabledComponents.remove(componentClassName);
7687 changed |= disabledComponents.remove(componentClassName);
7688 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 }
7690
7691 int currentEnabledStateLP(String componentName) {
7692 if (enabledComponents.contains(componentName)) {
7693 return COMPONENT_ENABLED_STATE_ENABLED;
7694 } else if (disabledComponents.contains(componentName)) {
7695 return COMPONENT_ENABLED_STATE_DISABLED;
7696 } else {
7697 return COMPONENT_ENABLED_STATE_DEFAULT;
7698 }
7699 }
7700 }
7701
7702 /**
7703 * Settings data for a particular package we know about.
7704 */
7705 static final class PackageSetting extends PackageSettingBase {
7706 int userId;
7707 PackageParser.Package pkg;
7708 SharedUserSetting sharedUser;
7709
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007710 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007711 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007712 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 @Override
7716 public String toString() {
7717 return "PackageSetting{"
7718 + Integer.toHexString(System.identityHashCode(this))
7719 + " " + name + "/" + userId + "}";
7720 }
7721 }
7722
7723 /**
7724 * Settings data for a particular shared user ID we know about.
7725 */
7726 static final class SharedUserSetting extends GrantedPermissions {
7727 final String name;
7728 int userId;
7729 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7730 final PackageSignatures signatures = new PackageSignatures();
7731
7732 SharedUserSetting(String _name, int _pkgFlags) {
7733 super(_pkgFlags);
7734 name = _name;
7735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 @Override
7738 public String toString() {
7739 return "SharedUserSetting{"
7740 + Integer.toHexString(System.identityHashCode(this))
7741 + " " + name + "/" + userId + "}";
7742 }
7743 }
7744
7745 /**
7746 * Holds information about dynamic settings.
7747 */
7748 private static final class Settings {
7749 private final File mSettingsFilename;
7750 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007751 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752 private final HashMap<String, PackageSetting> mPackages =
7753 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 // List of replaced system applications
7755 final HashMap<String, PackageSetting> mDisabledSysPackages =
7756 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007757
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007758 // These are the last platform API version we were using for
7759 // the apps installed on internal and external storage. It is
7760 // used to grant newer permissions one time during a system upgrade.
7761 int mInternalSdkPlatform;
7762 int mExternalSdkPlatform;
7763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 // The user's preferred activities associated with particular intent
7765 // filters.
7766 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7767 new IntentResolver<PreferredActivity, PreferredActivity>() {
7768 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007769 protected String packageForFilter(PreferredActivity filter) {
7770 return filter.mActivity.getPackageName();
7771 }
7772 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007773 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007775 out.print(prefix); out.print(
7776 Integer.toHexString(System.identityHashCode(filter)));
7777 out.print(' ');
7778 out.print(filter.mActivity.flattenToShortString());
7779 out.print(" match=0x");
7780 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007782 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007784 out.print(prefix); out.print(" ");
7785 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 }
7787 }
7788 }
7789 };
7790 private final HashMap<String, SharedUserSetting> mSharedUsers =
7791 new HashMap<String, SharedUserSetting>();
7792 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7793 private final SparseArray<Object> mOtherUserIds =
7794 new SparseArray<Object>();
7795
7796 // For reading/writing settings file.
7797 private final ArrayList<Signature> mPastSignatures =
7798 new ArrayList<Signature>();
7799
7800 // Mapping from permission names to info about them.
7801 final HashMap<String, BasePermission> mPermissions =
7802 new HashMap<String, BasePermission>();
7803
7804 // Mapping from permission tree names to info about them.
7805 final HashMap<String, BasePermission> mPermissionTrees =
7806 new HashMap<String, BasePermission>();
7807
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007808 // Packages that have been uninstalled and still need their external
7809 // storage data deleted.
7810 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7811
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007812 // Packages that have been renamed since they were first installed.
7813 // Keys are the new names of the packages, values are the original
7814 // names. The packages appear everwhere else under their original
7815 // names.
7816 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 private final StringBuilder mReadMessages = new StringBuilder();
7819
7820 private static final class PendingPackage extends PackageSettingBase {
7821 final int sharedId;
7822
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007823 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007824 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007825 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 this.sharedId = sharedId;
7827 }
7828 }
7829 private final ArrayList<PendingPackage> mPendingPackages
7830 = new ArrayList<PendingPackage>();
7831
7832 Settings() {
7833 File dataDir = Environment.getDataDirectory();
7834 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007835 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 systemDir.mkdirs();
7837 FileUtils.setPermissions(systemDir.toString(),
7838 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7839 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7840 -1, -1);
7841 mSettingsFilename = new File(systemDir, "packages.xml");
7842 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007843 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 }
7845
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007846 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007847 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 int pkgFlags, boolean create, boolean add) {
7849 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007850 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007851 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 return p;
7853 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007854
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007855 PackageSetting peekPackageLP(String name) {
7856 return mPackages.get(name);
7857 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007858 PackageSetting p = mPackages.get(name);
7859 if (p != null && p.codePath.getPath().equals(codePath)) {
7860 return p;
7861 }
7862 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007863 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 void setInstallStatus(String pkgName, int status) {
7867 PackageSetting p = mPackages.get(pkgName);
7868 if(p != null) {
7869 if(p.getInstallStatus() != status) {
7870 p.setInstallStatus(status);
7871 }
7872 }
7873 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007874
Jacek Surazski65e13172009-04-28 15:26:38 +02007875 void setInstallerPackageName(String pkgName,
7876 String installerPkgName) {
7877 PackageSetting p = mPackages.get(pkgName);
7878 if(p != null) {
7879 p.setInstallerPackageName(installerPkgName);
7880 }
7881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007882
Jacek Surazski65e13172009-04-28 15:26:38 +02007883 String getInstallerPackageName(String pkgName) {
7884 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007885 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007886 }
7887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007888 int getInstallStatus(String pkgName) {
7889 PackageSetting p = mPackages.get(pkgName);
7890 if(p != null) {
7891 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 return -1;
7894 }
7895
7896 SharedUserSetting getSharedUserLP(String name,
7897 int pkgFlags, boolean create) {
7898 SharedUserSetting s = mSharedUsers.get(name);
7899 if (s == null) {
7900 if (!create) {
7901 return null;
7902 }
7903 s = new SharedUserSetting(name, pkgFlags);
7904 if (MULTIPLE_APPLICATION_UIDS) {
7905 s.userId = newUserIdLP(s);
7906 } else {
7907 s.userId = FIRST_APPLICATION_UID;
7908 }
7909 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7910 // < 0 means we couldn't assign a userid; fall out and return
7911 // s, which is currently null
7912 if (s.userId >= 0) {
7913 mSharedUsers.put(name, s);
7914 }
7915 }
7916
7917 return s;
7918 }
7919
7920 int disableSystemPackageLP(String name) {
7921 PackageSetting p = mPackages.get(name);
7922 if(p == null) {
7923 Log.w(TAG, "Package:"+name+" is not an installed package");
7924 return -1;
7925 }
7926 PackageSetting dp = mDisabledSysPackages.get(name);
7927 // always make sure the system package code and resource paths dont change
7928 if(dp == null) {
7929 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7930 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7931 }
7932 mDisabledSysPackages.put(name, p);
7933 }
7934 return removePackageLP(name);
7935 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 PackageSetting enableSystemPackageLP(String name) {
7938 PackageSetting p = mDisabledSysPackages.get(name);
7939 if(p == null) {
7940 Log.w(TAG, "Package:"+name+" is not disabled");
7941 return null;
7942 }
7943 // Reset flag in ApplicationInfo object
7944 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7945 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7946 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007947 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007948 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007949 mDisabledSysPackages.remove(name);
7950 return ret;
7951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007952
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007953 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007954 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 PackageSetting p = mPackages.get(name);
7956 if (p != null) {
7957 if (p.userId == uid) {
7958 return p;
7959 }
7960 reportSettingsProblem(Log.ERROR,
7961 "Adding duplicate package, keeping first: " + name);
7962 return null;
7963 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007964 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007965 p.userId = uid;
7966 if (addUserIdLP(uid, p, name)) {
7967 mPackages.put(name, p);
7968 return p;
7969 }
7970 return null;
7971 }
7972
7973 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7974 SharedUserSetting s = mSharedUsers.get(name);
7975 if (s != null) {
7976 if (s.userId == uid) {
7977 return s;
7978 }
7979 reportSettingsProblem(Log.ERROR,
7980 "Adding duplicate shared user, keeping first: " + name);
7981 return null;
7982 }
7983 s = new SharedUserSetting(name, pkgFlags);
7984 s.userId = uid;
7985 if (addUserIdLP(uid, s, name)) {
7986 mSharedUsers.put(name, s);
7987 return s;
7988 }
7989 return null;
7990 }
7991
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007992 // Transfer ownership of permissions from one package to another.
7993 private void transferPermissions(String origPkg, String newPkg) {
7994 // Transfer ownership of permissions to the new package.
7995 for (int i=0; i<2; i++) {
7996 HashMap<String, BasePermission> permissions =
7997 i == 0 ? mPermissionTrees : mPermissions;
7998 for (BasePermission bp : permissions.values()) {
7999 if (origPkg.equals(bp.sourcePackage)) {
8000 if (DEBUG_UPGRADE) Log.v(TAG,
8001 "Moving permission " + bp.name
8002 + " from pkg " + bp.sourcePackage
8003 + " to " + newPkg);
8004 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008005 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008006 bp.perm = null;
8007 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008008 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008009 }
8010 bp.uid = 0;
8011 bp.gids = null;
8012 }
8013 }
8014 }
8015 }
8016
8017 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008018 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008019 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008020 PackageSetting p = mPackages.get(name);
8021 if (p != null) {
8022 if (!p.codePath.equals(codePath)) {
8023 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008024 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008025 // This is an updated system app with versions in both system
8026 // and data partition. Just let the most recent version
8027 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008028 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008029 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008030 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008031 // Just a change in the code path is not an issue, but
8032 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008033 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008034 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008036 }
8037 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 reportSettingsProblem(Log.WARN,
8039 "Package " + name + " shared user changed from "
8040 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8041 + " to "
8042 + (sharedUser != null ? sharedUser.name : "<nothing>")
8043 + "; replacing with new");
8044 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008045 } else {
8046 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8047 // If what we are scanning is a system package, then
8048 // make it so, regardless of whether it was previously
8049 // installed only in the data partition.
8050 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008052 }
8053 }
8054 if (p == null) {
8055 // Create a new PackageSettings entry. this can end up here because
8056 // of code path mismatch or user id mismatch of an updated system partition
8057 if (!create) {
8058 return null;
8059 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008060 if (origPackage != null) {
8061 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008062 p = new PackageSetting(origPackage.name, name, codePath,
8063 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008064 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8065 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008066 // Note that we will retain the new package's signature so
8067 // that we can keep its data.
8068 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008069 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008070 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008071 p.sharedUser = origPackage.sharedUser;
8072 p.userId = origPackage.userId;
8073 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008074 mRenamedPackages.put(name, origPackage.name);
8075 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008076 // Update new package state.
8077 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008079 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008080 p.setTimeStamp(codePath.lastModified());
8081 p.sharedUser = sharedUser;
8082 if (sharedUser != null) {
8083 p.userId = sharedUser.userId;
8084 } else if (MULTIPLE_APPLICATION_UIDS) {
8085 // Clone the setting here for disabled system packages
8086 PackageSetting dis = mDisabledSysPackages.get(name);
8087 if (dis != null) {
8088 // For disabled packages a new setting is created
8089 // from the existing user id. This still has to be
8090 // added to list of user id's
8091 // Copy signatures from previous setting
8092 if (dis.signatures.mSignatures != null) {
8093 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8094 }
8095 p.userId = dis.userId;
8096 // Clone permissions
8097 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008098 // Clone component info
8099 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8100 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8101 // Add new setting to list of user ids
8102 addUserIdLP(p.userId, p, name);
8103 } else {
8104 // Assign new user id
8105 p.userId = newUserIdLP(p);
8106 }
8107 } else {
8108 p.userId = FIRST_APPLICATION_UID;
8109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 }
8111 if (p.userId < 0) {
8112 reportSettingsProblem(Log.WARN,
8113 "Package " + name + " could not be assigned a valid uid");
8114 return null;
8115 }
8116 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008117 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008119 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008120 }
8121 }
8122 return p;
8123 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008124
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008125 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008126 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008127 String codePath = pkg.applicationInfo.sourceDir;
8128 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008129 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008130 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008131 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008132 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008133 p.codePath = new File(codePath);
8134 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008135 }
8136 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008137 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008138 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008139 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008140 p.resourcePath = new File(resourcePath);
8141 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008142 }
8143 // Update version code if needed
8144 if (pkg.mVersionCode != p.versionCode) {
8145 p.versionCode = pkg.mVersionCode;
8146 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008147 // Update signatures if needed.
8148 if (p.signatures.mSignatures == null) {
8149 p.signatures.assignSignatures(pkg.mSignatures);
8150 }
8151 // If this app defines a shared user id initialize
8152 // the shared user signatures as well.
8153 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8154 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8155 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008156 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8157 }
8158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 // Utility method that adds a PackageSetting to mPackages and
8160 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008161 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 SharedUserSetting sharedUser) {
8163 mPackages.put(name, p);
8164 if (sharedUser != null) {
8165 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8166 reportSettingsProblem(Log.ERROR,
8167 "Package " + p.name + " was user "
8168 + p.sharedUser + " but is now " + sharedUser
8169 + "; I am not changing its files so it will probably fail!");
8170 p.sharedUser.packages.remove(p);
8171 } else if (p.userId != sharedUser.userId) {
8172 reportSettingsProblem(Log.ERROR,
8173 "Package " + p.name + " was user id " + p.userId
8174 + " but is now user " + sharedUser
8175 + " with id " + sharedUser.userId
8176 + "; I am not changing its files so it will probably fail!");
8177 }
8178
8179 sharedUser.packages.add(p);
8180 p.sharedUser = sharedUser;
8181 p.userId = sharedUser.userId;
8182 }
8183 }
8184
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008185 /*
8186 * Update the shared user setting when a package using
8187 * specifying the shared user id is removed. The gids
8188 * associated with each permission of the deleted package
8189 * are removed from the shared user's gid list only if its
8190 * not in use by other permissions of packages in the
8191 * shared user setting.
8192 */
8193 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008194 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008195 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008196 return;
8197 }
8198 // No sharedUserId
8199 if (deletedPs.sharedUser == null) {
8200 return;
8201 }
8202 SharedUserSetting sus = deletedPs.sharedUser;
8203 // Update permissions
8204 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8205 boolean used = false;
8206 if (!sus.grantedPermissions.contains (eachPerm)) {
8207 continue;
8208 }
8209 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008210 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008211 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008212 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 used = true;
8214 break;
8215 }
8216 }
8217 if (!used) {
8218 // can safely delete this permission from list
8219 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 }
8221 }
8222 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008223 int newGids[] = globalGids;
8224 for (String eachPerm : sus.grantedPermissions) {
8225 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008226 if (bp != null) {
8227 newGids = appendInts(newGids, bp.gids);
8228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008229 }
8230 sus.gids = newGids;
8231 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008233 private int removePackageLP(String name) {
8234 PackageSetting p = mPackages.get(name);
8235 if (p != null) {
8236 mPackages.remove(name);
8237 if (p.sharedUser != null) {
8238 p.sharedUser.packages.remove(p);
8239 if (p.sharedUser.packages.size() == 0) {
8240 mSharedUsers.remove(p.sharedUser.name);
8241 removeUserIdLP(p.sharedUser.userId);
8242 return p.sharedUser.userId;
8243 }
8244 } else {
8245 removeUserIdLP(p.userId);
8246 return p.userId;
8247 }
8248 }
8249 return -1;
8250 }
8251
8252 private boolean addUserIdLP(int uid, Object obj, Object name) {
8253 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8254 return false;
8255 }
8256
8257 if (uid >= FIRST_APPLICATION_UID) {
8258 int N = mUserIds.size();
8259 final int index = uid - FIRST_APPLICATION_UID;
8260 while (index >= N) {
8261 mUserIds.add(null);
8262 N++;
8263 }
8264 if (mUserIds.get(index) != null) {
8265 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008266 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 + " name=" + name);
8268 return false;
8269 }
8270 mUserIds.set(index, obj);
8271 } else {
8272 if (mOtherUserIds.get(uid) != null) {
8273 reportSettingsProblem(Log.ERROR,
8274 "Adding duplicate shared id: " + uid
8275 + " name=" + name);
8276 return false;
8277 }
8278 mOtherUserIds.put(uid, obj);
8279 }
8280 return true;
8281 }
8282
8283 public Object getUserIdLP(int uid) {
8284 if (uid >= FIRST_APPLICATION_UID) {
8285 int N = mUserIds.size();
8286 final int index = uid - FIRST_APPLICATION_UID;
8287 return index < N ? mUserIds.get(index) : null;
8288 } else {
8289 return mOtherUserIds.get(uid);
8290 }
8291 }
8292
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008293 private Set<String> findPackagesWithFlag(int flag) {
8294 Set<String> ret = new HashSet<String>();
8295 for (PackageSetting ps : mPackages.values()) {
8296 // Has to match atleast all the flag bits set on flag
8297 if ((ps.pkgFlags & flag) == flag) {
8298 ret.add(ps.name);
8299 }
8300 }
8301 return ret;
8302 }
8303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 private void removeUserIdLP(int uid) {
8305 if (uid >= FIRST_APPLICATION_UID) {
8306 int N = mUserIds.size();
8307 final int index = uid - FIRST_APPLICATION_UID;
8308 if (index < N) mUserIds.set(index, null);
8309 } else {
8310 mOtherUserIds.remove(uid);
8311 }
8312 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314 void writeLP() {
8315 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8316
8317 // Keep the old settings around until we know the new ones have
8318 // been successfully written.
8319 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008320 // Presence of backup settings file indicates that we failed
8321 // to persist settings earlier. So preserve the older
8322 // backup for future reference since the current settings
8323 // might have been corrupted.
8324 if (!mBackupSettingsFilename.exists()) {
8325 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008326 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008327 return;
8328 }
8329 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008330 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008331 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008333 }
8334
8335 mPastSignatures.clear();
8336
8337 try {
8338 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8339
8340 //XmlSerializer serializer = XmlUtils.serializerInstance();
8341 XmlSerializer serializer = new FastXmlSerializer();
8342 serializer.setOutput(str, "utf-8");
8343 serializer.startDocument(null, true);
8344 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8345
8346 serializer.startTag(null, "packages");
8347
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008348 serializer.startTag(null, "last-platform-version");
8349 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8350 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8351 serializer.endTag(null, "last-platform-version");
8352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008353 serializer.startTag(null, "permission-trees");
8354 for (BasePermission bp : mPermissionTrees.values()) {
8355 writePermission(serializer, bp);
8356 }
8357 serializer.endTag(null, "permission-trees");
8358
8359 serializer.startTag(null, "permissions");
8360 for (BasePermission bp : mPermissions.values()) {
8361 writePermission(serializer, bp);
8362 }
8363 serializer.endTag(null, "permissions");
8364
8365 for (PackageSetting pkg : mPackages.values()) {
8366 writePackage(serializer, pkg);
8367 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008369 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8370 writeDisabledSysPackage(serializer, pkg);
8371 }
8372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008373 serializer.startTag(null, "preferred-activities");
8374 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8375 serializer.startTag(null, "item");
8376 pa.writeToXml(serializer);
8377 serializer.endTag(null, "item");
8378 }
8379 serializer.endTag(null, "preferred-activities");
8380
8381 for (SharedUserSetting usr : mSharedUsers.values()) {
8382 serializer.startTag(null, "shared-user");
8383 serializer.attribute(null, "name", usr.name);
8384 serializer.attribute(null, "userId",
8385 Integer.toString(usr.userId));
8386 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8387 serializer.startTag(null, "perms");
8388 for (String name : usr.grantedPermissions) {
8389 serializer.startTag(null, "item");
8390 serializer.attribute(null, "name", name);
8391 serializer.endTag(null, "item");
8392 }
8393 serializer.endTag(null, "perms");
8394 serializer.endTag(null, "shared-user");
8395 }
8396
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008397 if (mPackagesToBeCleaned.size() > 0) {
8398 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8399 serializer.startTag(null, "cleaning-package");
8400 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8401 serializer.endTag(null, "cleaning-package");
8402 }
8403 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008404
8405 if (mRenamedPackages.size() > 0) {
8406 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8407 serializer.startTag(null, "renamed-package");
8408 serializer.attribute(null, "new", e.getKey());
8409 serializer.attribute(null, "old", e.getValue());
8410 serializer.endTag(null, "renamed-package");
8411 }
8412 }
8413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 serializer.endTag(null, "packages");
8415
8416 serializer.endDocument();
8417
8418 str.flush();
8419 str.close();
8420
8421 // New settings successfully written, old ones are no longer
8422 // needed.
8423 mBackupSettingsFilename.delete();
8424 FileUtils.setPermissions(mSettingsFilename.toString(),
8425 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8426 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8427 |FileUtils.S_IROTH,
8428 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008429
8430 // Write package list file now, use a JournaledFile.
8431 //
8432 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8433 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8434
8435 str = new FileOutputStream(journal.chooseForWrite());
8436 try {
8437 StringBuilder sb = new StringBuilder();
8438 for (PackageSetting pkg : mPackages.values()) {
8439 ApplicationInfo ai = pkg.pkg.applicationInfo;
8440 String dataPath = ai.dataDir;
8441 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8442
8443 // Avoid any application that has a space in its path
8444 // or that is handled by the system.
8445 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8446 continue;
8447
8448 // we store on each line the following information for now:
8449 //
8450 // pkgName - package name
8451 // userId - application-specific user id
8452 // debugFlag - 0 or 1 if the package is debuggable.
8453 // dataPath - path to package's data path
8454 //
8455 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8456 //
8457 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8458 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8459 // system/core/run-as/run-as.c
8460 //
8461 sb.setLength(0);
8462 sb.append(ai.packageName);
8463 sb.append(" ");
8464 sb.append((int)ai.uid);
8465 sb.append(isDebug ? " 1 " : " 0 ");
8466 sb.append(dataPath);
8467 sb.append("\n");
8468 str.write(sb.toString().getBytes());
8469 }
8470 str.flush();
8471 str.close();
8472 journal.commit();
8473 }
8474 catch (Exception e) {
8475 journal.rollback();
8476 }
8477
8478 FileUtils.setPermissions(mPackageListFilename.toString(),
8479 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8480 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8481 |FileUtils.S_IROTH,
8482 -1, -1);
8483
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008484 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008485
8486 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008487 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 -08008488 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008489 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 -08008490 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008491 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008492 if (mSettingsFilename.exists()) {
8493 if (!mSettingsFilename.delete()) {
8494 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8495 }
8496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008497 //Debug.stopMethodTracing();
8498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008499
8500 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008501 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 serializer.startTag(null, "updated-package");
8503 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008504 if (pkg.realName != null) {
8505 serializer.attribute(null, "realName", pkg.realName);
8506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008507 serializer.attribute(null, "codePath", pkg.codePathString);
8508 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008509 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008510 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8511 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8512 }
8513 if (pkg.sharedUser == null) {
8514 serializer.attribute(null, "userId",
8515 Integer.toString(pkg.userId));
8516 } else {
8517 serializer.attribute(null, "sharedUserId",
8518 Integer.toString(pkg.userId));
8519 }
8520 serializer.startTag(null, "perms");
8521 if (pkg.sharedUser == null) {
8522 // If this is a shared user, the permissions will
8523 // be written there. We still need to write an
8524 // empty permissions list so permissionsFixed will
8525 // be set.
8526 for (final String name : pkg.grantedPermissions) {
8527 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008528 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008529 // We only need to write signature or system permissions but this wont
8530 // match the semantics of grantedPermissions. So write all permissions.
8531 serializer.startTag(null, "item");
8532 serializer.attribute(null, "name", name);
8533 serializer.endTag(null, "item");
8534 }
8535 }
8536 }
8537 serializer.endTag(null, "perms");
8538 serializer.endTag(null, "updated-package");
8539 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008540
8541 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008542 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 serializer.startTag(null, "package");
8544 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008545 if (pkg.realName != null) {
8546 serializer.attribute(null, "realName", pkg.realName);
8547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548 serializer.attribute(null, "codePath", pkg.codePathString);
8549 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8550 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8551 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008552 serializer.attribute(null, "flags",
8553 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008555 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 if (pkg.sharedUser == null) {
8557 serializer.attribute(null, "userId",
8558 Integer.toString(pkg.userId));
8559 } else {
8560 serializer.attribute(null, "sharedUserId",
8561 Integer.toString(pkg.userId));
8562 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008563 if (pkg.uidError) {
8564 serializer.attribute(null, "uidError", "true");
8565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008566 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8567 serializer.attribute(null, "enabled",
8568 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8569 ? "true" : "false");
8570 }
8571 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8572 serializer.attribute(null, "installStatus", "false");
8573 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008574 if (pkg.installerPackageName != null) {
8575 serializer.attribute(null, "installer", pkg.installerPackageName);
8576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8578 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8579 serializer.startTag(null, "perms");
8580 if (pkg.sharedUser == null) {
8581 // If this is a shared user, the permissions will
8582 // be written there. We still need to write an
8583 // empty permissions list so permissionsFixed will
8584 // be set.
8585 for (final String name : pkg.grantedPermissions) {
8586 serializer.startTag(null, "item");
8587 serializer.attribute(null, "name", name);
8588 serializer.endTag(null, "item");
8589 }
8590 }
8591 serializer.endTag(null, "perms");
8592 }
8593 if (pkg.disabledComponents.size() > 0) {
8594 serializer.startTag(null, "disabled-components");
8595 for (final String name : pkg.disabledComponents) {
8596 serializer.startTag(null, "item");
8597 serializer.attribute(null, "name", name);
8598 serializer.endTag(null, "item");
8599 }
8600 serializer.endTag(null, "disabled-components");
8601 }
8602 if (pkg.enabledComponents.size() > 0) {
8603 serializer.startTag(null, "enabled-components");
8604 for (final String name : pkg.enabledComponents) {
8605 serializer.startTag(null, "item");
8606 serializer.attribute(null, "name", name);
8607 serializer.endTag(null, "item");
8608 }
8609 serializer.endTag(null, "enabled-components");
8610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 serializer.endTag(null, "package");
8613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 void writePermission(XmlSerializer serializer, BasePermission bp)
8616 throws XmlPullParserException, java.io.IOException {
8617 if (bp.type != BasePermission.TYPE_BUILTIN
8618 && bp.sourcePackage != null) {
8619 serializer.startTag(null, "item");
8620 serializer.attribute(null, "name", bp.name);
8621 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008622 if (bp.protectionLevel !=
8623 PermissionInfo.PROTECTION_NORMAL) {
8624 serializer.attribute(null, "protection",
8625 Integer.toString(bp.protectionLevel));
8626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008627 if (DEBUG_SETTINGS) Log.v(TAG,
8628 "Writing perm: name=" + bp.name + " type=" + bp.type);
8629 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8630 PermissionInfo pi = bp.perm != null ? bp.perm.info
8631 : bp.pendingInfo;
8632 if (pi != null) {
8633 serializer.attribute(null, "type", "dynamic");
8634 if (pi.icon != 0) {
8635 serializer.attribute(null, "icon",
8636 Integer.toString(pi.icon));
8637 }
8638 if (pi.nonLocalizedLabel != null) {
8639 serializer.attribute(null, "label",
8640 pi.nonLocalizedLabel.toString());
8641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642 }
8643 }
8644 serializer.endTag(null, "item");
8645 }
8646 }
8647
8648 String getReadMessagesLP() {
8649 return mReadMessages.toString();
8650 }
8651
Oscar Montemayora8529f62009-11-18 10:14:20 -08008652 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8654 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008655 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 while(its.hasNext()) {
8657 String key = its.next();
8658 PackageSetting ps = mPackages.get(key);
8659 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008660 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 }
8662 }
8663 return ret;
8664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008666 boolean readLP() {
8667 FileInputStream str = null;
8668 if (mBackupSettingsFilename.exists()) {
8669 try {
8670 str = new FileInputStream(mBackupSettingsFilename);
8671 mReadMessages.append("Reading from backup settings file\n");
8672 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008673 if (mSettingsFilename.exists()) {
8674 // If both the backup and settings file exist, we
8675 // ignore the settings since it might have been
8676 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008677 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008678 mSettingsFilename.delete();
8679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 } catch (java.io.IOException e) {
8681 // We'll try for the normal settings file.
8682 }
8683 }
8684
8685 mPastSignatures.clear();
8686
8687 try {
8688 if (str == null) {
8689 if (!mSettingsFilename.exists()) {
8690 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008691 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008692 return false;
8693 }
8694 str = new FileInputStream(mSettingsFilename);
8695 }
8696 XmlPullParser parser = Xml.newPullParser();
8697 parser.setInput(str, null);
8698
8699 int type;
8700 while ((type=parser.next()) != XmlPullParser.START_TAG
8701 && type != XmlPullParser.END_DOCUMENT) {
8702 ;
8703 }
8704
8705 if (type != XmlPullParser.START_TAG) {
8706 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008707 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008708 return false;
8709 }
8710
8711 int outerDepth = parser.getDepth();
8712 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8713 && (type != XmlPullParser.END_TAG
8714 || parser.getDepth() > outerDepth)) {
8715 if (type == XmlPullParser.END_TAG
8716 || type == XmlPullParser.TEXT) {
8717 continue;
8718 }
8719
8720 String tagName = parser.getName();
8721 if (tagName.equals("package")) {
8722 readPackageLP(parser);
8723 } else if (tagName.equals("permissions")) {
8724 readPermissionsLP(mPermissions, parser);
8725 } else if (tagName.equals("permission-trees")) {
8726 readPermissionsLP(mPermissionTrees, parser);
8727 } else if (tagName.equals("shared-user")) {
8728 readSharedUserLP(parser);
8729 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008730 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008731 } else if (tagName.equals("preferred-activities")) {
8732 readPreferredActivitiesLP(parser);
8733 } else if(tagName.equals("updated-package")) {
8734 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008735 } else if (tagName.equals("cleaning-package")) {
8736 String name = parser.getAttributeValue(null, "name");
8737 if (name != null) {
8738 mPackagesToBeCleaned.add(name);
8739 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008740 } else if (tagName.equals("renamed-package")) {
8741 String nname = parser.getAttributeValue(null, "new");
8742 String oname = parser.getAttributeValue(null, "old");
8743 if (nname != null && oname != null) {
8744 mRenamedPackages.put(nname, oname);
8745 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008746 } else if (tagName.equals("last-platform-version")) {
8747 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8748 try {
8749 String internal = parser.getAttributeValue(null, "internal");
8750 if (internal != null) {
8751 mInternalSdkPlatform = Integer.parseInt(internal);
8752 }
8753 String external = parser.getAttributeValue(null, "external");
8754 if (external != null) {
8755 mInternalSdkPlatform = Integer.parseInt(external);
8756 }
8757 } catch (NumberFormatException e) {
8758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008760 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 + parser.getName());
8762 XmlUtils.skipCurrentTag(parser);
8763 }
8764 }
8765
8766 str.close();
8767
8768 } catch(XmlPullParserException e) {
8769 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008770 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771
8772 } catch(java.io.IOException e) {
8773 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008774 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008775
8776 }
8777
8778 int N = mPendingPackages.size();
8779 for (int i=0; i<N; i++) {
8780 final PendingPackage pp = mPendingPackages.get(i);
8781 Object idObj = getUserIdLP(pp.sharedId);
8782 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008783 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008784 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008785 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008787 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 + pp.name);
8789 continue;
8790 }
8791 p.copyFrom(pp);
8792 } else if (idObj != null) {
8793 String msg = "Bad package setting: package " + pp.name
8794 + " has shared uid " + pp.sharedId
8795 + " that is not a shared uid\n";
8796 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008797 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008798 } else {
8799 String msg = "Bad package setting: package " + pp.name
8800 + " has shared uid " + pp.sharedId
8801 + " that is not defined\n";
8802 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008803 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804 }
8805 }
8806 mPendingPackages.clear();
8807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808 mReadMessages.append("Read completed successfully: "
8809 + mPackages.size() + " packages, "
8810 + mSharedUsers.size() + " shared uids\n");
8811
8812 return true;
8813 }
8814
8815 private int readInt(XmlPullParser parser, String ns, String name,
8816 int defValue) {
8817 String v = parser.getAttributeValue(ns, name);
8818 try {
8819 if (v == null) {
8820 return defValue;
8821 }
8822 return Integer.parseInt(v);
8823 } catch (NumberFormatException e) {
8824 reportSettingsProblem(Log.WARN,
8825 "Error in package manager settings: attribute " +
8826 name + " has bad integer value " + v + " at "
8827 + parser.getPositionDescription());
8828 }
8829 return defValue;
8830 }
8831
8832 private void readPermissionsLP(HashMap<String, BasePermission> out,
8833 XmlPullParser parser)
8834 throws IOException, XmlPullParserException {
8835 int outerDepth = parser.getDepth();
8836 int type;
8837 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8838 && (type != XmlPullParser.END_TAG
8839 || parser.getDepth() > outerDepth)) {
8840 if (type == XmlPullParser.END_TAG
8841 || type == XmlPullParser.TEXT) {
8842 continue;
8843 }
8844
8845 String tagName = parser.getName();
8846 if (tagName.equals("item")) {
8847 String name = parser.getAttributeValue(null, "name");
8848 String sourcePackage = parser.getAttributeValue(null, "package");
8849 String ptype = parser.getAttributeValue(null, "type");
8850 if (name != null && sourcePackage != null) {
8851 boolean dynamic = "dynamic".equals(ptype);
8852 BasePermission bp = new BasePermission(name, sourcePackage,
8853 dynamic
8854 ? BasePermission.TYPE_DYNAMIC
8855 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008856 bp.protectionLevel = readInt(parser, null, "protection",
8857 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008858 if (dynamic) {
8859 PermissionInfo pi = new PermissionInfo();
8860 pi.packageName = sourcePackage.intern();
8861 pi.name = name.intern();
8862 pi.icon = readInt(parser, null, "icon", 0);
8863 pi.nonLocalizedLabel = parser.getAttributeValue(
8864 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008865 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 bp.pendingInfo = pi;
8867 }
8868 out.put(bp.name, bp);
8869 } else {
8870 reportSettingsProblem(Log.WARN,
8871 "Error in package manager settings: permissions has"
8872 + " no name at " + parser.getPositionDescription());
8873 }
8874 } else {
8875 reportSettingsProblem(Log.WARN,
8876 "Unknown element reading permissions: "
8877 + parser.getName() + " at "
8878 + parser.getPositionDescription());
8879 }
8880 XmlUtils.skipCurrentTag(parser);
8881 }
8882 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008885 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008887 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888 String codePathStr = parser.getAttributeValue(null, "codePath");
8889 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008890 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008891 resourcePathStr = codePathStr;
8892 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008893 String version = parser.getAttributeValue(null, "version");
8894 int versionCode = 0;
8895 if (version != null) {
8896 try {
8897 versionCode = Integer.parseInt(version);
8898 } catch (NumberFormatException e) {
8899 }
8900 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 int pkgFlags = 0;
8903 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008904 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008905 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008906 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 String timeStampStr = parser.getAttributeValue(null, "ts");
8908 if (timeStampStr != null) {
8909 try {
8910 long timeStamp = Long.parseLong(timeStampStr);
8911 ps.setTimeStamp(timeStamp, timeStampStr);
8912 } catch (NumberFormatException e) {
8913 }
8914 }
8915 String idStr = parser.getAttributeValue(null, "userId");
8916 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8917 if(ps.userId <= 0) {
8918 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8919 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8920 }
8921 int outerDepth = parser.getDepth();
8922 int type;
8923 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8924 && (type != XmlPullParser.END_TAG
8925 || parser.getDepth() > outerDepth)) {
8926 if (type == XmlPullParser.END_TAG
8927 || type == XmlPullParser.TEXT) {
8928 continue;
8929 }
8930
8931 String tagName = parser.getName();
8932 if (tagName.equals("perms")) {
8933 readGrantedPermissionsLP(parser,
8934 ps.grantedPermissions);
8935 } else {
8936 reportSettingsProblem(Log.WARN,
8937 "Unknown element under <updated-package>: "
8938 + parser.getName());
8939 XmlUtils.skipCurrentTag(parser);
8940 }
8941 }
8942 mDisabledSysPackages.put(name, ps);
8943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 private void readPackageLP(XmlPullParser parser)
8946 throws XmlPullParserException, IOException {
8947 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008948 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 String idStr = null;
8950 String sharedIdStr = null;
8951 String codePathStr = null;
8952 String resourcePathStr = null;
8953 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008954 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008955 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956 int pkgFlags = 0;
8957 String timeStampStr;
8958 long timeStamp = 0;
8959 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008960 String version = null;
8961 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 try {
8963 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008964 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008966 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008967 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8968 codePathStr = parser.getAttributeValue(null, "codePath");
8969 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008970 version = parser.getAttributeValue(null, "version");
8971 if (version != null) {
8972 try {
8973 versionCode = Integer.parseInt(version);
8974 } catch (NumberFormatException e) {
8975 }
8976 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008977 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008978
8979 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008980 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008981 try {
8982 pkgFlags = Integer.parseInt(systemStr);
8983 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984 }
8985 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008986 // For backward compatibility
8987 systemStr = parser.getAttributeValue(null, "system");
8988 if (systemStr != null) {
8989 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8990 } else {
8991 // Old settings that don't specify system... just treat
8992 // them as system, good enough.
8993 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008995 }
8996 timeStampStr = parser.getAttributeValue(null, "ts");
8997 if (timeStampStr != null) {
8998 try {
8999 timeStamp = Long.parseLong(timeStampStr);
9000 } catch (NumberFormatException e) {
9001 }
9002 }
9003 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9004 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9005 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9006 if (resourcePathStr == null) {
9007 resourcePathStr = codePathStr;
9008 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009009 if (realName != null) {
9010 realName = realName.intern();
9011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 if (name == null) {
9013 reportSettingsProblem(Log.WARN,
9014 "Error in package manager settings: <package> has no name at "
9015 + parser.getPositionDescription());
9016 } else if (codePathStr == null) {
9017 reportSettingsProblem(Log.WARN,
9018 "Error in package manager settings: <package> has no codePath at "
9019 + parser.getPositionDescription());
9020 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009021 packageSetting = addPackageLP(name.intern(), realName,
9022 new File(codePathStr), new File(resourcePathStr),
9023 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9025 + ": userId=" + userId + " pkg=" + packageSetting);
9026 if (packageSetting == null) {
9027 reportSettingsProblem(Log.ERROR,
9028 "Failure adding uid " + userId
9029 + " while parsing settings at "
9030 + parser.getPositionDescription());
9031 } else {
9032 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9033 }
9034 } else if (sharedIdStr != null) {
9035 userId = sharedIdStr != null
9036 ? Integer.parseInt(sharedIdStr) : 0;
9037 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009038 packageSetting = new PendingPackage(name.intern(), realName,
9039 new File(codePathStr), new File(resourcePathStr),
9040 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009041 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9042 mPendingPackages.add((PendingPackage) packageSetting);
9043 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9044 + ": sharedUserId=" + userId + " pkg="
9045 + packageSetting);
9046 } else {
9047 reportSettingsProblem(Log.WARN,
9048 "Error in package manager settings: package "
9049 + name + " has bad sharedId " + sharedIdStr
9050 + " at " + parser.getPositionDescription());
9051 }
9052 } else {
9053 reportSettingsProblem(Log.WARN,
9054 "Error in package manager settings: package "
9055 + name + " has bad userId " + idStr + " at "
9056 + parser.getPositionDescription());
9057 }
9058 } catch (NumberFormatException e) {
9059 reportSettingsProblem(Log.WARN,
9060 "Error in package manager settings: package "
9061 + name + " has bad userId " + idStr + " at "
9062 + parser.getPositionDescription());
9063 }
9064 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009065 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009066 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009067 final String enabledStr = parser.getAttributeValue(null, "enabled");
9068 if (enabledStr != null) {
9069 if (enabledStr.equalsIgnoreCase("true")) {
9070 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9071 } else if (enabledStr.equalsIgnoreCase("false")) {
9072 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9073 } else if (enabledStr.equalsIgnoreCase("default")) {
9074 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9075 } else {
9076 reportSettingsProblem(Log.WARN,
9077 "Error in package manager settings: package "
9078 + name + " has bad enabled value: " + idStr
9079 + " at " + parser.getPositionDescription());
9080 }
9081 } else {
9082 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9083 }
9084 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9085 if (installStatusStr != null) {
9086 if (installStatusStr.equalsIgnoreCase("false")) {
9087 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9088 } else {
9089 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9090 }
9091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009093 int outerDepth = parser.getDepth();
9094 int type;
9095 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9096 && (type != XmlPullParser.END_TAG
9097 || parser.getDepth() > outerDepth)) {
9098 if (type == XmlPullParser.END_TAG
9099 || type == XmlPullParser.TEXT) {
9100 continue;
9101 }
9102
9103 String tagName = parser.getName();
9104 if (tagName.equals("disabled-components")) {
9105 readDisabledComponentsLP(packageSetting, parser);
9106 } else if (tagName.equals("enabled-components")) {
9107 readEnabledComponentsLP(packageSetting, parser);
9108 } else if (tagName.equals("sigs")) {
9109 packageSetting.signatures.readXml(parser, mPastSignatures);
9110 } else if (tagName.equals("perms")) {
9111 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009112 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009113 packageSetting.permissionsFixed = true;
9114 } else {
9115 reportSettingsProblem(Log.WARN,
9116 "Unknown element under <package>: "
9117 + parser.getName());
9118 XmlUtils.skipCurrentTag(parser);
9119 }
9120 }
9121 } else {
9122 XmlUtils.skipCurrentTag(parser);
9123 }
9124 }
9125
9126 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9127 XmlPullParser parser)
9128 throws IOException, XmlPullParserException {
9129 int outerDepth = parser.getDepth();
9130 int type;
9131 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9132 && (type != XmlPullParser.END_TAG
9133 || parser.getDepth() > outerDepth)) {
9134 if (type == XmlPullParser.END_TAG
9135 || type == XmlPullParser.TEXT) {
9136 continue;
9137 }
9138
9139 String tagName = parser.getName();
9140 if (tagName.equals("item")) {
9141 String name = parser.getAttributeValue(null, "name");
9142 if (name != null) {
9143 packageSetting.disabledComponents.add(name.intern());
9144 } else {
9145 reportSettingsProblem(Log.WARN,
9146 "Error in package manager settings: <disabled-components> has"
9147 + " no name at " + parser.getPositionDescription());
9148 }
9149 } else {
9150 reportSettingsProblem(Log.WARN,
9151 "Unknown element under <disabled-components>: "
9152 + parser.getName());
9153 }
9154 XmlUtils.skipCurrentTag(parser);
9155 }
9156 }
9157
9158 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9159 XmlPullParser parser)
9160 throws IOException, XmlPullParserException {
9161 int outerDepth = parser.getDepth();
9162 int type;
9163 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9164 && (type != XmlPullParser.END_TAG
9165 || parser.getDepth() > outerDepth)) {
9166 if (type == XmlPullParser.END_TAG
9167 || type == XmlPullParser.TEXT) {
9168 continue;
9169 }
9170
9171 String tagName = parser.getName();
9172 if (tagName.equals("item")) {
9173 String name = parser.getAttributeValue(null, "name");
9174 if (name != null) {
9175 packageSetting.enabledComponents.add(name.intern());
9176 } else {
9177 reportSettingsProblem(Log.WARN,
9178 "Error in package manager settings: <enabled-components> has"
9179 + " no name at " + parser.getPositionDescription());
9180 }
9181 } else {
9182 reportSettingsProblem(Log.WARN,
9183 "Unknown element under <enabled-components>: "
9184 + parser.getName());
9185 }
9186 XmlUtils.skipCurrentTag(parser);
9187 }
9188 }
9189
9190 private void readSharedUserLP(XmlPullParser parser)
9191 throws XmlPullParserException, IOException {
9192 String name = null;
9193 String idStr = null;
9194 int pkgFlags = 0;
9195 SharedUserSetting su = null;
9196 try {
9197 name = parser.getAttributeValue(null, "name");
9198 idStr = parser.getAttributeValue(null, "userId");
9199 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9200 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9201 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9202 }
9203 if (name == null) {
9204 reportSettingsProblem(Log.WARN,
9205 "Error in package manager settings: <shared-user> has no name at "
9206 + parser.getPositionDescription());
9207 } else if (userId == 0) {
9208 reportSettingsProblem(Log.WARN,
9209 "Error in package manager settings: shared-user "
9210 + name + " has bad userId " + idStr + " at "
9211 + parser.getPositionDescription());
9212 } else {
9213 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9214 reportSettingsProblem(Log.ERROR,
9215 "Occurred while parsing settings at "
9216 + parser.getPositionDescription());
9217 }
9218 }
9219 } catch (NumberFormatException e) {
9220 reportSettingsProblem(Log.WARN,
9221 "Error in package manager settings: package "
9222 + name + " has bad userId " + idStr + " at "
9223 + parser.getPositionDescription());
9224 };
9225
9226 if (su != null) {
9227 int outerDepth = parser.getDepth();
9228 int type;
9229 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9230 && (type != XmlPullParser.END_TAG
9231 || parser.getDepth() > outerDepth)) {
9232 if (type == XmlPullParser.END_TAG
9233 || type == XmlPullParser.TEXT) {
9234 continue;
9235 }
9236
9237 String tagName = parser.getName();
9238 if (tagName.equals("sigs")) {
9239 su.signatures.readXml(parser, mPastSignatures);
9240 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009241 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009242 } else {
9243 reportSettingsProblem(Log.WARN,
9244 "Unknown element under <shared-user>: "
9245 + parser.getName());
9246 XmlUtils.skipCurrentTag(parser);
9247 }
9248 }
9249
9250 } else {
9251 XmlUtils.skipCurrentTag(parser);
9252 }
9253 }
9254
9255 private void readGrantedPermissionsLP(XmlPullParser parser,
9256 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9257 int outerDepth = parser.getDepth();
9258 int type;
9259 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9260 && (type != XmlPullParser.END_TAG
9261 || parser.getDepth() > outerDepth)) {
9262 if (type == XmlPullParser.END_TAG
9263 || type == XmlPullParser.TEXT) {
9264 continue;
9265 }
9266
9267 String tagName = parser.getName();
9268 if (tagName.equals("item")) {
9269 String name = parser.getAttributeValue(null, "name");
9270 if (name != null) {
9271 outPerms.add(name.intern());
9272 } else {
9273 reportSettingsProblem(Log.WARN,
9274 "Error in package manager settings: <perms> has"
9275 + " no name at " + parser.getPositionDescription());
9276 }
9277 } else {
9278 reportSettingsProblem(Log.WARN,
9279 "Unknown element under <perms>: "
9280 + parser.getName());
9281 }
9282 XmlUtils.skipCurrentTag(parser);
9283 }
9284 }
9285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 private void readPreferredActivitiesLP(XmlPullParser parser)
9287 throws XmlPullParserException, IOException {
9288 int outerDepth = parser.getDepth();
9289 int type;
9290 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9291 && (type != XmlPullParser.END_TAG
9292 || parser.getDepth() > outerDepth)) {
9293 if (type == XmlPullParser.END_TAG
9294 || type == XmlPullParser.TEXT) {
9295 continue;
9296 }
9297
9298 String tagName = parser.getName();
9299 if (tagName.equals("item")) {
9300 PreferredActivity pa = new PreferredActivity(parser);
9301 if (pa.mParseError == null) {
9302 mPreferredActivities.addFilter(pa);
9303 } else {
9304 reportSettingsProblem(Log.WARN,
9305 "Error in package manager settings: <preferred-activity> "
9306 + pa.mParseError + " at "
9307 + parser.getPositionDescription());
9308 }
9309 } else {
9310 reportSettingsProblem(Log.WARN,
9311 "Unknown element under <preferred-activities>: "
9312 + parser.getName());
9313 XmlUtils.skipCurrentTag(parser);
9314 }
9315 }
9316 }
9317
9318 // Returns -1 if we could not find an available UserId to assign
9319 private int newUserIdLP(Object obj) {
9320 // Let's be stupidly inefficient for now...
9321 final int N = mUserIds.size();
9322 for (int i=0; i<N; i++) {
9323 if (mUserIds.get(i) == null) {
9324 mUserIds.set(i, obj);
9325 return FIRST_APPLICATION_UID + i;
9326 }
9327 }
9328
9329 // None left?
9330 if (N >= MAX_APPLICATION_UIDS) {
9331 return -1;
9332 }
9333
9334 mUserIds.add(obj);
9335 return FIRST_APPLICATION_UID + N;
9336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009338 public PackageSetting getDisabledSystemPkg(String name) {
9339 synchronized(mPackages) {
9340 PackageSetting ps = mDisabledSysPackages.get(name);
9341 return ps;
9342 }
9343 }
9344
9345 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9346 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9347 if (Config.LOGV) {
9348 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9349 + " componentName = " + componentInfo.name);
9350 Log.v(TAG, "enabledComponents: "
9351 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9352 Log.v(TAG, "disabledComponents: "
9353 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9354 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009355 if (packageSettings == null) {
9356 if (false) {
9357 Log.w(TAG, "WAITING FOR DEBUGGER");
9358 Debug.waitForDebugger();
9359 Log.i(TAG, "We will crash!");
9360 }
9361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009362 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9363 || ((componentInfo.enabled
9364 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9365 || (componentInfo.applicationInfo.enabled
9366 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9367 && !packageSettings.disabledComponents.contains(componentInfo.name))
9368 || packageSettings.enabledComponents.contains(componentInfo.name));
9369 }
9370 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009371
9372 // ------- apps on sdcard specific code -------
9373 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009374 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009375 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009376 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009377 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009378
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009379 private String getEncryptKey() {
9380 try {
9381 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9382 if (sdEncKey == null) {
9383 sdEncKey = SystemKeyStore.getInstance().
9384 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9385 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009386 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009387 return null;
9388 }
9389 }
9390 return sdEncKey;
9391 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009392 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009393 return null;
9394 }
9395 }
9396
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009397 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009398 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009399 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009400 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009401 if (list != null) {
9402 int idx = 0;
9403 int idList[] = new int[MAX_CONTAINERS];
9404 boolean neverFound = true;
9405 for (String name : list) {
9406 // Ignore null entries
9407 if (name == null) {
9408 continue;
9409 }
9410 int sidx = name.indexOf(prefix);
9411 if (sidx == -1) {
9412 // Not a temp file. just ignore
9413 continue;
9414 }
9415 String subStr = name.substring(sidx + prefix.length());
9416 idList[idx] = -1;
9417 if (subStr != null) {
9418 try {
9419 int cid = Integer.parseInt(subStr);
9420 idList[idx++] = cid;
9421 neverFound = false;
9422 } catch (NumberFormatException e) {
9423 }
9424 }
9425 }
9426 if (!neverFound) {
9427 // Sort idList
9428 Arrays.sort(idList);
9429 for (int j = 1; j <= idList.length; j++) {
9430 if (idList[j-1] != j) {
9431 tmpIdx = j;
9432 break;
9433 }
9434 }
9435 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009436 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009437 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009438 }
9439
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009440 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009441 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009442 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009443 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9444 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9445 throw new SecurityException("Media status can only be updated by the system");
9446 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009447 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009448 Log.i(TAG, "Updating external media status from " +
9449 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9450 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009451 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9452 mediaStatus+", mMediaMounted=" + mMediaMounted);
9453 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009454 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9455 reportStatus ? 1 : 0, -1);
9456 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009457 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009458 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009459 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009460 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009461 // Queue up an async operation since the package installation may take a little while.
9462 mHandler.post(new Runnable() {
9463 public void run() {
9464 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009465 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009466 }
9467 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009468 }
9469
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009470 /*
9471 * Collect information of applications on external media, map them
9472 * against existing containers and update information based on current
9473 * mount status. Please note that we always have to report status
9474 * if reportStatus has been set to true especially when unloading packages.
9475 */
9476 private void updateExternalMediaStatusInner(boolean mediaStatus,
9477 boolean reportStatus) {
9478 // Collection of uids
9479 int uidArr[] = null;
9480 // Collection of stale containers
9481 HashSet<String> removeCids = new HashSet<String>();
9482 // Collection of packages on external media with valid containers.
9483 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9484 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009485 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009486 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009487 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009488 } else {
9489 // Process list of secure containers and categorize them
9490 // as active or stale based on their package internal state.
9491 int uidList[] = new int[list.length];
9492 int num = 0;
9493 synchronized (mPackages) {
9494 for (String cid : list) {
9495 SdInstallArgs args = new SdInstallArgs(cid);
9496 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009497 String pkgName = args.getPackageName();
9498 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009499 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9500 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009501 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009502 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009503 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9504 PackageSetting ps = mSettings.mPackages.get(pkgName);
9505 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009506 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009507 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9508 " corresponds to pkg : " + pkgName +
9509 " at code path: " + ps.codePathString);
9510 // We do have a valid package installed on sdcard
9511 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009512 int uid = ps.userId;
9513 if (uid != -1) {
9514 uidList[num++] = uid;
9515 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009516 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009517 // Stale container on sdcard. Just delete
9518 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9519 removeCids.add(cid);
9520 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009521 }
9522 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009523
9524 if (num > 0) {
9525 // Sort uid list
9526 Arrays.sort(uidList, 0, num);
9527 // Throw away duplicates
9528 uidArr = new int[num];
9529 uidArr[0] = uidList[0];
9530 int di = 0;
9531 for (int i = 1; i < num; i++) {
9532 if (uidList[i-1] != uidList[i]) {
9533 uidArr[di++] = uidList[i];
9534 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009535 }
9536 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009537 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009538 // Process packages with valid entries.
9539 if (mediaStatus) {
9540 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009541 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009542 startCleaningPackages();
9543 } else {
9544 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009545 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009546 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009547 }
9548
9549 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009550 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009551 int size = pkgList.size();
9552 if (size > 0) {
9553 // Send broadcasts here
9554 Bundle extras = new Bundle();
9555 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9556 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009557 if (uidArr != null) {
9558 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9559 }
9560 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9561 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009562 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009563 }
9564 }
9565
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009566 /*
9567 * Look at potentially valid container ids from processCids
9568 * If package information doesn't match the one on record
9569 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009570 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009571 */
9572 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009573 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009574 ArrayList<String> pkgList = new ArrayList<String>();
9575 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009576 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009577 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009578 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009579 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9580 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009581 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009582 try {
9583 // Make sure there are no container errors first.
9584 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9585 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009586 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009587 " when installing from sdcard");
9588 continue;
9589 }
9590 // Check code path here.
9591 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009592 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009593 " does not match one in settings " + codePath);
9594 continue;
9595 }
9596 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009597 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009598 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009599 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009600 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9601 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009602 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009603 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009604 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009605 retCode = PackageManager.INSTALL_SUCCEEDED;
9606 pkgList.add(pkg.packageName);
9607 // Post process args
9608 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9609 }
9610 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009611 Slog.i(TAG, "Failed to install pkg from " +
9612 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009613 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009614 }
9615
9616 } finally {
9617 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9618 // Don't destroy container here. Wait till gc clears things up.
9619 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009620 }
9621 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009622 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009623 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009624 // If the platform SDK has changed since the last time we booted,
9625 // we need to re-grant app permission to catch any new ones that
9626 // appear. This is really a hack, and means that apps can in some
9627 // cases get permissions that the user didn't initially explicitly
9628 // allow... it would be nice to have some better way to handle
9629 // this situation.
9630 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9631 != mSdkVersion;
9632 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9633 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9634 + "; regranting permissions for external storage");
9635 mSettings.mExternalSdkPlatform = mSdkVersion;
9636
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009637 // Make sure group IDs have been assigned, and any permission
9638 // changes in other apps are accounted for
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009639 updatePermissionsLP(null, null, true, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009640 // Persist settings
9641 mSettings.writeLP();
9642 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009643 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009644 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009645 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009646 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009647 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009648 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009649 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009650 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009651 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009652 if (removeCids != null) {
9653 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009654 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009655 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009656 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009657 }
9658
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009659 /*
9660 * Utility method to unload a list of specified containers
9661 */
9662 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9663 // Just unmount all valid containers.
9664 for (SdInstallArgs arg : cidArgs) {
9665 synchronized (mInstallLock) {
9666 arg.doPostDeleteLI(false);
9667 }
9668 }
9669 }
9670
9671 /*
9672 * Unload packages mounted on external media. This involves deleting
9673 * package data from internal structures, sending broadcasts about
9674 * diabled packages, gc'ing to free up references, unmounting all
9675 * secure containers corresponding to packages on external media, and
9676 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9677 * Please note that we always have to post this message if status has
9678 * been requested no matter what.
9679 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009680 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009681 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009682 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009683 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009684 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009685 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009686 for (SdInstallArgs args : keys) {
9687 String cid = args.cid;
9688 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009689 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009690 // Delete package internally
9691 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9692 synchronized (mInstallLock) {
9693 boolean res = deletePackageLI(pkgName, false,
9694 PackageManager.DONT_DELETE_DATA, outInfo);
9695 if (res) {
9696 pkgList.add(pkgName);
9697 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009698 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009699 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009700 }
9701 }
9702 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009703 // We have to absolutely send UPDATED_MEDIA_STATUS only
9704 // after confirming that all the receivers processed the ordered
9705 // broadcast when packages get disabled, force a gc to clean things up.
9706 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009707 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009708 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9709 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9710 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009711 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9712 reportStatus ? 1 : 0, 1, keys);
9713 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009714 }
9715 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009716 } else {
9717 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9718 reportStatus ? 1 : 0, -1, keys);
9719 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009720 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009721 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009722
9723 public void movePackage(final String packageName,
9724 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009725 mContext.enforceCallingOrSelfPermission(
9726 android.Manifest.permission.MOVE_PACKAGE, null);
9727 int returnCode = PackageManager.MOVE_SUCCEEDED;
9728 int currFlags = 0;
9729 int newFlags = 0;
9730 synchronized (mPackages) {
9731 PackageParser.Package pkg = mPackages.get(packageName);
9732 if (pkg == null) {
9733 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009734 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009735 // Disable moving fwd locked apps and system packages
9736 if (pkg.applicationInfo != null &&
9737 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9738 Slog.w(TAG, "Cannot move system application");
9739 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9740 } else if (pkg.applicationInfo != null &&
9741 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9742 Slog.w(TAG, "Cannot move forward locked app.");
9743 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009744 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009745 // Find install location first
9746 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9747 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9748 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009749 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009750 } else {
9751 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9752 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9753 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9754 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9755 if (newFlags == currFlags) {
9756 Slog.w(TAG, "No move required. Trying to move to same location");
9757 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9758 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009759 }
9760 }
9761 }
9762 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9763 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9764 } else {
9765 Message msg = mHandler.obtainMessage(INIT_COPY);
9766 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9767 pkg.applicationInfo.publicSourceDir);
9768 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9769 packageName);
9770 msg.obj = mp;
9771 mHandler.sendMessage(msg);
9772 }
9773 }
9774 }
9775
9776 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9777 // Queue up an async operation since the package deletion may take a little while.
9778 mHandler.post(new Runnable() {
9779 public void run() {
9780 mHandler.removeCallbacks(this);
9781 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009782 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9783 int uidArr[] = null;
9784 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009785 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009786 PackageParser.Package pkg = mPackages.get(mp.packageName);
9787 if (pkg == null ) {
9788 Slog.w(TAG, " Package " + mp.packageName +
9789 " doesn't exist. Aborting move");
9790 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9791 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9792 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9793 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9794 " Aborting move and returning error");
9795 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9796 } else {
9797 uidArr = new int[] { pkg.applicationInfo.uid };
9798 pkgList = new ArrayList<String>();
9799 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009800 }
9801 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009802 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9803 // Send resources unavailable broadcast
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009804 // TODO Add an ordered broadcast receiver here.
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009805 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009806 // Update package code and resource paths
9807 synchronized (mInstallLock) {
9808 synchronized (mPackages) {
9809 PackageParser.Package pkg = mPackages.get(mp.packageName);
9810 // Recheck for package again.
9811 if (pkg == null ) {
9812 Slog.w(TAG, " Package " + mp.packageName +
9813 " doesn't exist. Aborting move");
9814 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9815 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9816 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9817 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9818 " Aborting move and returning error");
9819 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9820 } else {
9821 String oldCodePath = pkg.mPath;
9822 String newCodePath = mp.targetArgs.getCodePath();
9823 String newResPath = mp.targetArgs.getResourcePath();
9824 pkg.mPath = newCodePath;
9825 // Move dex files around
9826 if (moveDexFilesLI(pkg)
9827 != PackageManager.INSTALL_SUCCEEDED) {
9828 // Moving of dex files failed. Set
9829 // error code and abort move.
9830 pkg.mPath = pkg.mScanPath;
9831 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9832 } else {
9833 pkg.mScanPath = newCodePath;
9834 pkg.applicationInfo.sourceDir = newCodePath;
9835 pkg.applicationInfo.publicSourceDir = newResPath;
9836 PackageSetting ps = (PackageSetting) pkg.mExtras;
9837 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9838 ps.codePathString = ps.codePath.getPath();
9839 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9840 ps.resourcePathString = ps.resourcePath.getPath();
9841 // Set the application info flag correctly.
9842 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9843 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9844 } else {
9845 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9846 }
9847 ps.setFlags(pkg.applicationInfo.flags);
9848 mAppDirs.remove(oldCodePath);
9849 mAppDirs.put(newCodePath, pkg);
9850 // Persist settings
9851 mSettings.writeLP();
9852 }
9853 }
9854 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009855 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009856 // Send resources available broadcast
9857 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009858 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009859 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009860 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009861 // Clean up failed installation
9862 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009863 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009864 }
9865 } else {
9866 // Force a gc to clear things up.
9867 Runtime.getRuntime().gc();
9868 // Delete older code
9869 synchronized (mInstallLock) {
9870 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009871 }
9872 }
9873 IPackageMoveObserver observer = mp.observer;
9874 if (observer != null) {
9875 try {
9876 observer.packageMoved(mp.packageName, returnCode);
9877 } catch (RemoteException e) {
9878 Log.i(TAG, "Observer no longer exists.");
9879 }
9880 }
9881 }
9882 });
9883 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009884
9885 public boolean setInstallLocation(int loc) {
9886 mContext.enforceCallingOrSelfPermission(
9887 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9888 if (getInstallLocation() == loc) {
9889 return true;
9890 }
9891 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9892 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9893 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9894 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9895 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9896 return true;
9897 }
9898 return false;
9899 }
9900
9901 public int getInstallLocation() {
9902 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9903 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009905}
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009906